blob: fa38ee80bf41e939068ee7cb6a9f45c68899e17d [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 //
George Rokos63bc9d62017-11-21 18:25:12 +0000671 // Call to int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
672 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Alexey Bataev50b3c952016-02-19 10:38:26 +0000673 // *arg_types);
674 OMPRTL__tgt_target,
Alexey Bataeva9f77c62017-12-13 21:04:20 +0000675 // Call to int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
676 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
677 // *arg_types);
678 OMPRTL__tgt_target_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000679 // Call to int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
680 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
681 // *arg_types, int32_t num_teams, int32_t thread_limit);
Samuel Antaob68e2db2016-03-03 16:20:23 +0000682 OMPRTL__tgt_target_teams,
Alexey Bataeva9f77c62017-12-13 21:04:20 +0000683 // Call to int32_t __tgt_target_teams_nowait(int64_t device_id, void
684 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
685 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
686 OMPRTL__tgt_target_teams_nowait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000687 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
688 OMPRTL__tgt_register_lib,
689 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
690 OMPRTL__tgt_unregister_lib,
George Rokos63bc9d62017-11-21 18:25:12 +0000691 // Call to void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
692 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antaodf158d52016-04-27 22:58:19 +0000693 OMPRTL__tgt_target_data_begin,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000694 // Call to void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
695 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
696 // *arg_types);
697 OMPRTL__tgt_target_data_begin_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000698 // Call to void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
699 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antaodf158d52016-04-27 22:58:19 +0000700 OMPRTL__tgt_target_data_end,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000701 // Call to void __tgt_target_data_end_nowait(int64_t device_id, int32_t
702 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
703 // *arg_types);
704 OMPRTL__tgt_target_data_end_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000705 // Call to void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
706 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antao8d2d7302016-05-26 18:30:22 +0000707 OMPRTL__tgt_target_data_update,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000708 // Call to void __tgt_target_data_update_nowait(int64_t device_id, int32_t
709 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
710 // *arg_types);
711 OMPRTL__tgt_target_data_update_nowait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000712};
713
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000714/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
715/// region.
716class CleanupTy final : public EHScopeStack::Cleanup {
717 PrePostActionTy *Action;
718
719public:
720 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
721 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
722 if (!CGF.HaveInsertPoint())
723 return;
724 Action->Exit(CGF);
725 }
726};
727
Hans Wennborg7eb54642015-09-10 17:07:54 +0000728} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000729
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000730void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
731 CodeGenFunction::RunCleanupsScope Scope(CGF);
732 if (PrePostAction) {
733 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
734 Callback(CodeGen, CGF, *PrePostAction);
735 } else {
736 PrePostActionTy Action;
737 Callback(CodeGen, CGF, Action);
738 }
739}
740
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000741/// Check if the combiner is a call to UDR combiner and if it is so return the
742/// UDR decl used for reduction.
743static const OMPDeclareReductionDecl *
744getReductionInit(const Expr *ReductionOp) {
745 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
746 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
747 if (auto *DRE =
748 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
749 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
750 return DRD;
751 return nullptr;
752}
753
754static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
755 const OMPDeclareReductionDecl *DRD,
756 const Expr *InitOp,
757 Address Private, Address Original,
758 QualType Ty) {
759 if (DRD->getInitializer()) {
760 std::pair<llvm::Function *, llvm::Function *> Reduction =
761 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
762 auto *CE = cast<CallExpr>(InitOp);
763 auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
764 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
765 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
766 auto *LHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
767 auto *RHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
768 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
769 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
770 [=]() -> Address { return Private; });
771 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
772 [=]() -> Address { return Original; });
773 (void)PrivateScope.Privatize();
774 RValue Func = RValue::get(Reduction.second);
775 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
776 CGF.EmitIgnoredExpr(InitOp);
777 } else {
778 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
779 auto *GV = new llvm::GlobalVariable(
780 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
781 llvm::GlobalValue::PrivateLinkage, Init, ".init");
782 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
783 RValue InitRVal;
784 switch (CGF.getEvaluationKind(Ty)) {
785 case TEK_Scalar:
786 InitRVal = CGF.EmitLoadOfLValue(LV, SourceLocation());
787 break;
788 case TEK_Complex:
789 InitRVal =
790 RValue::getComplex(CGF.EmitLoadOfComplex(LV, SourceLocation()));
791 break;
792 case TEK_Aggregate:
793 InitRVal = RValue::getAggregate(LV.getAddress());
794 break;
795 }
796 OpaqueValueExpr OVE(SourceLocation(), Ty, VK_RValue);
797 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
798 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
799 /*IsInitializer=*/false);
800 }
801}
802
803/// \brief Emit initialization of arrays of complex types.
804/// \param DestAddr Address of the array.
805/// \param Type Type of array.
806/// \param Init Initial expression of array.
807/// \param SrcAddr Address of the original array.
808static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
Alexey Bataeva7b19152017-10-12 20:03:39 +0000809 QualType Type, bool EmitDeclareReductionInit,
810 const Expr *Init,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000811 const OMPDeclareReductionDecl *DRD,
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000812 Address SrcAddr = Address::invalid()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000813 // Perform element-by-element initialization.
814 QualType ElementTy;
815
816 // Drill down to the base element type on both arrays.
817 auto ArrayTy = Type->getAsArrayTypeUnsafe();
818 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
819 DestAddr =
820 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
821 if (DRD)
822 SrcAddr =
823 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
824
825 llvm::Value *SrcBegin = nullptr;
826 if (DRD)
827 SrcBegin = SrcAddr.getPointer();
828 auto DestBegin = DestAddr.getPointer();
829 // Cast from pointer to array type to pointer to single element.
830 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
831 // The basic structure here is a while-do loop.
832 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
833 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
834 auto IsEmpty =
835 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
836 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
837
838 // Enter the loop body, making that address the current address.
839 auto EntryBB = CGF.Builder.GetInsertBlock();
840 CGF.EmitBlock(BodyBB);
841
842 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
843
844 llvm::PHINode *SrcElementPHI = nullptr;
845 Address SrcElementCurrent = Address::invalid();
846 if (DRD) {
847 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
848 "omp.arraycpy.srcElementPast");
849 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
850 SrcElementCurrent =
851 Address(SrcElementPHI,
852 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
853 }
854 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
855 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
856 DestElementPHI->addIncoming(DestBegin, EntryBB);
857 Address DestElementCurrent =
858 Address(DestElementPHI,
859 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
860
861 // Emit copy.
862 {
863 CodeGenFunction::RunCleanupsScope InitScope(CGF);
Alexey Bataeva7b19152017-10-12 20:03:39 +0000864 if (EmitDeclareReductionInit) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000865 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
866 SrcElementCurrent, ElementTy);
867 } else
868 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
869 /*IsInitializer=*/false);
870 }
871
872 if (DRD) {
873 // Shift the address forward by one element.
874 auto SrcElementNext = CGF.Builder.CreateConstGEP1_32(
875 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
876 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
877 }
878
879 // Shift the address forward by one element.
880 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
881 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
882 // Check whether we've reached the end.
883 auto Done =
884 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
885 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
886 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
887
888 // Done.
889 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
890}
891
892LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000893 return CGF.EmitOMPSharedLValue(E);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000894}
895
896LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
897 const Expr *E) {
898 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
899 return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
900 return LValue();
901}
902
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000903void ReductionCodeGen::emitAggregateInitialization(
904 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
905 const OMPDeclareReductionDecl *DRD) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000906 // Emit VarDecl with copy init for arrays.
907 // Get the address of the original variable captured in current
908 // captured region.
909 auto *PrivateVD =
910 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva7b19152017-10-12 20:03:39 +0000911 bool EmitDeclareReductionInit =
912 DRD && (DRD->getInitializer() || !PrivateVD->hasInit());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000913 EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
Alexey Bataeva7b19152017-10-12 20:03:39 +0000914 EmitDeclareReductionInit,
915 EmitDeclareReductionInit ? ClausesData[N].ReductionOp
916 : PrivateVD->getInit(),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000917 DRD, SharedLVal.getAddress());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000918}
919
920ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
921 ArrayRef<const Expr *> Privates,
922 ArrayRef<const Expr *> ReductionOps) {
923 ClausesData.reserve(Shareds.size());
924 SharedAddresses.reserve(Shareds.size());
925 Sizes.reserve(Shareds.size());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000926 BaseDecls.reserve(Shareds.size());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000927 auto IPriv = Privates.begin();
928 auto IRed = ReductionOps.begin();
929 for (const auto *Ref : Shareds) {
930 ClausesData.emplace_back(Ref, *IPriv, *IRed);
931 std::advance(IPriv, 1);
932 std::advance(IRed, 1);
933 }
934}
935
936void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
937 assert(SharedAddresses.size() == N &&
938 "Number of generated lvalues must be exactly N.");
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000939 LValue First = emitSharedLValue(CGF, ClausesData[N].Ref);
940 LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Ref);
941 SharedAddresses.emplace_back(First, Second);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000942}
943
944void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
945 auto *PrivateVD =
946 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
947 QualType PrivateType = PrivateVD->getType();
948 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000949 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000950 Sizes.emplace_back(
951 CGF.getTypeSize(
952 SharedAddresses[N].first.getType().getNonReferenceType()),
953 nullptr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000954 return;
955 }
956 llvm::Value *Size;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000957 llvm::Value *SizeInChars;
958 llvm::Type *ElemType =
959 cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
960 ->getElementType();
961 auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000962 if (AsArraySection) {
963 Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
964 SharedAddresses[N].first.getPointer());
965 Size = CGF.Builder.CreateNUWAdd(
966 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000967 SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000968 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000969 SizeInChars = CGF.getTypeSize(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000970 SharedAddresses[N].first.getType().getNonReferenceType());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000971 Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000972 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000973 Sizes.emplace_back(SizeInChars, Size);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000974 CodeGenFunction::OpaqueValueMapping OpaqueMap(
975 CGF,
976 cast<OpaqueValueExpr>(
977 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
978 RValue::get(Size));
979 CGF.EmitVariablyModifiedType(PrivateType);
980}
981
982void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
983 llvm::Value *Size) {
984 auto *PrivateVD =
985 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
986 QualType PrivateType = PrivateVD->getType();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000987 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000988 assert(!Size && !Sizes[N].second &&
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000989 "Size should be nullptr for non-variably modified reduction "
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000990 "items.");
991 return;
992 }
993 CodeGenFunction::OpaqueValueMapping OpaqueMap(
994 CGF,
995 cast<OpaqueValueExpr>(
996 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
997 RValue::get(Size));
998 CGF.EmitVariablyModifiedType(PrivateType);
999}
1000
1001void ReductionCodeGen::emitInitialization(
1002 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
1003 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
1004 assert(SharedAddresses.size() > N && "No variable was generated");
1005 auto *PrivateVD =
1006 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1007 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
1008 QualType PrivateType = PrivateVD->getType();
1009 PrivateAddr = CGF.Builder.CreateElementBitCast(
1010 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1011 QualType SharedType = SharedAddresses[N].first.getType();
1012 SharedLVal = CGF.MakeAddrLValue(
1013 CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
1014 CGF.ConvertTypeForMem(SharedType)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001015 SharedType, SharedAddresses[N].first.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001016 CGF.CGM.getTBAAInfoForSubobject(SharedAddresses[N].first, SharedType));
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001017 if (CGF.getContext().getAsArrayType(PrivateVD->getType())) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001018 emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001019 } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
1020 emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
1021 PrivateAddr, SharedLVal.getAddress(),
1022 SharedLVal.getType());
1023 } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
1024 !CGF.isTrivialInitializer(PrivateVD->getInit())) {
1025 CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
1026 PrivateVD->getType().getQualifiers(),
1027 /*IsInitializer=*/false);
1028 }
1029}
1030
1031bool ReductionCodeGen::needCleanups(unsigned N) {
1032 auto *PrivateVD =
1033 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1034 QualType PrivateType = PrivateVD->getType();
1035 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1036 return DTorKind != QualType::DK_none;
1037}
1038
1039void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
1040 Address PrivateAddr) {
1041 auto *PrivateVD =
1042 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1043 QualType PrivateType = PrivateVD->getType();
1044 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1045 if (needCleanups(N)) {
1046 PrivateAddr = CGF.Builder.CreateElementBitCast(
1047 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1048 CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
1049 }
1050}
1051
1052static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1053 LValue BaseLV) {
1054 BaseTy = BaseTy.getNonReferenceType();
1055 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1056 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1057 if (auto *PtrTy = BaseTy->getAs<PointerType>())
1058 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
1059 else {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00001060 LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(), BaseTy);
1061 BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001062 }
1063 BaseTy = BaseTy->getPointeeType();
1064 }
1065 return CGF.MakeAddrLValue(
1066 CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
1067 CGF.ConvertTypeForMem(ElTy)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001068 BaseLV.getType(), BaseLV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001069 CGF.CGM.getTBAAInfoForSubobject(BaseLV, BaseLV.getType()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001070}
1071
1072static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1073 llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
1074 llvm::Value *Addr) {
1075 Address Tmp = Address::invalid();
1076 Address TopTmp = Address::invalid();
1077 Address MostTopTmp = Address::invalid();
1078 BaseTy = BaseTy.getNonReferenceType();
1079 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1080 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1081 Tmp = CGF.CreateMemTemp(BaseTy);
1082 if (TopTmp.isValid())
1083 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
1084 else
1085 MostTopTmp = Tmp;
1086 TopTmp = Tmp;
1087 BaseTy = BaseTy->getPointeeType();
1088 }
1089 llvm::Type *Ty = BaseLVType;
1090 if (Tmp.isValid())
1091 Ty = Tmp.getElementType();
1092 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
1093 if (Tmp.isValid()) {
1094 CGF.Builder.CreateStore(Addr, Tmp);
1095 return MostTopTmp;
1096 }
1097 return Address(Addr, BaseLVAlignment);
1098}
1099
1100Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
1101 Address PrivateAddr) {
1102 const DeclRefExpr *DE;
1103 const VarDecl *OrigVD = nullptr;
1104 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(ClausesData[N].Ref)) {
1105 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
1106 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
1107 Base = TempOASE->getBase()->IgnoreParenImpCasts();
1108 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1109 Base = TempASE->getBase()->IgnoreParenImpCasts();
1110 DE = cast<DeclRefExpr>(Base);
1111 OrigVD = cast<VarDecl>(DE->getDecl());
1112 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(ClausesData[N].Ref)) {
1113 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
1114 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1115 Base = TempASE->getBase()->IgnoreParenImpCasts();
1116 DE = cast<DeclRefExpr>(Base);
1117 OrigVD = cast<VarDecl>(DE->getDecl());
1118 }
1119 if (OrigVD) {
1120 BaseDecls.emplace_back(OrigVD);
1121 auto OriginalBaseLValue = CGF.EmitLValue(DE);
1122 LValue BaseLValue =
1123 loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1124 OriginalBaseLValue);
1125 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1126 BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001127 llvm::Value *PrivatePointer =
1128 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1129 PrivateAddr.getPointer(),
1130 SharedAddresses[N].first.getAddress().getType());
1131 llvm::Value *Ptr = CGF.Builder.CreateGEP(PrivatePointer, Adjustment);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001132 return castToBase(CGF, OrigVD->getType(),
1133 SharedAddresses[N].first.getType(),
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001134 OriginalBaseLValue.getAddress().getType(),
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001135 OriginalBaseLValue.getAlignment(), Ptr);
1136 }
1137 BaseDecls.emplace_back(
1138 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1139 return PrivateAddr;
1140}
1141
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001142bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
1143 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
1144 return DRD && DRD->getInitializer();
1145}
1146
Alexey Bataev18095712014-10-10 12:19:54 +00001147LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00001148 return CGF.EmitLoadOfPointerLValue(
1149 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1150 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +00001151}
1152
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001153void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001154 if (!CGF.HaveInsertPoint())
1155 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001156 // 1.2.2 OpenMP Language Terminology
1157 // Structured block - An executable statement with a single entry at the
1158 // top and a single exit at the bottom.
1159 // The point of exit cannot be a branch out of the structured block.
1160 // longjmp() and throw() must not violate the entry/exit criteria.
1161 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001162 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001163 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001164}
1165
Alexey Bataev62b63b12015-03-10 07:28:44 +00001166LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1167 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001168 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1169 getThreadIDVariable()->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00001170 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001171}
1172
Alexey Bataev9959db52014-05-06 10:08:46 +00001173CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001174 : CGM(CGM), OffloadEntriesInfoManager(CGM) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001175 IdentTy = llvm::StructType::create(
1176 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
1177 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Serge Guelton1d993272017-05-09 19:31:30 +00001178 CGM.Int8PtrTy /* psource */);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001179 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +00001180
1181 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +00001182}
1183
Alexey Bataev91797552015-03-18 04:13:55 +00001184void CGOpenMPRuntime::clear() {
1185 InternalVars.clear();
1186}
1187
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001188static llvm::Function *
1189emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1190 const Expr *CombinerInitializer, const VarDecl *In,
1191 const VarDecl *Out, bool IsCombiner) {
1192 // void .omp_combiner.(Ty *in, Ty *out);
1193 auto &C = CGM.getContext();
1194 QualType PtrTy = C.getPointerType(Ty).withRestrict();
1195 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001196 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001197 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001198 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001199 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001200 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001201 Args.push_back(&OmpInParm);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001202 auto &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001203 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001204 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1205 auto *Fn = llvm::Function::Create(
1206 FnTy, llvm::GlobalValue::InternalLinkage,
1207 IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
1208 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001209 Fn->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001210 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001211 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001212 CodeGenFunction CGF(CGM);
1213 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1214 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
1215 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
1216 CodeGenFunction::OMPPrivateScope Scope(CGF);
1217 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
1218 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
1219 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1220 .getAddress();
1221 });
1222 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
1223 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
1224 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1225 .getAddress();
1226 });
1227 (void)Scope.Privatize();
Alexey Bataev070f43a2017-09-06 14:49:58 +00001228 if (!IsCombiner && Out->hasInit() &&
1229 !CGF.isTrivialInitializer(Out->getInit())) {
1230 CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
1231 Out->getType().getQualifiers(),
1232 /*IsInitializer=*/true);
1233 }
1234 if (CombinerInitializer)
1235 CGF.EmitIgnoredExpr(CombinerInitializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001236 Scope.ForceCleanup();
1237 CGF.FinishFunction();
1238 return Fn;
1239}
1240
1241void CGOpenMPRuntime::emitUserDefinedReduction(
1242 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1243 if (UDRMap.count(D) > 0)
1244 return;
1245 auto &C = CGM.getContext();
1246 if (!In || !Out) {
1247 In = &C.Idents.get("omp_in");
1248 Out = &C.Idents.get("omp_out");
1249 }
1250 llvm::Function *Combiner = emitCombinerOrInitializer(
1251 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
1252 cast<VarDecl>(D->lookup(Out).front()),
1253 /*IsCombiner=*/true);
1254 llvm::Function *Initializer = nullptr;
1255 if (auto *Init = D->getInitializer()) {
1256 if (!Priv || !Orig) {
1257 Priv = &C.Idents.get("omp_priv");
1258 Orig = &C.Idents.get("omp_orig");
1259 }
1260 Initializer = emitCombinerOrInitializer(
Alexey Bataev070f43a2017-09-06 14:49:58 +00001261 CGM, D->getType(),
1262 D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init
1263 : nullptr,
1264 cast<VarDecl>(D->lookup(Orig).front()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001265 cast<VarDecl>(D->lookup(Priv).front()),
1266 /*IsCombiner=*/false);
1267 }
1268 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
1269 if (CGF) {
1270 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1271 Decls.second.push_back(D);
1272 }
1273}
1274
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001275std::pair<llvm::Function *, llvm::Function *>
1276CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1277 auto I = UDRMap.find(D);
1278 if (I != UDRMap.end())
1279 return I->second;
1280 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1281 return UDRMap.lookup(D);
1282}
1283
John McCall7f416cc2015-09-08 08:05:57 +00001284// Layout information for ident_t.
1285static CharUnits getIdentAlign(CodeGenModule &CGM) {
1286 return CGM.getPointerAlign();
1287}
1288static CharUnits getIdentSize(CodeGenModule &CGM) {
1289 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
1290 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
1291}
Alexey Bataev50b3c952016-02-19 10:38:26 +00001292static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
John McCall7f416cc2015-09-08 08:05:57 +00001293 // All the fields except the last are i32, so this works beautifully.
1294 return unsigned(Field) * CharUnits::fromQuantity(4);
1295}
1296static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001297 IdentFieldIndex Field,
John McCall7f416cc2015-09-08 08:05:57 +00001298 const llvm::Twine &Name = "") {
1299 auto Offset = getOffsetOfIdentField(Field);
1300 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
1301}
1302
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001303static llvm::Value *emitParallelOrTeamsOutlinedFunction(
1304 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1305 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1306 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001307 assert(ThreadIDVar->getType()->isPointerType() &&
1308 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +00001309 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00001310 bool HasCancel = false;
1311 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
1312 HasCancel = OPD->hasCancel();
1313 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
1314 HasCancel = OPSD->hasCancel();
1315 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
1316 HasCancel = OPFD->hasCancel();
Alexey Bataev2139ed62017-11-16 18:20:21 +00001317 else if (auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D))
1318 HasCancel = OPFD->hasCancel();
Alexey Bataev10a54312017-11-27 16:54:08 +00001319 else if (auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&D))
1320 HasCancel = OPFD->hasCancel();
1321 else if (auto *OPFD = dyn_cast<OMPTeamsDistributeParallelForDirective>(&D))
1322 HasCancel = OPFD->hasCancel();
1323 else if (auto *OPFD =
1324 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D))
1325 HasCancel = OPFD->hasCancel();
Alexey Bataev25e5b442015-09-15 12:52:43 +00001326 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001327 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +00001328 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001329 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +00001330}
1331
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001332llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
1333 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1334 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1335 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1336 return emitParallelOrTeamsOutlinedFunction(
1337 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1338}
1339
1340llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1341 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1342 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1343 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1344 return emitParallelOrTeamsOutlinedFunction(
1345 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1346}
1347
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001348llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
1349 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +00001350 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1351 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1352 bool Tied, unsigned &NumberOfParts) {
1353 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1354 PrePostActionTy &) {
1355 auto *ThreadID = getThreadID(CGF, D.getLocStart());
1356 auto *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
1357 llvm::Value *TaskArgs[] = {
1358 UpLoc, ThreadID,
1359 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1360 TaskTVar->getType()->castAs<PointerType>())
1361 .getPointer()};
1362 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1363 };
1364 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1365 UntiedCodeGen);
1366 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001367 assert(!ThreadIDVar->getType()->isPointerType() &&
1368 "thread id variable must be of type kmp_int32 for tasks");
1369 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
Alexey Bataev7292c292016-04-25 12:22:29 +00001370 auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001371 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +00001372 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1373 InnermostKind,
1374 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +00001375 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev48591dd2016-04-20 04:01:36 +00001376 auto *Res = CGF.GenerateCapturedStmtFunction(*CS);
1377 if (!Tied)
1378 NumberOfParts = Action.getNumberOfParts();
1379 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001380}
1381
Alexey Bataev50b3c952016-02-19 10:38:26 +00001382Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +00001383 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +00001384 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +00001385 if (!Entry) {
1386 if (!DefaultOpenMPPSource) {
1387 // Initialize default location for psource field of ident_t structure of
1388 // all ident_t objects. Format is ";file;function;line;column;;".
1389 // Taken from
1390 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1391 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +00001392 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001393 DefaultOpenMPPSource =
1394 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1395 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001396
John McCall23c9dc62016-11-28 22:18:27 +00001397 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001398 auto fields = builder.beginStruct(IdentTy);
1399 fields.addInt(CGM.Int32Ty, 0);
1400 fields.addInt(CGM.Int32Ty, Flags);
1401 fields.addInt(CGM.Int32Ty, 0);
1402 fields.addInt(CGM.Int32Ty, 0);
1403 fields.add(DefaultOpenMPPSource);
1404 auto DefaultOpenMPLocation =
1405 fields.finishAndCreateGlobal("", Align, /*isConstant*/ true,
1406 llvm::GlobalValue::PrivateLinkage);
1407 DefaultOpenMPLocation->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1408
John McCall7f416cc2015-09-08 08:05:57 +00001409 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +00001410 }
John McCall7f416cc2015-09-08 08:05:57 +00001411 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +00001412}
1413
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001414llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1415 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001416 unsigned Flags) {
1417 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +00001418 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001419 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +00001420 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +00001421 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001422
1423 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1424
John McCall7f416cc2015-09-08 08:05:57 +00001425 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001426 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1427 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +00001428 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
1429
Alexander Musmanc6388682014-12-15 07:07:06 +00001430 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1431 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +00001432 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +00001433 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +00001434 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
1435 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +00001436 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +00001437 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001438 LocValue = AI;
1439
1440 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1441 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001442 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +00001443 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +00001444 }
1445
1446 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +00001447 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +00001448
Alexey Bataevf002aca2014-05-30 05:48:40 +00001449 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
1450 if (OMPDebugLoc == nullptr) {
1451 SmallString<128> Buffer2;
1452 llvm::raw_svector_ostream OS2(Buffer2);
1453 // Build debug location
1454 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1455 OS2 << ";" << PLoc.getFilename() << ";";
1456 if (const FunctionDecl *FD =
1457 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
1458 OS2 << FD->getQualifiedNameAsString();
1459 }
1460 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1461 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1462 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +00001463 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001464 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +00001465 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
1466
John McCall7f416cc2015-09-08 08:05:57 +00001467 // Our callers always pass this to a runtime function, so for
1468 // convenience, go ahead and return a naked pointer.
1469 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001470}
1471
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001472llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1473 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001474 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1475
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001476 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001477 // Check whether we've already cached a load of the thread id in this
1478 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001479 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001480 if (I != OpenMPLocThreadIDMap.end()) {
1481 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001482 if (ThreadID != nullptr)
1483 return ThreadID;
1484 }
Alexey Bataevaee18552017-08-16 14:01:00 +00001485 // If exceptions are enabled, do not use parameter to avoid possible crash.
Alexey Bataev5d2c9a42017-11-02 18:55:05 +00001486 if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions ||
1487 !CGF.getLangOpts().CXXExceptions ||
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001488 CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
Alexey Bataevaee18552017-08-16 14:01:00 +00001489 if (auto *OMPRegionInfo =
1490 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1491 if (OMPRegionInfo->getThreadIDVariable()) {
1492 // Check if this an outlined function with thread id passed as argument.
1493 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
1494 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
1495 // If value loaded in entry block, cache it and use it everywhere in
1496 // function.
1497 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1498 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1499 Elem.second.ThreadID = ThreadID;
1500 }
1501 return ThreadID;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001502 }
Alexey Bataevd6c57552014-07-25 07:55:17 +00001503 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001504 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001505
1506 // This is not an outlined function region - need to call __kmpc_int32
1507 // kmpc_global_thread_num(ident_t *loc).
1508 // Generate thread id value and cache this value for use across the
1509 // function.
1510 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1511 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001512 auto *Call = CGF.Builder.CreateCall(
1513 createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1514 emitUpdateLocation(CGF, Loc));
1515 Call->setCallingConv(CGF.getRuntimeCC());
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001516 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001517 Elem.second.ThreadID = Call;
1518 return Call;
Alexey Bataev9959db52014-05-06 10:08:46 +00001519}
1520
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001521void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001522 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001523 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1524 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001525 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1526 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
1527 UDRMap.erase(D);
1528 }
1529 FunctionUDRMap.erase(CGF.CurFn);
1530 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001531}
1532
1533llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001534 if (!IdentTy) {
1535 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001536 return llvm::PointerType::getUnqual(IdentTy);
1537}
1538
1539llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001540 if (!Kmpc_MicroTy) {
1541 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1542 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1543 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1544 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1545 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001546 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1547}
1548
1549llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001550CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001551 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001552 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001553 case OMPRTL__kmpc_fork_call: {
1554 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1555 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001556 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1557 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001558 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001559 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001560 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1561 break;
1562 }
1563 case OMPRTL__kmpc_global_thread_num: {
1564 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001565 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001566 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001567 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001568 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1569 break;
1570 }
Alexey Bataev97720002014-11-11 04:05:39 +00001571 case OMPRTL__kmpc_threadprivate_cached: {
1572 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1573 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1574 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1575 CGM.VoidPtrTy, CGM.SizeTy,
1576 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1577 llvm::FunctionType *FnTy =
1578 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1579 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1580 break;
1581 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001582 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001583 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1584 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001585 llvm::Type *TypeParams[] = {
1586 getIdentTyPointerTy(), CGM.Int32Ty,
1587 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1588 llvm::FunctionType *FnTy =
1589 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1590 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1591 break;
1592 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001593 case OMPRTL__kmpc_critical_with_hint: {
1594 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1595 // kmp_critical_name *crit, uintptr_t hint);
1596 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1597 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1598 CGM.IntPtrTy};
1599 llvm::FunctionType *FnTy =
1600 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1601 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1602 break;
1603 }
Alexey Bataev97720002014-11-11 04:05:39 +00001604 case OMPRTL__kmpc_threadprivate_register: {
1605 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1606 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1607 // typedef void *(*kmpc_ctor)(void *);
1608 auto KmpcCtorTy =
1609 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1610 /*isVarArg*/ false)->getPointerTo();
1611 // typedef void *(*kmpc_cctor)(void *, void *);
1612 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1613 auto KmpcCopyCtorTy =
1614 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1615 /*isVarArg*/ false)->getPointerTo();
1616 // typedef void (*kmpc_dtor)(void *);
1617 auto KmpcDtorTy =
1618 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1619 ->getPointerTo();
1620 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1621 KmpcCopyCtorTy, KmpcDtorTy};
1622 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1623 /*isVarArg*/ false);
1624 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1625 break;
1626 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001627 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001628 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1629 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001630 llvm::Type *TypeParams[] = {
1631 getIdentTyPointerTy(), CGM.Int32Ty,
1632 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1633 llvm::FunctionType *FnTy =
1634 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1635 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1636 break;
1637 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001638 case OMPRTL__kmpc_cancel_barrier: {
1639 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1640 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001641 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1642 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001643 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1644 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001645 break;
1646 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001647 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001648 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001649 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1650 llvm::FunctionType *FnTy =
1651 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1652 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1653 break;
1654 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001655 case OMPRTL__kmpc_for_static_fini: {
1656 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1657 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1658 llvm::FunctionType *FnTy =
1659 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1660 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1661 break;
1662 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001663 case OMPRTL__kmpc_push_num_threads: {
1664 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1665 // kmp_int32 num_threads)
1666 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1667 CGM.Int32Ty};
1668 llvm::FunctionType *FnTy =
1669 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1670 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1671 break;
1672 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001673 case OMPRTL__kmpc_serialized_parallel: {
1674 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1675 // global_tid);
1676 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1677 llvm::FunctionType *FnTy =
1678 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1679 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1680 break;
1681 }
1682 case OMPRTL__kmpc_end_serialized_parallel: {
1683 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1684 // global_tid);
1685 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1686 llvm::FunctionType *FnTy =
1687 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1688 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1689 break;
1690 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001691 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001692 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001693 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1694 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001695 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001696 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1697 break;
1698 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001699 case OMPRTL__kmpc_master: {
1700 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1701 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1702 llvm::FunctionType *FnTy =
1703 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1704 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1705 break;
1706 }
1707 case OMPRTL__kmpc_end_master: {
1708 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1709 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1710 llvm::FunctionType *FnTy =
1711 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1712 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1713 break;
1714 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001715 case OMPRTL__kmpc_omp_taskyield: {
1716 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1717 // int end_part);
1718 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1719 llvm::FunctionType *FnTy =
1720 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1721 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1722 break;
1723 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001724 case OMPRTL__kmpc_single: {
1725 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1726 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1727 llvm::FunctionType *FnTy =
1728 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1729 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1730 break;
1731 }
1732 case OMPRTL__kmpc_end_single: {
1733 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1734 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1735 llvm::FunctionType *FnTy =
1736 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1737 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1738 break;
1739 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001740 case OMPRTL__kmpc_omp_task_alloc: {
1741 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1742 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1743 // kmp_routine_entry_t *task_entry);
1744 assert(KmpRoutineEntryPtrTy != nullptr &&
1745 "Type kmp_routine_entry_t must be created.");
1746 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1747 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1748 // Return void * and then cast to particular kmp_task_t type.
1749 llvm::FunctionType *FnTy =
1750 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1751 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1752 break;
1753 }
1754 case OMPRTL__kmpc_omp_task: {
1755 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1756 // *new_task);
1757 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1758 CGM.VoidPtrTy};
1759 llvm::FunctionType *FnTy =
1760 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1761 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1762 break;
1763 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001764 case OMPRTL__kmpc_copyprivate: {
1765 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001766 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001767 // kmp_int32 didit);
1768 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1769 auto *CpyFnTy =
1770 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001771 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001772 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1773 CGM.Int32Ty};
1774 llvm::FunctionType *FnTy =
1775 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1776 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1777 break;
1778 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001779 case OMPRTL__kmpc_reduce: {
1780 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1781 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1782 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1783 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1784 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1785 /*isVarArg=*/false);
1786 llvm::Type *TypeParams[] = {
1787 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1788 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1789 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1790 llvm::FunctionType *FnTy =
1791 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1792 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1793 break;
1794 }
1795 case OMPRTL__kmpc_reduce_nowait: {
1796 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1797 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1798 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1799 // *lck);
1800 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1801 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1802 /*isVarArg=*/false);
1803 llvm::Type *TypeParams[] = {
1804 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1805 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1806 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1807 llvm::FunctionType *FnTy =
1808 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1809 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1810 break;
1811 }
1812 case OMPRTL__kmpc_end_reduce: {
1813 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1814 // kmp_critical_name *lck);
1815 llvm::Type *TypeParams[] = {
1816 getIdentTyPointerTy(), CGM.Int32Ty,
1817 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1818 llvm::FunctionType *FnTy =
1819 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1820 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1821 break;
1822 }
1823 case OMPRTL__kmpc_end_reduce_nowait: {
1824 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1825 // kmp_critical_name *lck);
1826 llvm::Type *TypeParams[] = {
1827 getIdentTyPointerTy(), CGM.Int32Ty,
1828 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1829 llvm::FunctionType *FnTy =
1830 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1831 RTLFn =
1832 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1833 break;
1834 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001835 case OMPRTL__kmpc_omp_task_begin_if0: {
1836 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1837 // *new_task);
1838 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1839 CGM.VoidPtrTy};
1840 llvm::FunctionType *FnTy =
1841 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1842 RTLFn =
1843 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1844 break;
1845 }
1846 case OMPRTL__kmpc_omp_task_complete_if0: {
1847 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1848 // *new_task);
1849 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1850 CGM.VoidPtrTy};
1851 llvm::FunctionType *FnTy =
1852 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1853 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1854 /*Name=*/"__kmpc_omp_task_complete_if0");
1855 break;
1856 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001857 case OMPRTL__kmpc_ordered: {
1858 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1859 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1860 llvm::FunctionType *FnTy =
1861 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1862 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1863 break;
1864 }
1865 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001866 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001867 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1868 llvm::FunctionType *FnTy =
1869 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1870 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1871 break;
1872 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001873 case OMPRTL__kmpc_omp_taskwait: {
1874 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1875 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1876 llvm::FunctionType *FnTy =
1877 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1878 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1879 break;
1880 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001881 case OMPRTL__kmpc_taskgroup: {
1882 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1883 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1884 llvm::FunctionType *FnTy =
1885 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1886 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1887 break;
1888 }
1889 case OMPRTL__kmpc_end_taskgroup: {
1890 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1891 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1892 llvm::FunctionType *FnTy =
1893 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1894 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1895 break;
1896 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001897 case OMPRTL__kmpc_push_proc_bind: {
1898 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1899 // int proc_bind)
1900 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1901 llvm::FunctionType *FnTy =
1902 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1903 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1904 break;
1905 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001906 case OMPRTL__kmpc_omp_task_with_deps: {
1907 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1908 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1909 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1910 llvm::Type *TypeParams[] = {
1911 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1912 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1913 llvm::FunctionType *FnTy =
1914 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1915 RTLFn =
1916 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1917 break;
1918 }
1919 case OMPRTL__kmpc_omp_wait_deps: {
1920 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1921 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1922 // kmp_depend_info_t *noalias_dep_list);
1923 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1924 CGM.Int32Ty, CGM.VoidPtrTy,
1925 CGM.Int32Ty, CGM.VoidPtrTy};
1926 llvm::FunctionType *FnTy =
1927 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1928 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1929 break;
1930 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001931 case OMPRTL__kmpc_cancellationpoint: {
1932 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1933 // global_tid, kmp_int32 cncl_kind)
1934 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1935 llvm::FunctionType *FnTy =
1936 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1937 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1938 break;
1939 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001940 case OMPRTL__kmpc_cancel: {
1941 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1942 // kmp_int32 cncl_kind)
1943 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1944 llvm::FunctionType *FnTy =
1945 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1946 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1947 break;
1948 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001949 case OMPRTL__kmpc_push_num_teams: {
1950 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1951 // kmp_int32 num_teams, kmp_int32 num_threads)
1952 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1953 CGM.Int32Ty};
1954 llvm::FunctionType *FnTy =
1955 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1956 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1957 break;
1958 }
1959 case OMPRTL__kmpc_fork_teams: {
1960 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1961 // microtask, ...);
1962 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1963 getKmpc_MicroPointerTy()};
1964 llvm::FunctionType *FnTy =
1965 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1966 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1967 break;
1968 }
Alexey Bataev7292c292016-04-25 12:22:29 +00001969 case OMPRTL__kmpc_taskloop: {
1970 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
1971 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
1972 // sched, kmp_uint64 grainsize, void *task_dup);
1973 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1974 CGM.IntTy,
1975 CGM.VoidPtrTy,
1976 CGM.IntTy,
1977 CGM.Int64Ty->getPointerTo(),
1978 CGM.Int64Ty->getPointerTo(),
1979 CGM.Int64Ty,
1980 CGM.IntTy,
1981 CGM.IntTy,
1982 CGM.Int64Ty,
1983 CGM.VoidPtrTy};
1984 llvm::FunctionType *FnTy =
1985 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1986 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
1987 break;
1988 }
Alexey Bataev8b427062016-05-25 12:36:08 +00001989 case OMPRTL__kmpc_doacross_init: {
1990 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
1991 // num_dims, struct kmp_dim *dims);
1992 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1993 CGM.Int32Ty,
1994 CGM.Int32Ty,
1995 CGM.VoidPtrTy};
1996 llvm::FunctionType *FnTy =
1997 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1998 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
1999 break;
2000 }
2001 case OMPRTL__kmpc_doacross_fini: {
2002 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
2003 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
2004 llvm::FunctionType *FnTy =
2005 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2006 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
2007 break;
2008 }
2009 case OMPRTL__kmpc_doacross_post: {
2010 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
2011 // *vec);
2012 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2013 CGM.Int64Ty->getPointerTo()};
2014 llvm::FunctionType *FnTy =
2015 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2016 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
2017 break;
2018 }
2019 case OMPRTL__kmpc_doacross_wait: {
2020 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
2021 // *vec);
2022 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2023 CGM.Int64Ty->getPointerTo()};
2024 llvm::FunctionType *FnTy =
2025 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2026 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
2027 break;
2028 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002029 case OMPRTL__kmpc_task_reduction_init: {
2030 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
2031 // *data);
2032 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
2033 llvm::FunctionType *FnTy =
2034 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2035 RTLFn =
2036 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
2037 break;
2038 }
2039 case OMPRTL__kmpc_task_reduction_get_th_data: {
2040 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
2041 // *d);
2042 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
2043 llvm::FunctionType *FnTy =
2044 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2045 RTLFn = CGM.CreateRuntimeFunction(
2046 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2047 break;
2048 }
Samuel Antaobed3c462015-10-02 16:14:20 +00002049 case OMPRTL__tgt_target: {
George Rokos63bc9d62017-11-21 18:25:12 +00002050 // Build int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
2051 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Samuel Antaobed3c462015-10-02 16:14:20 +00002052 // *arg_types);
George Rokos63bc9d62017-11-21 18:25:12 +00002053 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaobed3c462015-10-02 16:14:20 +00002054 CGM.VoidPtrTy,
2055 CGM.Int32Ty,
2056 CGM.VoidPtrPtrTy,
2057 CGM.VoidPtrPtrTy,
2058 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002059 CGM.Int64Ty->getPointerTo()};
Samuel Antaobed3c462015-10-02 16:14:20 +00002060 llvm::FunctionType *FnTy =
2061 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2062 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2063 break;
2064 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002065 case OMPRTL__tgt_target_nowait: {
2066 // Build int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
2067 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2068 // int64_t *arg_types);
2069 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2070 CGM.VoidPtrTy,
2071 CGM.Int32Ty,
2072 CGM.VoidPtrPtrTy,
2073 CGM.VoidPtrPtrTy,
2074 CGM.SizeTy->getPointerTo(),
2075 CGM.Int64Ty->getPointerTo()};
2076 llvm::FunctionType *FnTy =
2077 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2078 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_nowait");
2079 break;
2080 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00002081 case OMPRTL__tgt_target_teams: {
George Rokos63bc9d62017-11-21 18:25:12 +00002082 // Build int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002083 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
George Rokos63bc9d62017-11-21 18:25:12 +00002084 // int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2085 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002086 CGM.VoidPtrTy,
2087 CGM.Int32Ty,
2088 CGM.VoidPtrPtrTy,
2089 CGM.VoidPtrPtrTy,
2090 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002091 CGM.Int64Ty->getPointerTo(),
Samuel Antaob68e2db2016-03-03 16:20:23 +00002092 CGM.Int32Ty,
2093 CGM.Int32Ty};
2094 llvm::FunctionType *FnTy =
2095 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2096 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2097 break;
2098 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002099 case OMPRTL__tgt_target_teams_nowait: {
2100 // Build int32_t __tgt_target_teams_nowait(int64_t device_id, void
2101 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
2102 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2103 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2104 CGM.VoidPtrTy,
2105 CGM.Int32Ty,
2106 CGM.VoidPtrPtrTy,
2107 CGM.VoidPtrPtrTy,
2108 CGM.SizeTy->getPointerTo(),
2109 CGM.Int64Ty->getPointerTo(),
2110 CGM.Int32Ty,
2111 CGM.Int32Ty};
2112 llvm::FunctionType *FnTy =
2113 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2114 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams_nowait");
2115 break;
2116 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002117 case OMPRTL__tgt_register_lib: {
2118 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2119 QualType ParamTy =
2120 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2121 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2122 llvm::FunctionType *FnTy =
2123 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2124 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2125 break;
2126 }
2127 case OMPRTL__tgt_unregister_lib: {
2128 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2129 QualType ParamTy =
2130 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2131 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2132 llvm::FunctionType *FnTy =
2133 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2134 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2135 break;
2136 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002137 case OMPRTL__tgt_target_data_begin: {
George Rokos63bc9d62017-11-21 18:25:12 +00002138 // Build void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
2139 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2140 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002141 CGM.Int32Ty,
2142 CGM.VoidPtrPtrTy,
2143 CGM.VoidPtrPtrTy,
2144 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002145 CGM.Int64Ty->getPointerTo()};
Samuel Antaodf158d52016-04-27 22:58:19 +00002146 llvm::FunctionType *FnTy =
2147 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2148 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2149 break;
2150 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002151 case OMPRTL__tgt_target_data_begin_nowait: {
2152 // Build void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
2153 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2154 // *arg_types);
2155 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2156 CGM.Int32Ty,
2157 CGM.VoidPtrPtrTy,
2158 CGM.VoidPtrPtrTy,
2159 CGM.SizeTy->getPointerTo(),
2160 CGM.Int64Ty->getPointerTo()};
2161 auto *FnTy =
2162 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2163 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin_nowait");
2164 break;
2165 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002166 case OMPRTL__tgt_target_data_end: {
George Rokos63bc9d62017-11-21 18:25:12 +00002167 // Build void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
2168 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2169 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002170 CGM.Int32Ty,
2171 CGM.VoidPtrPtrTy,
2172 CGM.VoidPtrPtrTy,
2173 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002174 CGM.Int64Ty->getPointerTo()};
Samuel Antaodf158d52016-04-27 22:58:19 +00002175 llvm::FunctionType *FnTy =
2176 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2177 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2178 break;
2179 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002180 case OMPRTL__tgt_target_data_end_nowait: {
2181 // Build void __tgt_target_data_end_nowait(int64_t device_id, int32_t
2182 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2183 // *arg_types);
2184 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2185 CGM.Int32Ty,
2186 CGM.VoidPtrPtrTy,
2187 CGM.VoidPtrPtrTy,
2188 CGM.SizeTy->getPointerTo(),
2189 CGM.Int64Ty->getPointerTo()};
2190 auto *FnTy =
2191 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2192 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end_nowait");
2193 break;
2194 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002195 case OMPRTL__tgt_target_data_update: {
George Rokos63bc9d62017-11-21 18:25:12 +00002196 // Build void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
2197 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2198 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antao8d2d7302016-05-26 18:30:22 +00002199 CGM.Int32Ty,
2200 CGM.VoidPtrPtrTy,
2201 CGM.VoidPtrPtrTy,
2202 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002203 CGM.Int64Ty->getPointerTo()};
Samuel Antao8d2d7302016-05-26 18:30:22 +00002204 llvm::FunctionType *FnTy =
2205 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2206 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2207 break;
2208 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002209 case OMPRTL__tgt_target_data_update_nowait: {
2210 // Build void __tgt_target_data_update_nowait(int64_t device_id, int32_t
2211 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2212 // *arg_types);
2213 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2214 CGM.Int32Ty,
2215 CGM.VoidPtrPtrTy,
2216 CGM.VoidPtrPtrTy,
2217 CGM.SizeTy->getPointerTo(),
2218 CGM.Int64Ty->getPointerTo()};
2219 auto *FnTy =
2220 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2221 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update_nowait");
2222 break;
2223 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002224 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002225 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002226 return RTLFn;
2227}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002228
Alexander Musman21212e42015-03-13 10:38:23 +00002229llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2230 bool IVSigned) {
2231 assert((IVSize == 32 || IVSize == 64) &&
2232 "IV size is not compatible with the omp runtime");
2233 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2234 : "__kmpc_for_static_init_4u")
2235 : (IVSigned ? "__kmpc_for_static_init_8"
2236 : "__kmpc_for_static_init_8u");
2237 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2238 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2239 llvm::Type *TypeParams[] = {
2240 getIdentTyPointerTy(), // loc
2241 CGM.Int32Ty, // tid
2242 CGM.Int32Ty, // schedtype
2243 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2244 PtrTy, // p_lower
2245 PtrTy, // p_upper
2246 PtrTy, // p_stride
2247 ITy, // incr
2248 ITy // chunk
2249 };
2250 llvm::FunctionType *FnTy =
2251 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2252 return CGM.CreateRuntimeFunction(FnTy, Name);
2253}
2254
Alexander Musman92bdaab2015-03-12 13:37:50 +00002255llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2256 bool IVSigned) {
2257 assert((IVSize == 32 || IVSize == 64) &&
2258 "IV size is not compatible with the omp runtime");
2259 auto Name =
2260 IVSize == 32
2261 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2262 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
2263 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2264 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2265 CGM.Int32Ty, // tid
2266 CGM.Int32Ty, // schedtype
2267 ITy, // lower
2268 ITy, // upper
2269 ITy, // stride
2270 ITy // chunk
2271 };
2272 llvm::FunctionType *FnTy =
2273 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2274 return CGM.CreateRuntimeFunction(FnTy, Name);
2275}
2276
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002277llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2278 bool IVSigned) {
2279 assert((IVSize == 32 || IVSize == 64) &&
2280 "IV size is not compatible with the omp runtime");
2281 auto Name =
2282 IVSize == 32
2283 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2284 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2285 llvm::Type *TypeParams[] = {
2286 getIdentTyPointerTy(), // loc
2287 CGM.Int32Ty, // tid
2288 };
2289 llvm::FunctionType *FnTy =
2290 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2291 return CGM.CreateRuntimeFunction(FnTy, Name);
2292}
2293
Alexander Musman92bdaab2015-03-12 13:37:50 +00002294llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2295 bool IVSigned) {
2296 assert((IVSize == 32 || IVSize == 64) &&
2297 "IV size is not compatible with the omp runtime");
2298 auto Name =
2299 IVSize == 32
2300 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2301 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
2302 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2303 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2304 llvm::Type *TypeParams[] = {
2305 getIdentTyPointerTy(), // loc
2306 CGM.Int32Ty, // tid
2307 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2308 PtrTy, // p_lower
2309 PtrTy, // p_upper
2310 PtrTy // p_stride
2311 };
2312 llvm::FunctionType *FnTy =
2313 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2314 return CGM.CreateRuntimeFunction(FnTy, Name);
2315}
2316
Alexey Bataev97720002014-11-11 04:05:39 +00002317llvm::Constant *
2318CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002319 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2320 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002321 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002322 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002323 Twine(CGM.getMangledName(VD)) + ".cache.");
2324}
2325
John McCall7f416cc2015-09-08 08:05:57 +00002326Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2327 const VarDecl *VD,
2328 Address VDAddr,
2329 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002330 if (CGM.getLangOpts().OpenMPUseTLS &&
2331 CGM.getContext().getTargetInfo().isTLSSupported())
2332 return VDAddr;
2333
John McCall7f416cc2015-09-08 08:05:57 +00002334 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002335 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002336 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2337 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002338 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2339 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002340 return Address(CGF.EmitRuntimeCall(
2341 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2342 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002343}
2344
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002345void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002346 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002347 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2348 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2349 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002350 auto OMPLoc = emitUpdateLocation(CGF, Loc);
2351 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002352 OMPLoc);
2353 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2354 // to register constructor/destructor for variable.
2355 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00002356 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2357 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002358 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002359 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002360 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002361}
2362
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002363llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002364 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002365 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002366 if (CGM.getLangOpts().OpenMPUseTLS &&
2367 CGM.getContext().getTargetInfo().isTLSSupported())
2368 return nullptr;
2369
Alexey Bataev97720002014-11-11 04:05:39 +00002370 VD = VD->getDefinition(CGM.getContext());
2371 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
2372 ThreadPrivateWithDefinition.insert(VD);
2373 QualType ASTTy = VD->getType();
2374
2375 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
2376 auto Init = VD->getAnyInitializer();
2377 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2378 // Generate function that re-emits the declaration's initializer into the
2379 // threadprivate copy of the variable VD
2380 CodeGenFunction CtorCGF(CGM);
2381 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002382 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
2383 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002384 Args.push_back(&Dst);
2385
John McCallc56a8b32016-03-11 04:30:31 +00002386 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2387 CGM.getContext().VoidPtrTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002388 auto FTy = CGM.getTypes().GetFunctionType(FI);
2389 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002390 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002391 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
2392 Args, SourceLocation());
2393 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002394 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002395 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002396 Address Arg = Address(ArgVal, VDAddr.getAlignment());
2397 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
2398 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002399 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2400 /*IsInitializer=*/true);
2401 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002402 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002403 CGM.getContext().VoidPtrTy, Dst.getLocation());
2404 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2405 CtorCGF.FinishFunction();
2406 Ctor = Fn;
2407 }
2408 if (VD->getType().isDestructedType() != QualType::DK_none) {
2409 // Generate function that emits destructor call for the threadprivate copy
2410 // of the variable VD
2411 CodeGenFunction DtorCGF(CGM);
2412 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002413 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
2414 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002415 Args.push_back(&Dst);
2416
John McCallc56a8b32016-03-11 04:30:31 +00002417 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2418 CGM.getContext().VoidTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002419 auto FTy = CGM.getTypes().GetFunctionType(FI);
2420 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002421 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002422 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002423 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
2424 SourceLocation());
Adrian Prantl1858c662016-04-24 22:22:29 +00002425 // Create a scope with an artificial location for the body of this function.
2426 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002427 auto ArgVal = DtorCGF.EmitLoadOfScalar(
2428 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002429 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2430 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002431 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2432 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2433 DtorCGF.FinishFunction();
2434 Dtor = Fn;
2435 }
2436 // Do not emit init function if it is not required.
2437 if (!Ctor && !Dtor)
2438 return nullptr;
2439
2440 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
2441 auto CopyCtorTy =
2442 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2443 /*isVarArg=*/false)->getPointerTo();
2444 // Copying constructor for the threadprivate variable.
2445 // Must be NULL - reserved by runtime, but currently it requires that this
2446 // parameter is always NULL. Otherwise it fires assertion.
2447 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2448 if (Ctor == nullptr) {
2449 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2450 /*isVarArg=*/false)->getPointerTo();
2451 Ctor = llvm::Constant::getNullValue(CtorTy);
2452 }
2453 if (Dtor == nullptr) {
2454 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2455 /*isVarArg=*/false)->getPointerTo();
2456 Dtor = llvm::Constant::getNullValue(DtorTy);
2457 }
2458 if (!CGF) {
2459 auto InitFunctionTy =
2460 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
2461 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002462 InitFunctionTy, ".__omp_threadprivate_init_.",
2463 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002464 CodeGenFunction InitCGF(CGM);
2465 FunctionArgList ArgList;
2466 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2467 CGM.getTypes().arrangeNullaryFunction(), ArgList,
2468 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002469 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002470 InitCGF.FinishFunction();
2471 return InitFunction;
2472 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002473 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002474 }
2475 return nullptr;
2476}
2477
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002478Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2479 QualType VarType,
2480 StringRef Name) {
2481 llvm::Twine VarName(Name, ".artificial.");
2482 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
2483 llvm::Value *GAddr = getOrCreateInternalVariable(VarLVType, VarName);
2484 llvm::Value *Args[] = {
2485 emitUpdateLocation(CGF, SourceLocation()),
2486 getThreadID(CGF, SourceLocation()),
2487 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2488 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2489 /*IsSigned=*/false),
2490 getOrCreateInternalVariable(CGM.VoidPtrPtrTy, VarName + ".cache.")};
2491 return Address(
2492 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2493 CGF.EmitRuntimeCall(
2494 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2495 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2496 CGM.getPointerAlign());
2497}
2498
Alexey Bataev1d677132015-04-22 13:57:31 +00002499/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
2500/// function. Here is the logic:
2501/// if (Cond) {
2502/// ThenGen();
2503/// } else {
2504/// ElseGen();
2505/// }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002506void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2507 const RegionCodeGenTy &ThenGen,
2508 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002509 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2510
2511 // If the condition constant folds and can be elided, try to avoid emitting
2512 // the condition and the dead arm of the if/else.
2513 bool CondConstant;
2514 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002515 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002516 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002517 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002518 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002519 return;
2520 }
2521
2522 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2523 // emit the conditional branch.
2524 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
2525 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
2526 auto ContBlock = CGF.createBasicBlock("omp_if.end");
2527 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2528
2529 // Emit the 'then' code.
2530 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002531 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002532 CGF.EmitBranch(ContBlock);
2533 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002534 // There is no need to emit line number for unconditional branch.
2535 (void)ApplyDebugLocation::CreateEmpty(CGF);
2536 CGF.EmitBlock(ElseBlock);
2537 ElseGen(CGF);
2538 // There is no need to emit line number for unconditional branch.
2539 (void)ApplyDebugLocation::CreateEmpty(CGF);
2540 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002541 // Emit the continuation block for code after the if.
2542 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002543}
2544
Alexey Bataev1d677132015-04-22 13:57:31 +00002545void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2546 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002547 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002548 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002549 if (!CGF.HaveInsertPoint())
2550 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00002551 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002552 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2553 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002554 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002555 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002556 llvm::Value *Args[] = {
2557 RTLoc,
2558 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002559 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002560 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2561 RealArgs.append(std::begin(Args), std::end(Args));
2562 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2563
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002564 auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002565 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2566 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002567 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2568 PrePostActionTy &) {
2569 auto &RT = CGF.CGM.getOpenMPRuntime();
2570 auto ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00002571 // Build calls:
2572 // __kmpc_serialized_parallel(&Loc, GTid);
2573 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002574 CGF.EmitRuntimeCall(
2575 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002576
Alexey Bataev1d677132015-04-22 13:57:31 +00002577 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002578 auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00002579 Address ZeroAddr =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002580 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
2581 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00002582 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00002583 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2584 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2585 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2586 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002587 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002588
Alexey Bataev1d677132015-04-22 13:57:31 +00002589 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002590 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00002591 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002592 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2593 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002594 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002595 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00002596 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002597 else {
2598 RegionCodeGenTy ThenRCG(ThenGen);
2599 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002600 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002601}
2602
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002603// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002604// thread-ID variable (it is passed in a first argument of the outlined function
2605// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2606// regular serial code region, get thread ID by calling kmp_int32
2607// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2608// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002609Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2610 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002611 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002612 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002613 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002614 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002615
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002616 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002617 auto Int32Ty =
2618 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2619 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2620 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002621 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002622
2623 return ThreadIDTemp;
2624}
2625
Alexey Bataev97720002014-11-11 04:05:39 +00002626llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002627CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002628 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002629 SmallString<256> Buffer;
2630 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002631 Out << Name;
2632 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00002633 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
2634 if (Elem.second) {
2635 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002636 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002637 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002638 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002639
David Blaikie13156b62014-11-19 03:06:06 +00002640 return Elem.second = new llvm::GlobalVariable(
2641 CGM.getModule(), Ty, /*IsConstant*/ false,
2642 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2643 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002644}
2645
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002646llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00002647 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002648 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002649}
2650
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002651namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002652/// Common pre(post)-action for different OpenMP constructs.
2653class CommonActionTy final : public PrePostActionTy {
2654 llvm::Value *EnterCallee;
2655 ArrayRef<llvm::Value *> EnterArgs;
2656 llvm::Value *ExitCallee;
2657 ArrayRef<llvm::Value *> ExitArgs;
2658 bool Conditional;
2659 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002660
2661public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002662 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2663 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2664 bool Conditional = false)
2665 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2666 ExitArgs(ExitArgs), Conditional(Conditional) {}
2667 void Enter(CodeGenFunction &CGF) override {
2668 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2669 if (Conditional) {
2670 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2671 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2672 ContBlock = CGF.createBasicBlock("omp_if.end");
2673 // Generate the branch (If-stmt)
2674 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2675 CGF.EmitBlock(ThenBlock);
2676 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002677 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002678 void Done(CodeGenFunction &CGF) {
2679 // Emit the rest of blocks/branches
2680 CGF.EmitBranch(ContBlock);
2681 CGF.EmitBlock(ContBlock, true);
2682 }
2683 void Exit(CodeGenFunction &CGF) override {
2684 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002685 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002686};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002687} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002688
2689void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2690 StringRef CriticalName,
2691 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002692 SourceLocation Loc, const Expr *Hint) {
2693 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002694 // CriticalOpGen();
2695 // __kmpc_end_critical(ident_t *, gtid, Lock);
2696 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002697 if (!CGF.HaveInsertPoint())
2698 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002699 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2700 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002701 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2702 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002703 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002704 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2705 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2706 }
2707 CommonActionTy Action(
2708 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2709 : OMPRTL__kmpc_critical),
2710 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2711 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002712 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002713}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002714
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002715void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002716 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002717 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002718 if (!CGF.HaveInsertPoint())
2719 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002720 // if(__kmpc_master(ident_t *, gtid)) {
2721 // MasterOpGen();
2722 // __kmpc_end_master(ident_t *, gtid);
2723 // }
2724 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002725 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002726 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2727 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2728 /*Conditional=*/true);
2729 MasterOpGen.setAction(Action);
2730 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2731 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002732}
2733
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002734void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2735 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002736 if (!CGF.HaveInsertPoint())
2737 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00002738 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2739 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002740 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00002741 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002742 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002743 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2744 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00002745}
2746
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002747void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2748 const RegionCodeGenTy &TaskgroupOpGen,
2749 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002750 if (!CGF.HaveInsertPoint())
2751 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002752 // __kmpc_taskgroup(ident_t *, gtid);
2753 // TaskgroupOpGen();
2754 // __kmpc_end_taskgroup(ident_t *, gtid);
2755 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002756 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2757 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2758 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2759 Args);
2760 TaskgroupOpGen.setAction(Action);
2761 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002762}
2763
John McCall7f416cc2015-09-08 08:05:57 +00002764/// Given an array of pointers to variables, project the address of a
2765/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002766static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2767 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00002768 // Pull out the pointer to the variable.
2769 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002770 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00002771 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2772
2773 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002774 Addr = CGF.Builder.CreateElementBitCast(
2775 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002776 return Addr;
2777}
2778
Alexey Bataeva63048e2015-03-23 06:18:07 +00002779static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00002780 CodeGenModule &CGM, llvm::Type *ArgsType,
2781 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
2782 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002783 auto &C = CGM.getContext();
2784 // void copy_func(void *LHSArg, void *RHSArg);
2785 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002786 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
2787 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002788 Args.push_back(&LHSArg);
2789 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00002790 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002791 auto *Fn = llvm::Function::Create(
2792 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2793 ".omp.copyprivate.copy_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002794 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002795 CodeGenFunction CGF(CGM);
2796 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00002797 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002798 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00002799 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2800 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2801 ArgsType), CGF.getPointerAlign());
2802 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2803 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2804 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002805 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2806 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2807 // ...
2808 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00002809 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002810 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2811 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2812
2813 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2814 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2815
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002816 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2817 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00002818 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002819 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002820 CGF.FinishFunction();
2821 return Fn;
2822}
2823
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002824void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002825 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00002826 SourceLocation Loc,
2827 ArrayRef<const Expr *> CopyprivateVars,
2828 ArrayRef<const Expr *> SrcExprs,
2829 ArrayRef<const Expr *> DstExprs,
2830 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002831 if (!CGF.HaveInsertPoint())
2832 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002833 assert(CopyprivateVars.size() == SrcExprs.size() &&
2834 CopyprivateVars.size() == DstExprs.size() &&
2835 CopyprivateVars.size() == AssignmentOps.size());
2836 auto &C = CGM.getContext();
2837 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002838 // if(__kmpc_single(ident_t *, gtid)) {
2839 // SingleOpGen();
2840 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002841 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002842 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002843 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2844 // <copy_func>, did_it);
2845
John McCall7f416cc2015-09-08 08:05:57 +00002846 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00002847 if (!CopyprivateVars.empty()) {
2848 // int32 did_it = 0;
2849 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2850 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00002851 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002852 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002853 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002854 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002855 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
2856 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
2857 /*Conditional=*/true);
2858 SingleOpGen.setAction(Action);
2859 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2860 if (DidIt.isValid()) {
2861 // did_it = 1;
2862 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2863 }
2864 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002865 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2866 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00002867 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002868 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2869 auto CopyprivateArrayTy =
2870 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2871 /*IndexTypeQuals=*/0);
2872 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00002873 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00002874 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2875 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002876 Address Elem = CGF.Builder.CreateConstArrayGEP(
2877 CopyprivateList, I, CGF.getPointerSize());
2878 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00002879 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002880 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2881 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002882 }
2883 // Build function that copies private values from single region to all other
2884 // threads in the corresponding parallel region.
2885 auto *CpyFn = emitCopyprivateCopyFunction(
2886 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00002887 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev1189bd02016-01-26 12:20:39 +00002888 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00002889 Address CL =
2890 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2891 CGF.VoidPtrTy);
2892 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002893 llvm::Value *Args[] = {
2894 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2895 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00002896 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00002897 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00002898 CpyFn, // void (*) (void *, void *) <copy_func>
2899 DidItVal // i32 did_it
2900 };
2901 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2902 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002903}
2904
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002905void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2906 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00002907 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002908 if (!CGF.HaveInsertPoint())
2909 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002910 // __kmpc_ordered(ident_t *, gtid);
2911 // OrderedOpGen();
2912 // __kmpc_end_ordered(ident_t *, gtid);
2913 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00002914 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002915 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002916 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
2917 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2918 Args);
2919 OrderedOpGen.setAction(Action);
2920 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2921 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002922 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002923 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002924}
2925
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002926void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002927 OpenMPDirectiveKind Kind, bool EmitChecks,
2928 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002929 if (!CGF.HaveInsertPoint())
2930 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002931 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002932 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002933 unsigned Flags;
2934 if (Kind == OMPD_for)
2935 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2936 else if (Kind == OMPD_sections)
2937 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2938 else if (Kind == OMPD_single)
2939 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2940 else if (Kind == OMPD_barrier)
2941 Flags = OMP_IDENT_BARRIER_EXPL;
2942 else
2943 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002944 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2945 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002946 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2947 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002948 if (auto *OMPRegionInfo =
2949 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00002950 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002951 auto *Result = CGF.EmitRuntimeCall(
2952 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002953 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002954 // if (__kmpc_cancel_barrier()) {
2955 // exit from construct;
2956 // }
2957 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2958 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2959 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2960 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2961 CGF.EmitBlock(ExitBB);
2962 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002963 auto CancelDestination =
2964 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002965 CGF.EmitBranchThroughCleanup(CancelDestination);
2966 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2967 }
2968 return;
2969 }
2970 }
2971 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002972}
2973
Alexander Musmanc6388682014-12-15 07:07:06 +00002974/// \brief Map the OpenMP loop schedule to the runtime enumeration.
2975static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002976 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002977 switch (ScheduleKind) {
2978 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002979 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2980 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00002981 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002982 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002983 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002984 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002985 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002986 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2987 case OMPC_SCHEDULE_auto:
2988 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00002989 case OMPC_SCHEDULE_unknown:
2990 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002991 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00002992 }
2993 llvm_unreachable("Unexpected runtime schedule");
2994}
2995
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002996/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
2997static OpenMPSchedType
2998getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2999 // only static is allowed for dist_schedule
3000 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
3001}
3002
Alexander Musmanc6388682014-12-15 07:07:06 +00003003bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
3004 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003005 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00003006 return Schedule == OMP_sch_static;
3007}
3008
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003009bool CGOpenMPRuntime::isStaticNonchunked(
3010 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
3011 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
3012 return Schedule == OMP_dist_sch_static;
3013}
3014
3015
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003016bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003017 auto Schedule =
3018 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003019 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
3020 return Schedule != OMP_sch_static;
3021}
3022
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003023static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
3024 OpenMPScheduleClauseModifier M1,
3025 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00003026 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003027 switch (M1) {
3028 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003029 Modifier = OMP_sch_modifier_monotonic;
3030 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003031 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003032 Modifier = OMP_sch_modifier_nonmonotonic;
3033 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003034 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003035 if (Schedule == OMP_sch_static_chunked)
3036 Schedule = OMP_sch_static_balanced_chunked;
3037 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003038 case OMPC_SCHEDULE_MODIFIER_last:
3039 case OMPC_SCHEDULE_MODIFIER_unknown:
3040 break;
3041 }
3042 switch (M2) {
3043 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003044 Modifier = OMP_sch_modifier_monotonic;
3045 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003046 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003047 Modifier = OMP_sch_modifier_nonmonotonic;
3048 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003049 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003050 if (Schedule == OMP_sch_static_chunked)
3051 Schedule = OMP_sch_static_balanced_chunked;
3052 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003053 case OMPC_SCHEDULE_MODIFIER_last:
3054 case OMPC_SCHEDULE_MODIFIER_unknown:
3055 break;
3056 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00003057 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003058}
3059
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003060void CGOpenMPRuntime::emitForDispatchInit(
3061 CodeGenFunction &CGF, SourceLocation Loc,
3062 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
3063 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003064 if (!CGF.HaveInsertPoint())
3065 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003066 OpenMPSchedType Schedule = getRuntimeSchedule(
3067 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00003068 assert(Ordered ||
3069 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00003070 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
3071 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00003072 // Call __kmpc_dispatch_init(
3073 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
3074 // kmp_int[32|64] lower, kmp_int[32|64] upper,
3075 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00003076
John McCall7f416cc2015-09-08 08:05:57 +00003077 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003078 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
3079 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00003080 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003081 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3082 CGF.Builder.getInt32(addMonoNonMonoModifier(
3083 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003084 DispatchValues.LB, // Lower
3085 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003086 CGF.Builder.getIntN(IVSize, 1), // Stride
3087 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00003088 };
3089 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
3090}
3091
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003092static void emitForStaticInitCall(
3093 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
3094 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
3095 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003096 const CGOpenMPRuntime::StaticRTInput &Values) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003097 if (!CGF.HaveInsertPoint())
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003098 return;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003099
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003100 assert(!Values.Ordered);
3101 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
3102 Schedule == OMP_sch_static_balanced_chunked ||
3103 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
3104 Schedule == OMP_dist_sch_static ||
3105 Schedule == OMP_dist_sch_static_chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003106
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003107 // Call __kmpc_for_static_init(
3108 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
3109 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
3110 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
3111 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
3112 llvm::Value *Chunk = Values.Chunk;
3113 if (Chunk == nullptr) {
3114 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
3115 Schedule == OMP_dist_sch_static) &&
3116 "expected static non-chunked schedule");
3117 // If the Chunk was not specified in the clause - use default value 1.
3118 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3119 } else {
3120 assert((Schedule == OMP_sch_static_chunked ||
3121 Schedule == OMP_sch_static_balanced_chunked ||
3122 Schedule == OMP_ord_static_chunked ||
3123 Schedule == OMP_dist_sch_static_chunked) &&
3124 "expected static chunked schedule");
3125 }
3126 llvm::Value *Args[] = {
3127 UpdateLocation,
3128 ThreadId,
3129 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3130 M2)), // Schedule type
3131 Values.IL.getPointer(), // &isLastIter
3132 Values.LB.getPointer(), // &LB
3133 Values.UB.getPointer(), // &UB
3134 Values.ST.getPointer(), // &Stride
3135 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3136 Chunk // Chunk
3137 };
3138 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003139}
3140
John McCall7f416cc2015-09-08 08:05:57 +00003141void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3142 SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003143 OpenMPDirectiveKind DKind,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003144 const OpenMPScheduleTy &ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003145 const StaticRTInput &Values) {
3146 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3147 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3148 assert(isOpenMPWorksharingDirective(DKind) &&
3149 "Expected loop-based or sections-based directive.");
3150 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc,
3151 isOpenMPLoopDirective(DKind)
3152 ? OMP_IDENT_WORK_LOOP
3153 : OMP_IDENT_WORK_SECTIONS);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003154 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003155 auto *StaticInitFunction =
3156 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003157 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003158 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003159}
John McCall7f416cc2015-09-08 08:05:57 +00003160
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003161void CGOpenMPRuntime::emitDistributeStaticInit(
3162 CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003163 OpenMPDistScheduleClauseKind SchedKind,
3164 const CGOpenMPRuntime::StaticRTInput &Values) {
3165 OpenMPSchedType ScheduleNum =
3166 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
3167 auto *UpdatedLocation =
3168 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003169 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003170 auto *StaticInitFunction =
3171 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003172 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3173 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003174 OMPC_SCHEDULE_MODIFIER_unknown, Values);
Alexander Musmanc6388682014-12-15 07:07:06 +00003175}
3176
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003177void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
Alexey Bataevf43f7142017-09-06 16:17:35 +00003178 SourceLocation Loc,
3179 OpenMPDirectiveKind DKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003180 if (!CGF.HaveInsertPoint())
3181 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003182 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataevf43f7142017-09-06 16:17:35 +00003183 llvm::Value *Args[] = {
3184 emitUpdateLocation(CGF, Loc,
3185 isOpenMPDistributeDirective(DKind)
3186 ? OMP_IDENT_WORK_DISTRIBUTE
3187 : isOpenMPLoopDirective(DKind)
3188 ? OMP_IDENT_WORK_LOOP
3189 : OMP_IDENT_WORK_SECTIONS),
3190 getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003191 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3192 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003193}
3194
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003195void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3196 SourceLocation Loc,
3197 unsigned IVSize,
3198 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003199 if (!CGF.HaveInsertPoint())
3200 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003201 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003202 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003203 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3204}
3205
Alexander Musman92bdaab2015-03-12 13:37:50 +00003206llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3207 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003208 bool IVSigned, Address IL,
3209 Address LB, Address UB,
3210 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003211 // Call __kmpc_dispatch_next(
3212 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3213 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3214 // kmp_int[32|64] *p_stride);
3215 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003216 emitUpdateLocation(CGF, Loc),
3217 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003218 IL.getPointer(), // &isLastIter
3219 LB.getPointer(), // &Lower
3220 UB.getPointer(), // &Upper
3221 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003222 };
3223 llvm::Value *Call =
3224 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3225 return CGF.EmitScalarConversion(
3226 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003227 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003228}
3229
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003230void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3231 llvm::Value *NumThreads,
3232 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003233 if (!CGF.HaveInsertPoint())
3234 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003235 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3236 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003237 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003238 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003239 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3240 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003241}
3242
Alexey Bataev7f210c62015-06-18 13:40:03 +00003243void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3244 OpenMPProcBindClauseKind ProcBind,
3245 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003246 if (!CGF.HaveInsertPoint())
3247 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003248 // Constants for proc bind value accepted by the runtime.
3249 enum ProcBindTy {
3250 ProcBindFalse = 0,
3251 ProcBindTrue,
3252 ProcBindMaster,
3253 ProcBindClose,
3254 ProcBindSpread,
3255 ProcBindIntel,
3256 ProcBindDefault
3257 } RuntimeProcBind;
3258 switch (ProcBind) {
3259 case OMPC_PROC_BIND_master:
3260 RuntimeProcBind = ProcBindMaster;
3261 break;
3262 case OMPC_PROC_BIND_close:
3263 RuntimeProcBind = ProcBindClose;
3264 break;
3265 case OMPC_PROC_BIND_spread:
3266 RuntimeProcBind = ProcBindSpread;
3267 break;
3268 case OMPC_PROC_BIND_unknown:
3269 llvm_unreachable("Unsupported proc_bind value.");
3270 }
3271 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3272 llvm::Value *Args[] = {
3273 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3274 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3275 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3276}
3277
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003278void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3279 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003280 if (!CGF.HaveInsertPoint())
3281 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003282 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003283 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3284 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003285}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003286
Alexey Bataev62b63b12015-03-10 07:28:44 +00003287namespace {
3288/// \brief Indexes of fields for type kmp_task_t.
3289enum KmpTaskTFields {
3290 /// \brief List of shared variables.
3291 KmpTaskTShareds,
3292 /// \brief Task routine.
3293 KmpTaskTRoutine,
3294 /// \brief Partition id for the untied tasks.
3295 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003296 /// Function with call of destructors for private variables.
3297 Data1,
3298 /// Task priority.
3299 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003300 /// (Taskloops only) Lower bound.
3301 KmpTaskTLowerBound,
3302 /// (Taskloops only) Upper bound.
3303 KmpTaskTUpperBound,
3304 /// (Taskloops only) Stride.
3305 KmpTaskTStride,
3306 /// (Taskloops only) Is last iteration flag.
3307 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003308 /// (Taskloops only) Reduction data.
3309 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003310};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003311} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003312
Samuel Antaoee8fb302016-01-06 13:42:12 +00003313bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
3314 // FIXME: Add other entries type when they become supported.
3315 return OffloadEntriesTargetRegion.empty();
3316}
3317
3318/// \brief Initialize target region entry.
3319void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3320 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3321 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003322 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003323 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3324 "only required for the device "
3325 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003326 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003327 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
3328 /*Flags=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003329 ++OffloadingEntriesNum;
3330}
3331
3332void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3333 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3334 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003335 llvm::Constant *Addr, llvm::Constant *ID,
3336 int32_t Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003337 // If we are emitting code for a target, the entry is already initialized,
3338 // only has to be registered.
3339 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003340 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00003341 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003342 auto &Entry =
3343 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003344 assert(Entry.isValid() && "Entry not initialized!");
3345 Entry.setAddress(Addr);
3346 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003347 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003348 return;
3349 } else {
Samuel Antaof83efdb2017-01-05 16:02:49 +00003350 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003351 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003352 }
3353}
3354
3355bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003356 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3357 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003358 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3359 if (PerDevice == OffloadEntriesTargetRegion.end())
3360 return false;
3361 auto PerFile = PerDevice->second.find(FileID);
3362 if (PerFile == PerDevice->second.end())
3363 return false;
3364 auto PerParentName = PerFile->second.find(ParentName);
3365 if (PerParentName == PerFile->second.end())
3366 return false;
3367 auto PerLine = PerParentName->second.find(LineNum);
3368 if (PerLine == PerParentName->second.end())
3369 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003370 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003371 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003372 return false;
3373 return true;
3374}
3375
3376void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3377 const OffloadTargetRegionEntryInfoActTy &Action) {
3378 // Scan all target region entries and perform the provided action.
3379 for (auto &D : OffloadEntriesTargetRegion)
3380 for (auto &F : D.second)
3381 for (auto &P : F.second)
3382 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003383 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003384}
3385
3386/// \brief Create a Ctor/Dtor-like function whose body is emitted through
3387/// \a Codegen. This is used to emit the two functions that register and
3388/// unregister the descriptor of the current compilation unit.
3389static llvm::Function *
3390createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
3391 const RegionCodeGenTy &Codegen) {
3392 auto &C = CGM.getContext();
3393 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003394 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003395 Args.push_back(&DummyPtr);
3396
3397 CodeGenFunction CGF(CGM);
John McCallc56a8b32016-03-11 04:30:31 +00003398 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003399 auto FTy = CGM.getTypes().GetFunctionType(FI);
3400 auto *Fn =
3401 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
3402 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
3403 Codegen(CGF);
3404 CGF.FinishFunction();
3405 return Fn;
3406}
3407
3408llvm::Function *
3409CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
3410
3411 // If we don't have entries or if we are emitting code for the device, we
3412 // don't need to do anything.
3413 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3414 return nullptr;
3415
3416 auto &M = CGM.getModule();
3417 auto &C = CGM.getContext();
3418
3419 // Get list of devices we care about
3420 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
3421
3422 // We should be creating an offloading descriptor only if there are devices
3423 // specified.
3424 assert(!Devices.empty() && "No OpenMP offloading devices??");
3425
3426 // Create the external variables that will point to the begin and end of the
3427 // host entries section. These will be defined by the linker.
3428 auto *OffloadEntryTy =
3429 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
3430 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
3431 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003432 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003433 ".omp_offloading.entries_begin");
3434 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
3435 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003436 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003437 ".omp_offloading.entries_end");
3438
3439 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003440 auto *DeviceImageTy = cast<llvm::StructType>(
3441 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003442 ConstantInitBuilder DeviceImagesBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003443 auto DeviceImagesEntries = DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003444
3445 for (unsigned i = 0; i < Devices.size(); ++i) {
3446 StringRef T = Devices[i].getTriple();
3447 auto *ImgBegin = new llvm::GlobalVariable(
3448 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003449 /*Initializer=*/nullptr,
3450 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003451 auto *ImgEnd = new llvm::GlobalVariable(
3452 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003453 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003454
John McCall6c9f1fdb2016-11-19 08:17:24 +00003455 auto Dev = DeviceImagesEntries.beginStruct(DeviceImageTy);
3456 Dev.add(ImgBegin);
3457 Dev.add(ImgEnd);
3458 Dev.add(HostEntriesBegin);
3459 Dev.add(HostEntriesEnd);
John McCallf1788632016-11-28 22:18:30 +00003460 Dev.finishAndAddTo(DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003461 }
3462
3463 // Create device images global array.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003464 llvm::GlobalVariable *DeviceImages =
3465 DeviceImagesEntries.finishAndCreateGlobal(".omp_offloading.device_images",
3466 CGM.getPointerAlign(),
3467 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003468 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003469
3470 // This is a Zero array to be used in the creation of the constant expressions
3471 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3472 llvm::Constant::getNullValue(CGM.Int32Ty)};
3473
3474 // Create the target region descriptor.
3475 auto *BinaryDescriptorTy = cast<llvm::StructType>(
3476 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003477 ConstantInitBuilder DescBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003478 auto DescInit = DescBuilder.beginStruct(BinaryDescriptorTy);
3479 DescInit.addInt(CGM.Int32Ty, Devices.size());
3480 DescInit.add(llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3481 DeviceImages,
3482 Index));
3483 DescInit.add(HostEntriesBegin);
3484 DescInit.add(HostEntriesEnd);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003485
John McCall6c9f1fdb2016-11-19 08:17:24 +00003486 auto *Desc = DescInit.finishAndCreateGlobal(".omp_offloading.descriptor",
3487 CGM.getPointerAlign(),
3488 /*isConstant=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003489
3490 // Emit code to register or unregister the descriptor at execution
3491 // startup or closing, respectively.
3492
3493 // Create a variable to drive the registration and unregistration of the
3494 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3495 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
3496 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00003497 IdentInfo, C.CharTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003498
3499 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003500 CGM, ".omp_offloading.descriptor_unreg",
3501 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00003502 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3503 Desc);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003504 });
3505 auto *RegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003506 CGM, ".omp_offloading.descriptor_reg",
3507 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00003508 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib),
3509 Desc);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003510 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3511 });
George Rokos29d0f002017-05-27 03:03:13 +00003512 if (CGM.supportsCOMDAT()) {
3513 // It is sufficient to call registration function only once, so create a
3514 // COMDAT group for registration/unregistration functions and associated
3515 // data. That would reduce startup time and code size. Registration
3516 // function serves as a COMDAT group key.
3517 auto ComdatKey = M.getOrInsertComdat(RegFn->getName());
3518 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3519 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3520 RegFn->setComdat(ComdatKey);
3521 UnRegFn->setComdat(ComdatKey);
3522 DeviceImages->setComdat(ComdatKey);
3523 Desc->setComdat(ComdatKey);
3524 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003525 return RegFn;
3526}
3527
Samuel Antao2de62b02016-02-13 23:35:10 +00003528void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003529 llvm::Constant *Addr, uint64_t Size,
3530 int32_t Flags) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003531 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003532 auto *TgtOffloadEntryType = cast<llvm::StructType>(
3533 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
3534 llvm::LLVMContext &C = CGM.getModule().getContext();
3535 llvm::Module &M = CGM.getModule();
3536
3537 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00003538 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003539
3540 // Create constant string with the name.
3541 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3542
3543 llvm::GlobalVariable *Str =
3544 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
3545 llvm::GlobalValue::InternalLinkage, StrPtrInit,
3546 ".omp_offloading.entry_name");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003547 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003548 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
3549
John McCall6c9f1fdb2016-11-19 08:17:24 +00003550 // We can't have any padding between symbols, so we need to have 1-byte
3551 // alignment.
3552 auto Align = CharUnits::fromQuantity(1);
3553
Samuel Antaoee8fb302016-01-06 13:42:12 +00003554 // Create the entry struct.
John McCall23c9dc62016-11-28 22:18:27 +00003555 ConstantInitBuilder EntryBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003556 auto EntryInit = EntryBuilder.beginStruct(TgtOffloadEntryType);
3557 EntryInit.add(AddrPtr);
3558 EntryInit.add(StrPtr);
3559 EntryInit.addInt(CGM.SizeTy, Size);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003560 EntryInit.addInt(CGM.Int32Ty, Flags);
3561 EntryInit.addInt(CGM.Int32Ty, 0);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003562 llvm::GlobalVariable *Entry =
3563 EntryInit.finishAndCreateGlobal(".omp_offloading.entry",
3564 Align,
3565 /*constant*/ true,
3566 llvm::GlobalValue::ExternalLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003567
3568 // The entry has to be created in the section the linker expects it to be.
3569 Entry->setSection(".omp_offloading.entries");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003570}
3571
3572void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3573 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003574 // can easily figure out what to emit. The produced metadata looks like
3575 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003576 //
3577 // !omp_offload.info = !{!1, ...}
3578 //
3579 // Right now we only generate metadata for function that contain target
3580 // regions.
3581
3582 // If we do not have entries, we dont need to do anything.
3583 if (OffloadEntriesInfoManager.empty())
3584 return;
3585
3586 llvm::Module &M = CGM.getModule();
3587 llvm::LLVMContext &C = M.getContext();
3588 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
3589 OrderedEntries(OffloadEntriesInfoManager.size());
3590
3591 // Create the offloading info metadata node.
3592 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
3593
Simon Pilgrim2c518802017-03-30 14:13:19 +00003594 // Auxiliary methods to create metadata values and strings.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003595 auto getMDInt = [&](unsigned v) {
3596 return llvm::ConstantAsMetadata::get(
3597 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
3598 };
3599
3600 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
3601
3602 // Create function that emits metadata for each target region entry;
3603 auto &&TargetRegionMetadataEmitter = [&](
3604 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003605 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3606 llvm::SmallVector<llvm::Metadata *, 32> Ops;
3607 // Generate metadata for target regions. Each entry of this metadata
3608 // contains:
3609 // - Entry 0 -> Kind of this type of metadata (0).
3610 // - Entry 1 -> Device ID of the file where the entry was identified.
3611 // - Entry 2 -> File ID of the file where the entry was identified.
3612 // - Entry 3 -> Mangled name of the function where the entry was identified.
3613 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00003614 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003615 // The first element of the metadata node is the kind.
3616 Ops.push_back(getMDInt(E.getKind()));
3617 Ops.push_back(getMDInt(DeviceID));
3618 Ops.push_back(getMDInt(FileID));
3619 Ops.push_back(getMDString(ParentName));
3620 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003621 Ops.push_back(getMDInt(E.getOrder()));
3622
3623 // Save this entry in the right position of the ordered entries array.
3624 OrderedEntries[E.getOrder()] = &E;
3625
3626 // Add metadata to the named metadata node.
3627 MD->addOperand(llvm::MDNode::get(C, Ops));
3628 };
3629
3630 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3631 TargetRegionMetadataEmitter);
3632
3633 for (auto *E : OrderedEntries) {
3634 assert(E && "All ordered entries must exist!");
3635 if (auto *CE =
3636 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3637 E)) {
3638 assert(CE->getID() && CE->getAddress() &&
3639 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00003640 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003641 } else
3642 llvm_unreachable("Unsupported entry kind.");
3643 }
3644}
3645
3646/// \brief Loads all the offload entries information from the host IR
3647/// metadata.
3648void CGOpenMPRuntime::loadOffloadInfoMetadata() {
3649 // If we are in target mode, load the metadata from the host IR. This code has
3650 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
3651
3652 if (!CGM.getLangOpts().OpenMPIsDevice)
3653 return;
3654
3655 if (CGM.getLangOpts().OMPHostIRFile.empty())
3656 return;
3657
3658 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
3659 if (Buf.getError())
3660 return;
3661
3662 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00003663 auto ME = expectedToErrorOrAndEmitErrors(
3664 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003665
3666 if (ME.getError())
3667 return;
3668
3669 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
3670 if (!MD)
3671 return;
3672
3673 for (auto I : MD->operands()) {
3674 llvm::MDNode *MN = cast<llvm::MDNode>(I);
3675
3676 auto getMDInt = [&](unsigned Idx) {
3677 llvm::ConstantAsMetadata *V =
3678 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
3679 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
3680 };
3681
3682 auto getMDString = [&](unsigned Idx) {
3683 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
3684 return V->getString();
3685 };
3686
3687 switch (getMDInt(0)) {
3688 default:
3689 llvm_unreachable("Unexpected metadata!");
3690 break;
3691 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3692 OFFLOAD_ENTRY_INFO_TARGET_REGION:
3693 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
3694 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
3695 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00003696 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003697 break;
3698 }
3699 }
3700}
3701
Alexey Bataev62b63b12015-03-10 07:28:44 +00003702void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
3703 if (!KmpRoutineEntryPtrTy) {
3704 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
3705 auto &C = CGM.getContext();
3706 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
3707 FunctionProtoType::ExtProtoInfo EPI;
3708 KmpRoutineEntryPtrQTy = C.getPointerType(
3709 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
3710 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
3711 }
3712}
3713
Alexey Bataevc71a4092015-09-11 10:29:41 +00003714static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
3715 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003716 auto *Field = FieldDecl::Create(
3717 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
3718 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
3719 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
3720 Field->setAccess(AS_public);
3721 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003722 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003723}
3724
Samuel Antaoee8fb302016-01-06 13:42:12 +00003725QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
3726
3727 // Make sure the type of the entry is already created. This is the type we
3728 // have to create:
3729 // struct __tgt_offload_entry{
3730 // void *addr; // Pointer to the offload entry info.
3731 // // (function or global)
3732 // char *name; // Name of the function or global.
3733 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00003734 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
3735 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003736 // };
3737 if (TgtOffloadEntryQTy.isNull()) {
3738 ASTContext &C = CGM.getContext();
3739 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
3740 RD->startDefinition();
3741 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3742 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
3743 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00003744 addFieldToRecordDecl(
3745 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3746 addFieldToRecordDecl(
3747 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003748 RD->completeDefinition();
3749 TgtOffloadEntryQTy = C.getRecordType(RD);
3750 }
3751 return TgtOffloadEntryQTy;
3752}
3753
3754QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
3755 // These are the types we need to build:
3756 // struct __tgt_device_image{
3757 // void *ImageStart; // Pointer to the target code start.
3758 // void *ImageEnd; // Pointer to the target code end.
3759 // // We also add the host entries to the device image, as it may be useful
3760 // // for the target runtime to have access to that information.
3761 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
3762 // // the entries.
3763 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3764 // // entries (non inclusive).
3765 // };
3766 if (TgtDeviceImageQTy.isNull()) {
3767 ASTContext &C = CGM.getContext();
3768 auto *RD = C.buildImplicitRecord("__tgt_device_image");
3769 RD->startDefinition();
3770 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3771 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3772 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3773 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3774 RD->completeDefinition();
3775 TgtDeviceImageQTy = C.getRecordType(RD);
3776 }
3777 return TgtDeviceImageQTy;
3778}
3779
3780QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
3781 // struct __tgt_bin_desc{
3782 // int32_t NumDevices; // Number of devices supported.
3783 // __tgt_device_image *DeviceImages; // Arrays of device images
3784 // // (one per device).
3785 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
3786 // // entries.
3787 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3788 // // entries (non inclusive).
3789 // };
3790 if (TgtBinaryDescriptorQTy.isNull()) {
3791 ASTContext &C = CGM.getContext();
3792 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
3793 RD->startDefinition();
3794 addFieldToRecordDecl(
3795 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3796 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
3797 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3798 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3799 RD->completeDefinition();
3800 TgtBinaryDescriptorQTy = C.getRecordType(RD);
3801 }
3802 return TgtBinaryDescriptorQTy;
3803}
3804
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003805namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00003806struct PrivateHelpersTy {
3807 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
3808 const VarDecl *PrivateElemInit)
3809 : Original(Original), PrivateCopy(PrivateCopy),
3810 PrivateElemInit(PrivateElemInit) {}
3811 const VarDecl *Original;
3812 const VarDecl *PrivateCopy;
3813 const VarDecl *PrivateElemInit;
3814};
3815typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00003816} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003817
Alexey Bataev9e034042015-05-05 04:05:12 +00003818static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00003819createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003820 if (!Privates.empty()) {
3821 auto &C = CGM.getContext();
3822 // Build struct .kmp_privates_t. {
3823 // /* private vars */
3824 // };
3825 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
3826 RD->startDefinition();
3827 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00003828 auto *VD = Pair.second.Original;
3829 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003830 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00003831 auto *FD = addFieldToRecordDecl(C, RD, Type);
3832 if (VD->hasAttrs()) {
3833 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
3834 E(VD->getAttrs().end());
3835 I != E; ++I)
3836 FD->addAttr(*I);
3837 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003838 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003839 RD->completeDefinition();
3840 return RD;
3841 }
3842 return nullptr;
3843}
3844
Alexey Bataev9e034042015-05-05 04:05:12 +00003845static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00003846createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
3847 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003848 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003849 auto &C = CGM.getContext();
3850 // Build struct kmp_task_t {
3851 // void * shareds;
3852 // kmp_routine_entry_t routine;
3853 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00003854 // kmp_cmplrdata_t data1;
3855 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00003856 // For taskloops additional fields:
3857 // kmp_uint64 lb;
3858 // kmp_uint64 ub;
3859 // kmp_int64 st;
3860 // kmp_int32 liter;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003861 // void * reductions;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003862 // };
Alexey Bataevad537bb2016-05-30 09:06:50 +00003863 auto *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
3864 UD->startDefinition();
3865 addFieldToRecordDecl(C, UD, KmpInt32Ty);
3866 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
3867 UD->completeDefinition();
3868 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003869 auto *RD = C.buildImplicitRecord("kmp_task_t");
3870 RD->startDefinition();
3871 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3872 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
3873 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00003874 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3875 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003876 if (isOpenMPTaskLoopDirective(Kind)) {
3877 QualType KmpUInt64Ty =
3878 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3879 QualType KmpInt64Ty =
3880 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3881 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3882 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3883 addFieldToRecordDecl(C, RD, KmpInt64Ty);
3884 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003885 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003886 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003887 RD->completeDefinition();
3888 return RD;
3889}
3890
3891static RecordDecl *
3892createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003893 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003894 auto &C = CGM.getContext();
3895 // Build struct kmp_task_t_with_privates {
3896 // kmp_task_t task_data;
3897 // .kmp_privates_t. privates;
3898 // };
3899 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
3900 RD->startDefinition();
3901 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003902 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
3903 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
3904 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003905 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003906 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003907}
3908
3909/// \brief Emit a proxy function which accepts kmp_task_t as the second
3910/// argument.
3911/// \code
3912/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003913/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00003914/// For taskloops:
3915/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003916/// tt->reductions, tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003917/// return 0;
3918/// }
3919/// \endcode
3920static llvm::Value *
3921emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00003922 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
3923 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003924 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003925 QualType SharedsPtrTy, llvm::Value *TaskFunction,
3926 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003927 auto &C = CGM.getContext();
3928 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003929 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3930 ImplicitParamDecl::Other);
3931 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3932 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3933 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003934 Args.push_back(&GtidArg);
3935 Args.push_back(&TaskTypeArg);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003936 auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003937 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003938 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
3939 auto *TaskEntry =
3940 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
3941 ".omp_task_entry.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003942 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003943 CodeGenFunction CGF(CGM);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003944 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
3945
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003946 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00003947 // tt,
3948 // For taskloops:
3949 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3950 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003951 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00003952 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003953 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3954 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3955 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003956 auto *KmpTaskTWithPrivatesQTyRD =
3957 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003958 LValue Base =
3959 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003960 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3961 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3962 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003963 auto *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003964
3965 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3966 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003967 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003968 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003969 CGF.ConvertTypeForMem(SharedsPtrTy));
3970
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003971 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3972 llvm::Value *PrivatesParam;
3973 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3974 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3975 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003976 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003977 } else
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003978 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003979
Alexey Bataev7292c292016-04-25 12:22:29 +00003980 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
3981 TaskPrivatesMap,
3982 CGF.Builder
3983 .CreatePointerBitCastOrAddrSpaceCast(
3984 TDBase.getAddress(), CGF.VoidPtrTy)
3985 .getPointer()};
3986 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
3987 std::end(CommonArgs));
3988 if (isOpenMPTaskLoopDirective(Kind)) {
3989 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
3990 auto LBLVal = CGF.EmitLValueForField(Base, *LBFI);
3991 auto *LBParam = CGF.EmitLoadOfLValue(LBLVal, Loc).getScalarVal();
3992 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
3993 auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
3994 auto *UBParam = CGF.EmitLoadOfLValue(UBLVal, Loc).getScalarVal();
3995 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
3996 auto StLVal = CGF.EmitLValueForField(Base, *StFI);
3997 auto *StParam = CGF.EmitLoadOfLValue(StLVal, Loc).getScalarVal();
3998 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3999 auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
4000 auto *LIParam = CGF.EmitLoadOfLValue(LILVal, Loc).getScalarVal();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004001 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
4002 auto RLVal = CGF.EmitLValueForField(Base, *RFI);
4003 auto *RParam = CGF.EmitLoadOfLValue(RLVal, Loc).getScalarVal();
Alexey Bataev7292c292016-04-25 12:22:29 +00004004 CallArgs.push_back(LBParam);
4005 CallArgs.push_back(UBParam);
4006 CallArgs.push_back(StParam);
4007 CallArgs.push_back(LIParam);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004008 CallArgs.push_back(RParam);
Alexey Bataev7292c292016-04-25 12:22:29 +00004009 }
4010 CallArgs.push_back(SharedsParam);
4011
Alexey Bataev3c595a62017-08-14 15:01:03 +00004012 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
4013 CallArgs);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004014 CGF.EmitStoreThroughLValue(
4015 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00004016 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004017 CGF.FinishFunction();
4018 return TaskEntry;
4019}
4020
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004021static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
4022 SourceLocation Loc,
4023 QualType KmpInt32Ty,
4024 QualType KmpTaskTWithPrivatesPtrQTy,
4025 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00004026 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004027 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004028 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4029 ImplicitParamDecl::Other);
4030 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4031 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4032 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004033 Args.push_back(&GtidArg);
4034 Args.push_back(&TaskTypeArg);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004035 auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004036 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004037 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
4038 auto *DestructorFn =
4039 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
4040 ".omp_task_destructor.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004041 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
4042 DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004043 CodeGenFunction CGF(CGM);
4044 CGF.disableDebugInfo();
4045 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
4046 Args);
4047
Alexey Bataev31300ed2016-02-04 11:27:03 +00004048 LValue Base = CGF.EmitLoadOfPointerLValue(
4049 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4050 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004051 auto *KmpTaskTWithPrivatesQTyRD =
4052 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
4053 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004054 Base = CGF.EmitLValueForField(Base, *FI);
4055 for (auto *Field :
4056 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
4057 if (auto DtorKind = Field->getType().isDestructedType()) {
4058 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
4059 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
4060 }
4061 }
4062 CGF.FinishFunction();
4063 return DestructorFn;
4064}
4065
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004066/// \brief Emit a privates mapping function for correct handling of private and
4067/// firstprivate variables.
4068/// \code
4069/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
4070/// **noalias priv1,..., <tyn> **noalias privn) {
4071/// *priv1 = &.privates.priv1;
4072/// ...;
4073/// *privn = &.privates.privn;
4074/// }
4075/// \endcode
4076static llvm::Value *
4077emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00004078 ArrayRef<const Expr *> PrivateVars,
4079 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004080 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004081 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004082 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004083 auto &C = CGM.getContext();
4084 FunctionArgList Args;
4085 ImplicitParamDecl TaskPrivatesArg(
4086 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00004087 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
4088 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004089 Args.push_back(&TaskPrivatesArg);
4090 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
4091 unsigned Counter = 1;
4092 for (auto *E: PrivateVars) {
4093 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004094 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4095 C.getPointerType(C.getPointerType(E->getType()))
4096 .withConst()
4097 .withRestrict(),
4098 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004099 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4100 PrivateVarsPos[VD] = Counter;
4101 ++Counter;
4102 }
4103 for (auto *E : FirstprivateVars) {
4104 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004105 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4106 C.getPointerType(C.getPointerType(E->getType()))
4107 .withConst()
4108 .withRestrict(),
4109 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004110 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4111 PrivateVarsPos[VD] = Counter;
4112 ++Counter;
4113 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004114 for (auto *E: LastprivateVars) {
4115 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004116 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4117 C.getPointerType(C.getPointerType(E->getType()))
4118 .withConst()
4119 .withRestrict(),
4120 ImplicitParamDecl::Other));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004121 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4122 PrivateVarsPos[VD] = Counter;
4123 ++Counter;
4124 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004125 auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004126 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004127 auto *TaskPrivatesMapTy =
4128 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
4129 auto *TaskPrivatesMap = llvm::Function::Create(
4130 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
4131 ".omp_task_privates_map.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004132 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
4133 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00004134 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00004135 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00004136 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004137 CodeGenFunction CGF(CGM);
4138 CGF.disableDebugInfo();
4139 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
4140 TaskPrivatesMapFnInfo, Args);
4141
4142 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00004143 LValue Base = CGF.EmitLoadOfPointerLValue(
4144 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4145 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004146 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
4147 Counter = 0;
4148 for (auto *Field : PrivatesQTyRD->fields()) {
4149 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
4150 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00004151 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00004152 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
4153 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00004154 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004155 ++Counter;
4156 }
4157 CGF.FinishFunction();
4158 return TaskPrivatesMap;
4159}
4160
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004161static bool stable_sort_comparator(const PrivateDataTy P1,
4162 const PrivateDataTy P2) {
4163 return P1.first > P2.first;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004164}
4165
Alexey Bataevf93095a2016-05-05 08:46:22 +00004166/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00004167static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004168 const OMPExecutableDirective &D,
4169 Address KmpTaskSharedsPtr, LValue TDBase,
4170 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4171 QualType SharedsTy, QualType SharedsPtrTy,
4172 const OMPTaskDataTy &Data,
4173 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
4174 auto &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004175 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4176 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
4177 LValue SrcBase;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004178 bool IsTargetTask =
4179 isOpenMPTargetDataManagementDirective(D.getDirectiveKind()) ||
4180 isOpenMPTargetExecutionDirective(D.getDirectiveKind());
4181 // For target-based directives skip 3 firstprivate arrays BasePointersArray,
4182 // PointersArray and SizesArray. The original variables for these arrays are
4183 // not captured and we get their addresses explicitly.
4184 if ((!IsTargetTask && !Data.FirstprivateVars.empty()) ||
4185 (IsTargetTask && Data.FirstprivateVars.size() > 3)) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004186 SrcBase = CGF.MakeAddrLValue(
4187 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4188 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4189 SharedsTy);
4190 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004191 OpenMPDirectiveKind Kind = isOpenMPTaskLoopDirective(D.getDirectiveKind())
4192 ? OMPD_taskloop
4193 : OMPD_task;
4194 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(*D.getCapturedStmt(Kind));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004195 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
4196 for (auto &&Pair : Privates) {
4197 auto *VD = Pair.second.PrivateCopy;
4198 auto *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004199 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4200 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004201 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004202 if (auto *Elem = Pair.second.PrivateElemInit) {
4203 auto *OriginalVD = Pair.second.Original;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004204 // Check if the variable is the target-based BasePointersArray,
4205 // PointersArray or SizesArray.
4206 LValue SharedRefLValue;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004207 QualType Type = OriginalVD->getType();
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004208 if (IsTargetTask && isa<ImplicitParamDecl>(OriginalVD) &&
4209 isa<CapturedDecl>(OriginalVD->getDeclContext()) &&
4210 cast<CapturedDecl>(OriginalVD->getDeclContext())->getNumParams() ==
4211 0 &&
4212 isa<TranslationUnitDecl>(
4213 cast<CapturedDecl>(OriginalVD->getDeclContext())
4214 ->getDeclContext())) {
4215 SharedRefLValue =
4216 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type);
4217 } else {
4218 auto *SharedField = CapturesInfo.lookup(OriginalVD);
4219 SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4220 SharedRefLValue = CGF.MakeAddrLValue(
4221 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
4222 SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl),
4223 SharedRefLValue.getTBAAInfo());
4224 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004225 if (Type->isArrayType()) {
4226 // Initialize firstprivate array.
4227 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4228 // Perform simple memcpy.
4229 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
4230 SharedRefLValue.getAddress(), Type);
4231 } else {
4232 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00004233 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00004234 CGF.EmitOMPAggregateAssign(
4235 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4236 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4237 Address SrcElement) {
4238 // Clean up any temporaries needed by the initialization.
4239 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4240 InitScope.addPrivate(
4241 Elem, [SrcElement]() -> Address { return SrcElement; });
4242 (void)InitScope.Privatize();
4243 // Emit initialization for single element.
4244 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4245 CGF, &CapturesInfo);
4246 CGF.EmitAnyExprToMem(Init, DestElement,
4247 Init->getType().getQualifiers(),
4248 /*IsInitializer=*/false);
4249 });
4250 }
4251 } else {
4252 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4253 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4254 return SharedRefLValue.getAddress();
4255 });
4256 (void)InitScope.Privatize();
4257 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4258 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4259 /*capturedByInit=*/false);
4260 }
4261 } else
4262 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
4263 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004264 ++FI;
4265 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004266}
4267
4268/// Check if duplication function is required for taskloops.
4269static bool checkInitIsRequired(CodeGenFunction &CGF,
4270 ArrayRef<PrivateDataTy> Privates) {
4271 bool InitRequired = false;
4272 for (auto &&Pair : Privates) {
4273 auto *VD = Pair.second.PrivateCopy;
4274 auto *Init = VD->getAnyInitializer();
4275 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4276 !CGF.isTrivialInitializer(Init));
4277 }
4278 return InitRequired;
4279}
4280
4281
4282/// Emit task_dup function (for initialization of
4283/// private/firstprivate/lastprivate vars and last_iter flag)
4284/// \code
4285/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4286/// lastpriv) {
4287/// // setup lastprivate flag
4288/// task_dst->last = lastpriv;
4289/// // could be constructor calls here...
4290/// }
4291/// \endcode
4292static llvm::Value *
4293emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4294 const OMPExecutableDirective &D,
4295 QualType KmpTaskTWithPrivatesPtrQTy,
4296 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4297 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4298 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4299 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
4300 auto &C = CGM.getContext();
4301 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004302 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4303 KmpTaskTWithPrivatesPtrQTy,
4304 ImplicitParamDecl::Other);
4305 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4306 KmpTaskTWithPrivatesPtrQTy,
4307 ImplicitParamDecl::Other);
4308 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4309 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004310 Args.push_back(&DstArg);
4311 Args.push_back(&SrcArg);
4312 Args.push_back(&LastprivArg);
4313 auto &TaskDupFnInfo =
4314 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
4315 auto *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
4316 auto *TaskDup =
4317 llvm::Function::Create(TaskDupTy, llvm::GlobalValue::InternalLinkage,
4318 ".omp_task_dup.", &CGM.getModule());
4319 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskDup, TaskDupFnInfo);
4320 CodeGenFunction CGF(CGM);
4321 CGF.disableDebugInfo();
4322 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args);
4323
4324 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4325 CGF.GetAddrOfLocalVar(&DstArg),
4326 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4327 // task_dst->liter = lastpriv;
4328 if (WithLastIter) {
4329 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4330 LValue Base = CGF.EmitLValueForField(
4331 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4332 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4333 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4334 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4335 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4336 }
4337
4338 // Emit initial values for private copies (if any).
4339 assert(!Privates.empty());
4340 Address KmpTaskSharedsPtr = Address::invalid();
4341 if (!Data.FirstprivateVars.empty()) {
4342 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4343 CGF.GetAddrOfLocalVar(&SrcArg),
4344 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4345 LValue Base = CGF.EmitLValueForField(
4346 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4347 KmpTaskSharedsPtr = Address(
4348 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4349 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4350 KmpTaskTShareds)),
4351 Loc),
4352 CGF.getNaturalTypeAlignment(SharedsTy));
4353 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004354 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4355 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004356 CGF.FinishFunction();
4357 return TaskDup;
4358}
4359
Alexey Bataev8a831592016-05-10 10:36:51 +00004360/// Checks if destructor function is required to be generated.
4361/// \return true if cleanups are required, false otherwise.
4362static bool
4363checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4364 bool NeedsCleanup = false;
4365 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4366 auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4367 for (auto *FD : PrivateRD->fields()) {
4368 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4369 if (NeedsCleanup)
4370 break;
4371 }
4372 return NeedsCleanup;
4373}
4374
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004375CGOpenMPRuntime::TaskResultTy
4376CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4377 const OMPExecutableDirective &D,
4378 llvm::Value *TaskFunction, QualType SharedsTy,
4379 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004380 auto &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004381 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004382 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004383 auto I = Data.PrivateCopies.begin();
4384 for (auto *E : Data.PrivateVars) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004385 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4386 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004387 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004388 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4389 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004390 ++I;
4391 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004392 I = Data.FirstprivateCopies.begin();
4393 auto IElemInitRef = Data.FirstprivateInits.begin();
4394 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev9e034042015-05-05 04:05:12 +00004395 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4396 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004397 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004398 PrivateHelpersTy(
4399 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4400 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
Richard Trieucc3949d2016-02-18 22:34:54 +00004401 ++I;
4402 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004403 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004404 I = Data.LastprivateCopies.begin();
4405 for (auto *E : Data.LastprivateVars) {
4406 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4407 Privates.push_back(std::make_pair(
4408 C.getDeclAlign(VD),
4409 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4410 /*PrivateElemInit=*/nullptr)));
4411 ++I;
4412 }
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004413 std::stable_sort(Privates.begin(), Privates.end(), stable_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004414 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
4415 // Build type kmp_routine_entry_t (if not built yet).
4416 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004417 // Build type kmp_task_t (if not built yet).
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004418 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
4419 if (SavedKmpTaskloopTQTy.isNull()) {
4420 SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4421 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4422 }
4423 KmpTaskTQTy = SavedKmpTaskloopTQTy;
Alexey Bataev3a03a7f2017-10-11 15:56:38 +00004424 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004425 assert((D.getDirectiveKind() == OMPD_task ||
4426 isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||
4427 isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) &&
4428 "Expected taskloop, task or target directive");
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004429 if (SavedKmpTaskTQTy.isNull()) {
4430 SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4431 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4432 }
4433 KmpTaskTQTy = SavedKmpTaskTQTy;
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004434 }
4435 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004436 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004437 auto *KmpTaskTWithPrivatesQTyRD =
4438 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
4439 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
4440 QualType KmpTaskTWithPrivatesPtrQTy =
4441 C.getPointerType(KmpTaskTWithPrivatesQTy);
4442 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4443 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004444 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004445 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4446
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004447 // Emit initial values for private copies (if any).
4448 llvm::Value *TaskPrivatesMap = nullptr;
4449 auto *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00004450 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004451 if (!Privates.empty()) {
4452 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004453 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4454 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4455 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004456 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4457 TaskPrivatesMap, TaskPrivatesMapTy);
4458 } else {
4459 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4460 cast<llvm::PointerType>(TaskPrivatesMapTy));
4461 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004462 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4463 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004464 auto *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004465 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4466 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4467 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004468
4469 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4470 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4471 // kmp_routine_entry_t *task_entry);
4472 // Task flags. Format is taken from
4473 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4474 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004475 enum {
4476 TiedFlag = 0x1,
4477 FinalFlag = 0x2,
4478 DestructorsFlag = 0x8,
4479 PriorityFlag = 0x20
4480 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004481 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004482 bool NeedsCleanup = false;
4483 if (!Privates.empty()) {
4484 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4485 if (NeedsCleanup)
4486 Flags = Flags | DestructorsFlag;
4487 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004488 if (Data.Priority.getInt())
4489 Flags = Flags | PriorityFlag;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004490 auto *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004491 Data.Final.getPointer()
4492 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00004493 CGF.Builder.getInt32(FinalFlag),
4494 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004495 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004496 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00004497 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004498 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4499 getThreadID(CGF, Loc), TaskFlags,
4500 KmpTaskTWithPrivatesTySize, SharedsSize,
4501 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4502 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00004503 auto *NewTask = CGF.EmitRuntimeCall(
4504 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004505 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4506 NewTask, KmpTaskTWithPrivatesPtrTy);
4507 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4508 KmpTaskTWithPrivatesQTy);
4509 LValue TDBase =
4510 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004511 // Fill the data in the resulting kmp_task_t record.
4512 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00004513 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004514 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00004515 KmpTaskSharedsPtr =
4516 Address(CGF.EmitLoadOfScalar(
4517 CGF.EmitLValueForField(
4518 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4519 KmpTaskTShareds)),
4520 Loc),
4521 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004522 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004523 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004524 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00004525 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004526 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004527 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4528 SharedsTy, SharedsPtrTy, Data, Privates,
4529 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004530 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4531 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4532 Result.TaskDupFn = emitTaskDupFunction(
4533 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4534 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4535 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004536 }
4537 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00004538 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4539 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00004540 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00004541 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
4542 auto *KmpCmplrdataUD = (*FI)->getType()->getAsUnionType()->getDecl();
4543 if (NeedsCleanup) {
4544 llvm::Value *DestructorFn = emitDestructorsFunction(
4545 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4546 KmpTaskTWithPrivatesQTy);
4547 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4548 LValue DestructorsLV = CGF.EmitLValueForField(
4549 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4550 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4551 DestructorFn, KmpRoutineEntryPtrTy),
4552 DestructorsLV);
4553 }
4554 // Set priority.
4555 if (Data.Priority.getInt()) {
4556 LValue Data2LV = CGF.EmitLValueForField(
4557 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
4558 LValue PriorityLV = CGF.EmitLValueForField(
4559 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
4560 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
4561 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004562 Result.NewTask = NewTask;
4563 Result.TaskEntry = TaskEntry;
4564 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
4565 Result.TDBase = TDBase;
4566 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
4567 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00004568}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004569
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004570void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
4571 const OMPExecutableDirective &D,
4572 llvm::Value *TaskFunction,
4573 QualType SharedsTy, Address Shareds,
4574 const Expr *IfCond,
4575 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004576 if (!CGF.HaveInsertPoint())
4577 return;
4578
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004579 TaskResultTy Result =
4580 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4581 llvm::Value *NewTask = Result.NewTask;
4582 llvm::Value *TaskEntry = Result.TaskEntry;
4583 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
4584 LValue TDBase = Result.TDBase;
4585 RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
Alexey Bataev7292c292016-04-25 12:22:29 +00004586 auto &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004587 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00004588 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004589 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00004590 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004591 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00004592 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004593 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
4594 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004595 QualType FlagsTy =
4596 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004597 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
4598 if (KmpDependInfoTy.isNull()) {
4599 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
4600 KmpDependInfoRD->startDefinition();
4601 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
4602 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
4603 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
4604 KmpDependInfoRD->completeDefinition();
4605 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004606 } else
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004607 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
John McCall7f416cc2015-09-08 08:05:57 +00004608 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004609 // Define type kmp_depend_info[<Dependences.size()>];
4610 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00004611 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004612 ArrayType::Normal, /*IndexTypeQuals=*/0);
4613 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00004614 DependenciesArray =
4615 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
John McCall7f416cc2015-09-08 08:05:57 +00004616 for (unsigned i = 0; i < NumDependencies; ++i) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004617 const Expr *E = Data.Dependences[i].second;
John McCall7f416cc2015-09-08 08:05:57 +00004618 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004619 llvm::Value *Size;
4620 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004621 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
4622 LValue UpAddrLVal =
4623 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
4624 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00004625 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004626 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00004627 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004628 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
4629 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004630 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00004631 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00004632 auto Base = CGF.MakeAddrLValue(
4633 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004634 KmpDependInfoTy);
4635 // deps[i].base_addr = &<Dependences[i].second>;
4636 auto BaseAddrLVal = CGF.EmitLValueForField(
4637 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00004638 CGF.EmitStoreOfScalar(
4639 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
4640 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004641 // deps[i].len = sizeof(<Dependences[i].second>);
4642 auto LenLVal = CGF.EmitLValueForField(
4643 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
4644 CGF.EmitStoreOfScalar(Size, LenLVal);
4645 // deps[i].flags = <Dependences[i].first>;
4646 RTLDependenceKindTy DepKind;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004647 switch (Data.Dependences[i].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004648 case OMPC_DEPEND_in:
4649 DepKind = DepIn;
4650 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00004651 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004652 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004653 case OMPC_DEPEND_inout:
4654 DepKind = DepInOut;
4655 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00004656 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004657 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004658 case OMPC_DEPEND_unknown:
4659 llvm_unreachable("Unknown task dependence type");
4660 }
4661 auto FlagsLVal = CGF.EmitLValueForField(
4662 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
4663 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
4664 FlagsLVal);
4665 }
John McCall7f416cc2015-09-08 08:05:57 +00004666 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4667 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004668 CGF.VoidPtrTy);
4669 }
4670
Alexey Bataev62b63b12015-03-10 07:28:44 +00004671 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4672 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004673 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
4674 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
4675 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
4676 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00004677 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004678 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00004679 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
4680 llvm::Value *DepTaskArgs[7];
4681 if (NumDependencies) {
4682 DepTaskArgs[0] = UpLoc;
4683 DepTaskArgs[1] = ThreadID;
4684 DepTaskArgs[2] = NewTask;
4685 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
4686 DepTaskArgs[4] = DependenciesArray.getPointer();
4687 DepTaskArgs[5] = CGF.Builder.getInt32(0);
4688 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4689 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00004690 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
4691 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004692 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004693 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004694 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4695 auto PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
4696 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
4697 }
John McCall7f416cc2015-09-08 08:05:57 +00004698 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004699 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00004700 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00004701 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004702 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00004703 TaskArgs);
4704 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00004705 // Check if parent region is untied and build return for untied task;
4706 if (auto *Region =
4707 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4708 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00004709 };
John McCall7f416cc2015-09-08 08:05:57 +00004710
4711 llvm::Value *DepWaitTaskArgs[6];
4712 if (NumDependencies) {
4713 DepWaitTaskArgs[0] = UpLoc;
4714 DepWaitTaskArgs[1] = ThreadID;
4715 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
4716 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
4717 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
4718 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4719 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004720 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00004721 NumDependencies, &DepWaitTaskArgs,
4722 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004723 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004724 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
4725 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
4726 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
4727 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
4728 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00004729 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004730 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004731 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004732 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00004733 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
4734 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004735 Action.Enter(CGF);
4736 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00004737 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00004738 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004739 };
4740
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004741 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
4742 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004743 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
4744 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004745 RegionCodeGenTy RCG(CodeGen);
4746 CommonActionTy Action(
4747 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
4748 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
4749 RCG.setAction(Action);
4750 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004751 };
John McCall7f416cc2015-09-08 08:05:57 +00004752
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004753 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00004754 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004755 else {
4756 RegionCodeGenTy ThenRCG(ThenCodeGen);
4757 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00004758 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004759}
4760
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004761void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
4762 const OMPLoopDirective &D,
4763 llvm::Value *TaskFunction,
4764 QualType SharedsTy, Address Shareds,
4765 const Expr *IfCond,
4766 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004767 if (!CGF.HaveInsertPoint())
4768 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004769 TaskResultTy Result =
4770 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004771 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4772 // libcall.
4773 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
4774 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
4775 // sched, kmp_uint64 grainsize, void *task_dup);
4776 llvm::Value *ThreadID = getThreadID(CGF, Loc);
4777 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
4778 llvm::Value *IfVal;
4779 if (IfCond) {
4780 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
4781 /*isSigned=*/true);
4782 } else
4783 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
4784
4785 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004786 Result.TDBase,
4787 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004788 auto *LBVar =
4789 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
4790 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
4791 /*IsInitializer=*/true);
4792 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004793 Result.TDBase,
4794 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004795 auto *UBVar =
4796 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
4797 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
4798 /*IsInitializer=*/true);
4799 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004800 Result.TDBase,
4801 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataev7292c292016-04-25 12:22:29 +00004802 auto *StVar =
4803 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
4804 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
4805 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004806 // Store reductions address.
4807 LValue RedLVal = CGF.EmitLValueForField(
4808 Result.TDBase,
4809 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
4810 if (Data.Reductions)
4811 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
4812 else {
4813 CGF.EmitNullInitialization(RedLVal.getAddress(),
4814 CGF.getContext().VoidPtrTy);
4815 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004816 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00004817 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00004818 UpLoc,
4819 ThreadID,
4820 Result.NewTask,
4821 IfVal,
4822 LBLVal.getPointer(),
4823 UBLVal.getPointer(),
4824 CGF.EmitLoadOfScalar(StLVal, SourceLocation()),
4825 llvm::ConstantInt::getNullValue(
4826 CGF.IntTy), // Always 0 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004827 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004828 CGF.IntTy, Data.Schedule.getPointer()
4829 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004830 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004831 Data.Schedule.getPointer()
4832 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004833 /*isSigned=*/false)
4834 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00004835 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4836 Result.TaskDupFn, CGF.VoidPtrTy)
4837 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00004838 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
4839}
4840
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004841/// \brief Emit reduction operation for each element of array (required for
4842/// array sections) LHS op = RHS.
4843/// \param Type Type of array.
4844/// \param LHSVar Variable on the left side of the reduction operation
4845/// (references element of array in original variable).
4846/// \param RHSVar Variable on the right side of the reduction operation
4847/// (references element of array in original variable).
4848/// \param RedOpGen Generator of reduction operation with use of LHSVar and
4849/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00004850static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004851 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
4852 const VarDecl *RHSVar,
4853 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
4854 const Expr *, const Expr *)> &RedOpGen,
4855 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
4856 const Expr *UpExpr = nullptr) {
4857 // Perform element-by-element initialization.
4858 QualType ElementTy;
4859 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
4860 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
4861
4862 // Drill down to the base element type on both arrays.
4863 auto ArrayTy = Type->getAsArrayTypeUnsafe();
4864 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
4865
4866 auto RHSBegin = RHSAddr.getPointer();
4867 auto LHSBegin = LHSAddr.getPointer();
4868 // Cast from pointer to array type to pointer to single element.
4869 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
4870 // The basic structure here is a while-do loop.
4871 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
4872 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
4873 auto IsEmpty =
4874 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
4875 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
4876
4877 // Enter the loop body, making that address the current address.
4878 auto EntryBB = CGF.Builder.GetInsertBlock();
4879 CGF.EmitBlock(BodyBB);
4880
4881 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
4882
4883 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
4884 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
4885 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
4886 Address RHSElementCurrent =
4887 Address(RHSElementPHI,
4888 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4889
4890 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
4891 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
4892 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
4893 Address LHSElementCurrent =
4894 Address(LHSElementPHI,
4895 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4896
4897 // Emit copy.
4898 CodeGenFunction::OMPPrivateScope Scope(CGF);
4899 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
4900 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
4901 Scope.Privatize();
4902 RedOpGen(CGF, XExpr, EExpr, UpExpr);
4903 Scope.ForceCleanup();
4904
4905 // Shift the address forward by one element.
4906 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
4907 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
4908 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
4909 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
4910 // Check whether we've reached the end.
4911 auto Done =
4912 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
4913 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
4914 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
4915 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
4916
4917 // Done.
4918 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
4919}
4920
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004921/// Emit reduction combiner. If the combiner is a simple expression emit it as
4922/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
4923/// UDR combiner function.
4924static void emitReductionCombiner(CodeGenFunction &CGF,
4925 const Expr *ReductionOp) {
4926 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
4927 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
4928 if (auto *DRE =
4929 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
4930 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
4931 std::pair<llvm::Function *, llvm::Function *> Reduction =
4932 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
4933 RValue Func = RValue::get(Reduction.first);
4934 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
4935 CGF.EmitIgnoredExpr(ReductionOp);
4936 return;
4937 }
4938 CGF.EmitIgnoredExpr(ReductionOp);
4939}
4940
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004941llvm::Value *CGOpenMPRuntime::emitReductionFunction(
4942 CodeGenModule &CGM, llvm::Type *ArgsType, ArrayRef<const Expr *> Privates,
4943 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4944 ArrayRef<const Expr *> ReductionOps) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004945 auto &C = CGM.getContext();
4946
4947 // void reduction_func(void *LHSArg, void *RHSArg);
4948 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004949 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
4950 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004951 Args.push_back(&LHSArg);
4952 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00004953 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004954 auto *Fn = llvm::Function::Create(
4955 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
4956 ".omp.reduction.reduction_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004957 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004958 CodeGenFunction CGF(CGM);
4959 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
4960
4961 // Dst = (void*[n])(LHSArg);
4962 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00004963 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4964 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
4965 ArgsType), CGF.getPointerAlign());
4966 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4967 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
4968 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004969
4970 // ...
4971 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
4972 // ...
4973 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004974 auto IPriv = Privates.begin();
4975 unsigned Idx = 0;
4976 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004977 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
4978 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004979 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004980 });
4981 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
4982 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004983 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004984 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004985 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004986 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004987 // Get array size and emit VLA type.
4988 ++Idx;
4989 Address Elem =
4990 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
4991 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004992 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
4993 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004994 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00004995 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004996 CGF.EmitVariablyModifiedType(PrivTy);
4997 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004998 }
4999 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005000 IPriv = Privates.begin();
5001 auto ILHS = LHSExprs.begin();
5002 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005003 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005004 if ((*IPriv)->getType()->isArrayType()) {
5005 // Emit reduction for array section.
5006 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5007 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005008 EmitOMPAggregateReduction(
5009 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5010 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5011 emitReductionCombiner(CGF, E);
5012 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005013 } else
5014 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005015 emitReductionCombiner(CGF, E);
Richard Trieucc3949d2016-02-18 22:34:54 +00005016 ++IPriv;
5017 ++ILHS;
5018 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005019 }
5020 Scope.ForceCleanup();
5021 CGF.FinishFunction();
5022 return Fn;
5023}
5024
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005025void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
5026 const Expr *ReductionOp,
5027 const Expr *PrivateRef,
5028 const DeclRefExpr *LHS,
5029 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005030 if (PrivateRef->getType()->isArrayType()) {
5031 // Emit reduction for array section.
5032 auto *LHSVar = cast<VarDecl>(LHS->getDecl());
5033 auto *RHSVar = cast<VarDecl>(RHS->getDecl());
5034 EmitOMPAggregateReduction(
5035 CGF, PrivateRef->getType(), LHSVar, RHSVar,
5036 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5037 emitReductionCombiner(CGF, ReductionOp);
5038 });
5039 } else
5040 // Emit reduction for array subscript or single variable.
5041 emitReductionCombiner(CGF, ReductionOp);
5042}
5043
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005044void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005045 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005046 ArrayRef<const Expr *> LHSExprs,
5047 ArrayRef<const Expr *> RHSExprs,
5048 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005049 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005050 if (!CGF.HaveInsertPoint())
5051 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005052
5053 bool WithNowait = Options.WithNowait;
5054 bool SimpleReduction = Options.SimpleReduction;
5055
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005056 // Next code should be emitted for reduction:
5057 //
5058 // static kmp_critical_name lock = { 0 };
5059 //
5060 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
5061 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
5062 // ...
5063 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
5064 // *(Type<n>-1*)rhs[<n>-1]);
5065 // }
5066 //
5067 // ...
5068 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
5069 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5070 // RedList, reduce_func, &<lock>)) {
5071 // case 1:
5072 // ...
5073 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5074 // ...
5075 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5076 // break;
5077 // case 2:
5078 // ...
5079 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5080 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00005081 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005082 // break;
5083 // default:;
5084 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005085 //
5086 // if SimpleReduction is true, only the next code is generated:
5087 // ...
5088 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5089 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005090
5091 auto &C = CGM.getContext();
5092
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005093 if (SimpleReduction) {
5094 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005095 auto IPriv = Privates.begin();
5096 auto ILHS = LHSExprs.begin();
5097 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005098 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005099 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5100 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005101 ++IPriv;
5102 ++ILHS;
5103 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005104 }
5105 return;
5106 }
5107
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005108 // 1. Build a list of reduction variables.
5109 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005110 auto Size = RHSExprs.size();
5111 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005112 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005113 // Reserve place for array size.
5114 ++Size;
5115 }
5116 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005117 QualType ReductionArrayTy =
5118 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
5119 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00005120 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005121 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005122 auto IPriv = Privates.begin();
5123 unsigned Idx = 0;
5124 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00005125 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005126 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00005127 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005128 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00005129 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
5130 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005131 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005132 // Store array size.
5133 ++Idx;
5134 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
5135 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00005136 llvm::Value *Size = CGF.Builder.CreateIntCast(
5137 CGF.getVLASize(
5138 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
5139 .first,
5140 CGF.SizeTy, /*isSigned=*/false);
5141 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
5142 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005143 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005144 }
5145
5146 // 2. Emit reduce_func().
5147 auto *ReductionFn = emitReductionFunction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005148 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
5149 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005150
5151 // 3. Create static kmp_critical_name lock = { 0 };
5152 auto *Lock = getCriticalRegionLock(".reduction");
5153
5154 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5155 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00005156 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005157 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005158 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
Samuel Antao4c8035b2016-12-12 18:00:20 +00005159 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5160 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005161 llvm::Value *Args[] = {
5162 IdentTLoc, // ident_t *<loc>
5163 ThreadId, // i32 <gtid>
5164 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5165 ReductionArrayTySize, // size_type sizeof(RedList)
5166 RL, // void *RedList
5167 ReductionFn, // void (*) (void *, void *) <reduce_func>
5168 Lock // kmp_critical_name *&<lock>
5169 };
5170 auto Res = CGF.EmitRuntimeCall(
5171 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5172 : OMPRTL__kmpc_reduce),
5173 Args);
5174
5175 // 5. Build switch(res)
5176 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5177 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
5178
5179 // 6. Build case 1:
5180 // ...
5181 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5182 // ...
5183 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5184 // break;
5185 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
5186 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5187 CGF.EmitBlock(Case1BB);
5188
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005189 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5190 llvm::Value *EndArgs[] = {
5191 IdentTLoc, // ident_t *<loc>
5192 ThreadId, // i32 <gtid>
5193 Lock // kmp_critical_name *&<lock>
5194 };
5195 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5196 CodeGenFunction &CGF, PrePostActionTy &Action) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005197 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005198 auto IPriv = Privates.begin();
5199 auto ILHS = LHSExprs.begin();
5200 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005201 for (auto *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005202 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5203 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005204 ++IPriv;
5205 ++ILHS;
5206 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005207 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005208 };
5209 RegionCodeGenTy RCG(CodeGen);
5210 CommonActionTy Action(
5211 nullptr, llvm::None,
5212 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5213 : OMPRTL__kmpc_end_reduce),
5214 EndArgs);
5215 RCG.setAction(Action);
5216 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005217
5218 CGF.EmitBranch(DefaultBB);
5219
5220 // 7. Build case 2:
5221 // ...
5222 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5223 // ...
5224 // break;
5225 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
5226 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5227 CGF.EmitBlock(Case2BB);
5228
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005229 auto &&AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5230 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005231 auto ILHS = LHSExprs.begin();
5232 auto IRHS = RHSExprs.begin();
5233 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005234 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005235 const Expr *XExpr = nullptr;
5236 const Expr *EExpr = nullptr;
5237 const Expr *UpExpr = nullptr;
5238 BinaryOperatorKind BO = BO_Comma;
5239 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
5240 if (BO->getOpcode() == BO_Assign) {
5241 XExpr = BO->getLHS();
5242 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005243 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005244 }
5245 // Try to emit update expression as a simple atomic.
5246 auto *RHSExpr = UpExpr;
5247 if (RHSExpr) {
5248 // Analyze RHS part of the whole expression.
5249 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
5250 RHSExpr->IgnoreParenImpCasts())) {
5251 // If this is a conditional operator, analyze its condition for
5252 // min/max reduction operator.
5253 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005254 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005255 if (auto *BORHS =
5256 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5257 EExpr = BORHS->getRHS();
5258 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005259 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005260 }
5261 if (XExpr) {
5262 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005263 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005264 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5265 const Expr *EExpr, const Expr *UpExpr) {
5266 LValue X = CGF.EmitLValue(XExpr);
5267 RValue E;
5268 if (EExpr)
5269 E = CGF.EmitAnyExpr(EExpr);
5270 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005271 X, E, BO, /*IsXLHSInRHSPart=*/true,
5272 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005273 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005274 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5275 PrivateScope.addPrivate(
5276 VD, [&CGF, VD, XRValue, Loc]() -> Address {
5277 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5278 CGF.emitOMPSimpleStore(
5279 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5280 VD->getType().getNonReferenceType(), Loc);
5281 return LHSTemp;
5282 });
5283 (void)PrivateScope.Privatize();
5284 return CGF.EmitAnyExpr(UpExpr);
5285 });
5286 };
5287 if ((*IPriv)->getType()->isArrayType()) {
5288 // Emit atomic reduction for array section.
5289 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5290 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5291 AtomicRedGen, XExpr, EExpr, UpExpr);
5292 } else
5293 // Emit atomic reduction for array subscript or single variable.
5294 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
5295 } else {
5296 // Emit as a critical region.
5297 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
5298 const Expr *, const Expr *) {
5299 auto &RT = CGF.CGM.getOpenMPRuntime();
5300 RT.emitCriticalRegion(
5301 CGF, ".atomic_reduction",
5302 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5303 Action.Enter(CGF);
5304 emitReductionCombiner(CGF, E);
5305 },
5306 Loc);
5307 };
5308 if ((*IPriv)->getType()->isArrayType()) {
5309 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5310 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5311 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5312 CritRedGen);
5313 } else
5314 CritRedGen(CGF, nullptr, nullptr, nullptr);
5315 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005316 ++ILHS;
5317 ++IRHS;
5318 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005319 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005320 };
5321 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5322 if (!WithNowait) {
5323 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5324 llvm::Value *EndArgs[] = {
5325 IdentTLoc, // ident_t *<loc>
5326 ThreadId, // i32 <gtid>
5327 Lock // kmp_critical_name *&<lock>
5328 };
5329 CommonActionTy Action(nullptr, llvm::None,
5330 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5331 EndArgs);
5332 AtomicRCG.setAction(Action);
5333 AtomicRCG(CGF);
5334 } else
5335 AtomicRCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005336
5337 CGF.EmitBranch(DefaultBB);
5338 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5339}
5340
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005341/// Generates unique name for artificial threadprivate variables.
5342/// Format is: <Prefix> "." <Loc_raw_encoding> "_" <N>
5343static std::string generateUniqueName(StringRef Prefix, SourceLocation Loc,
5344 unsigned N) {
5345 SmallString<256> Buffer;
5346 llvm::raw_svector_ostream Out(Buffer);
5347 Out << Prefix << "." << Loc.getRawEncoding() << "_" << N;
5348 return Out.str();
5349}
5350
5351/// Emits reduction initializer function:
5352/// \code
5353/// void @.red_init(void* %arg) {
5354/// %0 = bitcast void* %arg to <type>*
5355/// store <type> <init>, <type>* %0
5356/// ret void
5357/// }
5358/// \endcode
5359static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5360 SourceLocation Loc,
5361 ReductionCodeGen &RCG, unsigned N) {
5362 auto &C = CGM.getContext();
5363 FunctionArgList Args;
5364 ImplicitParamDecl Param(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5365 Args.emplace_back(&Param);
5366 auto &FnInfo =
5367 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5368 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5369 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5370 ".red_init.", &CGM.getModule());
5371 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5372 CodeGenFunction CGF(CGM);
5373 CGF.disableDebugInfo();
5374 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5375 Address PrivateAddr = CGF.EmitLoadOfPointer(
5376 CGF.GetAddrOfLocalVar(&Param),
5377 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5378 llvm::Value *Size = nullptr;
5379 // If the size of the reduction item is non-constant, load it from global
5380 // threadprivate variable.
5381 if (RCG.getSizes(N).second) {
5382 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5383 CGF, CGM.getContext().getSizeType(),
5384 generateUniqueName("reduction_size", Loc, N));
5385 Size =
5386 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5387 CGM.getContext().getSizeType(), SourceLocation());
5388 }
5389 RCG.emitAggregateType(CGF, N, Size);
5390 LValue SharedLVal;
5391 // If initializer uses initializer from declare reduction construct, emit a
5392 // pointer to the address of the original reduction item (reuired by reduction
5393 // initializer)
5394 if (RCG.usesReductionInitializer(N)) {
5395 Address SharedAddr =
5396 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5397 CGF, CGM.getContext().VoidPtrTy,
5398 generateUniqueName("reduction", Loc, N));
5399 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5400 } else {
5401 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5402 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5403 CGM.getContext().VoidPtrTy);
5404 }
5405 // Emit the initializer:
5406 // %0 = bitcast void* %arg to <type>*
5407 // store <type> <init>, <type>* %0
5408 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5409 [](CodeGenFunction &) { return false; });
5410 CGF.FinishFunction();
5411 return Fn;
5412}
5413
5414/// Emits reduction combiner function:
5415/// \code
5416/// void @.red_comb(void* %arg0, void* %arg1) {
5417/// %lhs = bitcast void* %arg0 to <type>*
5418/// %rhs = bitcast void* %arg1 to <type>*
5419/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5420/// store <type> %2, <type>* %lhs
5421/// ret void
5422/// }
5423/// \endcode
5424static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5425 SourceLocation Loc,
5426 ReductionCodeGen &RCG, unsigned N,
5427 const Expr *ReductionOp,
5428 const Expr *LHS, const Expr *RHS,
5429 const Expr *PrivateRef) {
5430 auto &C = CGM.getContext();
5431 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5432 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
5433 FunctionArgList Args;
5434 ImplicitParamDecl ParamInOut(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5435 ImplicitParamDecl ParamIn(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5436 Args.emplace_back(&ParamInOut);
5437 Args.emplace_back(&ParamIn);
5438 auto &FnInfo =
5439 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5440 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5441 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5442 ".red_comb.", &CGM.getModule());
5443 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5444 CodeGenFunction CGF(CGM);
5445 CGF.disableDebugInfo();
5446 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5447 llvm::Value *Size = nullptr;
5448 // If the size of the reduction item is non-constant, load it from global
5449 // threadprivate variable.
5450 if (RCG.getSizes(N).second) {
5451 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5452 CGF, CGM.getContext().getSizeType(),
5453 generateUniqueName("reduction_size", Loc, N));
5454 Size =
5455 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5456 CGM.getContext().getSizeType(), SourceLocation());
5457 }
5458 RCG.emitAggregateType(CGF, N, Size);
5459 // Remap lhs and rhs variables to the addresses of the function arguments.
5460 // %lhs = bitcast void* %arg0 to <type>*
5461 // %rhs = bitcast void* %arg1 to <type>*
5462 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5463 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() -> Address {
5464 // Pull out the pointer to the variable.
5465 Address PtrAddr = CGF.EmitLoadOfPointer(
5466 CGF.GetAddrOfLocalVar(&ParamInOut),
5467 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5468 return CGF.Builder.CreateElementBitCast(
5469 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
5470 });
5471 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() -> Address {
5472 // Pull out the pointer to the variable.
5473 Address PtrAddr = CGF.EmitLoadOfPointer(
5474 CGF.GetAddrOfLocalVar(&ParamIn),
5475 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5476 return CGF.Builder.CreateElementBitCast(
5477 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
5478 });
5479 PrivateScope.Privatize();
5480 // Emit the combiner body:
5481 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
5482 // store <type> %2, <type>* %lhs
5483 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
5484 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
5485 cast<DeclRefExpr>(RHS));
5486 CGF.FinishFunction();
5487 return Fn;
5488}
5489
5490/// Emits reduction finalizer function:
5491/// \code
5492/// void @.red_fini(void* %arg) {
5493/// %0 = bitcast void* %arg to <type>*
5494/// <destroy>(<type>* %0)
5495/// ret void
5496/// }
5497/// \endcode
5498static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
5499 SourceLocation Loc,
5500 ReductionCodeGen &RCG, unsigned N) {
5501 if (!RCG.needCleanups(N))
5502 return nullptr;
5503 auto &C = CGM.getContext();
5504 FunctionArgList Args;
5505 ImplicitParamDecl Param(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5506 Args.emplace_back(&Param);
5507 auto &FnInfo =
5508 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5509 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5510 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5511 ".red_fini.", &CGM.getModule());
5512 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5513 CodeGenFunction CGF(CGM);
5514 CGF.disableDebugInfo();
5515 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5516 Address PrivateAddr = CGF.EmitLoadOfPointer(
5517 CGF.GetAddrOfLocalVar(&Param),
5518 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5519 llvm::Value *Size = nullptr;
5520 // If the size of the reduction item is non-constant, load it from global
5521 // threadprivate variable.
5522 if (RCG.getSizes(N).second) {
5523 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5524 CGF, CGM.getContext().getSizeType(),
5525 generateUniqueName("reduction_size", Loc, N));
5526 Size =
5527 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5528 CGM.getContext().getSizeType(), SourceLocation());
5529 }
5530 RCG.emitAggregateType(CGF, N, Size);
5531 // Emit the finalizer body:
5532 // <destroy>(<type>* %0)
5533 RCG.emitCleanups(CGF, N, PrivateAddr);
5534 CGF.FinishFunction();
5535 return Fn;
5536}
5537
5538llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
5539 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
5540 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
5541 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
5542 return nullptr;
5543
5544 // Build typedef struct:
5545 // kmp_task_red_input {
5546 // void *reduce_shar; // shared reduction item
5547 // size_t reduce_size; // size of data item
5548 // void *reduce_init; // data initialization routine
5549 // void *reduce_fini; // data finalization routine
5550 // void *reduce_comb; // data combiner routine
5551 // kmp_task_red_flags_t flags; // flags for additional info from compiler
5552 // } kmp_task_red_input_t;
5553 ASTContext &C = CGM.getContext();
5554 auto *RD = C.buildImplicitRecord("kmp_task_red_input_t");
5555 RD->startDefinition();
5556 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5557 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
5558 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5559 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5560 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5561 const FieldDecl *FlagsFD = addFieldToRecordDecl(
5562 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
5563 RD->completeDefinition();
5564 QualType RDType = C.getRecordType(RD);
5565 unsigned Size = Data.ReductionVars.size();
5566 llvm::APInt ArraySize(/*numBits=*/64, Size);
5567 QualType ArrayRDType = C.getConstantArrayType(
5568 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5569 // kmp_task_red_input_t .rd_input.[Size];
5570 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
5571 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
5572 Data.ReductionOps);
5573 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
5574 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
5575 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
5576 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
5577 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
5578 TaskRedInput.getPointer(), Idxs,
5579 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
5580 ".rd_input.gep.");
5581 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
5582 // ElemLVal.reduce_shar = &Shareds[Cnt];
5583 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
5584 RCG.emitSharedLValue(CGF, Cnt);
5585 llvm::Value *CastedShared =
5586 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
5587 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
5588 RCG.emitAggregateType(CGF, Cnt);
5589 llvm::Value *SizeValInChars;
5590 llvm::Value *SizeVal;
5591 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
5592 // We use delayed creation/initialization for VLAs, array sections and
5593 // custom reduction initializations. It is required because runtime does not
5594 // provide the way to pass the sizes of VLAs/array sections to
5595 // initializer/combiner/finalizer functions and does not pass the pointer to
5596 // original reduction item to the initializer. Instead threadprivate global
5597 // variables are used to store these values and use them in the functions.
5598 bool DelayedCreation = !!SizeVal;
5599 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
5600 /*isSigned=*/false);
5601 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
5602 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
5603 // ElemLVal.reduce_init = init;
5604 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
5605 llvm::Value *InitAddr =
5606 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
5607 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
5608 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
5609 // ElemLVal.reduce_fini = fini;
5610 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
5611 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
5612 llvm::Value *FiniAddr = Fini
5613 ? CGF.EmitCastToVoidPtr(Fini)
5614 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
5615 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
5616 // ElemLVal.reduce_comb = comb;
5617 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
5618 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
5619 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
5620 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
5621 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
5622 // ElemLVal.flags = 0;
5623 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
5624 if (DelayedCreation) {
5625 CGF.EmitStoreOfScalar(
5626 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
5627 FlagsLVal);
5628 } else
5629 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
5630 }
5631 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
5632 // *data);
5633 llvm::Value *Args[] = {
5634 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5635 /*isSigned=*/true),
5636 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
5637 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
5638 CGM.VoidPtrTy)};
5639 return CGF.EmitRuntimeCall(
5640 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
5641}
5642
5643void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
5644 SourceLocation Loc,
5645 ReductionCodeGen &RCG,
5646 unsigned N) {
5647 auto Sizes = RCG.getSizes(N);
5648 // Emit threadprivate global variable if the type is non-constant
5649 // (Sizes.second = nullptr).
5650 if (Sizes.second) {
5651 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
5652 /*isSigned=*/false);
5653 Address SizeAddr = getAddrOfArtificialThreadPrivate(
5654 CGF, CGM.getContext().getSizeType(),
5655 generateUniqueName("reduction_size", Loc, N));
5656 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
5657 }
5658 // Store address of the original reduction item if custom initializer is used.
5659 if (RCG.usesReductionInitializer(N)) {
5660 Address SharedAddr = getAddrOfArtificialThreadPrivate(
5661 CGF, CGM.getContext().VoidPtrTy,
5662 generateUniqueName("reduction", Loc, N));
5663 CGF.Builder.CreateStore(
5664 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5665 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
5666 SharedAddr, /*IsVolatile=*/false);
5667 }
5668}
5669
5670Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
5671 SourceLocation Loc,
5672 llvm::Value *ReductionsPtr,
5673 LValue SharedLVal) {
5674 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
5675 // *d);
5676 llvm::Value *Args[] = {
5677 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5678 /*isSigned=*/true),
5679 ReductionsPtr,
5680 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
5681 CGM.VoidPtrTy)};
5682 return Address(
5683 CGF.EmitRuntimeCall(
5684 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
5685 SharedLVal.getAlignment());
5686}
5687
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005688void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
5689 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005690 if (!CGF.HaveInsertPoint())
5691 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005692 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
5693 // global_tid);
5694 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
5695 // Ignore return result until untied tasks are supported.
5696 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005697 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5698 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005699}
5700
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005701void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005702 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005703 const RegionCodeGenTy &CodeGen,
5704 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005705 if (!CGF.HaveInsertPoint())
5706 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005707 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005708 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00005709}
5710
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005711namespace {
5712enum RTCancelKind {
5713 CancelNoreq = 0,
5714 CancelParallel = 1,
5715 CancelLoop = 2,
5716 CancelSections = 3,
5717 CancelTaskgroup = 4
5718};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00005719} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005720
5721static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
5722 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00005723 if (CancelRegion == OMPD_parallel)
5724 CancelKind = CancelParallel;
5725 else if (CancelRegion == OMPD_for)
5726 CancelKind = CancelLoop;
5727 else if (CancelRegion == OMPD_sections)
5728 CancelKind = CancelSections;
5729 else {
5730 assert(CancelRegion == OMPD_taskgroup);
5731 CancelKind = CancelTaskgroup;
5732 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005733 return CancelKind;
5734}
5735
5736void CGOpenMPRuntime::emitCancellationPointCall(
5737 CodeGenFunction &CGF, SourceLocation Loc,
5738 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005739 if (!CGF.HaveInsertPoint())
5740 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005741 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
5742 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005743 if (auto *OMPRegionInfo =
5744 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00005745 // For 'cancellation point taskgroup', the task region info may not have a
5746 // cancel. This may instead happen in another adjacent task.
5747 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005748 llvm::Value *Args[] = {
5749 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
5750 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005751 // Ignore return result until untied tasks are supported.
5752 auto *Result = CGF.EmitRuntimeCall(
5753 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
5754 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005755 // exit from construct;
5756 // }
5757 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5758 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5759 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5760 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5761 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005762 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005763 auto CancelDest =
5764 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005765 CGF.EmitBranchThroughCleanup(CancelDest);
5766 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5767 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005768 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005769}
5770
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005771void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00005772 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005773 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005774 if (!CGF.HaveInsertPoint())
5775 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005776 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
5777 // kmp_int32 cncl_kind);
5778 if (auto *OMPRegionInfo =
5779 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005780 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
5781 PrePostActionTy &) {
5782 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00005783 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005784 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00005785 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
5786 // Ignore return result until untied tasks are supported.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005787 auto *Result = CGF.EmitRuntimeCall(
5788 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00005789 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00005790 // exit from construct;
5791 // }
5792 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5793 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5794 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5795 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5796 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00005797 // exit from construct;
5798 auto CancelDest =
5799 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
5800 CGF.EmitBranchThroughCleanup(CancelDest);
5801 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5802 };
5803 if (IfCond)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005804 emitOMPIfClause(CGF, IfCond, ThenGen,
5805 [](CodeGenFunction &, PrePostActionTy &) {});
5806 else {
5807 RegionCodeGenTy ThenRCG(ThenGen);
5808 ThenRCG(CGF);
5809 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005810 }
5811}
Samuel Antaobed3c462015-10-02 16:14:20 +00005812
Samuel Antaoee8fb302016-01-06 13:42:12 +00005813/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00005814/// consists of the file and device IDs as well as line number associated with
5815/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005816static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
5817 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005818 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005819
5820 auto &SM = C.getSourceManager();
5821
5822 // The loc should be always valid and have a file ID (the user cannot use
5823 // #pragma directives in macros)
5824
5825 assert(Loc.isValid() && "Source location is expected to be always valid.");
5826 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
5827
5828 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
5829 assert(PLoc.isValid() && "Source location is expected to be always valid.");
5830
5831 llvm::sys::fs::UniqueID ID;
5832 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
5833 llvm_unreachable("Source file with target region no longer exists!");
5834
5835 DeviceID = ID.getDevice();
5836 FileID = ID.getFile();
5837 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00005838}
5839
5840void CGOpenMPRuntime::emitTargetOutlinedFunction(
5841 const OMPExecutableDirective &D, StringRef ParentName,
5842 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005843 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005844 assert(!ParentName.empty() && "Invalid target region parent name!");
5845
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005846 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
5847 IsOffloadEntry, CodeGen);
5848}
5849
5850void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
5851 const OMPExecutableDirective &D, StringRef ParentName,
5852 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
5853 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00005854 // Create a unique name for the entry function using the source location
5855 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00005856 //
Samuel Antao2de62b02016-02-13 23:35:10 +00005857 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00005858 //
5859 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00005860 // mangled name of the function that encloses the target region and BB is the
5861 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005862
5863 unsigned DeviceID;
5864 unsigned FileID;
5865 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005866 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005867 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005868 SmallString<64> EntryFnName;
5869 {
5870 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00005871 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
5872 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005873 }
5874
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005875 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5876
Samuel Antaobed3c462015-10-02 16:14:20 +00005877 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005878 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00005879 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005880
Samuel Antao6d004262016-06-16 18:39:34 +00005881 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005882
5883 // If this target outline function is not an offload entry, we don't need to
5884 // register it.
5885 if (!IsOffloadEntry)
5886 return;
5887
5888 // The target region ID is used by the runtime library to identify the current
5889 // target region, so it only has to be unique and not necessarily point to
5890 // anything. It could be the pointer to the outlined function that implements
5891 // the target region, but we aren't using that so that the compiler doesn't
5892 // need to keep that, and could therefore inline the host function if proven
5893 // worthwhile during optimization. In the other hand, if emitting code for the
5894 // device, the ID has to be the function address so that it can retrieved from
5895 // the offloading entry and launched by the runtime library. We also mark the
5896 // outlined function to have external linkage in case we are emitting code for
5897 // the device, because these functions will be entry points to the device.
5898
5899 if (CGM.getLangOpts().OpenMPIsDevice) {
5900 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
5901 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
5902 } else
5903 OutlinedFnID = new llvm::GlobalVariable(
5904 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
5905 llvm::GlobalValue::PrivateLinkage,
5906 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
5907
5908 // Register the information for the entry associated with this target region.
5909 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00005910 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
5911 /*Flags=*/0);
Samuel Antaobed3c462015-10-02 16:14:20 +00005912}
5913
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005914/// discard all CompoundStmts intervening between two constructs
5915static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
5916 while (auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
5917 Body = CS->body_front();
5918
5919 return Body;
5920}
5921
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005922/// Emit the number of teams for a target directive. Inspect the num_teams
5923/// clause associated with a teams construct combined or closely nested
5924/// with the target directive.
5925///
5926/// Emit a team of size one for directives such as 'target parallel' that
5927/// have no associated teams construct.
5928///
5929/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00005930static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005931emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
5932 CodeGenFunction &CGF,
5933 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005934
5935 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
5936 "teams directive expected to be "
5937 "emitted only for the host!");
5938
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005939 auto &Bld = CGF.Builder;
5940
5941 // If the target directive is combined with a teams directive:
5942 // Return the value in the num_teams clause, if any.
5943 // Otherwise, return 0 to denote the runtime default.
5944 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
5945 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
5946 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
5947 auto NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
5948 /*IgnoreResultAssign*/ true);
5949 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5950 /*IsSigned=*/true);
5951 }
5952
5953 // The default value is 0.
5954 return Bld.getInt32(0);
5955 }
5956
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005957 // If the target directive is combined with a parallel directive but not a
5958 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005959 if (isOpenMPParallelDirective(D.getDirectiveKind()))
5960 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005961
5962 // If the current target region has a teams region enclosed, we need to get
5963 // the number of teams to pass to the runtime function call. This is done
5964 // by generating the expression in a inlined region. This is required because
5965 // the expression is captured in the enclosing target environment when the
5966 // teams directive is not combined with target.
5967
5968 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5969
Alexey Bataev50a1c782017-12-01 21:31:08 +00005970 if (auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005971 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00005972 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
5973 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
5974 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5975 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5976 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
5977 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5978 /*IsSigned=*/true);
5979 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00005980
Alexey Bataev50a1c782017-12-01 21:31:08 +00005981 // If we have an enclosed teams directive but no num_teams clause we use
5982 // the default value 0.
5983 return Bld.getInt32(0);
5984 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00005985 }
5986
5987 // No teams associated with the directive.
5988 return nullptr;
5989}
5990
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005991/// Emit the number of threads for a target directive. Inspect the
5992/// thread_limit clause associated with a teams construct combined or closely
5993/// nested with the target directive.
5994///
5995/// Emit the num_threads clause for directives such as 'target parallel' that
5996/// have no associated teams construct.
5997///
5998/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00005999static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006000emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6001 CodeGenFunction &CGF,
6002 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006003
6004 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6005 "teams directive expected to be "
6006 "emitted only for the host!");
6007
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006008 auto &Bld = CGF.Builder;
6009
6010 //
6011 // If the target directive is combined with a teams directive:
6012 // Return the value in the thread_limit clause, if any.
6013 //
6014 // If the target directive is combined with a parallel directive:
6015 // Return the value in the num_threads clause, if any.
6016 //
6017 // If both clauses are set, select the minimum of the two.
6018 //
6019 // If neither teams or parallel combined directives set the number of threads
6020 // in a team, return 0 to denote the runtime default.
6021 //
6022 // If this is not a teams directive return nullptr.
6023
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006024 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
6025 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006026 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
6027 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006028 llvm::Value *ThreadLimitVal = nullptr;
6029
6030 if (const auto *ThreadLimitClause =
6031 D.getSingleClause<OMPThreadLimitClause>()) {
6032 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
6033 auto ThreadLimit = CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
6034 /*IgnoreResultAssign*/ true);
6035 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6036 /*IsSigned=*/true);
6037 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006038
6039 if (const auto *NumThreadsClause =
6040 D.getSingleClause<OMPNumThreadsClause>()) {
6041 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
6042 llvm::Value *NumThreads =
6043 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
6044 /*IgnoreResultAssign*/ true);
6045 NumThreadsVal =
6046 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
6047 }
6048
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006049 // Select the lesser of thread_limit and num_threads.
6050 if (NumThreadsVal)
6051 ThreadLimitVal = ThreadLimitVal
6052 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
6053 ThreadLimitVal),
6054 NumThreadsVal, ThreadLimitVal)
6055 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00006056
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006057 // Set default value passed to the runtime if either teams or a target
6058 // parallel type directive is found but no clause is specified.
6059 if (!ThreadLimitVal)
6060 ThreadLimitVal = DefaultThreadLimitVal;
6061
6062 return ThreadLimitVal;
6063 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00006064
Samuel Antaob68e2db2016-03-03 16:20:23 +00006065 // If the current target region has a teams region enclosed, we need to get
6066 // the thread limit to pass to the runtime function call. This is done
6067 // by generating the expression in a inlined region. This is required because
6068 // the expression is captured in the enclosing target environment when the
6069 // teams directive is not combined with target.
6070
6071 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
6072
Alexey Bataev50a1c782017-12-01 21:31:08 +00006073 if (auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006074 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006075 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
6076 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
6077 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6078 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6079 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
6080 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6081 /*IsSigned=*/true);
6082 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006083
Alexey Bataev50a1c782017-12-01 21:31:08 +00006084 // If we have an enclosed teams directive but no thread_limit clause we
6085 // use the default value 0.
6086 return CGF.Builder.getInt32(0);
6087 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006088 }
6089
6090 // No teams associated with the directive.
6091 return nullptr;
6092}
6093
Samuel Antao86ace552016-04-27 22:40:57 +00006094namespace {
6095// \brief Utility to handle information from clauses associated with a given
6096// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
6097// It provides a convenient interface to obtain the information and generate
6098// code for that information.
6099class MappableExprsHandler {
6100public:
6101 /// \brief Values for bit flags used to specify the mapping type for
6102 /// offloading.
6103 enum OpenMPOffloadMappingFlags {
Samuel Antao86ace552016-04-27 22:40:57 +00006104 /// \brief Allocate memory on the device and move data from host to device.
6105 OMP_MAP_TO = 0x01,
6106 /// \brief Allocate memory on the device and move data from device to host.
6107 OMP_MAP_FROM = 0x02,
6108 /// \brief Always perform the requested mapping action on the element, even
6109 /// if it was already mapped before.
6110 OMP_MAP_ALWAYS = 0x04,
Samuel Antao86ace552016-04-27 22:40:57 +00006111 /// \brief Delete the element from the device environment, ignoring the
6112 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00006113 OMP_MAP_DELETE = 0x08,
George Rokos065755d2017-11-07 18:27:04 +00006114 /// \brief The element being mapped is a pointer-pointee pair; both the
6115 /// pointer and the pointee should be mapped.
6116 OMP_MAP_PTR_AND_OBJ = 0x10,
6117 /// \brief This flags signals that the base address of an entry should be
6118 /// passed to the target kernel as an argument.
6119 OMP_MAP_TARGET_PARAM = 0x20,
Samuel Antaocc10b852016-07-28 14:23:26 +00006120 /// \brief Signal that the runtime library has to return the device pointer
George Rokos065755d2017-11-07 18:27:04 +00006121 /// in the current position for the data being mapped. Used when we have the
6122 /// use_device_ptr clause.
6123 OMP_MAP_RETURN_PARAM = 0x40,
Samuel Antaod486f842016-05-26 16:53:38 +00006124 /// \brief This flag signals that the reference being passed is a pointer to
6125 /// private data.
George Rokos065755d2017-11-07 18:27:04 +00006126 OMP_MAP_PRIVATE = 0x80,
Samuel Antao86ace552016-04-27 22:40:57 +00006127 /// \brief Pass the element to the device by value.
George Rokos065755d2017-11-07 18:27:04 +00006128 OMP_MAP_LITERAL = 0x100,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006129 /// Implicit map
6130 OMP_MAP_IMPLICIT = 0x200,
Samuel Antao86ace552016-04-27 22:40:57 +00006131 };
6132
Samuel Antaocc10b852016-07-28 14:23:26 +00006133 /// Class that associates information with a base pointer to be passed to the
6134 /// runtime library.
6135 class BasePointerInfo {
6136 /// The base pointer.
6137 llvm::Value *Ptr = nullptr;
6138 /// The base declaration that refers to this device pointer, or null if
6139 /// there is none.
6140 const ValueDecl *DevPtrDecl = nullptr;
6141
6142 public:
6143 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
6144 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
6145 llvm::Value *operator*() const { return Ptr; }
6146 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
6147 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
6148 };
6149
6150 typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00006151 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
George Rokos63bc9d62017-11-21 18:25:12 +00006152 typedef SmallVector<uint64_t, 16> MapFlagsArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00006153
6154private:
6155 /// \brief Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00006156 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00006157
6158 /// \brief Function the directive is being generated for.
6159 CodeGenFunction &CGF;
6160
Samuel Antaod486f842016-05-26 16:53:38 +00006161 /// \brief Set of all first private variables in the current directive.
6162 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
Alexey Bataev3f96fe62017-12-13 17:31:39 +00006163 /// Set of all reduction variables in the current directive.
6164 llvm::SmallPtrSet<const VarDecl *, 8> ReductionDecls;
Samuel Antaod486f842016-05-26 16:53:38 +00006165
Samuel Antao6890b092016-07-28 14:25:09 +00006166 /// Map between device pointer declarations and their expression components.
6167 /// The key value for declarations in 'this' is null.
6168 llvm::DenseMap<
6169 const ValueDecl *,
6170 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6171 DevPointersMap;
6172
Samuel Antao86ace552016-04-27 22:40:57 +00006173 llvm::Value *getExprTypeSize(const Expr *E) const {
6174 auto ExprTy = E->getType().getCanonicalType();
6175
6176 // Reference types are ignored for mapping purposes.
6177 if (auto *RefTy = ExprTy->getAs<ReferenceType>())
6178 ExprTy = RefTy->getPointeeType().getCanonicalType();
6179
6180 // Given that an array section is considered a built-in type, we need to
6181 // do the calculation based on the length of the section instead of relying
6182 // on CGF.getTypeSize(E->getType()).
6183 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6184 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6185 OAE->getBase()->IgnoreParenImpCasts())
6186 .getCanonicalType();
6187
6188 // If there is no length associated with the expression, that means we
6189 // are using the whole length of the base.
6190 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6191 return CGF.getTypeSize(BaseTy);
6192
6193 llvm::Value *ElemSize;
6194 if (auto *PTy = BaseTy->getAs<PointerType>())
6195 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
6196 else {
6197 auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
6198 assert(ATy && "Expecting array type if not a pointer type.");
6199 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6200 }
6201
6202 // If we don't have a length at this point, that is because we have an
6203 // array section with a single element.
6204 if (!OAE->getLength())
6205 return ElemSize;
6206
6207 auto *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
6208 LengthVal =
6209 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6210 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6211 }
6212 return CGF.getTypeSize(ExprTy);
6213 }
6214
6215 /// \brief Return the corresponding bits for a given map clause modifier. Add
6216 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006217 /// map as the first one of a series of maps that relate to the same map
6218 /// expression.
George Rokos63bc9d62017-11-21 18:25:12 +00006219 uint64_t getMapTypeBits(OpenMPMapClauseKind MapType,
Samuel Antao86ace552016-04-27 22:40:57 +00006220 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
George Rokos065755d2017-11-07 18:27:04 +00006221 bool AddIsTargetParamFlag) const {
George Rokos63bc9d62017-11-21 18:25:12 +00006222 uint64_t Bits = 0u;
Samuel Antao86ace552016-04-27 22:40:57 +00006223 switch (MapType) {
6224 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006225 case OMPC_MAP_release:
6226 // alloc and release is the default behavior in the runtime library, i.e.
6227 // if we don't pass any bits alloc/release that is what the runtime is
6228 // going to do. Therefore, we don't need to signal anything for these two
6229 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006230 break;
6231 case OMPC_MAP_to:
6232 Bits = OMP_MAP_TO;
6233 break;
6234 case OMPC_MAP_from:
6235 Bits = OMP_MAP_FROM;
6236 break;
6237 case OMPC_MAP_tofrom:
6238 Bits = OMP_MAP_TO | OMP_MAP_FROM;
6239 break;
6240 case OMPC_MAP_delete:
6241 Bits = OMP_MAP_DELETE;
6242 break;
Samuel Antao86ace552016-04-27 22:40:57 +00006243 default:
6244 llvm_unreachable("Unexpected map type!");
6245 break;
6246 }
6247 if (AddPtrFlag)
George Rokos065755d2017-11-07 18:27:04 +00006248 Bits |= OMP_MAP_PTR_AND_OBJ;
6249 if (AddIsTargetParamFlag)
6250 Bits |= OMP_MAP_TARGET_PARAM;
Samuel Antao86ace552016-04-27 22:40:57 +00006251 if (MapTypeModifier == OMPC_MAP_always)
6252 Bits |= OMP_MAP_ALWAYS;
6253 return Bits;
6254 }
6255
6256 /// \brief Return true if the provided expression is a final array section. A
6257 /// final array section, is one whose length can't be proved to be one.
6258 bool isFinalArraySectionExpression(const Expr *E) const {
6259 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
6260
6261 // It is not an array section and therefore not a unity-size one.
6262 if (!OASE)
6263 return false;
6264
6265 // An array section with no colon always refer to a single element.
6266 if (OASE->getColonLoc().isInvalid())
6267 return false;
6268
6269 auto *Length = OASE->getLength();
6270
6271 // If we don't have a length we have to check if the array has size 1
6272 // for this dimension. Also, we should always expect a length if the
6273 // base type is pointer.
6274 if (!Length) {
6275 auto BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6276 OASE->getBase()->IgnoreParenImpCasts())
6277 .getCanonicalType();
6278 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
6279 return ATy->getSize().getSExtValue() != 1;
6280 // If we don't have a constant dimension length, we have to consider
6281 // the current section as having any size, so it is not necessarily
6282 // unitary. If it happen to be unity size, that's user fault.
6283 return true;
6284 }
6285
6286 // Check if the length evaluates to 1.
6287 llvm::APSInt ConstLength;
6288 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
6289 return true; // Can have more that size 1.
6290
6291 return ConstLength.getSExtValue() != 1;
6292 }
6293
6294 /// \brief Generate the base pointers, section pointers, sizes and map type
6295 /// bits for the provided map type, map modifier, and expression components.
6296 /// \a IsFirstComponent should be set to true if the provided set of
6297 /// components is the first associated with a capture.
6298 void generateInfoForComponentList(
6299 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6300 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006301 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006302 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006303 bool IsFirstComponentList, bool IsImplicit) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006304
6305 // The following summarizes what has to be generated for each map and the
6306 // types bellow. The generated information is expressed in this order:
6307 // base pointer, section pointer, size, flags
6308 // (to add to the ones that come from the map type and modifier).
6309 //
6310 // double d;
6311 // int i[100];
6312 // float *p;
6313 //
6314 // struct S1 {
6315 // int i;
6316 // float f[50];
6317 // }
6318 // struct S2 {
6319 // int i;
6320 // float f[50];
6321 // S1 s;
6322 // double *p;
6323 // struct S2 *ps;
6324 // }
6325 // S2 s;
6326 // S2 *ps;
6327 //
6328 // map(d)
6329 // &d, &d, sizeof(double), noflags
6330 //
6331 // map(i)
6332 // &i, &i, 100*sizeof(int), noflags
6333 //
6334 // map(i[1:23])
6335 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
6336 //
6337 // map(p)
6338 // &p, &p, sizeof(float*), noflags
6339 //
6340 // map(p[1:24])
6341 // p, &p[1], 24*sizeof(float), noflags
6342 //
6343 // map(s)
6344 // &s, &s, sizeof(S2), noflags
6345 //
6346 // map(s.i)
6347 // &s, &(s.i), sizeof(int), noflags
6348 //
6349 // map(s.s.f)
6350 // &s, &(s.i.f), 50*sizeof(int), noflags
6351 //
6352 // map(s.p)
6353 // &s, &(s.p), sizeof(double*), noflags
6354 //
6355 // map(s.p[:22], s.a s.b)
6356 // &s, &(s.p), sizeof(double*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006357 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006358 //
6359 // map(s.ps)
6360 // &s, &(s.ps), sizeof(S2*), noflags
6361 //
6362 // map(s.ps->s.i)
6363 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006364 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006365 //
6366 // map(s.ps->ps)
6367 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006368 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006369 //
6370 // map(s.ps->ps->ps)
6371 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006372 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
6373 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006374 //
6375 // map(s.ps->ps->s.f[:22])
6376 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006377 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
6378 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006379 //
6380 // map(ps)
6381 // &ps, &ps, sizeof(S2*), noflags
6382 //
6383 // map(ps->i)
6384 // ps, &(ps->i), sizeof(int), noflags
6385 //
6386 // map(ps->s.f)
6387 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
6388 //
6389 // map(ps->p)
6390 // ps, &(ps->p), sizeof(double*), noflags
6391 //
6392 // map(ps->p[:22])
6393 // ps, &(ps->p), sizeof(double*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006394 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006395 //
6396 // map(ps->ps)
6397 // ps, &(ps->ps), sizeof(S2*), noflags
6398 //
6399 // map(ps->ps->s.i)
6400 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006401 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006402 //
6403 // map(ps->ps->ps)
6404 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006405 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006406 //
6407 // map(ps->ps->ps->ps)
6408 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006409 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
6410 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006411 //
6412 // map(ps->ps->ps->s.f[:22])
6413 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006414 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
6415 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006416
6417 // Track if the map information being generated is the first for a capture.
6418 bool IsCaptureFirstInfo = IsFirstComponentList;
6419
6420 // Scan the components from the base to the complete expression.
6421 auto CI = Components.rbegin();
6422 auto CE = Components.rend();
6423 auto I = CI;
6424
6425 // Track if the map information being generated is the first for a list of
6426 // components.
6427 bool IsExpressionFirstInfo = true;
6428 llvm::Value *BP = nullptr;
6429
6430 if (auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
6431 // The base is the 'this' pointer. The content of the pointer is going
6432 // to be the base of the field being mapped.
6433 BP = CGF.EmitScalarExpr(ME->getBase());
6434 } else {
6435 // The base is the reference to the variable.
6436 // BP = &Var.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006437 BP = CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Samuel Antao86ace552016-04-27 22:40:57 +00006438
6439 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00006440 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00006441 // reference. References are ignored for mapping purposes.
6442 QualType Ty =
6443 I->getAssociatedDeclaration()->getType().getNonReferenceType();
6444 if (Ty->isAnyPointerType() && std::next(I) != CE) {
6445 auto PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
Samuel Antao86ace552016-04-27 22:40:57 +00006446 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
Samuel Antao403ffd42016-07-27 22:49:49 +00006447 Ty->castAs<PointerType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006448 .getPointer();
6449
6450 // We do not need to generate individual map information for the
6451 // pointer, it can be associated with the combined storage.
6452 ++I;
6453 }
6454 }
6455
George Rokos63bc9d62017-11-21 18:25:12 +00006456 uint64_t DefaultFlags = IsImplicit ? OMP_MAP_IMPLICIT : 0;
Samuel Antao86ace552016-04-27 22:40:57 +00006457 for (; I != CE; ++I) {
6458 auto Next = std::next(I);
6459
6460 // We need to generate the addresses and sizes if this is the last
6461 // component, if the component is a pointer or if it is an array section
6462 // whose length can't be proved to be one. If this is a pointer, it
6463 // becomes the base address for the following components.
6464
6465 // A final array section, is one whose length can't be proved to be one.
6466 bool IsFinalArraySection =
6467 isFinalArraySectionExpression(I->getAssociatedExpression());
6468
6469 // Get information on whether the element is a pointer. Have to do a
6470 // special treatment for array sections given that they are built-in
6471 // types.
6472 const auto *OASE =
6473 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
6474 bool IsPointer =
6475 (OASE &&
6476 OMPArraySectionExpr::getBaseOriginalType(OASE)
6477 .getCanonicalType()
6478 ->isAnyPointerType()) ||
6479 I->getAssociatedExpression()->getType()->isAnyPointerType();
6480
6481 if (Next == CE || IsPointer || IsFinalArraySection) {
6482
6483 // If this is not the last component, we expect the pointer to be
6484 // associated with an array expression or member expression.
6485 assert((Next == CE ||
6486 isa<MemberExpr>(Next->getAssociatedExpression()) ||
6487 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
6488 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
6489 "Unexpected expression");
6490
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006491 llvm::Value *LB =
6492 CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Samuel Antao86ace552016-04-27 22:40:57 +00006493 auto *Size = getExprTypeSize(I->getAssociatedExpression());
6494
Samuel Antao03a3cec2016-07-27 22:52:16 +00006495 // If we have a member expression and the current component is a
6496 // reference, we have to map the reference too. Whenever we have a
6497 // reference, the section that reference refers to is going to be a
6498 // load instruction from the storage assigned to the reference.
6499 if (isa<MemberExpr>(I->getAssociatedExpression()) &&
6500 I->getAssociatedDeclaration()->getType()->isReferenceType()) {
6501 auto *LI = cast<llvm::LoadInst>(LB);
6502 auto *RefAddr = LI->getPointerOperand();
6503
6504 BasePointers.push_back(BP);
6505 Pointers.push_back(RefAddr);
6506 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006507 Types.push_back(DefaultFlags |
6508 getMapTypeBits(
6509 /*MapType*/ OMPC_MAP_alloc,
6510 /*MapTypeModifier=*/OMPC_MAP_unknown,
6511 !IsExpressionFirstInfo, IsCaptureFirstInfo));
Samuel Antao03a3cec2016-07-27 22:52:16 +00006512 IsExpressionFirstInfo = false;
6513 IsCaptureFirstInfo = false;
6514 // The reference will be the next base address.
6515 BP = RefAddr;
6516 }
6517
6518 BasePointers.push_back(BP);
Samuel Antao86ace552016-04-27 22:40:57 +00006519 Pointers.push_back(LB);
6520 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00006521
Samuel Antao6782e942016-05-26 16:48:10 +00006522 // We need to add a pointer flag for each map that comes from the
6523 // same expression except for the first one. We also need to signal
6524 // this map is the first one that relates with the current capture
6525 // (there is a set of entries for each capture).
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006526 Types.push_back(DefaultFlags | getMapTypeBits(MapType, MapTypeModifier,
6527 !IsExpressionFirstInfo,
6528 IsCaptureFirstInfo));
Samuel Antao86ace552016-04-27 22:40:57 +00006529
6530 // If we have a final array section, we are done with this expression.
6531 if (IsFinalArraySection)
6532 break;
6533
6534 // The pointer becomes the base for the next element.
6535 if (Next != CE)
6536 BP = LB;
6537
6538 IsExpressionFirstInfo = false;
6539 IsCaptureFirstInfo = false;
Samuel Antao86ace552016-04-27 22:40:57 +00006540 }
6541 }
6542 }
6543
Samuel Antaod486f842016-05-26 16:53:38 +00006544 /// \brief Return the adjusted map modifiers if the declaration a capture
6545 /// refers to appears in a first-private clause. This is expected to be used
6546 /// only with directives that start with 'target'.
6547 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
6548 unsigned CurrentModifiers) {
6549 assert(Cap.capturesVariable() && "Expected capture by reference only!");
6550
6551 // A first private variable captured by reference will use only the
6552 // 'private ptr' and 'map to' flag. Return the right flags if the captured
6553 // declaration is known as first-private in this handler.
6554 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
George Rokos065755d2017-11-07 18:27:04 +00006555 return MappableExprsHandler::OMP_MAP_PRIVATE |
Samuel Antaod486f842016-05-26 16:53:38 +00006556 MappableExprsHandler::OMP_MAP_TO;
Alexey Bataev3f96fe62017-12-13 17:31:39 +00006557 // Reduction variable will use only the 'private ptr' and 'map to_from'
6558 // flag.
6559 if (ReductionDecls.count(Cap.getCapturedVar())) {
6560 return MappableExprsHandler::OMP_MAP_TO |
6561 MappableExprsHandler::OMP_MAP_FROM;
6562 }
Samuel Antaod486f842016-05-26 16:53:38 +00006563
6564 // We didn't modify anything.
6565 return CurrentModifiers;
6566 }
6567
Samuel Antao86ace552016-04-27 22:40:57 +00006568public:
6569 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
Samuel Antao44bcdb32016-07-28 15:31:29 +00006570 : CurDir(Dir), CGF(CGF) {
Samuel Antaod486f842016-05-26 16:53:38 +00006571 // Extract firstprivate clause information.
6572 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
6573 for (const auto *D : C->varlists())
6574 FirstPrivateDecls.insert(
6575 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
Alexey Bataev3f96fe62017-12-13 17:31:39 +00006576 for (const auto *C : Dir.getClausesOfKind<OMPReductionClause>()) {
6577 for (const auto *D : C->varlists()) {
6578 ReductionDecls.insert(
6579 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
6580 }
6581 }
Samuel Antao6890b092016-07-28 14:25:09 +00006582 // Extract device pointer clause information.
6583 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
6584 for (auto L : C->component_lists())
6585 DevPointersMap[L.first].push_back(L.second);
Samuel Antaod486f842016-05-26 16:53:38 +00006586 }
Samuel Antao86ace552016-04-27 22:40:57 +00006587
6588 /// \brief Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00006589 /// types for the extracted mappable expressions. Also, for each item that
6590 /// relates with a device pointer, a pair of the relevant declaration and
6591 /// index where it occurs is appended to the device pointers info array.
6592 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006593 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
6594 MapFlagsArrayTy &Types) const {
6595 BasePointers.clear();
6596 Pointers.clear();
6597 Sizes.clear();
6598 Types.clear();
6599
6600 struct MapInfo {
Samuel Antaocc10b852016-07-28 14:23:26 +00006601 /// Kind that defines how a device pointer has to be returned.
6602 enum ReturnPointerKind {
6603 // Don't have to return any pointer.
6604 RPK_None,
6605 // Pointer is the base of the declaration.
6606 RPK_Base,
6607 // Pointer is a member of the base declaration - 'this'
6608 RPK_Member,
6609 // Pointer is a reference and a member of the base declaration - 'this'
6610 RPK_MemberReference,
6611 };
Samuel Antao86ace552016-04-27 22:40:57 +00006612 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006613 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
6614 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
6615 ReturnPointerKind ReturnDevicePointer = RPK_None;
6616 bool IsImplicit = false;
Hans Wennborgbc1b58d2016-07-30 00:41:37 +00006617
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006618 MapInfo() = default;
Samuel Antaocc10b852016-07-28 14:23:26 +00006619 MapInfo(
6620 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
6621 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006622 ReturnPointerKind ReturnDevicePointer, bool IsImplicit)
Samuel Antaocc10b852016-07-28 14:23:26 +00006623 : Components(Components), MapType(MapType),
6624 MapTypeModifier(MapTypeModifier),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006625 ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
Samuel Antao86ace552016-04-27 22:40:57 +00006626 };
6627
6628 // We have to process the component lists that relate with the same
6629 // declaration in a single chunk so that we can generate the map flags
6630 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00006631 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00006632
6633 // Helper function to fill the information map for the different supported
6634 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00006635 auto &&InfoGen = [&Info](
6636 const ValueDecl *D,
6637 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
6638 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006639 MapInfo::ReturnPointerKind ReturnDevicePointer, bool IsImplicit) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006640 const ValueDecl *VD =
6641 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006642 Info[VD].emplace_back(L, MapType, MapModifier, ReturnDevicePointer,
6643 IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00006644 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00006645
Paul Robinson78fb1322016-08-01 22:12:46 +00006646 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006647 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006648 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006649 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006650 MapInfo::RPK_None, C->isImplicit());
6651 }
Paul Robinson15c84002016-07-29 20:46:16 +00006652 for (auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006653 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006654 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006655 MapInfo::RPK_None, C->isImplicit());
6656 }
Paul Robinson15c84002016-07-29 20:46:16 +00006657 for (auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006658 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006659 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006660 MapInfo::RPK_None, C->isImplicit());
6661 }
Samuel Antao86ace552016-04-27 22:40:57 +00006662
Samuel Antaocc10b852016-07-28 14:23:26 +00006663 // Look at the use_device_ptr clause information and mark the existing map
6664 // entries as such. If there is no map information for an entry in the
6665 // use_device_ptr list, we create one with map type 'alloc' and zero size
6666 // section. It is the user fault if that was not mapped before.
Paul Robinson78fb1322016-08-01 22:12:46 +00006667 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006668 for (auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
Samuel Antaocc10b852016-07-28 14:23:26 +00006669 for (auto L : C->component_lists()) {
6670 assert(!L.second.empty() && "Not expecting empty list of components!");
6671 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
6672 VD = cast<ValueDecl>(VD->getCanonicalDecl());
6673 auto *IE = L.second.back().getAssociatedExpression();
6674 // If the first component is a member expression, we have to look into
6675 // 'this', which maps to null in the map of map information. Otherwise
6676 // look directly for the information.
6677 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
6678
6679 // We potentially have map information for this declaration already.
6680 // Look for the first set of components that refer to it.
6681 if (It != Info.end()) {
6682 auto CI = std::find_if(
6683 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
6684 return MI.Components.back().getAssociatedDeclaration() == VD;
6685 });
6686 // If we found a map entry, signal that the pointer has to be returned
6687 // and move on to the next declaration.
6688 if (CI != It->second.end()) {
6689 CI->ReturnDevicePointer = isa<MemberExpr>(IE)
6690 ? (VD->getType()->isReferenceType()
6691 ? MapInfo::RPK_MemberReference
6692 : MapInfo::RPK_Member)
6693 : MapInfo::RPK_Base;
6694 continue;
6695 }
6696 }
6697
6698 // We didn't find any match in our map information - generate a zero
6699 // size array section.
Paul Robinson78fb1322016-08-01 22:12:46 +00006700 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Samuel Antaocc10b852016-07-28 14:23:26 +00006701 llvm::Value *Ptr =
Paul Robinson15c84002016-07-29 20:46:16 +00006702 this->CGF
6703 .EmitLoadOfLValue(this->CGF.EmitLValue(IE), SourceLocation())
Samuel Antaocc10b852016-07-28 14:23:26 +00006704 .getScalarVal();
6705 BasePointers.push_back({Ptr, VD});
6706 Pointers.push_back(Ptr);
Paul Robinson15c84002016-07-29 20:46:16 +00006707 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
George Rokos065755d2017-11-07 18:27:04 +00006708 Types.push_back(OMP_MAP_RETURN_PARAM | OMP_MAP_TARGET_PARAM);
Samuel Antaocc10b852016-07-28 14:23:26 +00006709 }
6710
Samuel Antao86ace552016-04-27 22:40:57 +00006711 for (auto &M : Info) {
6712 // We need to know when we generate information for the first component
6713 // associated with a capture, because the mapping flags depend on it.
6714 bool IsFirstComponentList = true;
6715 for (MapInfo &L : M.second) {
6716 assert(!L.Components.empty() &&
6717 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00006718
6719 // Remember the current base pointer index.
6720 unsigned CurrentBasePointersIdx = BasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00006721 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006722 this->generateInfoForComponentList(
6723 L.MapType, L.MapTypeModifier, L.Components, BasePointers, Pointers,
6724 Sizes, Types, IsFirstComponentList, L.IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00006725
6726 // If this entry relates with a device pointer, set the relevant
6727 // declaration and add the 'return pointer' flag.
6728 if (IsFirstComponentList &&
6729 L.ReturnDevicePointer != MapInfo::RPK_None) {
6730 // If the pointer is not the base of the map, we need to skip the
6731 // base. If it is a reference in a member field, we also need to skip
6732 // the map of the reference.
6733 if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
6734 ++CurrentBasePointersIdx;
6735 if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
6736 ++CurrentBasePointersIdx;
6737 }
6738 assert(BasePointers.size() > CurrentBasePointersIdx &&
6739 "Unexpected number of mapped base pointers.");
6740
6741 auto *RelevantVD = L.Components.back().getAssociatedDeclaration();
6742 assert(RelevantVD &&
6743 "No relevant declaration related with device pointer??");
6744
6745 BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
George Rokos065755d2017-11-07 18:27:04 +00006746 Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PARAM;
Samuel Antaocc10b852016-07-28 14:23:26 +00006747 }
Samuel Antao86ace552016-04-27 22:40:57 +00006748 IsFirstComponentList = false;
6749 }
6750 }
6751 }
6752
6753 /// \brief Generate the base pointers, section pointers, sizes and map types
6754 /// associated to a given capture.
6755 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00006756 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006757 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006758 MapValuesArrayTy &Pointers,
6759 MapValuesArrayTy &Sizes,
6760 MapFlagsArrayTy &Types) const {
6761 assert(!Cap->capturesVariableArrayType() &&
6762 "Not expecting to generate map info for a variable array type!");
6763
6764 BasePointers.clear();
6765 Pointers.clear();
6766 Sizes.clear();
6767 Types.clear();
6768
Samuel Antao6890b092016-07-28 14:25:09 +00006769 // We need to know when we generating information for the first component
6770 // associated with a capture, because the mapping flags depend on it.
6771 bool IsFirstComponentList = true;
6772
Samuel Antao86ace552016-04-27 22:40:57 +00006773 const ValueDecl *VD =
6774 Cap->capturesThis()
6775 ? nullptr
6776 : cast<ValueDecl>(Cap->getCapturedVar()->getCanonicalDecl());
6777
Samuel Antao6890b092016-07-28 14:25:09 +00006778 // If this declaration appears in a is_device_ptr clause we just have to
6779 // pass the pointer by value. If it is a reference to a declaration, we just
6780 // pass its value, otherwise, if it is a member expression, we need to map
6781 // 'to' the field.
6782 if (!VD) {
6783 auto It = DevPointersMap.find(VD);
6784 if (It != DevPointersMap.end()) {
6785 for (auto L : It->second) {
6786 generateInfoForComponentList(
6787 /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006788 BasePointers, Pointers, Sizes, Types, IsFirstComponentList,
6789 /*IsImplicit=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +00006790 IsFirstComponentList = false;
6791 }
6792 return;
6793 }
6794 } else if (DevPointersMap.count(VD)) {
6795 BasePointers.push_back({Arg, VD});
6796 Pointers.push_back(Arg);
6797 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
George Rokos065755d2017-11-07 18:27:04 +00006798 Types.push_back(OMP_MAP_LITERAL | OMP_MAP_TARGET_PARAM);
Samuel Antao6890b092016-07-28 14:25:09 +00006799 return;
6800 }
6801
Paul Robinson78fb1322016-08-01 22:12:46 +00006802 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006803 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao86ace552016-04-27 22:40:57 +00006804 for (auto L : C->decl_component_lists(VD)) {
6805 assert(L.first == VD &&
6806 "We got information for the wrong declaration??");
6807 assert(!L.second.empty() &&
6808 "Not expecting declaration with no component lists.");
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006809 generateInfoForComponentList(
6810 C->getMapType(), C->getMapTypeModifier(), L.second, BasePointers,
6811 Pointers, Sizes, Types, IsFirstComponentList, C->isImplicit());
Samuel Antao86ace552016-04-27 22:40:57 +00006812 IsFirstComponentList = false;
6813 }
6814
6815 return;
6816 }
Samuel Antaod486f842016-05-26 16:53:38 +00006817
6818 /// \brief Generate the default map information for a given capture \a CI,
6819 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00006820 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
6821 const FieldDecl &RI, llvm::Value *CV,
6822 MapBaseValuesArrayTy &CurBasePointers,
6823 MapValuesArrayTy &CurPointers,
6824 MapValuesArrayTy &CurSizes,
6825 MapFlagsArrayTy &CurMapTypes) {
Samuel Antaod486f842016-05-26 16:53:38 +00006826
6827 // Do the default mapping.
6828 if (CI.capturesThis()) {
6829 CurBasePointers.push_back(CV);
6830 CurPointers.push_back(CV);
6831 const PointerType *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
6832 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
6833 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00006834 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00006835 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00006836 CurBasePointers.push_back(CV);
6837 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00006838 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00006839 // We have to signal to the runtime captures passed by value that are
6840 // not pointers.
George Rokos065755d2017-11-07 18:27:04 +00006841 CurMapTypes.push_back(OMP_MAP_LITERAL);
Samuel Antaod486f842016-05-26 16:53:38 +00006842 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
6843 } else {
6844 // Pointers are implicitly mapped with a zero size and no flags
6845 // (other than first map that is added for all implicit maps).
6846 CurMapTypes.push_back(0u);
Samuel Antaod486f842016-05-26 16:53:38 +00006847 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
6848 }
6849 } else {
6850 assert(CI.capturesVariable() && "Expected captured reference.");
6851 CurBasePointers.push_back(CV);
6852 CurPointers.push_back(CV);
6853
6854 const ReferenceType *PtrTy =
6855 cast<ReferenceType>(RI.getType().getTypePtr());
6856 QualType ElementType = PtrTy->getPointeeType();
6857 CurSizes.push_back(CGF.getTypeSize(ElementType));
6858 // The default map type for a scalar/complex type is 'to' because by
6859 // default the value doesn't have to be retrieved. For an aggregate
6860 // type, the default is 'tofrom'.
Alexey Bataev3f96fe62017-12-13 17:31:39 +00006861 CurMapTypes.emplace_back(adjustMapModifiersForPrivateClauses(
6862 CI, ElementType->isAggregateType() ? (OMP_MAP_TO | OMP_MAP_FROM)
6863 : OMP_MAP_TO));
Samuel Antaod486f842016-05-26 16:53:38 +00006864 }
George Rokos065755d2017-11-07 18:27:04 +00006865 // Every default map produces a single argument which is a target parameter.
6866 CurMapTypes.back() |= OMP_MAP_TARGET_PARAM;
Samuel Antaod486f842016-05-26 16:53:38 +00006867 }
Samuel Antao86ace552016-04-27 22:40:57 +00006868};
Samuel Antaodf158d52016-04-27 22:58:19 +00006869
6870enum OpenMPOffloadingReservedDeviceIDs {
6871 /// \brief Device ID if the device was not defined, runtime should get it
6872 /// from environment variables in the spec.
6873 OMP_DEVICEID_UNDEF = -1,
6874};
6875} // anonymous namespace
6876
6877/// \brief Emit the arrays used to pass the captures and map information to the
6878/// offloading runtime library. If there is no map or capture information,
6879/// return nullptr by reference.
6880static void
Samuel Antaocc10b852016-07-28 14:23:26 +00006881emitOffloadingArrays(CodeGenFunction &CGF,
6882 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00006883 MappableExprsHandler::MapValuesArrayTy &Pointers,
6884 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00006885 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
6886 CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006887 auto &CGM = CGF.CGM;
6888 auto &Ctx = CGF.getContext();
6889
Samuel Antaocc10b852016-07-28 14:23:26 +00006890 // Reset the array information.
6891 Info.clearArrayInfo();
6892 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00006893
Samuel Antaocc10b852016-07-28 14:23:26 +00006894 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006895 // Detect if we have any capture size requiring runtime evaluation of the
6896 // size so that a constant array could be eventually used.
6897 bool hasRuntimeEvaluationCaptureSize = false;
6898 for (auto *S : Sizes)
6899 if (!isa<llvm::Constant>(S)) {
6900 hasRuntimeEvaluationCaptureSize = true;
6901 break;
6902 }
6903
Samuel Antaocc10b852016-07-28 14:23:26 +00006904 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00006905 QualType PointerArrayType =
6906 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
6907 /*IndexTypeQuals=*/0);
6908
Samuel Antaocc10b852016-07-28 14:23:26 +00006909 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006910 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00006911 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006912 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
6913
6914 // If we don't have any VLA types or other types that require runtime
6915 // evaluation, we can use a constant array for the map sizes, otherwise we
6916 // need to fill up the arrays as we do for the pointers.
6917 if (hasRuntimeEvaluationCaptureSize) {
6918 QualType SizeArrayType = Ctx.getConstantArrayType(
6919 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
6920 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00006921 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006922 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
6923 } else {
6924 // We expect all the sizes to be constant, so we collect them to create
6925 // a constant array.
6926 SmallVector<llvm::Constant *, 16> ConstSizes;
6927 for (auto S : Sizes)
6928 ConstSizes.push_back(cast<llvm::Constant>(S));
6929
6930 auto *SizesArrayInit = llvm::ConstantArray::get(
6931 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
6932 auto *SizesArrayGbl = new llvm::GlobalVariable(
6933 CGM.getModule(), SizesArrayInit->getType(),
6934 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
6935 SizesArrayInit, ".offload_sizes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00006936 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00006937 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00006938 }
6939
6940 // The map types are always constant so we don't need to generate code to
6941 // fill arrays. Instead, we create an array constant.
6942 llvm::Constant *MapTypesArrayInit =
6943 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
6944 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
6945 CGM.getModule(), MapTypesArrayInit->getType(),
6946 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
6947 MapTypesArrayInit, ".offload_maptypes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00006948 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00006949 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00006950
Samuel Antaocc10b852016-07-28 14:23:26 +00006951 for (unsigned i = 0; i < Info.NumberOfPtrs; ++i) {
6952 llvm::Value *BPVal = *BasePointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00006953 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006954 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6955 Info.BasePointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00006956 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6957 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00006958 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
6959 CGF.Builder.CreateStore(BPVal, BPAddr);
6960
Samuel Antaocc10b852016-07-28 14:23:26 +00006961 if (Info.requiresDevicePointerInfo())
6962 if (auto *DevVD = BasePointers[i].getDevicePtrDecl())
6963 Info.CaptureDeviceAddrMap.insert(std::make_pair(DevVD, BPAddr));
6964
Samuel Antaodf158d52016-04-27 22:58:19 +00006965 llvm::Value *PVal = Pointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00006966 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006967 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6968 Info.PointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00006969 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6970 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00006971 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
6972 CGF.Builder.CreateStore(PVal, PAddr);
6973
6974 if (hasRuntimeEvaluationCaptureSize) {
6975 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006976 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
6977 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006978 /*Idx0=*/0,
6979 /*Idx1=*/i);
6980 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
6981 CGF.Builder.CreateStore(
6982 CGF.Builder.CreateIntCast(Sizes[i], CGM.SizeTy, /*isSigned=*/true),
6983 SAddr);
6984 }
6985 }
6986 }
6987}
6988/// \brief Emit the arguments to be passed to the runtime library based on the
6989/// arrays of pointers, sizes and map types.
6990static void emitOffloadingArraysArgument(
6991 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
6992 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006993 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006994 auto &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00006995 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006996 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006997 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6998 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006999 /*Idx0=*/0, /*Idx1=*/0);
7000 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007001 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
7002 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007003 /*Idx0=*/0,
7004 /*Idx1=*/0);
7005 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007006 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007007 /*Idx0=*/0, /*Idx1=*/0);
7008 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
George Rokos63bc9d62017-11-21 18:25:12 +00007009 llvm::ArrayType::get(CGM.Int64Ty, Info.NumberOfPtrs),
Samuel Antaocc10b852016-07-28 14:23:26 +00007010 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007011 /*Idx0=*/0,
7012 /*Idx1=*/0);
7013 } else {
7014 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
7015 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
7016 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
7017 MapTypesArrayArg =
George Rokos63bc9d62017-11-21 18:25:12 +00007018 llvm::ConstantPointerNull::get(CGM.Int64Ty->getPointerTo());
Samuel Antaodf158d52016-04-27 22:58:19 +00007019 }
Samuel Antao86ace552016-04-27 22:40:57 +00007020}
7021
Samuel Antaobed3c462015-10-02 16:14:20 +00007022void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
7023 const OMPExecutableDirective &D,
7024 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00007025 llvm::Value *OutlinedFnID,
Samuel Antaobed3c462015-10-02 16:14:20 +00007026 const Expr *IfCond, const Expr *Device,
7027 ArrayRef<llvm::Value *> CapturedVars) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00007028 if (!CGF.HaveInsertPoint())
7029 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00007030
Samuel Antaoee8fb302016-01-06 13:42:12 +00007031 assert(OutlinedFn && "Invalid outlined function!");
7032
Samuel Antao86ace552016-04-27 22:40:57 +00007033 // Fill up the arrays with all the captured variables.
7034 MappableExprsHandler::MapValuesArrayTy KernelArgs;
Samuel Antaocc10b852016-07-28 14:23:26 +00007035 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00007036 MappableExprsHandler::MapValuesArrayTy Pointers;
7037 MappableExprsHandler::MapValuesArrayTy Sizes;
7038 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobed3c462015-10-02 16:14:20 +00007039
Samuel Antaocc10b852016-07-28 14:23:26 +00007040 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00007041 MappableExprsHandler::MapValuesArrayTy CurPointers;
7042 MappableExprsHandler::MapValuesArrayTy CurSizes;
7043 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
7044
Samuel Antaod486f842016-05-26 16:53:38 +00007045 // Get mappable expression information.
7046 MappableExprsHandler MEHandler(D, CGF);
Samuel Antaobed3c462015-10-02 16:14:20 +00007047
7048 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
7049 auto RI = CS.getCapturedRecordDecl()->field_begin();
Samuel Antaobed3c462015-10-02 16:14:20 +00007050 auto CV = CapturedVars.begin();
7051 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
7052 CE = CS.capture_end();
7053 CI != CE; ++CI, ++RI, ++CV) {
Samuel Antao86ace552016-04-27 22:40:57 +00007054 CurBasePointers.clear();
7055 CurPointers.clear();
7056 CurSizes.clear();
7057 CurMapTypes.clear();
7058
7059 // VLA sizes are passed to the outlined region by copy and do not have map
7060 // information associated.
Samuel Antaobed3c462015-10-02 16:14:20 +00007061 if (CI->capturesVariableArrayType()) {
Samuel Antao86ace552016-04-27 22:40:57 +00007062 CurBasePointers.push_back(*CV);
7063 CurPointers.push_back(*CV);
7064 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
Samuel Antao4af1b7b2015-12-02 17:44:43 +00007065 // Copy to the device as an argument. No need to retrieve it.
George Rokos065755d2017-11-07 18:27:04 +00007066 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_LITERAL |
7067 MappableExprsHandler::OMP_MAP_TARGET_PARAM);
Samuel Antaobed3c462015-10-02 16:14:20 +00007068 } else {
Samuel Antao86ace552016-04-27 22:40:57 +00007069 // If we have any information in the map clause, we use it, otherwise we
7070 // just do a default mapping.
Samuel Antao6890b092016-07-28 14:25:09 +00007071 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007072 CurSizes, CurMapTypes);
Samuel Antaod486f842016-05-26 16:53:38 +00007073 if (CurBasePointers.empty())
7074 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
7075 CurPointers, CurSizes, CurMapTypes);
Samuel Antaobed3c462015-10-02 16:14:20 +00007076 }
Samuel Antao86ace552016-04-27 22:40:57 +00007077 // We expect to have at least an element of information for this capture.
7078 assert(!CurBasePointers.empty() && "Non-existing map pointer for capture!");
7079 assert(CurBasePointers.size() == CurPointers.size() &&
7080 CurBasePointers.size() == CurSizes.size() &&
7081 CurBasePointers.size() == CurMapTypes.size() &&
7082 "Inconsistent map information sizes!");
Samuel Antaobed3c462015-10-02 16:14:20 +00007083
Samuel Antao86ace552016-04-27 22:40:57 +00007084 // The kernel args are always the first elements of the base pointers
7085 // associated with a capture.
Samuel Antaocc10b852016-07-28 14:23:26 +00007086 KernelArgs.push_back(*CurBasePointers.front());
Samuel Antao86ace552016-04-27 22:40:57 +00007087 // We need to append the results of this capture to what we already have.
7088 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
7089 Pointers.append(CurPointers.begin(), CurPointers.end());
7090 Sizes.append(CurSizes.begin(), CurSizes.end());
7091 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
Samuel Antaobed3c462015-10-02 16:14:20 +00007092 }
7093
Samuel Antaobed3c462015-10-02 16:14:20 +00007094 // Fill up the pointer arrays and transfer execution to the device.
Alexey Bataev2a007e02017-10-02 14:20:58 +00007095 auto &&ThenGen = [this, &BasePointers, &Pointers, &Sizes, &MapTypes, Device,
7096 OutlinedFn, OutlinedFnID, &D,
7097 &KernelArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007098 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antaodf158d52016-04-27 22:58:19 +00007099 // Emit the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007100 TargetDataInfo Info;
7101 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
7102 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
7103 Info.PointersArray, Info.SizesArray,
7104 Info.MapTypesArray, Info);
Samuel Antaobed3c462015-10-02 16:14:20 +00007105
7106 // On top of the arrays that were filled up, the target offloading call
7107 // takes as arguments the device id as well as the host pointer. The host
7108 // pointer is used by the runtime library to identify the current target
7109 // region, so it only has to be unique and not necessarily point to
7110 // anything. It could be the pointer to the outlined function that
7111 // implements the target region, but we aren't using that so that the
7112 // compiler doesn't need to keep that, and could therefore inline the host
7113 // function if proven worthwhile during optimization.
7114
Samuel Antaoee8fb302016-01-06 13:42:12 +00007115 // From this point on, we need to have an ID of the target region defined.
7116 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00007117
7118 // Emit device ID if any.
7119 llvm::Value *DeviceID;
George Rokos63bc9d62017-11-21 18:25:12 +00007120 if (Device) {
Samuel Antaobed3c462015-10-02 16:14:20 +00007121 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007122 CGF.Int64Ty, /*isSigned=*/true);
7123 } else {
7124 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7125 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007126
Samuel Antaodf158d52016-04-27 22:58:19 +00007127 // Emit the number of elements in the offloading arrays.
7128 llvm::Value *PointerNum = CGF.Builder.getInt32(BasePointers.size());
7129
Samuel Antaob68e2db2016-03-03 16:20:23 +00007130 // Return value of the runtime offloading call.
7131 llvm::Value *Return;
7132
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007133 auto *NumTeams = emitNumTeamsForTargetDirective(RT, CGF, D);
7134 auto *NumThreads = emitNumThreadsForTargetDirective(RT, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007135
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007136 bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007137 // The target region is an outlined function launched by the runtime
7138 // via calls __tgt_target() or __tgt_target_teams().
7139 //
7140 // __tgt_target() launches a target region with one team and one thread,
7141 // executing a serial region. This master thread may in turn launch
7142 // more threads within its team upon encountering a parallel region,
7143 // however, no additional teams can be launched on the device.
7144 //
7145 // __tgt_target_teams() launches a target region with one or more teams,
7146 // each with one or more threads. This call is required for target
7147 // constructs such as:
7148 // 'target teams'
7149 // 'target' / 'teams'
7150 // 'target teams distribute parallel for'
7151 // 'target parallel'
7152 // and so on.
7153 //
7154 // Note that on the host and CPU targets, the runtime implementation of
7155 // these calls simply call the outlined function without forking threads.
7156 // The outlined functions themselves have runtime calls to
7157 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
7158 // the compiler in emitTeamsCall() and emitParallelCall().
7159 //
7160 // In contrast, on the NVPTX target, the implementation of
7161 // __tgt_target_teams() launches a GPU kernel with the requested number
7162 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00007163 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007164 // If we have NumTeams defined this means that we have an enclosed teams
7165 // region. Therefore we also expect to have NumThreads defined. These two
7166 // values should be defined in the presence of a teams directive,
7167 // regardless of having any clauses associated. If the user is using teams
7168 // but no clauses, these two values will be the default that should be
7169 // passed to the runtime library - a 32-bit integer with the value zero.
7170 assert(NumThreads && "Thread limit expression should be available along "
7171 "with number of teams.");
Samuel Antaob68e2db2016-03-03 16:20:23 +00007172 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007173 DeviceID, OutlinedFnID,
7174 PointerNum, Info.BasePointersArray,
7175 Info.PointersArray, Info.SizesArray,
7176 Info.MapTypesArray, NumTeams,
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007177 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00007178 Return = CGF.EmitRuntimeCall(
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007179 RT.createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_teams_nowait
7180 : OMPRTL__tgt_target_teams),
7181 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007182 } else {
7183 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007184 DeviceID, OutlinedFnID,
7185 PointerNum, Info.BasePointersArray,
7186 Info.PointersArray, Info.SizesArray,
7187 Info.MapTypesArray};
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007188 Return = CGF.EmitRuntimeCall(
7189 RT.createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_nowait
7190 : OMPRTL__tgt_target),
7191 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007192 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007193
Alexey Bataev2a007e02017-10-02 14:20:58 +00007194 // Check the error code and execute the host version if required.
7195 llvm::BasicBlock *OffloadFailedBlock =
7196 CGF.createBasicBlock("omp_offload.failed");
7197 llvm::BasicBlock *OffloadContBlock =
7198 CGF.createBasicBlock("omp_offload.cont");
7199 llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
7200 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
7201
7202 CGF.EmitBlock(OffloadFailedBlock);
7203 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, KernelArgs);
7204 CGF.EmitBranch(OffloadContBlock);
7205
7206 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00007207 };
7208
Samuel Antaoee8fb302016-01-06 13:42:12 +00007209 // Notify that the host version must be executed.
Alexey Bataev2a007e02017-10-02 14:20:58 +00007210 auto &&ElseGen = [this, &D, OutlinedFn, &KernelArgs](CodeGenFunction &CGF,
7211 PrePostActionTy &) {
7212 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn,
7213 KernelArgs);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007214 };
7215
7216 // If we have a target function ID it means that we need to support
7217 // offloading, otherwise, just execute on the host. We need to execute on host
7218 // regardless of the conditional in the if clause if, e.g., the user do not
7219 // specify target triples.
7220 if (OutlinedFnID) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007221 if (IfCond)
Samuel Antaoee8fb302016-01-06 13:42:12 +00007222 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007223 else {
7224 RegionCodeGenTy ThenRCG(ThenGen);
7225 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007226 }
7227 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007228 RegionCodeGenTy ElseRCG(ElseGen);
7229 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007230 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007231}
Samuel Antaoee8fb302016-01-06 13:42:12 +00007232
7233void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
7234 StringRef ParentName) {
7235 if (!S)
7236 return;
7237
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007238 // Codegen OMP target directives that offload compute to the device.
7239 bool requiresDeviceCodegen =
7240 isa<OMPExecutableDirective>(S) &&
7241 isOpenMPTargetExecutionDirective(
7242 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00007243
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007244 if (requiresDeviceCodegen) {
7245 auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007246 unsigned DeviceID;
7247 unsigned FileID;
7248 unsigned Line;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007249 getTargetEntryUniqueInfo(CGM.getContext(), E.getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00007250 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007251
7252 // Is this a target region that should not be emitted as an entry point? If
7253 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00007254 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
7255 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007256 return;
7257
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007258 switch (S->getStmtClass()) {
7259 case Stmt::OMPTargetDirectiveClass:
7260 CodeGenFunction::EmitOMPTargetDeviceFunction(
7261 CGM, ParentName, cast<OMPTargetDirective>(*S));
7262 break;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00007263 case Stmt::OMPTargetParallelDirectiveClass:
7264 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
7265 CGM, ParentName, cast<OMPTargetParallelDirective>(*S));
7266 break;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00007267 case Stmt::OMPTargetTeamsDirectiveClass:
7268 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
7269 CGM, ParentName, cast<OMPTargetTeamsDirective>(*S));
7270 break;
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007271 case Stmt::OMPTargetTeamsDistributeDirectiveClass:
7272 CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
7273 CGM, ParentName, cast<OMPTargetTeamsDistributeDirective>(*S));
7274 break;
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007275 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
7276 CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
7277 CGM, ParentName, cast<OMPTargetTeamsDistributeSimdDirective>(*S));
7278 break;
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007279 case Stmt::OMPTargetParallelForDirectiveClass:
7280 CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
7281 CGM, ParentName, cast<OMPTargetParallelForDirective>(*S));
7282 break;
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007283 case Stmt::OMPTargetParallelForSimdDirectiveClass:
7284 CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
7285 CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(*S));
7286 break;
Alexey Bataevf8365372017-11-17 17:57:25 +00007287 case Stmt::OMPTargetSimdDirectiveClass:
7288 CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
7289 CGM, ParentName, cast<OMPTargetSimdDirective>(*S));
7290 break;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007291 default:
7292 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
7293 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00007294 return;
7295 }
7296
7297 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
Samuel Antaoe49645c2016-05-08 06:43:56 +00007298 if (!E->hasAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00007299 return;
7300
7301 scanForTargetRegionsFunctions(
7302 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
7303 ParentName);
7304 return;
7305 }
7306
7307 // If this is a lambda function, look into its body.
7308 if (auto *L = dyn_cast<LambdaExpr>(S))
7309 S = L->getBody();
7310
7311 // Keep looking for target regions recursively.
7312 for (auto *II : S->children())
7313 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007314}
7315
7316bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
7317 auto &FD = *cast<FunctionDecl>(GD.getDecl());
7318
7319 // If emitting code for the host, we do not process FD here. Instead we do
7320 // the normal code generation.
7321 if (!CGM.getLangOpts().OpenMPIsDevice)
7322 return false;
7323
7324 // Try to detect target regions in the function.
7325 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
7326
Samuel Antao4b75b872016-12-12 19:26:31 +00007327 // We should not emit any function other that the ones created during the
Samuel Antaoee8fb302016-01-06 13:42:12 +00007328 // scanning. Therefore, we signal that this function is completely dealt
7329 // with.
7330 return true;
7331}
7332
7333bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
7334 if (!CGM.getLangOpts().OpenMPIsDevice)
7335 return false;
7336
7337 // Check if there are Ctors/Dtors in this declaration and look for target
7338 // regions in it. We use the complete variant to produce the kernel name
7339 // mangling.
7340 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
7341 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
7342 for (auto *Ctor : RD->ctors()) {
7343 StringRef ParentName =
7344 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
7345 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
7346 }
7347 auto *Dtor = RD->getDestructor();
7348 if (Dtor) {
7349 StringRef ParentName =
7350 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
7351 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
7352 }
7353 }
7354
Gheorghe-Teodor Bercea47633db2017-06-13 15:35:27 +00007355 // If we are in target mode, we do not emit any global (declare target is not
Samuel Antaoee8fb302016-01-06 13:42:12 +00007356 // implemented yet). Therefore we signal that GD was processed in this case.
7357 return true;
7358}
7359
7360bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
7361 auto *VD = GD.getDecl();
7362 if (isa<FunctionDecl>(VD))
7363 return emitTargetFunctions(GD);
7364
7365 return emitTargetGlobalVariable(GD);
7366}
7367
7368llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
7369 // If we have offloading in the current module, we need to emit the entries
7370 // now and register the offloading descriptor.
7371 createOffloadEntriesAndInfoMetadata();
7372
7373 // Create and register the offloading binary descriptors. This is the main
7374 // entity that captures all the information about offloading in the current
7375 // compilation unit.
7376 return createOffloadingBinaryDescriptorRegistration();
7377}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007378
7379void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
7380 const OMPExecutableDirective &D,
7381 SourceLocation Loc,
7382 llvm::Value *OutlinedFn,
7383 ArrayRef<llvm::Value *> CapturedVars) {
7384 if (!CGF.HaveInsertPoint())
7385 return;
7386
7387 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7388 CodeGenFunction::RunCleanupsScope Scope(CGF);
7389
7390 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
7391 llvm::Value *Args[] = {
7392 RTLoc,
7393 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
7394 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
7395 llvm::SmallVector<llvm::Value *, 16> RealArgs;
7396 RealArgs.append(std::begin(Args), std::end(Args));
7397 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
7398
7399 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
7400 CGF.EmitRuntimeCall(RTLFn, RealArgs);
7401}
7402
7403void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00007404 const Expr *NumTeams,
7405 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007406 SourceLocation Loc) {
7407 if (!CGF.HaveInsertPoint())
7408 return;
7409
7410 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7411
Carlo Bertollic6872252016-04-04 15:55:02 +00007412 llvm::Value *NumTeamsVal =
7413 (NumTeams)
7414 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
7415 CGF.CGM.Int32Ty, /* isSigned = */ true)
7416 : CGF.Builder.getInt32(0);
7417
7418 llvm::Value *ThreadLimitVal =
7419 (ThreadLimit)
7420 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
7421 CGF.CGM.Int32Ty, /* isSigned = */ true)
7422 : CGF.Builder.getInt32(0);
7423
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007424 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00007425 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
7426 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007427 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
7428 PushNumTeamsArgs);
7429}
Samuel Antaodf158d52016-04-27 22:58:19 +00007430
Samuel Antaocc10b852016-07-28 14:23:26 +00007431void CGOpenMPRuntime::emitTargetDataCalls(
7432 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7433 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007434 if (!CGF.HaveInsertPoint())
7435 return;
7436
Samuel Antaocc10b852016-07-28 14:23:26 +00007437 // Action used to replace the default codegen action and turn privatization
7438 // off.
7439 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00007440
7441 // Generate the code for the opening of the data environment. Capture all the
7442 // arguments of the runtime call by reference because they are used in the
7443 // closing of the region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007444 auto &&BeginThenGen = [this, &D, Device, &Info,
7445 &CodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007446 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00007447 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00007448 MappableExprsHandler::MapValuesArrayTy Pointers;
7449 MappableExprsHandler::MapValuesArrayTy Sizes;
7450 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7451
7452 // Get map clause information.
7453 MappableExprsHandler MCHandler(D, CGF);
7454 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00007455
7456 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00007457 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007458
7459 llvm::Value *BasePointersArrayArg = nullptr;
7460 llvm::Value *PointersArrayArg = nullptr;
7461 llvm::Value *SizesArrayArg = nullptr;
7462 llvm::Value *MapTypesArrayArg = nullptr;
7463 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007464 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007465
7466 // Emit device ID if any.
7467 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00007468 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007469 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007470 CGF.Int64Ty, /*isSigned=*/true);
7471 } else {
7472 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7473 }
Samuel Antaodf158d52016-04-27 22:58:19 +00007474
7475 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007476 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007477
7478 llvm::Value *OffloadingArgs[] = {
7479 DeviceID, PointerNum, BasePointersArrayArg,
7480 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007481 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_begin),
Samuel Antaodf158d52016-04-27 22:58:19 +00007482 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00007483
7484 // If device pointer privatization is required, emit the body of the region
7485 // here. It will have to be duplicated: with and without privatization.
7486 if (!Info.CaptureDeviceAddrMap.empty())
7487 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007488 };
7489
7490 // Generate code for the closing of the data region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007491 auto &&EndThenGen = [this, Device, &Info](CodeGenFunction &CGF,
7492 PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007493 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00007494
7495 llvm::Value *BasePointersArrayArg = nullptr;
7496 llvm::Value *PointersArrayArg = nullptr;
7497 llvm::Value *SizesArrayArg = nullptr;
7498 llvm::Value *MapTypesArrayArg = nullptr;
7499 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007500 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007501
7502 // Emit device ID if any.
7503 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00007504 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007505 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007506 CGF.Int64Ty, /*isSigned=*/true);
7507 } else {
7508 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7509 }
Samuel Antaodf158d52016-04-27 22:58:19 +00007510
7511 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007512 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007513
7514 llvm::Value *OffloadingArgs[] = {
7515 DeviceID, PointerNum, BasePointersArrayArg,
7516 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007517 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_end),
Samuel Antaodf158d52016-04-27 22:58:19 +00007518 OffloadingArgs);
7519 };
7520
Samuel Antaocc10b852016-07-28 14:23:26 +00007521 // If we need device pointer privatization, we need to emit the body of the
7522 // region with no privatization in the 'else' branch of the conditional.
7523 // Otherwise, we don't have to do anything.
7524 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
7525 PrePostActionTy &) {
7526 if (!Info.CaptureDeviceAddrMap.empty()) {
7527 CodeGen.setAction(NoPrivAction);
7528 CodeGen(CGF);
7529 }
7530 };
7531
7532 // We don't have to do anything to close the region if the if clause evaluates
7533 // to false.
7534 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00007535
7536 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007537 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007538 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007539 RegionCodeGenTy RCG(BeginThenGen);
7540 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007541 }
7542
Samuel Antaocc10b852016-07-28 14:23:26 +00007543 // If we don't require privatization of device pointers, we emit the body in
7544 // between the runtime calls. This avoids duplicating the body code.
7545 if (Info.CaptureDeviceAddrMap.empty()) {
7546 CodeGen.setAction(NoPrivAction);
7547 CodeGen(CGF);
7548 }
Samuel Antaodf158d52016-04-27 22:58:19 +00007549
7550 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007551 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007552 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007553 RegionCodeGenTy RCG(EndThenGen);
7554 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007555 }
7556}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007557
Samuel Antao8d2d7302016-05-26 18:30:22 +00007558void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00007559 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7560 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007561 if (!CGF.HaveInsertPoint())
7562 return;
7563
Samuel Antao8dd66282016-04-27 23:14:30 +00007564 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00007565 isa<OMPTargetExitDataDirective>(D) ||
7566 isa<OMPTargetUpdateDirective>(D)) &&
7567 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00007568
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007569 CodeGenFunction::OMPTargetDataInfo InputInfo;
7570 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007571 // Generate the code for the opening of the data environment.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007572 auto &&ThenGen = [this, &D, Device, &InputInfo,
7573 &MapTypesArray](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007574 // Emit device ID if any.
7575 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00007576 if (Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007577 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007578 CGF.Int64Ty, /*isSigned=*/true);
7579 } else {
7580 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7581 }
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007582
7583 // Emit the number of elements in the offloading arrays.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007584 llvm::Constant *PointerNum =
7585 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007586
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007587 llvm::Value *OffloadingArgs[] = {DeviceID,
7588 PointerNum,
7589 InputInfo.BasePointersArray.getPointer(),
7590 InputInfo.PointersArray.getPointer(),
7591 InputInfo.SizesArray.getPointer(),
7592 MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00007593
Samuel Antao8d2d7302016-05-26 18:30:22 +00007594 // Select the right runtime function call for each expected standalone
7595 // directive.
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00007596 const bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Samuel Antao8d2d7302016-05-26 18:30:22 +00007597 OpenMPRTLFunction RTLFn;
7598 switch (D.getDirectiveKind()) {
7599 default:
7600 llvm_unreachable("Unexpected standalone target data directive.");
7601 break;
7602 case OMPD_target_enter_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00007603 RTLFn = HasNowait ? OMPRTL__tgt_target_data_begin_nowait
7604 : OMPRTL__tgt_target_data_begin;
Samuel Antao8d2d7302016-05-26 18:30:22 +00007605 break;
7606 case OMPD_target_exit_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00007607 RTLFn = HasNowait ? OMPRTL__tgt_target_data_end_nowait
7608 : OMPRTL__tgt_target_data_end;
Samuel Antao8d2d7302016-05-26 18:30:22 +00007609 break;
7610 case OMPD_target_update:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00007611 RTLFn = HasNowait ? OMPRTL__tgt_target_data_update_nowait
7612 : OMPRTL__tgt_target_data_update;
Samuel Antao8d2d7302016-05-26 18:30:22 +00007613 break;
7614 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007615 CGF.EmitRuntimeCall(createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007616 };
7617
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007618 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray](
7619 CodeGenFunction &CGF, PrePostActionTy &) {
7620 // Fill up the arrays with all the mapped variables.
7621 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
7622 MappableExprsHandler::MapValuesArrayTy Pointers;
7623 MappableExprsHandler::MapValuesArrayTy Sizes;
7624 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007625
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007626 // Get map clause information.
7627 MappableExprsHandler MEHandler(D, CGF);
7628 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
7629
7630 TargetDataInfo Info;
7631 // Fill up the arrays and create the arguments.
7632 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
7633 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
7634 Info.PointersArray, Info.SizesArray,
7635 Info.MapTypesArray, Info);
7636 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
7637 InputInfo.BasePointersArray =
7638 Address(Info.BasePointersArray, CGM.getPointerAlign());
7639 InputInfo.PointersArray =
7640 Address(Info.PointersArray, CGM.getPointerAlign());
7641 InputInfo.SizesArray =
7642 Address(Info.SizesArray, CGM.getPointerAlign());
7643 MapTypesArray = Info.MapTypesArray;
7644 if (D.hasClausesOfKind<OMPDependClause>())
7645 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
7646 else
7647 emitInlinedDirective(CGF, OMPD_target_update, ThenGen);
7648 };
7649
7650 if (IfCond)
7651 emitOMPIfClause(CGF, IfCond, TargetThenGen,
7652 [](CodeGenFunction &CGF, PrePostActionTy &) {});
7653 else {
7654 RegionCodeGenTy ThenRCG(TargetThenGen);
7655 ThenRCG(CGF);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007656 }
7657}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007658
7659namespace {
7660 /// Kind of parameter in a function with 'declare simd' directive.
7661 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
7662 /// Attribute set of the parameter.
7663 struct ParamAttrTy {
7664 ParamKindTy Kind = Vector;
7665 llvm::APSInt StrideOrArg;
7666 llvm::APSInt Alignment;
7667 };
7668} // namespace
7669
7670static unsigned evaluateCDTSize(const FunctionDecl *FD,
7671 ArrayRef<ParamAttrTy> ParamAttrs) {
7672 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
7673 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
7674 // of that clause. The VLEN value must be power of 2.
7675 // In other case the notion of the function`s "characteristic data type" (CDT)
7676 // is used to compute the vector length.
7677 // CDT is defined in the following order:
7678 // a) For non-void function, the CDT is the return type.
7679 // b) If the function has any non-uniform, non-linear parameters, then the
7680 // CDT is the type of the first such parameter.
7681 // c) If the CDT determined by a) or b) above is struct, union, or class
7682 // type which is pass-by-value (except for the type that maps to the
7683 // built-in complex data type), the characteristic data type is int.
7684 // d) If none of the above three cases is applicable, the CDT is int.
7685 // The VLEN is then determined based on the CDT and the size of vector
7686 // register of that ISA for which current vector version is generated. The
7687 // VLEN is computed using the formula below:
7688 // VLEN = sizeof(vector_register) / sizeof(CDT),
7689 // where vector register size specified in section 3.2.1 Registers and the
7690 // Stack Frame of original AMD64 ABI document.
7691 QualType RetType = FD->getReturnType();
7692 if (RetType.isNull())
7693 return 0;
7694 ASTContext &C = FD->getASTContext();
7695 QualType CDT;
7696 if (!RetType.isNull() && !RetType->isVoidType())
7697 CDT = RetType;
7698 else {
7699 unsigned Offset = 0;
7700 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
7701 if (ParamAttrs[Offset].Kind == Vector)
7702 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
7703 ++Offset;
7704 }
7705 if (CDT.isNull()) {
7706 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
7707 if (ParamAttrs[I + Offset].Kind == Vector) {
7708 CDT = FD->getParamDecl(I)->getType();
7709 break;
7710 }
7711 }
7712 }
7713 }
7714 if (CDT.isNull())
7715 CDT = C.IntTy;
7716 CDT = CDT->getCanonicalTypeUnqualified();
7717 if (CDT->isRecordType() || CDT->isUnionType())
7718 CDT = C.IntTy;
7719 return C.getTypeSize(CDT);
7720}
7721
7722static void
7723emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00007724 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007725 ArrayRef<ParamAttrTy> ParamAttrs,
7726 OMPDeclareSimdDeclAttr::BranchStateTy State) {
7727 struct ISADataTy {
7728 char ISA;
7729 unsigned VecRegSize;
7730 };
7731 ISADataTy ISAData[] = {
7732 {
7733 'b', 128
7734 }, // SSE
7735 {
7736 'c', 256
7737 }, // AVX
7738 {
7739 'd', 256
7740 }, // AVX2
7741 {
7742 'e', 512
7743 }, // AVX512
7744 };
7745 llvm::SmallVector<char, 2> Masked;
7746 switch (State) {
7747 case OMPDeclareSimdDeclAttr::BS_Undefined:
7748 Masked.push_back('N');
7749 Masked.push_back('M');
7750 break;
7751 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
7752 Masked.push_back('N');
7753 break;
7754 case OMPDeclareSimdDeclAttr::BS_Inbranch:
7755 Masked.push_back('M');
7756 break;
7757 }
7758 for (auto Mask : Masked) {
7759 for (auto &Data : ISAData) {
7760 SmallString<256> Buffer;
7761 llvm::raw_svector_ostream Out(Buffer);
7762 Out << "_ZGV" << Data.ISA << Mask;
7763 if (!VLENVal) {
7764 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
7765 evaluateCDTSize(FD, ParamAttrs));
7766 } else
7767 Out << VLENVal;
7768 for (auto &ParamAttr : ParamAttrs) {
7769 switch (ParamAttr.Kind){
7770 case LinearWithVarStride:
7771 Out << 's' << ParamAttr.StrideOrArg;
7772 break;
7773 case Linear:
7774 Out << 'l';
7775 if (!!ParamAttr.StrideOrArg)
7776 Out << ParamAttr.StrideOrArg;
7777 break;
7778 case Uniform:
7779 Out << 'u';
7780 break;
7781 case Vector:
7782 Out << 'v';
7783 break;
7784 }
7785 if (!!ParamAttr.Alignment)
7786 Out << 'a' << ParamAttr.Alignment;
7787 }
7788 Out << '_' << Fn->getName();
7789 Fn->addFnAttr(Out.str());
7790 }
7791 }
7792}
7793
7794void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
7795 llvm::Function *Fn) {
7796 ASTContext &C = CGM.getContext();
7797 FD = FD->getCanonicalDecl();
7798 // Map params to their positions in function decl.
7799 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
7800 if (isa<CXXMethodDecl>(FD))
7801 ParamPositions.insert({FD, 0});
7802 unsigned ParamPos = ParamPositions.size();
David Majnemer59f77922016-06-24 04:05:48 +00007803 for (auto *P : FD->parameters()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007804 ParamPositions.insert({P->getCanonicalDecl(), ParamPos});
7805 ++ParamPos;
7806 }
7807 for (auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
7808 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
7809 // Mark uniform parameters.
7810 for (auto *E : Attr->uniforms()) {
7811 E = E->IgnoreParenImpCasts();
7812 unsigned Pos;
7813 if (isa<CXXThisExpr>(E))
7814 Pos = ParamPositions[FD];
7815 else {
7816 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7817 ->getCanonicalDecl();
7818 Pos = ParamPositions[PVD];
7819 }
7820 ParamAttrs[Pos].Kind = Uniform;
7821 }
7822 // Get alignment info.
7823 auto NI = Attr->alignments_begin();
7824 for (auto *E : Attr->aligneds()) {
7825 E = E->IgnoreParenImpCasts();
7826 unsigned Pos;
7827 QualType ParmTy;
7828 if (isa<CXXThisExpr>(E)) {
7829 Pos = ParamPositions[FD];
7830 ParmTy = E->getType();
7831 } else {
7832 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7833 ->getCanonicalDecl();
7834 Pos = ParamPositions[PVD];
7835 ParmTy = PVD->getType();
7836 }
7837 ParamAttrs[Pos].Alignment =
7838 (*NI) ? (*NI)->EvaluateKnownConstInt(C)
7839 : llvm::APSInt::getUnsigned(
7840 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
7841 .getQuantity());
7842 ++NI;
7843 }
7844 // Mark linear parameters.
7845 auto SI = Attr->steps_begin();
7846 auto MI = Attr->modifiers_begin();
7847 for (auto *E : Attr->linears()) {
7848 E = E->IgnoreParenImpCasts();
7849 unsigned Pos;
7850 if (isa<CXXThisExpr>(E))
7851 Pos = ParamPositions[FD];
7852 else {
7853 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7854 ->getCanonicalDecl();
7855 Pos = ParamPositions[PVD];
7856 }
7857 auto &ParamAttr = ParamAttrs[Pos];
7858 ParamAttr.Kind = Linear;
7859 if (*SI) {
7860 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
7861 Expr::SE_AllowSideEffects)) {
7862 if (auto *DRE = cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
7863 if (auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
7864 ParamAttr.Kind = LinearWithVarStride;
7865 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
7866 ParamPositions[StridePVD->getCanonicalDecl()]);
7867 }
7868 }
7869 }
7870 }
7871 ++SI;
7872 ++MI;
7873 }
7874 llvm::APSInt VLENVal;
7875 if (const Expr *VLEN = Attr->getSimdlen())
7876 VLENVal = VLEN->EvaluateKnownConstInt(C);
7877 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
7878 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
7879 CGM.getTriple().getArch() == llvm::Triple::x86_64)
7880 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
7881 }
7882}
Alexey Bataev8b427062016-05-25 12:36:08 +00007883
7884namespace {
7885/// Cleanup action for doacross support.
7886class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
7887public:
7888 static const int DoacrossFinArgs = 2;
7889
7890private:
7891 llvm::Value *RTLFn;
7892 llvm::Value *Args[DoacrossFinArgs];
7893
7894public:
7895 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
7896 : RTLFn(RTLFn) {
7897 assert(CallArgs.size() == DoacrossFinArgs);
7898 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
7899 }
7900 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
7901 if (!CGF.HaveInsertPoint())
7902 return;
7903 CGF.EmitRuntimeCall(RTLFn, Args);
7904 }
7905};
7906} // namespace
7907
7908void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
7909 const OMPLoopDirective &D) {
7910 if (!CGF.HaveInsertPoint())
7911 return;
7912
7913 ASTContext &C = CGM.getContext();
7914 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
7915 RecordDecl *RD;
7916 if (KmpDimTy.isNull()) {
7917 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
7918 // kmp_int64 lo; // lower
7919 // kmp_int64 up; // upper
7920 // kmp_int64 st; // stride
7921 // };
7922 RD = C.buildImplicitRecord("kmp_dim");
7923 RD->startDefinition();
7924 addFieldToRecordDecl(C, RD, Int64Ty);
7925 addFieldToRecordDecl(C, RD, Int64Ty);
7926 addFieldToRecordDecl(C, RD, Int64Ty);
7927 RD->completeDefinition();
7928 KmpDimTy = C.getRecordType(RD);
7929 } else
7930 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
7931
7932 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
7933 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
7934 enum { LowerFD = 0, UpperFD, StrideFD };
7935 // Fill dims with data.
7936 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
7937 // dims.upper = num_iterations;
7938 LValue UpperLVal =
7939 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
7940 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
7941 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
7942 Int64Ty, D.getNumIterations()->getExprLoc());
7943 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
7944 // dims.stride = 1;
7945 LValue StrideLVal =
7946 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
7947 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
7948 StrideLVal);
7949
7950 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
7951 // kmp_int32 num_dims, struct kmp_dim * dims);
7952 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
7953 getThreadID(CGF, D.getLocStart()),
7954 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
7955 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7956 DimsAddr.getPointer(), CGM.VoidPtrTy)};
7957
7958 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
7959 CGF.EmitRuntimeCall(RTLFn, Args);
7960 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
7961 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
7962 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
7963 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
7964 llvm::makeArrayRef(FiniArgs));
7965}
7966
7967void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
7968 const OMPDependClause *C) {
7969 QualType Int64Ty =
7970 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
7971 const Expr *CounterVal = C->getCounterValue();
7972 assert(CounterVal);
7973 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
7974 CounterVal->getType(), Int64Ty,
7975 CounterVal->getExprLoc());
7976 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
7977 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
7978 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
7979 getThreadID(CGF, C->getLocStart()),
7980 CntAddr.getPointer()};
7981 llvm::Value *RTLFn;
7982 if (C->getDependencyKind() == OMPC_DEPEND_source)
7983 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
7984 else {
7985 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
7986 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
7987 }
7988 CGF.EmitRuntimeCall(RTLFn, Args);
7989}
7990
Alexey Bataev3c595a62017-08-14 15:01:03 +00007991void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, llvm::Value *Callee,
7992 ArrayRef<llvm::Value *> Args,
7993 SourceLocation Loc) const {
7994 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
7995
7996 if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007997 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00007998 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007999 return;
8000 }
8001 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00008002 CGF.EmitRuntimeCall(Callee, Args);
8003}
8004
8005void CGOpenMPRuntime::emitOutlinedFunctionCall(
8006 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
8007 ArrayRef<llvm::Value *> Args) const {
8008 assert(Loc.isValid() && "Outlined function call location must be valid.");
8009 emitCall(CGF, OutlinedFn, Args, Loc);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008010}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00008011
8012Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
8013 const VarDecl *NativeParam,
8014 const VarDecl *TargetParam) const {
8015 return CGF.GetAddrOfLocalVar(NativeParam);
8016}