blob: 5aab7722b99668f284df9d448130e949cdfa049e [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,
George Rokos63bc9d62017-11-21 18:25:12 +0000675 // Call to int32_t __tgt_target_teams(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, int32_t num_teams, int32_t thread_limit);
Samuel Antaob68e2db2016-03-03 16:20:23 +0000678 OMPRTL__tgt_target_teams,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000679 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
680 OMPRTL__tgt_register_lib,
681 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
682 OMPRTL__tgt_unregister_lib,
George Rokos63bc9d62017-11-21 18:25:12 +0000683 // Call to void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
684 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antaodf158d52016-04-27 22:58:19 +0000685 OMPRTL__tgt_target_data_begin,
George Rokos63bc9d62017-11-21 18:25:12 +0000686 // Call to void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
687 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antaodf158d52016-04-27 22:58:19 +0000688 OMPRTL__tgt_target_data_end,
George Rokos63bc9d62017-11-21 18:25:12 +0000689 // Call to void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
690 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antao8d2d7302016-05-26 18:30:22 +0000691 OMPRTL__tgt_target_data_update,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000692};
693
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000694/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
695/// region.
696class CleanupTy final : public EHScopeStack::Cleanup {
697 PrePostActionTy *Action;
698
699public:
700 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
701 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
702 if (!CGF.HaveInsertPoint())
703 return;
704 Action->Exit(CGF);
705 }
706};
707
Hans Wennborg7eb54642015-09-10 17:07:54 +0000708} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000709
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000710void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
711 CodeGenFunction::RunCleanupsScope Scope(CGF);
712 if (PrePostAction) {
713 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
714 Callback(CodeGen, CGF, *PrePostAction);
715 } else {
716 PrePostActionTy Action;
717 Callback(CodeGen, CGF, Action);
718 }
719}
720
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000721/// Check if the combiner is a call to UDR combiner and if it is so return the
722/// UDR decl used for reduction.
723static const OMPDeclareReductionDecl *
724getReductionInit(const Expr *ReductionOp) {
725 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
726 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
727 if (auto *DRE =
728 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
729 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
730 return DRD;
731 return nullptr;
732}
733
734static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
735 const OMPDeclareReductionDecl *DRD,
736 const Expr *InitOp,
737 Address Private, Address Original,
738 QualType Ty) {
739 if (DRD->getInitializer()) {
740 std::pair<llvm::Function *, llvm::Function *> Reduction =
741 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
742 auto *CE = cast<CallExpr>(InitOp);
743 auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
744 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
745 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
746 auto *LHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
747 auto *RHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
748 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
749 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
750 [=]() -> Address { return Private; });
751 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
752 [=]() -> Address { return Original; });
753 (void)PrivateScope.Privatize();
754 RValue Func = RValue::get(Reduction.second);
755 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
756 CGF.EmitIgnoredExpr(InitOp);
757 } else {
758 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
759 auto *GV = new llvm::GlobalVariable(
760 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
761 llvm::GlobalValue::PrivateLinkage, Init, ".init");
762 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
763 RValue InitRVal;
764 switch (CGF.getEvaluationKind(Ty)) {
765 case TEK_Scalar:
766 InitRVal = CGF.EmitLoadOfLValue(LV, SourceLocation());
767 break;
768 case TEK_Complex:
769 InitRVal =
770 RValue::getComplex(CGF.EmitLoadOfComplex(LV, SourceLocation()));
771 break;
772 case TEK_Aggregate:
773 InitRVal = RValue::getAggregate(LV.getAddress());
774 break;
775 }
776 OpaqueValueExpr OVE(SourceLocation(), Ty, VK_RValue);
777 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
778 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
779 /*IsInitializer=*/false);
780 }
781}
782
783/// \brief Emit initialization of arrays of complex types.
784/// \param DestAddr Address of the array.
785/// \param Type Type of array.
786/// \param Init Initial expression of array.
787/// \param SrcAddr Address of the original array.
788static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
Alexey Bataeva7b19152017-10-12 20:03:39 +0000789 QualType Type, bool EmitDeclareReductionInit,
790 const Expr *Init,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000791 const OMPDeclareReductionDecl *DRD,
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000792 Address SrcAddr = Address::invalid()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000793 // Perform element-by-element initialization.
794 QualType ElementTy;
795
796 // Drill down to the base element type on both arrays.
797 auto ArrayTy = Type->getAsArrayTypeUnsafe();
798 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
799 DestAddr =
800 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
801 if (DRD)
802 SrcAddr =
803 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
804
805 llvm::Value *SrcBegin = nullptr;
806 if (DRD)
807 SrcBegin = SrcAddr.getPointer();
808 auto DestBegin = DestAddr.getPointer();
809 // Cast from pointer to array type to pointer to single element.
810 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
811 // The basic structure here is a while-do loop.
812 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
813 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
814 auto IsEmpty =
815 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
816 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
817
818 // Enter the loop body, making that address the current address.
819 auto EntryBB = CGF.Builder.GetInsertBlock();
820 CGF.EmitBlock(BodyBB);
821
822 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
823
824 llvm::PHINode *SrcElementPHI = nullptr;
825 Address SrcElementCurrent = Address::invalid();
826 if (DRD) {
827 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
828 "omp.arraycpy.srcElementPast");
829 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
830 SrcElementCurrent =
831 Address(SrcElementPHI,
832 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
833 }
834 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
835 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
836 DestElementPHI->addIncoming(DestBegin, EntryBB);
837 Address DestElementCurrent =
838 Address(DestElementPHI,
839 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
840
841 // Emit copy.
842 {
843 CodeGenFunction::RunCleanupsScope InitScope(CGF);
Alexey Bataeva7b19152017-10-12 20:03:39 +0000844 if (EmitDeclareReductionInit) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000845 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
846 SrcElementCurrent, ElementTy);
847 } else
848 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
849 /*IsInitializer=*/false);
850 }
851
852 if (DRD) {
853 // Shift the address forward by one element.
854 auto SrcElementNext = CGF.Builder.CreateConstGEP1_32(
855 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
856 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
857 }
858
859 // Shift the address forward by one element.
860 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
861 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
862 // Check whether we've reached the end.
863 auto Done =
864 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
865 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
866 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
867
868 // Done.
869 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
870}
871
872LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000873 return CGF.EmitOMPSharedLValue(E);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000874}
875
876LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
877 const Expr *E) {
878 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
879 return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
880 return LValue();
881}
882
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000883void ReductionCodeGen::emitAggregateInitialization(
884 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
885 const OMPDeclareReductionDecl *DRD) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000886 // Emit VarDecl with copy init for arrays.
887 // Get the address of the original variable captured in current
888 // captured region.
889 auto *PrivateVD =
890 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva7b19152017-10-12 20:03:39 +0000891 bool EmitDeclareReductionInit =
892 DRD && (DRD->getInitializer() || !PrivateVD->hasInit());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000893 EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
Alexey Bataeva7b19152017-10-12 20:03:39 +0000894 EmitDeclareReductionInit,
895 EmitDeclareReductionInit ? ClausesData[N].ReductionOp
896 : PrivateVD->getInit(),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000897 DRD, SharedLVal.getAddress());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000898}
899
900ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
901 ArrayRef<const Expr *> Privates,
902 ArrayRef<const Expr *> ReductionOps) {
903 ClausesData.reserve(Shareds.size());
904 SharedAddresses.reserve(Shareds.size());
905 Sizes.reserve(Shareds.size());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000906 BaseDecls.reserve(Shareds.size());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000907 auto IPriv = Privates.begin();
908 auto IRed = ReductionOps.begin();
909 for (const auto *Ref : Shareds) {
910 ClausesData.emplace_back(Ref, *IPriv, *IRed);
911 std::advance(IPriv, 1);
912 std::advance(IRed, 1);
913 }
914}
915
916void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
917 assert(SharedAddresses.size() == N &&
918 "Number of generated lvalues must be exactly N.");
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000919 LValue First = emitSharedLValue(CGF, ClausesData[N].Ref);
920 LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Ref);
921 SharedAddresses.emplace_back(First, Second);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000922}
923
924void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
925 auto *PrivateVD =
926 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
927 QualType PrivateType = PrivateVD->getType();
928 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000929 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000930 Sizes.emplace_back(
931 CGF.getTypeSize(
932 SharedAddresses[N].first.getType().getNonReferenceType()),
933 nullptr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000934 return;
935 }
936 llvm::Value *Size;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000937 llvm::Value *SizeInChars;
938 llvm::Type *ElemType =
939 cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
940 ->getElementType();
941 auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000942 if (AsArraySection) {
943 Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
944 SharedAddresses[N].first.getPointer());
945 Size = CGF.Builder.CreateNUWAdd(
946 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000947 SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000948 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000949 SizeInChars = CGF.getTypeSize(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000950 SharedAddresses[N].first.getType().getNonReferenceType());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000951 Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000952 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000953 Sizes.emplace_back(SizeInChars, Size);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000954 CodeGenFunction::OpaqueValueMapping OpaqueMap(
955 CGF,
956 cast<OpaqueValueExpr>(
957 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
958 RValue::get(Size));
959 CGF.EmitVariablyModifiedType(PrivateType);
960}
961
962void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
963 llvm::Value *Size) {
964 auto *PrivateVD =
965 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
966 QualType PrivateType = PrivateVD->getType();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000967 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000968 assert(!Size && !Sizes[N].second &&
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000969 "Size should be nullptr for non-variably modified reduction "
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000970 "items.");
971 return;
972 }
973 CodeGenFunction::OpaqueValueMapping OpaqueMap(
974 CGF,
975 cast<OpaqueValueExpr>(
976 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
977 RValue::get(Size));
978 CGF.EmitVariablyModifiedType(PrivateType);
979}
980
981void ReductionCodeGen::emitInitialization(
982 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
983 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
984 assert(SharedAddresses.size() > N && "No variable was generated");
985 auto *PrivateVD =
986 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
987 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
988 QualType PrivateType = PrivateVD->getType();
989 PrivateAddr = CGF.Builder.CreateElementBitCast(
990 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
991 QualType SharedType = SharedAddresses[N].first.getType();
992 SharedLVal = CGF.MakeAddrLValue(
993 CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
994 CGF.ConvertTypeForMem(SharedType)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +0000995 SharedType, SharedAddresses[N].first.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +0000996 CGF.CGM.getTBAAInfoForSubobject(SharedAddresses[N].first, SharedType));
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000997 if (CGF.getContext().getAsArrayType(PrivateVD->getType())) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000998 emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000999 } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
1000 emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
1001 PrivateAddr, SharedLVal.getAddress(),
1002 SharedLVal.getType());
1003 } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
1004 !CGF.isTrivialInitializer(PrivateVD->getInit())) {
1005 CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
1006 PrivateVD->getType().getQualifiers(),
1007 /*IsInitializer=*/false);
1008 }
1009}
1010
1011bool ReductionCodeGen::needCleanups(unsigned N) {
1012 auto *PrivateVD =
1013 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1014 QualType PrivateType = PrivateVD->getType();
1015 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1016 return DTorKind != QualType::DK_none;
1017}
1018
1019void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
1020 Address PrivateAddr) {
1021 auto *PrivateVD =
1022 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1023 QualType PrivateType = PrivateVD->getType();
1024 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1025 if (needCleanups(N)) {
1026 PrivateAddr = CGF.Builder.CreateElementBitCast(
1027 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1028 CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
1029 }
1030}
1031
1032static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1033 LValue BaseLV) {
1034 BaseTy = BaseTy.getNonReferenceType();
1035 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1036 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1037 if (auto *PtrTy = BaseTy->getAs<PointerType>())
1038 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
1039 else {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00001040 LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(), BaseTy);
1041 BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001042 }
1043 BaseTy = BaseTy->getPointeeType();
1044 }
1045 return CGF.MakeAddrLValue(
1046 CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
1047 CGF.ConvertTypeForMem(ElTy)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001048 BaseLV.getType(), BaseLV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001049 CGF.CGM.getTBAAInfoForSubobject(BaseLV, BaseLV.getType()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001050}
1051
1052static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1053 llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
1054 llvm::Value *Addr) {
1055 Address Tmp = Address::invalid();
1056 Address TopTmp = Address::invalid();
1057 Address MostTopTmp = Address::invalid();
1058 BaseTy = BaseTy.getNonReferenceType();
1059 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1060 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1061 Tmp = CGF.CreateMemTemp(BaseTy);
1062 if (TopTmp.isValid())
1063 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
1064 else
1065 MostTopTmp = Tmp;
1066 TopTmp = Tmp;
1067 BaseTy = BaseTy->getPointeeType();
1068 }
1069 llvm::Type *Ty = BaseLVType;
1070 if (Tmp.isValid())
1071 Ty = Tmp.getElementType();
1072 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
1073 if (Tmp.isValid()) {
1074 CGF.Builder.CreateStore(Addr, Tmp);
1075 return MostTopTmp;
1076 }
1077 return Address(Addr, BaseLVAlignment);
1078}
1079
1080Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
1081 Address PrivateAddr) {
1082 const DeclRefExpr *DE;
1083 const VarDecl *OrigVD = nullptr;
1084 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(ClausesData[N].Ref)) {
1085 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
1086 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
1087 Base = TempOASE->getBase()->IgnoreParenImpCasts();
1088 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1089 Base = TempASE->getBase()->IgnoreParenImpCasts();
1090 DE = cast<DeclRefExpr>(Base);
1091 OrigVD = cast<VarDecl>(DE->getDecl());
1092 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(ClausesData[N].Ref)) {
1093 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
1094 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1095 Base = TempASE->getBase()->IgnoreParenImpCasts();
1096 DE = cast<DeclRefExpr>(Base);
1097 OrigVD = cast<VarDecl>(DE->getDecl());
1098 }
1099 if (OrigVD) {
1100 BaseDecls.emplace_back(OrigVD);
1101 auto OriginalBaseLValue = CGF.EmitLValue(DE);
1102 LValue BaseLValue =
1103 loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1104 OriginalBaseLValue);
1105 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1106 BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
1107 llvm::Value *Ptr =
1108 CGF.Builder.CreateGEP(PrivateAddr.getPointer(), Adjustment);
1109 return castToBase(CGF, OrigVD->getType(),
1110 SharedAddresses[N].first.getType(),
1111 OriginalBaseLValue.getPointer()->getType(),
1112 OriginalBaseLValue.getAlignment(), Ptr);
1113 }
1114 BaseDecls.emplace_back(
1115 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1116 return PrivateAddr;
1117}
1118
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001119bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
1120 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
1121 return DRD && DRD->getInitializer();
1122}
1123
Alexey Bataev18095712014-10-10 12:19:54 +00001124LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00001125 return CGF.EmitLoadOfPointerLValue(
1126 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1127 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +00001128}
1129
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001130void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001131 if (!CGF.HaveInsertPoint())
1132 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001133 // 1.2.2 OpenMP Language Terminology
1134 // Structured block - An executable statement with a single entry at the
1135 // top and a single exit at the bottom.
1136 // The point of exit cannot be a branch out of the structured block.
1137 // longjmp() and throw() must not violate the entry/exit criteria.
1138 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001139 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001140 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001141}
1142
Alexey Bataev62b63b12015-03-10 07:28:44 +00001143LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1144 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001145 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1146 getThreadIDVariable()->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00001147 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001148}
1149
Alexey Bataev9959db52014-05-06 10:08:46 +00001150CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001151 : CGM(CGM), OffloadEntriesInfoManager(CGM) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001152 IdentTy = llvm::StructType::create(
1153 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
1154 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Serge Guelton1d993272017-05-09 19:31:30 +00001155 CGM.Int8PtrTy /* psource */);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001156 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +00001157
1158 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +00001159}
1160
Alexey Bataev91797552015-03-18 04:13:55 +00001161void CGOpenMPRuntime::clear() {
1162 InternalVars.clear();
1163}
1164
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001165static llvm::Function *
1166emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1167 const Expr *CombinerInitializer, const VarDecl *In,
1168 const VarDecl *Out, bool IsCombiner) {
1169 // void .omp_combiner.(Ty *in, Ty *out);
1170 auto &C = CGM.getContext();
1171 QualType PtrTy = C.getPointerType(Ty).withRestrict();
1172 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001173 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001174 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001175 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001176 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001177 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001178 Args.push_back(&OmpInParm);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001179 auto &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001180 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001181 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1182 auto *Fn = llvm::Function::Create(
1183 FnTy, llvm::GlobalValue::InternalLinkage,
1184 IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
1185 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001186 Fn->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001187 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001188 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001189 CodeGenFunction CGF(CGM);
1190 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1191 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
1192 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
1193 CodeGenFunction::OMPPrivateScope Scope(CGF);
1194 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
1195 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
1196 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1197 .getAddress();
1198 });
1199 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
1200 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
1201 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1202 .getAddress();
1203 });
1204 (void)Scope.Privatize();
Alexey Bataev070f43a2017-09-06 14:49:58 +00001205 if (!IsCombiner && Out->hasInit() &&
1206 !CGF.isTrivialInitializer(Out->getInit())) {
1207 CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
1208 Out->getType().getQualifiers(),
1209 /*IsInitializer=*/true);
1210 }
1211 if (CombinerInitializer)
1212 CGF.EmitIgnoredExpr(CombinerInitializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001213 Scope.ForceCleanup();
1214 CGF.FinishFunction();
1215 return Fn;
1216}
1217
1218void CGOpenMPRuntime::emitUserDefinedReduction(
1219 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1220 if (UDRMap.count(D) > 0)
1221 return;
1222 auto &C = CGM.getContext();
1223 if (!In || !Out) {
1224 In = &C.Idents.get("omp_in");
1225 Out = &C.Idents.get("omp_out");
1226 }
1227 llvm::Function *Combiner = emitCombinerOrInitializer(
1228 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
1229 cast<VarDecl>(D->lookup(Out).front()),
1230 /*IsCombiner=*/true);
1231 llvm::Function *Initializer = nullptr;
1232 if (auto *Init = D->getInitializer()) {
1233 if (!Priv || !Orig) {
1234 Priv = &C.Idents.get("omp_priv");
1235 Orig = &C.Idents.get("omp_orig");
1236 }
1237 Initializer = emitCombinerOrInitializer(
Alexey Bataev070f43a2017-09-06 14:49:58 +00001238 CGM, D->getType(),
1239 D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init
1240 : nullptr,
1241 cast<VarDecl>(D->lookup(Orig).front()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001242 cast<VarDecl>(D->lookup(Priv).front()),
1243 /*IsCombiner=*/false);
1244 }
1245 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
1246 if (CGF) {
1247 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1248 Decls.second.push_back(D);
1249 }
1250}
1251
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001252std::pair<llvm::Function *, llvm::Function *>
1253CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1254 auto I = UDRMap.find(D);
1255 if (I != UDRMap.end())
1256 return I->second;
1257 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1258 return UDRMap.lookup(D);
1259}
1260
John McCall7f416cc2015-09-08 08:05:57 +00001261// Layout information for ident_t.
1262static CharUnits getIdentAlign(CodeGenModule &CGM) {
1263 return CGM.getPointerAlign();
1264}
1265static CharUnits getIdentSize(CodeGenModule &CGM) {
1266 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
1267 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
1268}
Alexey Bataev50b3c952016-02-19 10:38:26 +00001269static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
John McCall7f416cc2015-09-08 08:05:57 +00001270 // All the fields except the last are i32, so this works beautifully.
1271 return unsigned(Field) * CharUnits::fromQuantity(4);
1272}
1273static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001274 IdentFieldIndex Field,
John McCall7f416cc2015-09-08 08:05:57 +00001275 const llvm::Twine &Name = "") {
1276 auto Offset = getOffsetOfIdentField(Field);
1277 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
1278}
1279
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001280static llvm::Value *emitParallelOrTeamsOutlinedFunction(
1281 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1282 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1283 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001284 assert(ThreadIDVar->getType()->isPointerType() &&
1285 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +00001286 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00001287 bool HasCancel = false;
1288 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
1289 HasCancel = OPD->hasCancel();
1290 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
1291 HasCancel = OPSD->hasCancel();
1292 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
1293 HasCancel = OPFD->hasCancel();
Alexey Bataev2139ed62017-11-16 18:20:21 +00001294 else if (auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D))
1295 HasCancel = OPFD->hasCancel();
Alexey Bataev10a54312017-11-27 16:54:08 +00001296 else if (auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&D))
1297 HasCancel = OPFD->hasCancel();
1298 else if (auto *OPFD = dyn_cast<OMPTeamsDistributeParallelForDirective>(&D))
1299 HasCancel = OPFD->hasCancel();
1300 else if (auto *OPFD =
1301 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D))
1302 HasCancel = OPFD->hasCancel();
Alexey Bataev25e5b442015-09-15 12:52:43 +00001303 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001304 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +00001305 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001306 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +00001307}
1308
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001309llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
1310 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1311 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1312 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1313 return emitParallelOrTeamsOutlinedFunction(
1314 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1315}
1316
1317llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1318 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1319 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1320 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1321 return emitParallelOrTeamsOutlinedFunction(
1322 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1323}
1324
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001325llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
1326 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +00001327 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1328 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1329 bool Tied, unsigned &NumberOfParts) {
1330 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1331 PrePostActionTy &) {
1332 auto *ThreadID = getThreadID(CGF, D.getLocStart());
1333 auto *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
1334 llvm::Value *TaskArgs[] = {
1335 UpLoc, ThreadID,
1336 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1337 TaskTVar->getType()->castAs<PointerType>())
1338 .getPointer()};
1339 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1340 };
1341 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1342 UntiedCodeGen);
1343 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001344 assert(!ThreadIDVar->getType()->isPointerType() &&
1345 "thread id variable must be of type kmp_int32 for tasks");
1346 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
Alexey Bataev7292c292016-04-25 12:22:29 +00001347 auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001348 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +00001349 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1350 InnermostKind,
1351 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +00001352 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev48591dd2016-04-20 04:01:36 +00001353 auto *Res = CGF.GenerateCapturedStmtFunction(*CS);
1354 if (!Tied)
1355 NumberOfParts = Action.getNumberOfParts();
1356 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001357}
1358
Alexey Bataev50b3c952016-02-19 10:38:26 +00001359Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +00001360 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +00001361 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +00001362 if (!Entry) {
1363 if (!DefaultOpenMPPSource) {
1364 // Initialize default location for psource field of ident_t structure of
1365 // all ident_t objects. Format is ";file;function;line;column;;".
1366 // Taken from
1367 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1368 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +00001369 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001370 DefaultOpenMPPSource =
1371 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1372 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001373
John McCall23c9dc62016-11-28 22:18:27 +00001374 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001375 auto fields = builder.beginStruct(IdentTy);
1376 fields.addInt(CGM.Int32Ty, 0);
1377 fields.addInt(CGM.Int32Ty, Flags);
1378 fields.addInt(CGM.Int32Ty, 0);
1379 fields.addInt(CGM.Int32Ty, 0);
1380 fields.add(DefaultOpenMPPSource);
1381 auto DefaultOpenMPLocation =
1382 fields.finishAndCreateGlobal("", Align, /*isConstant*/ true,
1383 llvm::GlobalValue::PrivateLinkage);
1384 DefaultOpenMPLocation->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1385
John McCall7f416cc2015-09-08 08:05:57 +00001386 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +00001387 }
John McCall7f416cc2015-09-08 08:05:57 +00001388 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +00001389}
1390
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001391llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1392 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001393 unsigned Flags) {
1394 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +00001395 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001396 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +00001397 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +00001398 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001399
1400 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1401
John McCall7f416cc2015-09-08 08:05:57 +00001402 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001403 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1404 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +00001405 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
1406
Alexander Musmanc6388682014-12-15 07:07:06 +00001407 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1408 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +00001409 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +00001410 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +00001411 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
1412 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +00001413 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +00001414 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001415 LocValue = AI;
1416
1417 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1418 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001419 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +00001420 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +00001421 }
1422
1423 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +00001424 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +00001425
Alexey Bataevf002aca2014-05-30 05:48:40 +00001426 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
1427 if (OMPDebugLoc == nullptr) {
1428 SmallString<128> Buffer2;
1429 llvm::raw_svector_ostream OS2(Buffer2);
1430 // Build debug location
1431 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1432 OS2 << ";" << PLoc.getFilename() << ";";
1433 if (const FunctionDecl *FD =
1434 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
1435 OS2 << FD->getQualifiedNameAsString();
1436 }
1437 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1438 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1439 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +00001440 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001441 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +00001442 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
1443
John McCall7f416cc2015-09-08 08:05:57 +00001444 // Our callers always pass this to a runtime function, so for
1445 // convenience, go ahead and return a naked pointer.
1446 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001447}
1448
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001449llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1450 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001451 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1452
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001453 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001454 // Check whether we've already cached a load of the thread id in this
1455 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001456 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001457 if (I != OpenMPLocThreadIDMap.end()) {
1458 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001459 if (ThreadID != nullptr)
1460 return ThreadID;
1461 }
Alexey Bataevaee18552017-08-16 14:01:00 +00001462 // If exceptions are enabled, do not use parameter to avoid possible crash.
Alexey Bataev5d2c9a42017-11-02 18:55:05 +00001463 if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions ||
1464 !CGF.getLangOpts().CXXExceptions ||
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001465 CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
Alexey Bataevaee18552017-08-16 14:01:00 +00001466 if (auto *OMPRegionInfo =
1467 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1468 if (OMPRegionInfo->getThreadIDVariable()) {
1469 // Check if this an outlined function with thread id passed as argument.
1470 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
1471 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
1472 // If value loaded in entry block, cache it and use it everywhere in
1473 // function.
1474 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1475 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1476 Elem.second.ThreadID = ThreadID;
1477 }
1478 return ThreadID;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001479 }
Alexey Bataevd6c57552014-07-25 07:55:17 +00001480 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001481 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001482
1483 // This is not an outlined function region - need to call __kmpc_int32
1484 // kmpc_global_thread_num(ident_t *loc).
1485 // Generate thread id value and cache this value for use across the
1486 // function.
1487 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1488 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001489 auto *Call = CGF.Builder.CreateCall(
1490 createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1491 emitUpdateLocation(CGF, Loc));
1492 Call->setCallingConv(CGF.getRuntimeCC());
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001493 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001494 Elem.second.ThreadID = Call;
1495 return Call;
Alexey Bataev9959db52014-05-06 10:08:46 +00001496}
1497
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001498void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001499 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001500 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1501 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001502 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1503 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
1504 UDRMap.erase(D);
1505 }
1506 FunctionUDRMap.erase(CGF.CurFn);
1507 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001508}
1509
1510llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001511 if (!IdentTy) {
1512 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001513 return llvm::PointerType::getUnqual(IdentTy);
1514}
1515
1516llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001517 if (!Kmpc_MicroTy) {
1518 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1519 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1520 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1521 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1522 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001523 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1524}
1525
1526llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001527CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001528 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001529 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001530 case OMPRTL__kmpc_fork_call: {
1531 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1532 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001533 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1534 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001535 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001536 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001537 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1538 break;
1539 }
1540 case OMPRTL__kmpc_global_thread_num: {
1541 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001542 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001543 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001544 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001545 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1546 break;
1547 }
Alexey Bataev97720002014-11-11 04:05:39 +00001548 case OMPRTL__kmpc_threadprivate_cached: {
1549 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1550 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1551 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1552 CGM.VoidPtrTy, CGM.SizeTy,
1553 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1554 llvm::FunctionType *FnTy =
1555 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1556 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1557 break;
1558 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001559 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001560 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1561 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001562 llvm::Type *TypeParams[] = {
1563 getIdentTyPointerTy(), CGM.Int32Ty,
1564 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1565 llvm::FunctionType *FnTy =
1566 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1567 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1568 break;
1569 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001570 case OMPRTL__kmpc_critical_with_hint: {
1571 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1572 // kmp_critical_name *crit, uintptr_t hint);
1573 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1574 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1575 CGM.IntPtrTy};
1576 llvm::FunctionType *FnTy =
1577 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1578 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1579 break;
1580 }
Alexey Bataev97720002014-11-11 04:05:39 +00001581 case OMPRTL__kmpc_threadprivate_register: {
1582 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1583 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1584 // typedef void *(*kmpc_ctor)(void *);
1585 auto KmpcCtorTy =
1586 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1587 /*isVarArg*/ false)->getPointerTo();
1588 // typedef void *(*kmpc_cctor)(void *, void *);
1589 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1590 auto KmpcCopyCtorTy =
1591 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1592 /*isVarArg*/ false)->getPointerTo();
1593 // typedef void (*kmpc_dtor)(void *);
1594 auto KmpcDtorTy =
1595 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1596 ->getPointerTo();
1597 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1598 KmpcCopyCtorTy, KmpcDtorTy};
1599 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1600 /*isVarArg*/ false);
1601 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1602 break;
1603 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001604 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001605 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1606 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001607 llvm::Type *TypeParams[] = {
1608 getIdentTyPointerTy(), CGM.Int32Ty,
1609 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1610 llvm::FunctionType *FnTy =
1611 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1612 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1613 break;
1614 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001615 case OMPRTL__kmpc_cancel_barrier: {
1616 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1617 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001618 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1619 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001620 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1621 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001622 break;
1623 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001624 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001625 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001626 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1627 llvm::FunctionType *FnTy =
1628 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1629 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1630 break;
1631 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001632 case OMPRTL__kmpc_for_static_fini: {
1633 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1634 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1635 llvm::FunctionType *FnTy =
1636 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1637 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1638 break;
1639 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001640 case OMPRTL__kmpc_push_num_threads: {
1641 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1642 // kmp_int32 num_threads)
1643 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1644 CGM.Int32Ty};
1645 llvm::FunctionType *FnTy =
1646 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1647 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1648 break;
1649 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001650 case OMPRTL__kmpc_serialized_parallel: {
1651 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1652 // global_tid);
1653 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1654 llvm::FunctionType *FnTy =
1655 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1656 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1657 break;
1658 }
1659 case OMPRTL__kmpc_end_serialized_parallel: {
1660 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1661 // global_tid);
1662 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1663 llvm::FunctionType *FnTy =
1664 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1665 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1666 break;
1667 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001668 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001669 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001670 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1671 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001672 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001673 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1674 break;
1675 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001676 case OMPRTL__kmpc_master: {
1677 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1678 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1679 llvm::FunctionType *FnTy =
1680 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1681 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1682 break;
1683 }
1684 case OMPRTL__kmpc_end_master: {
1685 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1686 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1687 llvm::FunctionType *FnTy =
1688 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1689 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1690 break;
1691 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001692 case OMPRTL__kmpc_omp_taskyield: {
1693 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1694 // int end_part);
1695 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1696 llvm::FunctionType *FnTy =
1697 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1698 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1699 break;
1700 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001701 case OMPRTL__kmpc_single: {
1702 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1703 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1704 llvm::FunctionType *FnTy =
1705 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1706 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1707 break;
1708 }
1709 case OMPRTL__kmpc_end_single: {
1710 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1711 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1712 llvm::FunctionType *FnTy =
1713 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1714 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1715 break;
1716 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001717 case OMPRTL__kmpc_omp_task_alloc: {
1718 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1719 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1720 // kmp_routine_entry_t *task_entry);
1721 assert(KmpRoutineEntryPtrTy != nullptr &&
1722 "Type kmp_routine_entry_t must be created.");
1723 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1724 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1725 // Return void * and then cast to particular kmp_task_t type.
1726 llvm::FunctionType *FnTy =
1727 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1728 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1729 break;
1730 }
1731 case OMPRTL__kmpc_omp_task: {
1732 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1733 // *new_task);
1734 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1735 CGM.VoidPtrTy};
1736 llvm::FunctionType *FnTy =
1737 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1738 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1739 break;
1740 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001741 case OMPRTL__kmpc_copyprivate: {
1742 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001743 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001744 // kmp_int32 didit);
1745 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1746 auto *CpyFnTy =
1747 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001748 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001749 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1750 CGM.Int32Ty};
1751 llvm::FunctionType *FnTy =
1752 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1753 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1754 break;
1755 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001756 case OMPRTL__kmpc_reduce: {
1757 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1758 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1759 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1760 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1761 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1762 /*isVarArg=*/false);
1763 llvm::Type *TypeParams[] = {
1764 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1765 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1766 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1767 llvm::FunctionType *FnTy =
1768 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1769 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1770 break;
1771 }
1772 case OMPRTL__kmpc_reduce_nowait: {
1773 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1774 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1775 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1776 // *lck);
1777 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1778 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1779 /*isVarArg=*/false);
1780 llvm::Type *TypeParams[] = {
1781 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1782 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1783 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1784 llvm::FunctionType *FnTy =
1785 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1786 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1787 break;
1788 }
1789 case OMPRTL__kmpc_end_reduce: {
1790 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1791 // kmp_critical_name *lck);
1792 llvm::Type *TypeParams[] = {
1793 getIdentTyPointerTy(), CGM.Int32Ty,
1794 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1795 llvm::FunctionType *FnTy =
1796 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1797 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1798 break;
1799 }
1800 case OMPRTL__kmpc_end_reduce_nowait: {
1801 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1802 // kmp_critical_name *lck);
1803 llvm::Type *TypeParams[] = {
1804 getIdentTyPointerTy(), CGM.Int32Ty,
1805 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1806 llvm::FunctionType *FnTy =
1807 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1808 RTLFn =
1809 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1810 break;
1811 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001812 case OMPRTL__kmpc_omp_task_begin_if0: {
1813 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1814 // *new_task);
1815 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1816 CGM.VoidPtrTy};
1817 llvm::FunctionType *FnTy =
1818 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1819 RTLFn =
1820 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1821 break;
1822 }
1823 case OMPRTL__kmpc_omp_task_complete_if0: {
1824 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1825 // *new_task);
1826 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1827 CGM.VoidPtrTy};
1828 llvm::FunctionType *FnTy =
1829 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1830 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1831 /*Name=*/"__kmpc_omp_task_complete_if0");
1832 break;
1833 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001834 case OMPRTL__kmpc_ordered: {
1835 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1836 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1837 llvm::FunctionType *FnTy =
1838 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1839 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1840 break;
1841 }
1842 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001843 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001844 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1845 llvm::FunctionType *FnTy =
1846 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1847 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1848 break;
1849 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001850 case OMPRTL__kmpc_omp_taskwait: {
1851 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1852 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1853 llvm::FunctionType *FnTy =
1854 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1855 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1856 break;
1857 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001858 case OMPRTL__kmpc_taskgroup: {
1859 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1860 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1861 llvm::FunctionType *FnTy =
1862 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1863 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1864 break;
1865 }
1866 case OMPRTL__kmpc_end_taskgroup: {
1867 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1868 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1869 llvm::FunctionType *FnTy =
1870 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1871 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1872 break;
1873 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001874 case OMPRTL__kmpc_push_proc_bind: {
1875 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1876 // int proc_bind)
1877 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1878 llvm::FunctionType *FnTy =
1879 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1880 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1881 break;
1882 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001883 case OMPRTL__kmpc_omp_task_with_deps: {
1884 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1885 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1886 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1887 llvm::Type *TypeParams[] = {
1888 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1889 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1890 llvm::FunctionType *FnTy =
1891 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1892 RTLFn =
1893 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1894 break;
1895 }
1896 case OMPRTL__kmpc_omp_wait_deps: {
1897 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1898 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1899 // kmp_depend_info_t *noalias_dep_list);
1900 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1901 CGM.Int32Ty, CGM.VoidPtrTy,
1902 CGM.Int32Ty, CGM.VoidPtrTy};
1903 llvm::FunctionType *FnTy =
1904 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1905 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1906 break;
1907 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001908 case OMPRTL__kmpc_cancellationpoint: {
1909 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1910 // global_tid, kmp_int32 cncl_kind)
1911 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1912 llvm::FunctionType *FnTy =
1913 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1914 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1915 break;
1916 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001917 case OMPRTL__kmpc_cancel: {
1918 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1919 // kmp_int32 cncl_kind)
1920 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1921 llvm::FunctionType *FnTy =
1922 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1923 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1924 break;
1925 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001926 case OMPRTL__kmpc_push_num_teams: {
1927 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1928 // kmp_int32 num_teams, kmp_int32 num_threads)
1929 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1930 CGM.Int32Ty};
1931 llvm::FunctionType *FnTy =
1932 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1933 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1934 break;
1935 }
1936 case OMPRTL__kmpc_fork_teams: {
1937 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1938 // microtask, ...);
1939 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1940 getKmpc_MicroPointerTy()};
1941 llvm::FunctionType *FnTy =
1942 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1943 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1944 break;
1945 }
Alexey Bataev7292c292016-04-25 12:22:29 +00001946 case OMPRTL__kmpc_taskloop: {
1947 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
1948 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
1949 // sched, kmp_uint64 grainsize, void *task_dup);
1950 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1951 CGM.IntTy,
1952 CGM.VoidPtrTy,
1953 CGM.IntTy,
1954 CGM.Int64Ty->getPointerTo(),
1955 CGM.Int64Ty->getPointerTo(),
1956 CGM.Int64Ty,
1957 CGM.IntTy,
1958 CGM.IntTy,
1959 CGM.Int64Ty,
1960 CGM.VoidPtrTy};
1961 llvm::FunctionType *FnTy =
1962 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1963 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
1964 break;
1965 }
Alexey Bataev8b427062016-05-25 12:36:08 +00001966 case OMPRTL__kmpc_doacross_init: {
1967 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
1968 // num_dims, struct kmp_dim *dims);
1969 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1970 CGM.Int32Ty,
1971 CGM.Int32Ty,
1972 CGM.VoidPtrTy};
1973 llvm::FunctionType *FnTy =
1974 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1975 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
1976 break;
1977 }
1978 case OMPRTL__kmpc_doacross_fini: {
1979 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
1980 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1981 llvm::FunctionType *FnTy =
1982 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1983 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
1984 break;
1985 }
1986 case OMPRTL__kmpc_doacross_post: {
1987 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
1988 // *vec);
1989 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1990 CGM.Int64Ty->getPointerTo()};
1991 llvm::FunctionType *FnTy =
1992 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1993 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
1994 break;
1995 }
1996 case OMPRTL__kmpc_doacross_wait: {
1997 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
1998 // *vec);
1999 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2000 CGM.Int64Ty->getPointerTo()};
2001 llvm::FunctionType *FnTy =
2002 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2003 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
2004 break;
2005 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002006 case OMPRTL__kmpc_task_reduction_init: {
2007 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
2008 // *data);
2009 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
2010 llvm::FunctionType *FnTy =
2011 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2012 RTLFn =
2013 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
2014 break;
2015 }
2016 case OMPRTL__kmpc_task_reduction_get_th_data: {
2017 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
2018 // *d);
2019 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
2020 llvm::FunctionType *FnTy =
2021 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2022 RTLFn = CGM.CreateRuntimeFunction(
2023 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2024 break;
2025 }
Samuel Antaobed3c462015-10-02 16:14:20 +00002026 case OMPRTL__tgt_target: {
George Rokos63bc9d62017-11-21 18:25:12 +00002027 // Build int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
2028 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Samuel Antaobed3c462015-10-02 16:14:20 +00002029 // *arg_types);
George Rokos63bc9d62017-11-21 18:25:12 +00002030 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaobed3c462015-10-02 16:14:20 +00002031 CGM.VoidPtrTy,
2032 CGM.Int32Ty,
2033 CGM.VoidPtrPtrTy,
2034 CGM.VoidPtrPtrTy,
2035 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002036 CGM.Int64Ty->getPointerTo()};
Samuel Antaobed3c462015-10-02 16:14:20 +00002037 llvm::FunctionType *FnTy =
2038 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2039 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2040 break;
2041 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00002042 case OMPRTL__tgt_target_teams: {
George Rokos63bc9d62017-11-21 18:25:12 +00002043 // Build int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002044 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
George Rokos63bc9d62017-11-21 18:25:12 +00002045 // int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2046 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002047 CGM.VoidPtrTy,
2048 CGM.Int32Ty,
2049 CGM.VoidPtrPtrTy,
2050 CGM.VoidPtrPtrTy,
2051 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002052 CGM.Int64Ty->getPointerTo(),
Samuel Antaob68e2db2016-03-03 16:20:23 +00002053 CGM.Int32Ty,
2054 CGM.Int32Ty};
2055 llvm::FunctionType *FnTy =
2056 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2057 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2058 break;
2059 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002060 case OMPRTL__tgt_register_lib: {
2061 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2062 QualType ParamTy =
2063 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2064 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2065 llvm::FunctionType *FnTy =
2066 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2067 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2068 break;
2069 }
2070 case OMPRTL__tgt_unregister_lib: {
2071 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2072 QualType ParamTy =
2073 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2074 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2075 llvm::FunctionType *FnTy =
2076 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2077 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2078 break;
2079 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002080 case OMPRTL__tgt_target_data_begin: {
George Rokos63bc9d62017-11-21 18:25:12 +00002081 // Build void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
2082 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2083 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002084 CGM.Int32Ty,
2085 CGM.VoidPtrPtrTy,
2086 CGM.VoidPtrPtrTy,
2087 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002088 CGM.Int64Ty->getPointerTo()};
Samuel Antaodf158d52016-04-27 22:58:19 +00002089 llvm::FunctionType *FnTy =
2090 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2091 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2092 break;
2093 }
2094 case OMPRTL__tgt_target_data_end: {
George Rokos63bc9d62017-11-21 18:25:12 +00002095 // Build void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
2096 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2097 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002098 CGM.Int32Ty,
2099 CGM.VoidPtrPtrTy,
2100 CGM.VoidPtrPtrTy,
2101 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002102 CGM.Int64Ty->getPointerTo()};
Samuel Antaodf158d52016-04-27 22:58:19 +00002103 llvm::FunctionType *FnTy =
2104 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2105 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2106 break;
2107 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002108 case OMPRTL__tgt_target_data_update: {
George Rokos63bc9d62017-11-21 18:25:12 +00002109 // Build void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
2110 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2111 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antao8d2d7302016-05-26 18:30:22 +00002112 CGM.Int32Ty,
2113 CGM.VoidPtrPtrTy,
2114 CGM.VoidPtrPtrTy,
2115 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002116 CGM.Int64Ty->getPointerTo()};
Samuel Antao8d2d7302016-05-26 18:30:22 +00002117 llvm::FunctionType *FnTy =
2118 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2119 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2120 break;
2121 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002122 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002123 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002124 return RTLFn;
2125}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002126
Alexander Musman21212e42015-03-13 10:38:23 +00002127llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2128 bool IVSigned) {
2129 assert((IVSize == 32 || IVSize == 64) &&
2130 "IV size is not compatible with the omp runtime");
2131 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2132 : "__kmpc_for_static_init_4u")
2133 : (IVSigned ? "__kmpc_for_static_init_8"
2134 : "__kmpc_for_static_init_8u");
2135 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2136 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2137 llvm::Type *TypeParams[] = {
2138 getIdentTyPointerTy(), // loc
2139 CGM.Int32Ty, // tid
2140 CGM.Int32Ty, // schedtype
2141 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2142 PtrTy, // p_lower
2143 PtrTy, // p_upper
2144 PtrTy, // p_stride
2145 ITy, // incr
2146 ITy // chunk
2147 };
2148 llvm::FunctionType *FnTy =
2149 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2150 return CGM.CreateRuntimeFunction(FnTy, Name);
2151}
2152
Alexander Musman92bdaab2015-03-12 13:37:50 +00002153llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2154 bool IVSigned) {
2155 assert((IVSize == 32 || IVSize == 64) &&
2156 "IV size is not compatible with the omp runtime");
2157 auto Name =
2158 IVSize == 32
2159 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2160 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
2161 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2162 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2163 CGM.Int32Ty, // tid
2164 CGM.Int32Ty, // schedtype
2165 ITy, // lower
2166 ITy, // upper
2167 ITy, // stride
2168 ITy // chunk
2169 };
2170 llvm::FunctionType *FnTy =
2171 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2172 return CGM.CreateRuntimeFunction(FnTy, Name);
2173}
2174
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002175llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2176 bool IVSigned) {
2177 assert((IVSize == 32 || IVSize == 64) &&
2178 "IV size is not compatible with the omp runtime");
2179 auto Name =
2180 IVSize == 32
2181 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2182 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2183 llvm::Type *TypeParams[] = {
2184 getIdentTyPointerTy(), // loc
2185 CGM.Int32Ty, // tid
2186 };
2187 llvm::FunctionType *FnTy =
2188 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2189 return CGM.CreateRuntimeFunction(FnTy, Name);
2190}
2191
Alexander Musman92bdaab2015-03-12 13:37:50 +00002192llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2193 bool IVSigned) {
2194 assert((IVSize == 32 || IVSize == 64) &&
2195 "IV size is not compatible with the omp runtime");
2196 auto Name =
2197 IVSize == 32
2198 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2199 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
2200 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2201 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2202 llvm::Type *TypeParams[] = {
2203 getIdentTyPointerTy(), // loc
2204 CGM.Int32Ty, // tid
2205 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2206 PtrTy, // p_lower
2207 PtrTy, // p_upper
2208 PtrTy // p_stride
2209 };
2210 llvm::FunctionType *FnTy =
2211 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2212 return CGM.CreateRuntimeFunction(FnTy, Name);
2213}
2214
Alexey Bataev97720002014-11-11 04:05:39 +00002215llvm::Constant *
2216CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002217 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2218 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002219 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002220 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002221 Twine(CGM.getMangledName(VD)) + ".cache.");
2222}
2223
John McCall7f416cc2015-09-08 08:05:57 +00002224Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2225 const VarDecl *VD,
2226 Address VDAddr,
2227 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002228 if (CGM.getLangOpts().OpenMPUseTLS &&
2229 CGM.getContext().getTargetInfo().isTLSSupported())
2230 return VDAddr;
2231
John McCall7f416cc2015-09-08 08:05:57 +00002232 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002233 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002234 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2235 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002236 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2237 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002238 return Address(CGF.EmitRuntimeCall(
2239 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2240 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002241}
2242
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002243void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002244 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002245 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2246 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2247 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002248 auto OMPLoc = emitUpdateLocation(CGF, Loc);
2249 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002250 OMPLoc);
2251 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2252 // to register constructor/destructor for variable.
2253 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00002254 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2255 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002256 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002257 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002258 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002259}
2260
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002261llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002262 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002263 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002264 if (CGM.getLangOpts().OpenMPUseTLS &&
2265 CGM.getContext().getTargetInfo().isTLSSupported())
2266 return nullptr;
2267
Alexey Bataev97720002014-11-11 04:05:39 +00002268 VD = VD->getDefinition(CGM.getContext());
2269 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
2270 ThreadPrivateWithDefinition.insert(VD);
2271 QualType ASTTy = VD->getType();
2272
2273 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
2274 auto Init = VD->getAnyInitializer();
2275 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2276 // Generate function that re-emits the declaration's initializer into the
2277 // threadprivate copy of the variable VD
2278 CodeGenFunction CtorCGF(CGM);
2279 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002280 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
2281 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002282 Args.push_back(&Dst);
2283
John McCallc56a8b32016-03-11 04:30:31 +00002284 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2285 CGM.getContext().VoidPtrTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002286 auto FTy = CGM.getTypes().GetFunctionType(FI);
2287 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002288 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002289 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
2290 Args, SourceLocation());
2291 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002292 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002293 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002294 Address Arg = Address(ArgVal, VDAddr.getAlignment());
2295 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
2296 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002297 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2298 /*IsInitializer=*/true);
2299 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002300 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002301 CGM.getContext().VoidPtrTy, Dst.getLocation());
2302 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2303 CtorCGF.FinishFunction();
2304 Ctor = Fn;
2305 }
2306 if (VD->getType().isDestructedType() != QualType::DK_none) {
2307 // Generate function that emits destructor call for the threadprivate copy
2308 // of the variable VD
2309 CodeGenFunction DtorCGF(CGM);
2310 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002311 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
2312 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002313 Args.push_back(&Dst);
2314
John McCallc56a8b32016-03-11 04:30:31 +00002315 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2316 CGM.getContext().VoidTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002317 auto FTy = CGM.getTypes().GetFunctionType(FI);
2318 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002319 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002320 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002321 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
2322 SourceLocation());
Adrian Prantl1858c662016-04-24 22:22:29 +00002323 // Create a scope with an artificial location for the body of this function.
2324 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002325 auto ArgVal = DtorCGF.EmitLoadOfScalar(
2326 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002327 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2328 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002329 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2330 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2331 DtorCGF.FinishFunction();
2332 Dtor = Fn;
2333 }
2334 // Do not emit init function if it is not required.
2335 if (!Ctor && !Dtor)
2336 return nullptr;
2337
2338 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
2339 auto CopyCtorTy =
2340 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2341 /*isVarArg=*/false)->getPointerTo();
2342 // Copying constructor for the threadprivate variable.
2343 // Must be NULL - reserved by runtime, but currently it requires that this
2344 // parameter is always NULL. Otherwise it fires assertion.
2345 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2346 if (Ctor == nullptr) {
2347 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2348 /*isVarArg=*/false)->getPointerTo();
2349 Ctor = llvm::Constant::getNullValue(CtorTy);
2350 }
2351 if (Dtor == nullptr) {
2352 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2353 /*isVarArg=*/false)->getPointerTo();
2354 Dtor = llvm::Constant::getNullValue(DtorTy);
2355 }
2356 if (!CGF) {
2357 auto InitFunctionTy =
2358 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
2359 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002360 InitFunctionTy, ".__omp_threadprivate_init_.",
2361 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002362 CodeGenFunction InitCGF(CGM);
2363 FunctionArgList ArgList;
2364 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2365 CGM.getTypes().arrangeNullaryFunction(), ArgList,
2366 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002367 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002368 InitCGF.FinishFunction();
2369 return InitFunction;
2370 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002371 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002372 }
2373 return nullptr;
2374}
2375
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002376Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2377 QualType VarType,
2378 StringRef Name) {
2379 llvm::Twine VarName(Name, ".artificial.");
2380 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
2381 llvm::Value *GAddr = getOrCreateInternalVariable(VarLVType, VarName);
2382 llvm::Value *Args[] = {
2383 emitUpdateLocation(CGF, SourceLocation()),
2384 getThreadID(CGF, SourceLocation()),
2385 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2386 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2387 /*IsSigned=*/false),
2388 getOrCreateInternalVariable(CGM.VoidPtrPtrTy, VarName + ".cache.")};
2389 return Address(
2390 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2391 CGF.EmitRuntimeCall(
2392 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2393 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2394 CGM.getPointerAlign());
2395}
2396
Alexey Bataev1d677132015-04-22 13:57:31 +00002397/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
2398/// function. Here is the logic:
2399/// if (Cond) {
2400/// ThenGen();
2401/// } else {
2402/// ElseGen();
2403/// }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002404void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2405 const RegionCodeGenTy &ThenGen,
2406 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002407 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2408
2409 // If the condition constant folds and can be elided, try to avoid emitting
2410 // the condition and the dead arm of the if/else.
2411 bool CondConstant;
2412 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002413 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002414 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002415 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002416 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002417 return;
2418 }
2419
2420 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2421 // emit the conditional branch.
2422 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
2423 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
2424 auto ContBlock = CGF.createBasicBlock("omp_if.end");
2425 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2426
2427 // Emit the 'then' code.
2428 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002429 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002430 CGF.EmitBranch(ContBlock);
2431 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002432 // There is no need to emit line number for unconditional branch.
2433 (void)ApplyDebugLocation::CreateEmpty(CGF);
2434 CGF.EmitBlock(ElseBlock);
2435 ElseGen(CGF);
2436 // There is no need to emit line number for unconditional branch.
2437 (void)ApplyDebugLocation::CreateEmpty(CGF);
2438 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002439 // Emit the continuation block for code after the if.
2440 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002441}
2442
Alexey Bataev1d677132015-04-22 13:57:31 +00002443void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2444 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002445 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002446 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002447 if (!CGF.HaveInsertPoint())
2448 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00002449 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002450 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2451 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002452 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002453 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002454 llvm::Value *Args[] = {
2455 RTLoc,
2456 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002457 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002458 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2459 RealArgs.append(std::begin(Args), std::end(Args));
2460 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2461
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002462 auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002463 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2464 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002465 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2466 PrePostActionTy &) {
2467 auto &RT = CGF.CGM.getOpenMPRuntime();
2468 auto ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00002469 // Build calls:
2470 // __kmpc_serialized_parallel(&Loc, GTid);
2471 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002472 CGF.EmitRuntimeCall(
2473 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002474
Alexey Bataev1d677132015-04-22 13:57:31 +00002475 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002476 auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00002477 Address ZeroAddr =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002478 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
2479 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00002480 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00002481 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2482 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2483 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2484 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002485 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002486
Alexey Bataev1d677132015-04-22 13:57:31 +00002487 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002488 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00002489 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002490 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2491 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002492 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002493 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00002494 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002495 else {
2496 RegionCodeGenTy ThenRCG(ThenGen);
2497 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002498 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002499}
2500
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002501// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002502// thread-ID variable (it is passed in a first argument of the outlined function
2503// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2504// regular serial code region, get thread ID by calling kmp_int32
2505// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2506// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002507Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2508 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002509 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002510 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002511 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002512 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002513
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002514 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002515 auto Int32Ty =
2516 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2517 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2518 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002519 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002520
2521 return ThreadIDTemp;
2522}
2523
Alexey Bataev97720002014-11-11 04:05:39 +00002524llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002525CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002526 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002527 SmallString<256> Buffer;
2528 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002529 Out << Name;
2530 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00002531 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
2532 if (Elem.second) {
2533 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002534 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002535 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002536 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002537
David Blaikie13156b62014-11-19 03:06:06 +00002538 return Elem.second = new llvm::GlobalVariable(
2539 CGM.getModule(), Ty, /*IsConstant*/ false,
2540 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2541 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002542}
2543
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002544llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00002545 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002546 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002547}
2548
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002549namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002550/// Common pre(post)-action for different OpenMP constructs.
2551class CommonActionTy final : public PrePostActionTy {
2552 llvm::Value *EnterCallee;
2553 ArrayRef<llvm::Value *> EnterArgs;
2554 llvm::Value *ExitCallee;
2555 ArrayRef<llvm::Value *> ExitArgs;
2556 bool Conditional;
2557 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002558
2559public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002560 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2561 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2562 bool Conditional = false)
2563 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2564 ExitArgs(ExitArgs), Conditional(Conditional) {}
2565 void Enter(CodeGenFunction &CGF) override {
2566 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2567 if (Conditional) {
2568 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2569 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2570 ContBlock = CGF.createBasicBlock("omp_if.end");
2571 // Generate the branch (If-stmt)
2572 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2573 CGF.EmitBlock(ThenBlock);
2574 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002575 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002576 void Done(CodeGenFunction &CGF) {
2577 // Emit the rest of blocks/branches
2578 CGF.EmitBranch(ContBlock);
2579 CGF.EmitBlock(ContBlock, true);
2580 }
2581 void Exit(CodeGenFunction &CGF) override {
2582 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002583 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002584};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002585} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002586
2587void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2588 StringRef CriticalName,
2589 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002590 SourceLocation Loc, const Expr *Hint) {
2591 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002592 // CriticalOpGen();
2593 // __kmpc_end_critical(ident_t *, gtid, Lock);
2594 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002595 if (!CGF.HaveInsertPoint())
2596 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002597 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2598 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002599 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2600 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002601 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002602 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2603 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2604 }
2605 CommonActionTy Action(
2606 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2607 : OMPRTL__kmpc_critical),
2608 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2609 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002610 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002611}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002612
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002613void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002614 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002615 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002616 if (!CGF.HaveInsertPoint())
2617 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002618 // if(__kmpc_master(ident_t *, gtid)) {
2619 // MasterOpGen();
2620 // __kmpc_end_master(ident_t *, gtid);
2621 // }
2622 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002623 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002624 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2625 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2626 /*Conditional=*/true);
2627 MasterOpGen.setAction(Action);
2628 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2629 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002630}
2631
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002632void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2633 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002634 if (!CGF.HaveInsertPoint())
2635 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00002636 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2637 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002638 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00002639 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002640 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002641 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2642 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00002643}
2644
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002645void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2646 const RegionCodeGenTy &TaskgroupOpGen,
2647 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002648 if (!CGF.HaveInsertPoint())
2649 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002650 // __kmpc_taskgroup(ident_t *, gtid);
2651 // TaskgroupOpGen();
2652 // __kmpc_end_taskgroup(ident_t *, gtid);
2653 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002654 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2655 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2656 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2657 Args);
2658 TaskgroupOpGen.setAction(Action);
2659 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002660}
2661
John McCall7f416cc2015-09-08 08:05:57 +00002662/// Given an array of pointers to variables, project the address of a
2663/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002664static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2665 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00002666 // Pull out the pointer to the variable.
2667 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002668 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00002669 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2670
2671 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002672 Addr = CGF.Builder.CreateElementBitCast(
2673 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002674 return Addr;
2675}
2676
Alexey Bataeva63048e2015-03-23 06:18:07 +00002677static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00002678 CodeGenModule &CGM, llvm::Type *ArgsType,
2679 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
2680 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002681 auto &C = CGM.getContext();
2682 // void copy_func(void *LHSArg, void *RHSArg);
2683 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002684 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
2685 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002686 Args.push_back(&LHSArg);
2687 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00002688 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002689 auto *Fn = llvm::Function::Create(
2690 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2691 ".omp.copyprivate.copy_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002692 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002693 CodeGenFunction CGF(CGM);
2694 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00002695 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002696 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00002697 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2698 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2699 ArgsType), CGF.getPointerAlign());
2700 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2701 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2702 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002703 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2704 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2705 // ...
2706 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00002707 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002708 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2709 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2710
2711 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2712 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2713
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002714 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2715 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00002716 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002717 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002718 CGF.FinishFunction();
2719 return Fn;
2720}
2721
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002722void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002723 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00002724 SourceLocation Loc,
2725 ArrayRef<const Expr *> CopyprivateVars,
2726 ArrayRef<const Expr *> SrcExprs,
2727 ArrayRef<const Expr *> DstExprs,
2728 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002729 if (!CGF.HaveInsertPoint())
2730 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002731 assert(CopyprivateVars.size() == SrcExprs.size() &&
2732 CopyprivateVars.size() == DstExprs.size() &&
2733 CopyprivateVars.size() == AssignmentOps.size());
2734 auto &C = CGM.getContext();
2735 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002736 // if(__kmpc_single(ident_t *, gtid)) {
2737 // SingleOpGen();
2738 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002739 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002740 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002741 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2742 // <copy_func>, did_it);
2743
John McCall7f416cc2015-09-08 08:05:57 +00002744 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00002745 if (!CopyprivateVars.empty()) {
2746 // int32 did_it = 0;
2747 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2748 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00002749 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002750 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002751 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002752 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002753 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
2754 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
2755 /*Conditional=*/true);
2756 SingleOpGen.setAction(Action);
2757 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2758 if (DidIt.isValid()) {
2759 // did_it = 1;
2760 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2761 }
2762 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002763 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2764 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00002765 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002766 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2767 auto CopyprivateArrayTy =
2768 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2769 /*IndexTypeQuals=*/0);
2770 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00002771 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00002772 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2773 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002774 Address Elem = CGF.Builder.CreateConstArrayGEP(
2775 CopyprivateList, I, CGF.getPointerSize());
2776 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00002777 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002778 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2779 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002780 }
2781 // Build function that copies private values from single region to all other
2782 // threads in the corresponding parallel region.
2783 auto *CpyFn = emitCopyprivateCopyFunction(
2784 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00002785 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev1189bd02016-01-26 12:20:39 +00002786 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00002787 Address CL =
2788 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2789 CGF.VoidPtrTy);
2790 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002791 llvm::Value *Args[] = {
2792 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2793 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00002794 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00002795 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00002796 CpyFn, // void (*) (void *, void *) <copy_func>
2797 DidItVal // i32 did_it
2798 };
2799 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2800 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002801}
2802
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002803void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2804 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00002805 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002806 if (!CGF.HaveInsertPoint())
2807 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002808 // __kmpc_ordered(ident_t *, gtid);
2809 // OrderedOpGen();
2810 // __kmpc_end_ordered(ident_t *, gtid);
2811 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00002812 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002813 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002814 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
2815 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2816 Args);
2817 OrderedOpGen.setAction(Action);
2818 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2819 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002820 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002821 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002822}
2823
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002824void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002825 OpenMPDirectiveKind Kind, bool EmitChecks,
2826 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002827 if (!CGF.HaveInsertPoint())
2828 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002829 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002830 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002831 unsigned Flags;
2832 if (Kind == OMPD_for)
2833 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2834 else if (Kind == OMPD_sections)
2835 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2836 else if (Kind == OMPD_single)
2837 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2838 else if (Kind == OMPD_barrier)
2839 Flags = OMP_IDENT_BARRIER_EXPL;
2840 else
2841 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002842 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2843 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002844 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2845 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002846 if (auto *OMPRegionInfo =
2847 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00002848 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002849 auto *Result = CGF.EmitRuntimeCall(
2850 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002851 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002852 // if (__kmpc_cancel_barrier()) {
2853 // exit from construct;
2854 // }
2855 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2856 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2857 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2858 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2859 CGF.EmitBlock(ExitBB);
2860 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002861 auto CancelDestination =
2862 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002863 CGF.EmitBranchThroughCleanup(CancelDestination);
2864 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2865 }
2866 return;
2867 }
2868 }
2869 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002870}
2871
Alexander Musmanc6388682014-12-15 07:07:06 +00002872/// \brief Map the OpenMP loop schedule to the runtime enumeration.
2873static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002874 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002875 switch (ScheduleKind) {
2876 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002877 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2878 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00002879 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002880 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002881 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002882 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002883 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002884 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2885 case OMPC_SCHEDULE_auto:
2886 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00002887 case OMPC_SCHEDULE_unknown:
2888 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002889 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00002890 }
2891 llvm_unreachable("Unexpected runtime schedule");
2892}
2893
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002894/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
2895static OpenMPSchedType
2896getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2897 // only static is allowed for dist_schedule
2898 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
2899}
2900
Alexander Musmanc6388682014-12-15 07:07:06 +00002901bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2902 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002903 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00002904 return Schedule == OMP_sch_static;
2905}
2906
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002907bool CGOpenMPRuntime::isStaticNonchunked(
2908 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2909 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2910 return Schedule == OMP_dist_sch_static;
2911}
2912
2913
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002914bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002915 auto Schedule =
2916 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002917 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2918 return Schedule != OMP_sch_static;
2919}
2920
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002921static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
2922 OpenMPScheduleClauseModifier M1,
2923 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00002924 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002925 switch (M1) {
2926 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002927 Modifier = OMP_sch_modifier_monotonic;
2928 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002929 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002930 Modifier = OMP_sch_modifier_nonmonotonic;
2931 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002932 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002933 if (Schedule == OMP_sch_static_chunked)
2934 Schedule = OMP_sch_static_balanced_chunked;
2935 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002936 case OMPC_SCHEDULE_MODIFIER_last:
2937 case OMPC_SCHEDULE_MODIFIER_unknown:
2938 break;
2939 }
2940 switch (M2) {
2941 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002942 Modifier = OMP_sch_modifier_monotonic;
2943 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002944 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002945 Modifier = OMP_sch_modifier_nonmonotonic;
2946 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002947 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002948 if (Schedule == OMP_sch_static_chunked)
2949 Schedule = OMP_sch_static_balanced_chunked;
2950 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002951 case OMPC_SCHEDULE_MODIFIER_last:
2952 case OMPC_SCHEDULE_MODIFIER_unknown:
2953 break;
2954 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00002955 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002956}
2957
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002958void CGOpenMPRuntime::emitForDispatchInit(
2959 CodeGenFunction &CGF, SourceLocation Loc,
2960 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
2961 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002962 if (!CGF.HaveInsertPoint())
2963 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002964 OpenMPSchedType Schedule = getRuntimeSchedule(
2965 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00002966 assert(Ordered ||
2967 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00002968 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
2969 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00002970 // Call __kmpc_dispatch_init(
2971 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2972 // kmp_int[32|64] lower, kmp_int[32|64] upper,
2973 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002974
John McCall7f416cc2015-09-08 08:05:57 +00002975 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002976 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
2977 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00002978 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002979 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2980 CGF.Builder.getInt32(addMonoNonMonoModifier(
2981 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002982 DispatchValues.LB, // Lower
2983 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002984 CGF.Builder.getIntN(IVSize, 1), // Stride
2985 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00002986 };
2987 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2988}
2989
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002990static void emitForStaticInitCall(
2991 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
2992 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
2993 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002994 const CGOpenMPRuntime::StaticRTInput &Values) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002995 if (!CGF.HaveInsertPoint())
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002996 return;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002997
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002998 assert(!Values.Ordered);
2999 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
3000 Schedule == OMP_sch_static_balanced_chunked ||
3001 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
3002 Schedule == OMP_dist_sch_static ||
3003 Schedule == OMP_dist_sch_static_chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003004
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003005 // Call __kmpc_for_static_init(
3006 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
3007 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
3008 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
3009 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
3010 llvm::Value *Chunk = Values.Chunk;
3011 if (Chunk == nullptr) {
3012 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
3013 Schedule == OMP_dist_sch_static) &&
3014 "expected static non-chunked schedule");
3015 // If the Chunk was not specified in the clause - use default value 1.
3016 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3017 } else {
3018 assert((Schedule == OMP_sch_static_chunked ||
3019 Schedule == OMP_sch_static_balanced_chunked ||
3020 Schedule == OMP_ord_static_chunked ||
3021 Schedule == OMP_dist_sch_static_chunked) &&
3022 "expected static chunked schedule");
3023 }
3024 llvm::Value *Args[] = {
3025 UpdateLocation,
3026 ThreadId,
3027 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3028 M2)), // Schedule type
3029 Values.IL.getPointer(), // &isLastIter
3030 Values.LB.getPointer(), // &LB
3031 Values.UB.getPointer(), // &UB
3032 Values.ST.getPointer(), // &Stride
3033 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3034 Chunk // Chunk
3035 };
3036 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003037}
3038
John McCall7f416cc2015-09-08 08:05:57 +00003039void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3040 SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003041 OpenMPDirectiveKind DKind,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003042 const OpenMPScheduleTy &ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003043 const StaticRTInput &Values) {
3044 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3045 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3046 assert(isOpenMPWorksharingDirective(DKind) &&
3047 "Expected loop-based or sections-based directive.");
3048 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc,
3049 isOpenMPLoopDirective(DKind)
3050 ? OMP_IDENT_WORK_LOOP
3051 : OMP_IDENT_WORK_SECTIONS);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003052 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003053 auto *StaticInitFunction =
3054 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003055 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003056 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003057}
John McCall7f416cc2015-09-08 08:05:57 +00003058
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003059void CGOpenMPRuntime::emitDistributeStaticInit(
3060 CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003061 OpenMPDistScheduleClauseKind SchedKind,
3062 const CGOpenMPRuntime::StaticRTInput &Values) {
3063 OpenMPSchedType ScheduleNum =
3064 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
3065 auto *UpdatedLocation =
3066 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003067 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003068 auto *StaticInitFunction =
3069 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003070 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3071 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003072 OMPC_SCHEDULE_MODIFIER_unknown, Values);
Alexander Musmanc6388682014-12-15 07:07:06 +00003073}
3074
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003075void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
Alexey Bataevf43f7142017-09-06 16:17:35 +00003076 SourceLocation Loc,
3077 OpenMPDirectiveKind DKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003078 if (!CGF.HaveInsertPoint())
3079 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003080 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataevf43f7142017-09-06 16:17:35 +00003081 llvm::Value *Args[] = {
3082 emitUpdateLocation(CGF, Loc,
3083 isOpenMPDistributeDirective(DKind)
3084 ? OMP_IDENT_WORK_DISTRIBUTE
3085 : isOpenMPLoopDirective(DKind)
3086 ? OMP_IDENT_WORK_LOOP
3087 : OMP_IDENT_WORK_SECTIONS),
3088 getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003089 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3090 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003091}
3092
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003093void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3094 SourceLocation Loc,
3095 unsigned IVSize,
3096 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003097 if (!CGF.HaveInsertPoint())
3098 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003099 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003100 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003101 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3102}
3103
Alexander Musman92bdaab2015-03-12 13:37:50 +00003104llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3105 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003106 bool IVSigned, Address IL,
3107 Address LB, Address UB,
3108 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003109 // Call __kmpc_dispatch_next(
3110 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3111 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3112 // kmp_int[32|64] *p_stride);
3113 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003114 emitUpdateLocation(CGF, Loc),
3115 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003116 IL.getPointer(), // &isLastIter
3117 LB.getPointer(), // &Lower
3118 UB.getPointer(), // &Upper
3119 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003120 };
3121 llvm::Value *Call =
3122 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3123 return CGF.EmitScalarConversion(
3124 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003125 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003126}
3127
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003128void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3129 llvm::Value *NumThreads,
3130 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003131 if (!CGF.HaveInsertPoint())
3132 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003133 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3134 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003135 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003136 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003137 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3138 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003139}
3140
Alexey Bataev7f210c62015-06-18 13:40:03 +00003141void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3142 OpenMPProcBindClauseKind ProcBind,
3143 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003144 if (!CGF.HaveInsertPoint())
3145 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003146 // Constants for proc bind value accepted by the runtime.
3147 enum ProcBindTy {
3148 ProcBindFalse = 0,
3149 ProcBindTrue,
3150 ProcBindMaster,
3151 ProcBindClose,
3152 ProcBindSpread,
3153 ProcBindIntel,
3154 ProcBindDefault
3155 } RuntimeProcBind;
3156 switch (ProcBind) {
3157 case OMPC_PROC_BIND_master:
3158 RuntimeProcBind = ProcBindMaster;
3159 break;
3160 case OMPC_PROC_BIND_close:
3161 RuntimeProcBind = ProcBindClose;
3162 break;
3163 case OMPC_PROC_BIND_spread:
3164 RuntimeProcBind = ProcBindSpread;
3165 break;
3166 case OMPC_PROC_BIND_unknown:
3167 llvm_unreachable("Unsupported proc_bind value.");
3168 }
3169 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3170 llvm::Value *Args[] = {
3171 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3172 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3173 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3174}
3175
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003176void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3177 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003178 if (!CGF.HaveInsertPoint())
3179 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003180 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003181 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3182 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003183}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003184
Alexey Bataev62b63b12015-03-10 07:28:44 +00003185namespace {
3186/// \brief Indexes of fields for type kmp_task_t.
3187enum KmpTaskTFields {
3188 /// \brief List of shared variables.
3189 KmpTaskTShareds,
3190 /// \brief Task routine.
3191 KmpTaskTRoutine,
3192 /// \brief Partition id for the untied tasks.
3193 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003194 /// Function with call of destructors for private variables.
3195 Data1,
3196 /// Task priority.
3197 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003198 /// (Taskloops only) Lower bound.
3199 KmpTaskTLowerBound,
3200 /// (Taskloops only) Upper bound.
3201 KmpTaskTUpperBound,
3202 /// (Taskloops only) Stride.
3203 KmpTaskTStride,
3204 /// (Taskloops only) Is last iteration flag.
3205 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003206 /// (Taskloops only) Reduction data.
3207 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003208};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003209} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003210
Samuel Antaoee8fb302016-01-06 13:42:12 +00003211bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
3212 // FIXME: Add other entries type when they become supported.
3213 return OffloadEntriesTargetRegion.empty();
3214}
3215
3216/// \brief Initialize target region entry.
3217void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3218 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3219 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003220 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003221 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3222 "only required for the device "
3223 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003224 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003225 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
3226 /*Flags=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003227 ++OffloadingEntriesNum;
3228}
3229
3230void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3231 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3232 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003233 llvm::Constant *Addr, llvm::Constant *ID,
3234 int32_t Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003235 // If we are emitting code for a target, the entry is already initialized,
3236 // only has to be registered.
3237 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003238 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00003239 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003240 auto &Entry =
3241 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003242 assert(Entry.isValid() && "Entry not initialized!");
3243 Entry.setAddress(Addr);
3244 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003245 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003246 return;
3247 } else {
Samuel Antaof83efdb2017-01-05 16:02:49 +00003248 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003249 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003250 }
3251}
3252
3253bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003254 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3255 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003256 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3257 if (PerDevice == OffloadEntriesTargetRegion.end())
3258 return false;
3259 auto PerFile = PerDevice->second.find(FileID);
3260 if (PerFile == PerDevice->second.end())
3261 return false;
3262 auto PerParentName = PerFile->second.find(ParentName);
3263 if (PerParentName == PerFile->second.end())
3264 return false;
3265 auto PerLine = PerParentName->second.find(LineNum);
3266 if (PerLine == PerParentName->second.end())
3267 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003268 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003269 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003270 return false;
3271 return true;
3272}
3273
3274void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3275 const OffloadTargetRegionEntryInfoActTy &Action) {
3276 // Scan all target region entries and perform the provided action.
3277 for (auto &D : OffloadEntriesTargetRegion)
3278 for (auto &F : D.second)
3279 for (auto &P : F.second)
3280 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003281 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003282}
3283
3284/// \brief Create a Ctor/Dtor-like function whose body is emitted through
3285/// \a Codegen. This is used to emit the two functions that register and
3286/// unregister the descriptor of the current compilation unit.
3287static llvm::Function *
3288createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
3289 const RegionCodeGenTy &Codegen) {
3290 auto &C = CGM.getContext();
3291 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003292 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003293 Args.push_back(&DummyPtr);
3294
3295 CodeGenFunction CGF(CGM);
John McCallc56a8b32016-03-11 04:30:31 +00003296 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003297 auto FTy = CGM.getTypes().GetFunctionType(FI);
3298 auto *Fn =
3299 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
3300 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
3301 Codegen(CGF);
3302 CGF.FinishFunction();
3303 return Fn;
3304}
3305
3306llvm::Function *
3307CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
3308
3309 // If we don't have entries or if we are emitting code for the device, we
3310 // don't need to do anything.
3311 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3312 return nullptr;
3313
3314 auto &M = CGM.getModule();
3315 auto &C = CGM.getContext();
3316
3317 // Get list of devices we care about
3318 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
3319
3320 // We should be creating an offloading descriptor only if there are devices
3321 // specified.
3322 assert(!Devices.empty() && "No OpenMP offloading devices??");
3323
3324 // Create the external variables that will point to the begin and end of the
3325 // host entries section. These will be defined by the linker.
3326 auto *OffloadEntryTy =
3327 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
3328 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
3329 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003330 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003331 ".omp_offloading.entries_begin");
3332 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
3333 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003334 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003335 ".omp_offloading.entries_end");
3336
3337 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003338 auto *DeviceImageTy = cast<llvm::StructType>(
3339 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003340 ConstantInitBuilder DeviceImagesBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003341 auto DeviceImagesEntries = DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003342
3343 for (unsigned i = 0; i < Devices.size(); ++i) {
3344 StringRef T = Devices[i].getTriple();
3345 auto *ImgBegin = new llvm::GlobalVariable(
3346 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003347 /*Initializer=*/nullptr,
3348 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003349 auto *ImgEnd = new llvm::GlobalVariable(
3350 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003351 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003352
John McCall6c9f1fdb2016-11-19 08:17:24 +00003353 auto Dev = DeviceImagesEntries.beginStruct(DeviceImageTy);
3354 Dev.add(ImgBegin);
3355 Dev.add(ImgEnd);
3356 Dev.add(HostEntriesBegin);
3357 Dev.add(HostEntriesEnd);
John McCallf1788632016-11-28 22:18:30 +00003358 Dev.finishAndAddTo(DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003359 }
3360
3361 // Create device images global array.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003362 llvm::GlobalVariable *DeviceImages =
3363 DeviceImagesEntries.finishAndCreateGlobal(".omp_offloading.device_images",
3364 CGM.getPointerAlign(),
3365 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003366 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003367
3368 // This is a Zero array to be used in the creation of the constant expressions
3369 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3370 llvm::Constant::getNullValue(CGM.Int32Ty)};
3371
3372 // Create the target region descriptor.
3373 auto *BinaryDescriptorTy = cast<llvm::StructType>(
3374 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003375 ConstantInitBuilder DescBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003376 auto DescInit = DescBuilder.beginStruct(BinaryDescriptorTy);
3377 DescInit.addInt(CGM.Int32Ty, Devices.size());
3378 DescInit.add(llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3379 DeviceImages,
3380 Index));
3381 DescInit.add(HostEntriesBegin);
3382 DescInit.add(HostEntriesEnd);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003383
John McCall6c9f1fdb2016-11-19 08:17:24 +00003384 auto *Desc = DescInit.finishAndCreateGlobal(".omp_offloading.descriptor",
3385 CGM.getPointerAlign(),
3386 /*isConstant=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003387
3388 // Emit code to register or unregister the descriptor at execution
3389 // startup or closing, respectively.
3390
3391 // Create a variable to drive the registration and unregistration of the
3392 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3393 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
3394 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00003395 IdentInfo, C.CharTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003396
3397 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003398 CGM, ".omp_offloading.descriptor_unreg",
3399 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00003400 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3401 Desc);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003402 });
3403 auto *RegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003404 CGM, ".omp_offloading.descriptor_reg",
3405 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00003406 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib),
3407 Desc);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003408 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3409 });
George Rokos29d0f002017-05-27 03:03:13 +00003410 if (CGM.supportsCOMDAT()) {
3411 // It is sufficient to call registration function only once, so create a
3412 // COMDAT group for registration/unregistration functions and associated
3413 // data. That would reduce startup time and code size. Registration
3414 // function serves as a COMDAT group key.
3415 auto ComdatKey = M.getOrInsertComdat(RegFn->getName());
3416 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3417 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3418 RegFn->setComdat(ComdatKey);
3419 UnRegFn->setComdat(ComdatKey);
3420 DeviceImages->setComdat(ComdatKey);
3421 Desc->setComdat(ComdatKey);
3422 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003423 return RegFn;
3424}
3425
Samuel Antao2de62b02016-02-13 23:35:10 +00003426void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003427 llvm::Constant *Addr, uint64_t Size,
3428 int32_t Flags) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003429 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003430 auto *TgtOffloadEntryType = cast<llvm::StructType>(
3431 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
3432 llvm::LLVMContext &C = CGM.getModule().getContext();
3433 llvm::Module &M = CGM.getModule();
3434
3435 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00003436 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003437
3438 // Create constant string with the name.
3439 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3440
3441 llvm::GlobalVariable *Str =
3442 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
3443 llvm::GlobalValue::InternalLinkage, StrPtrInit,
3444 ".omp_offloading.entry_name");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003445 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003446 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
3447
John McCall6c9f1fdb2016-11-19 08:17:24 +00003448 // We can't have any padding between symbols, so we need to have 1-byte
3449 // alignment.
3450 auto Align = CharUnits::fromQuantity(1);
3451
Samuel Antaoee8fb302016-01-06 13:42:12 +00003452 // Create the entry struct.
John McCall23c9dc62016-11-28 22:18:27 +00003453 ConstantInitBuilder EntryBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003454 auto EntryInit = EntryBuilder.beginStruct(TgtOffloadEntryType);
3455 EntryInit.add(AddrPtr);
3456 EntryInit.add(StrPtr);
3457 EntryInit.addInt(CGM.SizeTy, Size);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003458 EntryInit.addInt(CGM.Int32Ty, Flags);
3459 EntryInit.addInt(CGM.Int32Ty, 0);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003460 llvm::GlobalVariable *Entry =
3461 EntryInit.finishAndCreateGlobal(".omp_offloading.entry",
3462 Align,
3463 /*constant*/ true,
3464 llvm::GlobalValue::ExternalLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003465
3466 // The entry has to be created in the section the linker expects it to be.
3467 Entry->setSection(".omp_offloading.entries");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003468}
3469
3470void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3471 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003472 // can easily figure out what to emit. The produced metadata looks like
3473 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003474 //
3475 // !omp_offload.info = !{!1, ...}
3476 //
3477 // Right now we only generate metadata for function that contain target
3478 // regions.
3479
3480 // If we do not have entries, we dont need to do anything.
3481 if (OffloadEntriesInfoManager.empty())
3482 return;
3483
3484 llvm::Module &M = CGM.getModule();
3485 llvm::LLVMContext &C = M.getContext();
3486 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
3487 OrderedEntries(OffloadEntriesInfoManager.size());
3488
3489 // Create the offloading info metadata node.
3490 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
3491
Simon Pilgrim2c518802017-03-30 14:13:19 +00003492 // Auxiliary methods to create metadata values and strings.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003493 auto getMDInt = [&](unsigned v) {
3494 return llvm::ConstantAsMetadata::get(
3495 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
3496 };
3497
3498 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
3499
3500 // Create function that emits metadata for each target region entry;
3501 auto &&TargetRegionMetadataEmitter = [&](
3502 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003503 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3504 llvm::SmallVector<llvm::Metadata *, 32> Ops;
3505 // Generate metadata for target regions. Each entry of this metadata
3506 // contains:
3507 // - Entry 0 -> Kind of this type of metadata (0).
3508 // - Entry 1 -> Device ID of the file where the entry was identified.
3509 // - Entry 2 -> File ID of the file where the entry was identified.
3510 // - Entry 3 -> Mangled name of the function where the entry was identified.
3511 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00003512 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003513 // The first element of the metadata node is the kind.
3514 Ops.push_back(getMDInt(E.getKind()));
3515 Ops.push_back(getMDInt(DeviceID));
3516 Ops.push_back(getMDInt(FileID));
3517 Ops.push_back(getMDString(ParentName));
3518 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003519 Ops.push_back(getMDInt(E.getOrder()));
3520
3521 // Save this entry in the right position of the ordered entries array.
3522 OrderedEntries[E.getOrder()] = &E;
3523
3524 // Add metadata to the named metadata node.
3525 MD->addOperand(llvm::MDNode::get(C, Ops));
3526 };
3527
3528 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3529 TargetRegionMetadataEmitter);
3530
3531 for (auto *E : OrderedEntries) {
3532 assert(E && "All ordered entries must exist!");
3533 if (auto *CE =
3534 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3535 E)) {
3536 assert(CE->getID() && CE->getAddress() &&
3537 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00003538 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003539 } else
3540 llvm_unreachable("Unsupported entry kind.");
3541 }
3542}
3543
3544/// \brief Loads all the offload entries information from the host IR
3545/// metadata.
3546void CGOpenMPRuntime::loadOffloadInfoMetadata() {
3547 // If we are in target mode, load the metadata from the host IR. This code has
3548 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
3549
3550 if (!CGM.getLangOpts().OpenMPIsDevice)
3551 return;
3552
3553 if (CGM.getLangOpts().OMPHostIRFile.empty())
3554 return;
3555
3556 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
3557 if (Buf.getError())
3558 return;
3559
3560 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00003561 auto ME = expectedToErrorOrAndEmitErrors(
3562 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003563
3564 if (ME.getError())
3565 return;
3566
3567 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
3568 if (!MD)
3569 return;
3570
3571 for (auto I : MD->operands()) {
3572 llvm::MDNode *MN = cast<llvm::MDNode>(I);
3573
3574 auto getMDInt = [&](unsigned Idx) {
3575 llvm::ConstantAsMetadata *V =
3576 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
3577 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
3578 };
3579
3580 auto getMDString = [&](unsigned Idx) {
3581 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
3582 return V->getString();
3583 };
3584
3585 switch (getMDInt(0)) {
3586 default:
3587 llvm_unreachable("Unexpected metadata!");
3588 break;
3589 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3590 OFFLOAD_ENTRY_INFO_TARGET_REGION:
3591 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
3592 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
3593 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00003594 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003595 break;
3596 }
3597 }
3598}
3599
Alexey Bataev62b63b12015-03-10 07:28:44 +00003600void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
3601 if (!KmpRoutineEntryPtrTy) {
3602 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
3603 auto &C = CGM.getContext();
3604 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
3605 FunctionProtoType::ExtProtoInfo EPI;
3606 KmpRoutineEntryPtrQTy = C.getPointerType(
3607 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
3608 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
3609 }
3610}
3611
Alexey Bataevc71a4092015-09-11 10:29:41 +00003612static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
3613 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003614 auto *Field = FieldDecl::Create(
3615 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
3616 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
3617 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
3618 Field->setAccess(AS_public);
3619 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003620 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003621}
3622
Samuel Antaoee8fb302016-01-06 13:42:12 +00003623QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
3624
3625 // Make sure the type of the entry is already created. This is the type we
3626 // have to create:
3627 // struct __tgt_offload_entry{
3628 // void *addr; // Pointer to the offload entry info.
3629 // // (function or global)
3630 // char *name; // Name of the function or global.
3631 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00003632 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
3633 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003634 // };
3635 if (TgtOffloadEntryQTy.isNull()) {
3636 ASTContext &C = CGM.getContext();
3637 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
3638 RD->startDefinition();
3639 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3640 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
3641 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00003642 addFieldToRecordDecl(
3643 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3644 addFieldToRecordDecl(
3645 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003646 RD->completeDefinition();
3647 TgtOffloadEntryQTy = C.getRecordType(RD);
3648 }
3649 return TgtOffloadEntryQTy;
3650}
3651
3652QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
3653 // These are the types we need to build:
3654 // struct __tgt_device_image{
3655 // void *ImageStart; // Pointer to the target code start.
3656 // void *ImageEnd; // Pointer to the target code end.
3657 // // We also add the host entries to the device image, as it may be useful
3658 // // for the target runtime to have access to that information.
3659 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
3660 // // the entries.
3661 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3662 // // entries (non inclusive).
3663 // };
3664 if (TgtDeviceImageQTy.isNull()) {
3665 ASTContext &C = CGM.getContext();
3666 auto *RD = C.buildImplicitRecord("__tgt_device_image");
3667 RD->startDefinition();
3668 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3669 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3670 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3671 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3672 RD->completeDefinition();
3673 TgtDeviceImageQTy = C.getRecordType(RD);
3674 }
3675 return TgtDeviceImageQTy;
3676}
3677
3678QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
3679 // struct __tgt_bin_desc{
3680 // int32_t NumDevices; // Number of devices supported.
3681 // __tgt_device_image *DeviceImages; // Arrays of device images
3682 // // (one per device).
3683 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
3684 // // entries.
3685 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3686 // // entries (non inclusive).
3687 // };
3688 if (TgtBinaryDescriptorQTy.isNull()) {
3689 ASTContext &C = CGM.getContext();
3690 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
3691 RD->startDefinition();
3692 addFieldToRecordDecl(
3693 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3694 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
3695 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3696 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3697 RD->completeDefinition();
3698 TgtBinaryDescriptorQTy = C.getRecordType(RD);
3699 }
3700 return TgtBinaryDescriptorQTy;
3701}
3702
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003703namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00003704struct PrivateHelpersTy {
3705 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
3706 const VarDecl *PrivateElemInit)
3707 : Original(Original), PrivateCopy(PrivateCopy),
3708 PrivateElemInit(PrivateElemInit) {}
3709 const VarDecl *Original;
3710 const VarDecl *PrivateCopy;
3711 const VarDecl *PrivateElemInit;
3712};
3713typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00003714} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003715
Alexey Bataev9e034042015-05-05 04:05:12 +00003716static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00003717createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003718 if (!Privates.empty()) {
3719 auto &C = CGM.getContext();
3720 // Build struct .kmp_privates_t. {
3721 // /* private vars */
3722 // };
3723 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
3724 RD->startDefinition();
3725 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00003726 auto *VD = Pair.second.Original;
3727 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003728 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00003729 auto *FD = addFieldToRecordDecl(C, RD, Type);
3730 if (VD->hasAttrs()) {
3731 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
3732 E(VD->getAttrs().end());
3733 I != E; ++I)
3734 FD->addAttr(*I);
3735 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003736 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003737 RD->completeDefinition();
3738 return RD;
3739 }
3740 return nullptr;
3741}
3742
Alexey Bataev9e034042015-05-05 04:05:12 +00003743static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00003744createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
3745 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003746 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003747 auto &C = CGM.getContext();
3748 // Build struct kmp_task_t {
3749 // void * shareds;
3750 // kmp_routine_entry_t routine;
3751 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00003752 // kmp_cmplrdata_t data1;
3753 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00003754 // For taskloops additional fields:
3755 // kmp_uint64 lb;
3756 // kmp_uint64 ub;
3757 // kmp_int64 st;
3758 // kmp_int32 liter;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003759 // void * reductions;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003760 // };
Alexey Bataevad537bb2016-05-30 09:06:50 +00003761 auto *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
3762 UD->startDefinition();
3763 addFieldToRecordDecl(C, UD, KmpInt32Ty);
3764 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
3765 UD->completeDefinition();
3766 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003767 auto *RD = C.buildImplicitRecord("kmp_task_t");
3768 RD->startDefinition();
3769 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3770 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
3771 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00003772 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3773 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003774 if (isOpenMPTaskLoopDirective(Kind)) {
3775 QualType KmpUInt64Ty =
3776 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3777 QualType KmpInt64Ty =
3778 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3779 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3780 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3781 addFieldToRecordDecl(C, RD, KmpInt64Ty);
3782 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003783 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003784 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003785 RD->completeDefinition();
3786 return RD;
3787}
3788
3789static RecordDecl *
3790createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003791 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003792 auto &C = CGM.getContext();
3793 // Build struct kmp_task_t_with_privates {
3794 // kmp_task_t task_data;
3795 // .kmp_privates_t. privates;
3796 // };
3797 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
3798 RD->startDefinition();
3799 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003800 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
3801 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
3802 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003803 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003804 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003805}
3806
3807/// \brief Emit a proxy function which accepts kmp_task_t as the second
3808/// argument.
3809/// \code
3810/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003811/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00003812/// For taskloops:
3813/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003814/// tt->reductions, tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003815/// return 0;
3816/// }
3817/// \endcode
3818static llvm::Value *
3819emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00003820 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
3821 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003822 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003823 QualType SharedsPtrTy, llvm::Value *TaskFunction,
3824 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003825 auto &C = CGM.getContext();
3826 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003827 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3828 ImplicitParamDecl::Other);
3829 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3830 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3831 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003832 Args.push_back(&GtidArg);
3833 Args.push_back(&TaskTypeArg);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003834 auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003835 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003836 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
3837 auto *TaskEntry =
3838 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
3839 ".omp_task_entry.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003840 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003841 CodeGenFunction CGF(CGM);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003842 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
3843
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003844 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00003845 // tt,
3846 // For taskloops:
3847 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3848 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003849 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00003850 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003851 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3852 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3853 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003854 auto *KmpTaskTWithPrivatesQTyRD =
3855 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003856 LValue Base =
3857 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003858 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3859 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3860 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003861 auto *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003862
3863 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3864 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003865 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003866 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003867 CGF.ConvertTypeForMem(SharedsPtrTy));
3868
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003869 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3870 llvm::Value *PrivatesParam;
3871 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3872 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3873 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003874 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003875 } else
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003876 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003877
Alexey Bataev7292c292016-04-25 12:22:29 +00003878 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
3879 TaskPrivatesMap,
3880 CGF.Builder
3881 .CreatePointerBitCastOrAddrSpaceCast(
3882 TDBase.getAddress(), CGF.VoidPtrTy)
3883 .getPointer()};
3884 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
3885 std::end(CommonArgs));
3886 if (isOpenMPTaskLoopDirective(Kind)) {
3887 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
3888 auto LBLVal = CGF.EmitLValueForField(Base, *LBFI);
3889 auto *LBParam = CGF.EmitLoadOfLValue(LBLVal, Loc).getScalarVal();
3890 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
3891 auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
3892 auto *UBParam = CGF.EmitLoadOfLValue(UBLVal, Loc).getScalarVal();
3893 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
3894 auto StLVal = CGF.EmitLValueForField(Base, *StFI);
3895 auto *StParam = CGF.EmitLoadOfLValue(StLVal, Loc).getScalarVal();
3896 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3897 auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
3898 auto *LIParam = CGF.EmitLoadOfLValue(LILVal, Loc).getScalarVal();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003899 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
3900 auto RLVal = CGF.EmitLValueForField(Base, *RFI);
3901 auto *RParam = CGF.EmitLoadOfLValue(RLVal, Loc).getScalarVal();
Alexey Bataev7292c292016-04-25 12:22:29 +00003902 CallArgs.push_back(LBParam);
3903 CallArgs.push_back(UBParam);
3904 CallArgs.push_back(StParam);
3905 CallArgs.push_back(LIParam);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003906 CallArgs.push_back(RParam);
Alexey Bataev7292c292016-04-25 12:22:29 +00003907 }
3908 CallArgs.push_back(SharedsParam);
3909
Alexey Bataev3c595a62017-08-14 15:01:03 +00003910 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
3911 CallArgs);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003912 CGF.EmitStoreThroughLValue(
3913 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00003914 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00003915 CGF.FinishFunction();
3916 return TaskEntry;
3917}
3918
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003919static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
3920 SourceLocation Loc,
3921 QualType KmpInt32Ty,
3922 QualType KmpTaskTWithPrivatesPtrQTy,
3923 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003924 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003925 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003926 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3927 ImplicitParamDecl::Other);
3928 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3929 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3930 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003931 Args.push_back(&GtidArg);
3932 Args.push_back(&TaskTypeArg);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003933 auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003934 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003935 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
3936 auto *DestructorFn =
3937 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
3938 ".omp_task_destructor.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003939 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
3940 DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003941 CodeGenFunction CGF(CGM);
3942 CGF.disableDebugInfo();
3943 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
3944 Args);
3945
Alexey Bataev31300ed2016-02-04 11:27:03 +00003946 LValue Base = CGF.EmitLoadOfPointerLValue(
3947 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3948 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003949 auto *KmpTaskTWithPrivatesQTyRD =
3950 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3951 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003952 Base = CGF.EmitLValueForField(Base, *FI);
3953 for (auto *Field :
3954 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
3955 if (auto DtorKind = Field->getType().isDestructedType()) {
3956 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
3957 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
3958 }
3959 }
3960 CGF.FinishFunction();
3961 return DestructorFn;
3962}
3963
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003964/// \brief Emit a privates mapping function for correct handling of private and
3965/// firstprivate variables.
3966/// \code
3967/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
3968/// **noalias priv1,..., <tyn> **noalias privn) {
3969/// *priv1 = &.privates.priv1;
3970/// ...;
3971/// *privn = &.privates.privn;
3972/// }
3973/// \endcode
3974static llvm::Value *
3975emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00003976 ArrayRef<const Expr *> PrivateVars,
3977 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00003978 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003979 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003980 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003981 auto &C = CGM.getContext();
3982 FunctionArgList Args;
3983 ImplicitParamDecl TaskPrivatesArg(
3984 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003985 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
3986 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003987 Args.push_back(&TaskPrivatesArg);
3988 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
3989 unsigned Counter = 1;
3990 for (auto *E: PrivateVars) {
3991 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003992 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3993 C.getPointerType(C.getPointerType(E->getType()))
3994 .withConst()
3995 .withRestrict(),
3996 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003997 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3998 PrivateVarsPos[VD] = Counter;
3999 ++Counter;
4000 }
4001 for (auto *E : FirstprivateVars) {
4002 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004003 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4004 C.getPointerType(C.getPointerType(E->getType()))
4005 .withConst()
4006 .withRestrict(),
4007 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004008 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4009 PrivateVarsPos[VD] = Counter;
4010 ++Counter;
4011 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004012 for (auto *E: LastprivateVars) {
4013 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004014 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4015 C.getPointerType(C.getPointerType(E->getType()))
4016 .withConst()
4017 .withRestrict(),
4018 ImplicitParamDecl::Other));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004019 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4020 PrivateVarsPos[VD] = Counter;
4021 ++Counter;
4022 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004023 auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004024 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004025 auto *TaskPrivatesMapTy =
4026 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
4027 auto *TaskPrivatesMap = llvm::Function::Create(
4028 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
4029 ".omp_task_privates_map.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004030 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
4031 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00004032 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00004033 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00004034 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004035 CodeGenFunction CGF(CGM);
4036 CGF.disableDebugInfo();
4037 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
4038 TaskPrivatesMapFnInfo, Args);
4039
4040 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00004041 LValue Base = CGF.EmitLoadOfPointerLValue(
4042 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4043 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004044 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
4045 Counter = 0;
4046 for (auto *Field : PrivatesQTyRD->fields()) {
4047 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
4048 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00004049 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00004050 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
4051 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00004052 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004053 ++Counter;
4054 }
4055 CGF.FinishFunction();
4056 return TaskPrivatesMap;
4057}
4058
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004059static bool stable_sort_comparator(const PrivateDataTy P1,
4060 const PrivateDataTy P2) {
4061 return P1.first > P2.first;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004062}
4063
Alexey Bataevf93095a2016-05-05 08:46:22 +00004064/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00004065static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004066 const OMPExecutableDirective &D,
4067 Address KmpTaskSharedsPtr, LValue TDBase,
4068 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4069 QualType SharedsTy, QualType SharedsPtrTy,
4070 const OMPTaskDataTy &Data,
4071 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
4072 auto &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004073 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4074 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
4075 LValue SrcBase;
4076 if (!Data.FirstprivateVars.empty()) {
4077 SrcBase = CGF.MakeAddrLValue(
4078 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4079 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4080 SharedsTy);
4081 }
4082 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
4083 cast<CapturedStmt>(*D.getAssociatedStmt()));
4084 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
4085 for (auto &&Pair : Privates) {
4086 auto *VD = Pair.second.PrivateCopy;
4087 auto *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004088 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4089 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004090 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004091 if (auto *Elem = Pair.second.PrivateElemInit) {
4092 auto *OriginalVD = Pair.second.Original;
4093 auto *SharedField = CapturesInfo.lookup(OriginalVD);
4094 auto SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4095 SharedRefLValue = CGF.MakeAddrLValue(
4096 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004097 SharedRefLValue.getType(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00004098 LValueBaseInfo(AlignmentSource::Decl),
4099 SharedRefLValue.getTBAAInfo());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004100 QualType Type = OriginalVD->getType();
4101 if (Type->isArrayType()) {
4102 // Initialize firstprivate array.
4103 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4104 // Perform simple memcpy.
4105 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
4106 SharedRefLValue.getAddress(), Type);
4107 } else {
4108 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00004109 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00004110 CGF.EmitOMPAggregateAssign(
4111 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4112 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4113 Address SrcElement) {
4114 // Clean up any temporaries needed by the initialization.
4115 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4116 InitScope.addPrivate(
4117 Elem, [SrcElement]() -> Address { return SrcElement; });
4118 (void)InitScope.Privatize();
4119 // Emit initialization for single element.
4120 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4121 CGF, &CapturesInfo);
4122 CGF.EmitAnyExprToMem(Init, DestElement,
4123 Init->getType().getQualifiers(),
4124 /*IsInitializer=*/false);
4125 });
4126 }
4127 } else {
4128 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4129 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4130 return SharedRefLValue.getAddress();
4131 });
4132 (void)InitScope.Privatize();
4133 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4134 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4135 /*capturedByInit=*/false);
4136 }
4137 } else
4138 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
4139 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004140 ++FI;
4141 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004142}
4143
4144/// Check if duplication function is required for taskloops.
4145static bool checkInitIsRequired(CodeGenFunction &CGF,
4146 ArrayRef<PrivateDataTy> Privates) {
4147 bool InitRequired = false;
4148 for (auto &&Pair : Privates) {
4149 auto *VD = Pair.second.PrivateCopy;
4150 auto *Init = VD->getAnyInitializer();
4151 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4152 !CGF.isTrivialInitializer(Init));
4153 }
4154 return InitRequired;
4155}
4156
4157
4158/// Emit task_dup function (for initialization of
4159/// private/firstprivate/lastprivate vars and last_iter flag)
4160/// \code
4161/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4162/// lastpriv) {
4163/// // setup lastprivate flag
4164/// task_dst->last = lastpriv;
4165/// // could be constructor calls here...
4166/// }
4167/// \endcode
4168static llvm::Value *
4169emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4170 const OMPExecutableDirective &D,
4171 QualType KmpTaskTWithPrivatesPtrQTy,
4172 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4173 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4174 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4175 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
4176 auto &C = CGM.getContext();
4177 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004178 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4179 KmpTaskTWithPrivatesPtrQTy,
4180 ImplicitParamDecl::Other);
4181 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4182 KmpTaskTWithPrivatesPtrQTy,
4183 ImplicitParamDecl::Other);
4184 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4185 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004186 Args.push_back(&DstArg);
4187 Args.push_back(&SrcArg);
4188 Args.push_back(&LastprivArg);
4189 auto &TaskDupFnInfo =
4190 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
4191 auto *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
4192 auto *TaskDup =
4193 llvm::Function::Create(TaskDupTy, llvm::GlobalValue::InternalLinkage,
4194 ".omp_task_dup.", &CGM.getModule());
4195 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskDup, TaskDupFnInfo);
4196 CodeGenFunction CGF(CGM);
4197 CGF.disableDebugInfo();
4198 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args);
4199
4200 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4201 CGF.GetAddrOfLocalVar(&DstArg),
4202 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4203 // task_dst->liter = lastpriv;
4204 if (WithLastIter) {
4205 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4206 LValue Base = CGF.EmitLValueForField(
4207 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4208 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4209 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4210 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4211 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4212 }
4213
4214 // Emit initial values for private copies (if any).
4215 assert(!Privates.empty());
4216 Address KmpTaskSharedsPtr = Address::invalid();
4217 if (!Data.FirstprivateVars.empty()) {
4218 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4219 CGF.GetAddrOfLocalVar(&SrcArg),
4220 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4221 LValue Base = CGF.EmitLValueForField(
4222 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4223 KmpTaskSharedsPtr = Address(
4224 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4225 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4226 KmpTaskTShareds)),
4227 Loc),
4228 CGF.getNaturalTypeAlignment(SharedsTy));
4229 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004230 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4231 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004232 CGF.FinishFunction();
4233 return TaskDup;
4234}
4235
Alexey Bataev8a831592016-05-10 10:36:51 +00004236/// Checks if destructor function is required to be generated.
4237/// \return true if cleanups are required, false otherwise.
4238static bool
4239checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4240 bool NeedsCleanup = false;
4241 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4242 auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4243 for (auto *FD : PrivateRD->fields()) {
4244 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4245 if (NeedsCleanup)
4246 break;
4247 }
4248 return NeedsCleanup;
4249}
4250
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004251CGOpenMPRuntime::TaskResultTy
4252CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4253 const OMPExecutableDirective &D,
4254 llvm::Value *TaskFunction, QualType SharedsTy,
4255 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004256 auto &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004257 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004258 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004259 auto I = Data.PrivateCopies.begin();
4260 for (auto *E : Data.PrivateVars) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004261 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4262 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004263 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004264 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4265 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004266 ++I;
4267 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004268 I = Data.FirstprivateCopies.begin();
4269 auto IElemInitRef = Data.FirstprivateInits.begin();
4270 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev9e034042015-05-05 04:05:12 +00004271 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4272 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004273 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004274 PrivateHelpersTy(
4275 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4276 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
Richard Trieucc3949d2016-02-18 22:34:54 +00004277 ++I;
4278 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004279 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004280 I = Data.LastprivateCopies.begin();
4281 for (auto *E : Data.LastprivateVars) {
4282 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4283 Privates.push_back(std::make_pair(
4284 C.getDeclAlign(VD),
4285 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4286 /*PrivateElemInit=*/nullptr)));
4287 ++I;
4288 }
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004289 std::stable_sort(Privates.begin(), Privates.end(), stable_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004290 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
4291 // Build type kmp_routine_entry_t (if not built yet).
4292 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004293 // Build type kmp_task_t (if not built yet).
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004294 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
4295 if (SavedKmpTaskloopTQTy.isNull()) {
4296 SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4297 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4298 }
4299 KmpTaskTQTy = SavedKmpTaskloopTQTy;
Alexey Bataev3a03a7f2017-10-11 15:56:38 +00004300 } else {
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004301 assert(D.getDirectiveKind() == OMPD_task &&
4302 "Expected taskloop or task directive");
4303 if (SavedKmpTaskTQTy.isNull()) {
4304 SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4305 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4306 }
4307 KmpTaskTQTy = SavedKmpTaskTQTy;
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004308 }
4309 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004310 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004311 auto *KmpTaskTWithPrivatesQTyRD =
4312 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
4313 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
4314 QualType KmpTaskTWithPrivatesPtrQTy =
4315 C.getPointerType(KmpTaskTWithPrivatesQTy);
4316 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4317 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004318 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004319 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4320
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004321 // Emit initial values for private copies (if any).
4322 llvm::Value *TaskPrivatesMap = nullptr;
4323 auto *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00004324 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004325 if (!Privates.empty()) {
4326 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004327 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4328 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4329 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004330 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4331 TaskPrivatesMap, TaskPrivatesMapTy);
4332 } else {
4333 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4334 cast<llvm::PointerType>(TaskPrivatesMapTy));
4335 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004336 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4337 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004338 auto *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004339 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4340 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4341 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004342
4343 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4344 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4345 // kmp_routine_entry_t *task_entry);
4346 // Task flags. Format is taken from
4347 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4348 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004349 enum {
4350 TiedFlag = 0x1,
4351 FinalFlag = 0x2,
4352 DestructorsFlag = 0x8,
4353 PriorityFlag = 0x20
4354 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004355 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004356 bool NeedsCleanup = false;
4357 if (!Privates.empty()) {
4358 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4359 if (NeedsCleanup)
4360 Flags = Flags | DestructorsFlag;
4361 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004362 if (Data.Priority.getInt())
4363 Flags = Flags | PriorityFlag;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004364 auto *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004365 Data.Final.getPointer()
4366 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00004367 CGF.Builder.getInt32(FinalFlag),
4368 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004369 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004370 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00004371 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004372 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4373 getThreadID(CGF, Loc), TaskFlags,
4374 KmpTaskTWithPrivatesTySize, SharedsSize,
4375 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4376 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00004377 auto *NewTask = CGF.EmitRuntimeCall(
4378 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004379 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4380 NewTask, KmpTaskTWithPrivatesPtrTy);
4381 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4382 KmpTaskTWithPrivatesQTy);
4383 LValue TDBase =
4384 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004385 // Fill the data in the resulting kmp_task_t record.
4386 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00004387 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004388 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00004389 KmpTaskSharedsPtr =
4390 Address(CGF.EmitLoadOfScalar(
4391 CGF.EmitLValueForField(
4392 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4393 KmpTaskTShareds)),
4394 Loc),
4395 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004396 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004397 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004398 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00004399 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004400 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004401 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4402 SharedsTy, SharedsPtrTy, Data, Privates,
4403 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004404 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4405 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4406 Result.TaskDupFn = emitTaskDupFunction(
4407 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4408 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4409 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004410 }
4411 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00004412 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4413 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00004414 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00004415 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
4416 auto *KmpCmplrdataUD = (*FI)->getType()->getAsUnionType()->getDecl();
4417 if (NeedsCleanup) {
4418 llvm::Value *DestructorFn = emitDestructorsFunction(
4419 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4420 KmpTaskTWithPrivatesQTy);
4421 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4422 LValue DestructorsLV = CGF.EmitLValueForField(
4423 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4424 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4425 DestructorFn, KmpRoutineEntryPtrTy),
4426 DestructorsLV);
4427 }
4428 // Set priority.
4429 if (Data.Priority.getInt()) {
4430 LValue Data2LV = CGF.EmitLValueForField(
4431 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
4432 LValue PriorityLV = CGF.EmitLValueForField(
4433 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
4434 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
4435 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004436 Result.NewTask = NewTask;
4437 Result.TaskEntry = TaskEntry;
4438 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
4439 Result.TDBase = TDBase;
4440 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
4441 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00004442}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004443
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004444void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
4445 const OMPExecutableDirective &D,
4446 llvm::Value *TaskFunction,
4447 QualType SharedsTy, Address Shareds,
4448 const Expr *IfCond,
4449 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004450 if (!CGF.HaveInsertPoint())
4451 return;
4452
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004453 TaskResultTy Result =
4454 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4455 llvm::Value *NewTask = Result.NewTask;
4456 llvm::Value *TaskEntry = Result.TaskEntry;
4457 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
4458 LValue TDBase = Result.TDBase;
4459 RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
Alexey Bataev7292c292016-04-25 12:22:29 +00004460 auto &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004461 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00004462 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004463 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00004464 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004465 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00004466 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004467 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
4468 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004469 QualType FlagsTy =
4470 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004471 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
4472 if (KmpDependInfoTy.isNull()) {
4473 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
4474 KmpDependInfoRD->startDefinition();
4475 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
4476 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
4477 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
4478 KmpDependInfoRD->completeDefinition();
4479 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004480 } else
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004481 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
John McCall7f416cc2015-09-08 08:05:57 +00004482 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004483 // Define type kmp_depend_info[<Dependences.size()>];
4484 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00004485 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004486 ArrayType::Normal, /*IndexTypeQuals=*/0);
4487 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00004488 DependenciesArray =
4489 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
John McCall7f416cc2015-09-08 08:05:57 +00004490 for (unsigned i = 0; i < NumDependencies; ++i) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004491 const Expr *E = Data.Dependences[i].second;
John McCall7f416cc2015-09-08 08:05:57 +00004492 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004493 llvm::Value *Size;
4494 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004495 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
4496 LValue UpAddrLVal =
4497 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
4498 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00004499 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004500 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00004501 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004502 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
4503 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004504 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00004505 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00004506 auto Base = CGF.MakeAddrLValue(
4507 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004508 KmpDependInfoTy);
4509 // deps[i].base_addr = &<Dependences[i].second>;
4510 auto BaseAddrLVal = CGF.EmitLValueForField(
4511 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00004512 CGF.EmitStoreOfScalar(
4513 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
4514 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004515 // deps[i].len = sizeof(<Dependences[i].second>);
4516 auto LenLVal = CGF.EmitLValueForField(
4517 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
4518 CGF.EmitStoreOfScalar(Size, LenLVal);
4519 // deps[i].flags = <Dependences[i].first>;
4520 RTLDependenceKindTy DepKind;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004521 switch (Data.Dependences[i].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004522 case OMPC_DEPEND_in:
4523 DepKind = DepIn;
4524 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00004525 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004526 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004527 case OMPC_DEPEND_inout:
4528 DepKind = DepInOut;
4529 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00004530 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004531 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004532 case OMPC_DEPEND_unknown:
4533 llvm_unreachable("Unknown task dependence type");
4534 }
4535 auto FlagsLVal = CGF.EmitLValueForField(
4536 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
4537 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
4538 FlagsLVal);
4539 }
John McCall7f416cc2015-09-08 08:05:57 +00004540 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4541 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004542 CGF.VoidPtrTy);
4543 }
4544
Alexey Bataev62b63b12015-03-10 07:28:44 +00004545 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4546 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004547 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
4548 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
4549 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
4550 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00004551 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004552 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00004553 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
4554 llvm::Value *DepTaskArgs[7];
4555 if (NumDependencies) {
4556 DepTaskArgs[0] = UpLoc;
4557 DepTaskArgs[1] = ThreadID;
4558 DepTaskArgs[2] = NewTask;
4559 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
4560 DepTaskArgs[4] = DependenciesArray.getPointer();
4561 DepTaskArgs[5] = CGF.Builder.getInt32(0);
4562 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4563 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00004564 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
4565 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004566 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004567 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004568 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4569 auto PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
4570 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
4571 }
John McCall7f416cc2015-09-08 08:05:57 +00004572 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004573 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00004574 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00004575 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004576 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00004577 TaskArgs);
4578 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00004579 // Check if parent region is untied and build return for untied task;
4580 if (auto *Region =
4581 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4582 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00004583 };
John McCall7f416cc2015-09-08 08:05:57 +00004584
4585 llvm::Value *DepWaitTaskArgs[6];
4586 if (NumDependencies) {
4587 DepWaitTaskArgs[0] = UpLoc;
4588 DepWaitTaskArgs[1] = ThreadID;
4589 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
4590 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
4591 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
4592 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4593 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004594 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00004595 NumDependencies, &DepWaitTaskArgs,
4596 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004597 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004598 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
4599 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
4600 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
4601 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
4602 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00004603 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004604 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004605 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004606 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00004607 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
4608 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004609 Action.Enter(CGF);
4610 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00004611 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00004612 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004613 };
4614
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004615 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
4616 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004617 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
4618 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004619 RegionCodeGenTy RCG(CodeGen);
4620 CommonActionTy Action(
4621 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
4622 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
4623 RCG.setAction(Action);
4624 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004625 };
John McCall7f416cc2015-09-08 08:05:57 +00004626
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004627 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00004628 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004629 else {
4630 RegionCodeGenTy ThenRCG(ThenCodeGen);
4631 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00004632 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004633}
4634
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004635void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
4636 const OMPLoopDirective &D,
4637 llvm::Value *TaskFunction,
4638 QualType SharedsTy, Address Shareds,
4639 const Expr *IfCond,
4640 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004641 if (!CGF.HaveInsertPoint())
4642 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004643 TaskResultTy Result =
4644 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004645 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4646 // libcall.
4647 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
4648 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
4649 // sched, kmp_uint64 grainsize, void *task_dup);
4650 llvm::Value *ThreadID = getThreadID(CGF, Loc);
4651 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
4652 llvm::Value *IfVal;
4653 if (IfCond) {
4654 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
4655 /*isSigned=*/true);
4656 } else
4657 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
4658
4659 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004660 Result.TDBase,
4661 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004662 auto *LBVar =
4663 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
4664 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
4665 /*IsInitializer=*/true);
4666 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004667 Result.TDBase,
4668 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004669 auto *UBVar =
4670 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
4671 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
4672 /*IsInitializer=*/true);
4673 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004674 Result.TDBase,
4675 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataev7292c292016-04-25 12:22:29 +00004676 auto *StVar =
4677 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
4678 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
4679 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004680 // Store reductions address.
4681 LValue RedLVal = CGF.EmitLValueForField(
4682 Result.TDBase,
4683 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
4684 if (Data.Reductions)
4685 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
4686 else {
4687 CGF.EmitNullInitialization(RedLVal.getAddress(),
4688 CGF.getContext().VoidPtrTy);
4689 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004690 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00004691 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00004692 UpLoc,
4693 ThreadID,
4694 Result.NewTask,
4695 IfVal,
4696 LBLVal.getPointer(),
4697 UBLVal.getPointer(),
4698 CGF.EmitLoadOfScalar(StLVal, SourceLocation()),
4699 llvm::ConstantInt::getNullValue(
4700 CGF.IntTy), // Always 0 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004701 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004702 CGF.IntTy, Data.Schedule.getPointer()
4703 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004704 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004705 Data.Schedule.getPointer()
4706 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004707 /*isSigned=*/false)
4708 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00004709 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4710 Result.TaskDupFn, CGF.VoidPtrTy)
4711 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00004712 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
4713}
4714
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004715/// \brief Emit reduction operation for each element of array (required for
4716/// array sections) LHS op = RHS.
4717/// \param Type Type of array.
4718/// \param LHSVar Variable on the left side of the reduction operation
4719/// (references element of array in original variable).
4720/// \param RHSVar Variable on the right side of the reduction operation
4721/// (references element of array in original variable).
4722/// \param RedOpGen Generator of reduction operation with use of LHSVar and
4723/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00004724static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004725 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
4726 const VarDecl *RHSVar,
4727 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
4728 const Expr *, const Expr *)> &RedOpGen,
4729 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
4730 const Expr *UpExpr = nullptr) {
4731 // Perform element-by-element initialization.
4732 QualType ElementTy;
4733 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
4734 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
4735
4736 // Drill down to the base element type on both arrays.
4737 auto ArrayTy = Type->getAsArrayTypeUnsafe();
4738 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
4739
4740 auto RHSBegin = RHSAddr.getPointer();
4741 auto LHSBegin = LHSAddr.getPointer();
4742 // Cast from pointer to array type to pointer to single element.
4743 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
4744 // The basic structure here is a while-do loop.
4745 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
4746 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
4747 auto IsEmpty =
4748 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
4749 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
4750
4751 // Enter the loop body, making that address the current address.
4752 auto EntryBB = CGF.Builder.GetInsertBlock();
4753 CGF.EmitBlock(BodyBB);
4754
4755 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
4756
4757 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
4758 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
4759 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
4760 Address RHSElementCurrent =
4761 Address(RHSElementPHI,
4762 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4763
4764 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
4765 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
4766 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
4767 Address LHSElementCurrent =
4768 Address(LHSElementPHI,
4769 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4770
4771 // Emit copy.
4772 CodeGenFunction::OMPPrivateScope Scope(CGF);
4773 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
4774 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
4775 Scope.Privatize();
4776 RedOpGen(CGF, XExpr, EExpr, UpExpr);
4777 Scope.ForceCleanup();
4778
4779 // Shift the address forward by one element.
4780 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
4781 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
4782 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
4783 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
4784 // Check whether we've reached the end.
4785 auto Done =
4786 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
4787 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
4788 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
4789 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
4790
4791 // Done.
4792 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
4793}
4794
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004795/// Emit reduction combiner. If the combiner is a simple expression emit it as
4796/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
4797/// UDR combiner function.
4798static void emitReductionCombiner(CodeGenFunction &CGF,
4799 const Expr *ReductionOp) {
4800 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
4801 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
4802 if (auto *DRE =
4803 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
4804 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
4805 std::pair<llvm::Function *, llvm::Function *> Reduction =
4806 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
4807 RValue Func = RValue::get(Reduction.first);
4808 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
4809 CGF.EmitIgnoredExpr(ReductionOp);
4810 return;
4811 }
4812 CGF.EmitIgnoredExpr(ReductionOp);
4813}
4814
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004815llvm::Value *CGOpenMPRuntime::emitReductionFunction(
4816 CodeGenModule &CGM, llvm::Type *ArgsType, ArrayRef<const Expr *> Privates,
4817 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4818 ArrayRef<const Expr *> ReductionOps) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004819 auto &C = CGM.getContext();
4820
4821 // void reduction_func(void *LHSArg, void *RHSArg);
4822 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004823 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
4824 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004825 Args.push_back(&LHSArg);
4826 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00004827 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004828 auto *Fn = llvm::Function::Create(
4829 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
4830 ".omp.reduction.reduction_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004831 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004832 CodeGenFunction CGF(CGM);
4833 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
4834
4835 // Dst = (void*[n])(LHSArg);
4836 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00004837 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4838 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
4839 ArgsType), CGF.getPointerAlign());
4840 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4841 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
4842 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004843
4844 // ...
4845 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
4846 // ...
4847 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004848 auto IPriv = Privates.begin();
4849 unsigned Idx = 0;
4850 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004851 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
4852 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004853 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004854 });
4855 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
4856 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004857 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004858 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004859 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004860 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004861 // Get array size and emit VLA type.
4862 ++Idx;
4863 Address Elem =
4864 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
4865 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004866 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
4867 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004868 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00004869 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004870 CGF.EmitVariablyModifiedType(PrivTy);
4871 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004872 }
4873 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004874 IPriv = Privates.begin();
4875 auto ILHS = LHSExprs.begin();
4876 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004877 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004878 if ((*IPriv)->getType()->isArrayType()) {
4879 // Emit reduction for array section.
4880 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4881 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004882 EmitOMPAggregateReduction(
4883 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4884 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4885 emitReductionCombiner(CGF, E);
4886 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004887 } else
4888 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004889 emitReductionCombiner(CGF, E);
Richard Trieucc3949d2016-02-18 22:34:54 +00004890 ++IPriv;
4891 ++ILHS;
4892 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004893 }
4894 Scope.ForceCleanup();
4895 CGF.FinishFunction();
4896 return Fn;
4897}
4898
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004899void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
4900 const Expr *ReductionOp,
4901 const Expr *PrivateRef,
4902 const DeclRefExpr *LHS,
4903 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004904 if (PrivateRef->getType()->isArrayType()) {
4905 // Emit reduction for array section.
4906 auto *LHSVar = cast<VarDecl>(LHS->getDecl());
4907 auto *RHSVar = cast<VarDecl>(RHS->getDecl());
4908 EmitOMPAggregateReduction(
4909 CGF, PrivateRef->getType(), LHSVar, RHSVar,
4910 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4911 emitReductionCombiner(CGF, ReductionOp);
4912 });
4913 } else
4914 // Emit reduction for array subscript or single variable.
4915 emitReductionCombiner(CGF, ReductionOp);
4916}
4917
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004918void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004919 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004920 ArrayRef<const Expr *> LHSExprs,
4921 ArrayRef<const Expr *> RHSExprs,
4922 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004923 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004924 if (!CGF.HaveInsertPoint())
4925 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004926
4927 bool WithNowait = Options.WithNowait;
4928 bool SimpleReduction = Options.SimpleReduction;
4929
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004930 // Next code should be emitted for reduction:
4931 //
4932 // static kmp_critical_name lock = { 0 };
4933 //
4934 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
4935 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
4936 // ...
4937 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
4938 // *(Type<n>-1*)rhs[<n>-1]);
4939 // }
4940 //
4941 // ...
4942 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
4943 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4944 // RedList, reduce_func, &<lock>)) {
4945 // case 1:
4946 // ...
4947 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4948 // ...
4949 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4950 // break;
4951 // case 2:
4952 // ...
4953 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4954 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00004955 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004956 // break;
4957 // default:;
4958 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004959 //
4960 // if SimpleReduction is true, only the next code is generated:
4961 // ...
4962 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4963 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004964
4965 auto &C = CGM.getContext();
4966
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004967 if (SimpleReduction) {
4968 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004969 auto IPriv = Privates.begin();
4970 auto ILHS = LHSExprs.begin();
4971 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004972 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004973 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4974 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00004975 ++IPriv;
4976 ++ILHS;
4977 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004978 }
4979 return;
4980 }
4981
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004982 // 1. Build a list of reduction variables.
4983 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004984 auto Size = RHSExprs.size();
4985 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00004986 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004987 // Reserve place for array size.
4988 ++Size;
4989 }
4990 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004991 QualType ReductionArrayTy =
4992 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4993 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00004994 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004995 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004996 auto IPriv = Privates.begin();
4997 unsigned Idx = 0;
4998 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004999 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005000 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00005001 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005002 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00005003 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
5004 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005005 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005006 // Store array size.
5007 ++Idx;
5008 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
5009 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00005010 llvm::Value *Size = CGF.Builder.CreateIntCast(
5011 CGF.getVLASize(
5012 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
5013 .first,
5014 CGF.SizeTy, /*isSigned=*/false);
5015 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
5016 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005017 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005018 }
5019
5020 // 2. Emit reduce_func().
5021 auto *ReductionFn = emitReductionFunction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005022 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
5023 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005024
5025 // 3. Create static kmp_critical_name lock = { 0 };
5026 auto *Lock = getCriticalRegionLock(".reduction");
5027
5028 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5029 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00005030 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005031 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005032 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
Samuel Antao4c8035b2016-12-12 18:00:20 +00005033 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5034 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005035 llvm::Value *Args[] = {
5036 IdentTLoc, // ident_t *<loc>
5037 ThreadId, // i32 <gtid>
5038 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5039 ReductionArrayTySize, // size_type sizeof(RedList)
5040 RL, // void *RedList
5041 ReductionFn, // void (*) (void *, void *) <reduce_func>
5042 Lock // kmp_critical_name *&<lock>
5043 };
5044 auto Res = CGF.EmitRuntimeCall(
5045 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5046 : OMPRTL__kmpc_reduce),
5047 Args);
5048
5049 // 5. Build switch(res)
5050 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5051 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
5052
5053 // 6. Build case 1:
5054 // ...
5055 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5056 // ...
5057 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5058 // break;
5059 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
5060 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5061 CGF.EmitBlock(Case1BB);
5062
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005063 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5064 llvm::Value *EndArgs[] = {
5065 IdentTLoc, // ident_t *<loc>
5066 ThreadId, // i32 <gtid>
5067 Lock // kmp_critical_name *&<lock>
5068 };
5069 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5070 CodeGenFunction &CGF, PrePostActionTy &Action) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005071 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005072 auto IPriv = Privates.begin();
5073 auto ILHS = LHSExprs.begin();
5074 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005075 for (auto *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005076 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5077 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005078 ++IPriv;
5079 ++ILHS;
5080 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005081 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005082 };
5083 RegionCodeGenTy RCG(CodeGen);
5084 CommonActionTy Action(
5085 nullptr, llvm::None,
5086 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5087 : OMPRTL__kmpc_end_reduce),
5088 EndArgs);
5089 RCG.setAction(Action);
5090 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005091
5092 CGF.EmitBranch(DefaultBB);
5093
5094 // 7. Build case 2:
5095 // ...
5096 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5097 // ...
5098 // break;
5099 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
5100 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5101 CGF.EmitBlock(Case2BB);
5102
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005103 auto &&AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5104 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005105 auto ILHS = LHSExprs.begin();
5106 auto IRHS = RHSExprs.begin();
5107 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005108 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005109 const Expr *XExpr = nullptr;
5110 const Expr *EExpr = nullptr;
5111 const Expr *UpExpr = nullptr;
5112 BinaryOperatorKind BO = BO_Comma;
5113 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
5114 if (BO->getOpcode() == BO_Assign) {
5115 XExpr = BO->getLHS();
5116 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005117 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005118 }
5119 // Try to emit update expression as a simple atomic.
5120 auto *RHSExpr = UpExpr;
5121 if (RHSExpr) {
5122 // Analyze RHS part of the whole expression.
5123 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
5124 RHSExpr->IgnoreParenImpCasts())) {
5125 // If this is a conditional operator, analyze its condition for
5126 // min/max reduction operator.
5127 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005128 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005129 if (auto *BORHS =
5130 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5131 EExpr = BORHS->getRHS();
5132 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005133 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005134 }
5135 if (XExpr) {
5136 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005137 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005138 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5139 const Expr *EExpr, const Expr *UpExpr) {
5140 LValue X = CGF.EmitLValue(XExpr);
5141 RValue E;
5142 if (EExpr)
5143 E = CGF.EmitAnyExpr(EExpr);
5144 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005145 X, E, BO, /*IsXLHSInRHSPart=*/true,
5146 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005147 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005148 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5149 PrivateScope.addPrivate(
5150 VD, [&CGF, VD, XRValue, Loc]() -> Address {
5151 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5152 CGF.emitOMPSimpleStore(
5153 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5154 VD->getType().getNonReferenceType(), Loc);
5155 return LHSTemp;
5156 });
5157 (void)PrivateScope.Privatize();
5158 return CGF.EmitAnyExpr(UpExpr);
5159 });
5160 };
5161 if ((*IPriv)->getType()->isArrayType()) {
5162 // Emit atomic reduction for array section.
5163 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5164 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5165 AtomicRedGen, XExpr, EExpr, UpExpr);
5166 } else
5167 // Emit atomic reduction for array subscript or single variable.
5168 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
5169 } else {
5170 // Emit as a critical region.
5171 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
5172 const Expr *, const Expr *) {
5173 auto &RT = CGF.CGM.getOpenMPRuntime();
5174 RT.emitCriticalRegion(
5175 CGF, ".atomic_reduction",
5176 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5177 Action.Enter(CGF);
5178 emitReductionCombiner(CGF, E);
5179 },
5180 Loc);
5181 };
5182 if ((*IPriv)->getType()->isArrayType()) {
5183 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5184 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5185 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5186 CritRedGen);
5187 } else
5188 CritRedGen(CGF, nullptr, nullptr, nullptr);
5189 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005190 ++ILHS;
5191 ++IRHS;
5192 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005193 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005194 };
5195 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5196 if (!WithNowait) {
5197 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5198 llvm::Value *EndArgs[] = {
5199 IdentTLoc, // ident_t *<loc>
5200 ThreadId, // i32 <gtid>
5201 Lock // kmp_critical_name *&<lock>
5202 };
5203 CommonActionTy Action(nullptr, llvm::None,
5204 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5205 EndArgs);
5206 AtomicRCG.setAction(Action);
5207 AtomicRCG(CGF);
5208 } else
5209 AtomicRCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005210
5211 CGF.EmitBranch(DefaultBB);
5212 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5213}
5214
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005215/// Generates unique name for artificial threadprivate variables.
5216/// Format is: <Prefix> "." <Loc_raw_encoding> "_" <N>
5217static std::string generateUniqueName(StringRef Prefix, SourceLocation Loc,
5218 unsigned N) {
5219 SmallString<256> Buffer;
5220 llvm::raw_svector_ostream Out(Buffer);
5221 Out << Prefix << "." << Loc.getRawEncoding() << "_" << N;
5222 return Out.str();
5223}
5224
5225/// Emits reduction initializer function:
5226/// \code
5227/// void @.red_init(void* %arg) {
5228/// %0 = bitcast void* %arg to <type>*
5229/// store <type> <init>, <type>* %0
5230/// ret void
5231/// }
5232/// \endcode
5233static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5234 SourceLocation Loc,
5235 ReductionCodeGen &RCG, unsigned N) {
5236 auto &C = CGM.getContext();
5237 FunctionArgList Args;
5238 ImplicitParamDecl Param(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5239 Args.emplace_back(&Param);
5240 auto &FnInfo =
5241 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5242 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5243 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5244 ".red_init.", &CGM.getModule());
5245 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5246 CodeGenFunction CGF(CGM);
5247 CGF.disableDebugInfo();
5248 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5249 Address PrivateAddr = CGF.EmitLoadOfPointer(
5250 CGF.GetAddrOfLocalVar(&Param),
5251 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5252 llvm::Value *Size = nullptr;
5253 // If the size of the reduction item is non-constant, load it from global
5254 // threadprivate variable.
5255 if (RCG.getSizes(N).second) {
5256 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5257 CGF, CGM.getContext().getSizeType(),
5258 generateUniqueName("reduction_size", Loc, N));
5259 Size =
5260 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5261 CGM.getContext().getSizeType(), SourceLocation());
5262 }
5263 RCG.emitAggregateType(CGF, N, Size);
5264 LValue SharedLVal;
5265 // If initializer uses initializer from declare reduction construct, emit a
5266 // pointer to the address of the original reduction item (reuired by reduction
5267 // initializer)
5268 if (RCG.usesReductionInitializer(N)) {
5269 Address SharedAddr =
5270 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5271 CGF, CGM.getContext().VoidPtrTy,
5272 generateUniqueName("reduction", Loc, N));
5273 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5274 } else {
5275 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5276 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5277 CGM.getContext().VoidPtrTy);
5278 }
5279 // Emit the initializer:
5280 // %0 = bitcast void* %arg to <type>*
5281 // store <type> <init>, <type>* %0
5282 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5283 [](CodeGenFunction &) { return false; });
5284 CGF.FinishFunction();
5285 return Fn;
5286}
5287
5288/// Emits reduction combiner function:
5289/// \code
5290/// void @.red_comb(void* %arg0, void* %arg1) {
5291/// %lhs = bitcast void* %arg0 to <type>*
5292/// %rhs = bitcast void* %arg1 to <type>*
5293/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5294/// store <type> %2, <type>* %lhs
5295/// ret void
5296/// }
5297/// \endcode
5298static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5299 SourceLocation Loc,
5300 ReductionCodeGen &RCG, unsigned N,
5301 const Expr *ReductionOp,
5302 const Expr *LHS, const Expr *RHS,
5303 const Expr *PrivateRef) {
5304 auto &C = CGM.getContext();
5305 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5306 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
5307 FunctionArgList Args;
5308 ImplicitParamDecl ParamInOut(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5309 ImplicitParamDecl ParamIn(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5310 Args.emplace_back(&ParamInOut);
5311 Args.emplace_back(&ParamIn);
5312 auto &FnInfo =
5313 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5314 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5315 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5316 ".red_comb.", &CGM.getModule());
5317 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5318 CodeGenFunction CGF(CGM);
5319 CGF.disableDebugInfo();
5320 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5321 llvm::Value *Size = nullptr;
5322 // If the size of the reduction item is non-constant, load it from global
5323 // threadprivate variable.
5324 if (RCG.getSizes(N).second) {
5325 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5326 CGF, CGM.getContext().getSizeType(),
5327 generateUniqueName("reduction_size", Loc, N));
5328 Size =
5329 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5330 CGM.getContext().getSizeType(), SourceLocation());
5331 }
5332 RCG.emitAggregateType(CGF, N, Size);
5333 // Remap lhs and rhs variables to the addresses of the function arguments.
5334 // %lhs = bitcast void* %arg0 to <type>*
5335 // %rhs = bitcast void* %arg1 to <type>*
5336 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5337 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() -> Address {
5338 // Pull out the pointer to the variable.
5339 Address PtrAddr = CGF.EmitLoadOfPointer(
5340 CGF.GetAddrOfLocalVar(&ParamInOut),
5341 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5342 return CGF.Builder.CreateElementBitCast(
5343 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
5344 });
5345 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() -> Address {
5346 // Pull out the pointer to the variable.
5347 Address PtrAddr = CGF.EmitLoadOfPointer(
5348 CGF.GetAddrOfLocalVar(&ParamIn),
5349 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5350 return CGF.Builder.CreateElementBitCast(
5351 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
5352 });
5353 PrivateScope.Privatize();
5354 // Emit the combiner body:
5355 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
5356 // store <type> %2, <type>* %lhs
5357 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
5358 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
5359 cast<DeclRefExpr>(RHS));
5360 CGF.FinishFunction();
5361 return Fn;
5362}
5363
5364/// Emits reduction finalizer function:
5365/// \code
5366/// void @.red_fini(void* %arg) {
5367/// %0 = bitcast void* %arg to <type>*
5368/// <destroy>(<type>* %0)
5369/// ret void
5370/// }
5371/// \endcode
5372static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
5373 SourceLocation Loc,
5374 ReductionCodeGen &RCG, unsigned N) {
5375 if (!RCG.needCleanups(N))
5376 return nullptr;
5377 auto &C = CGM.getContext();
5378 FunctionArgList Args;
5379 ImplicitParamDecl Param(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5380 Args.emplace_back(&Param);
5381 auto &FnInfo =
5382 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5383 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5384 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5385 ".red_fini.", &CGM.getModule());
5386 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5387 CodeGenFunction CGF(CGM);
5388 CGF.disableDebugInfo();
5389 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5390 Address PrivateAddr = CGF.EmitLoadOfPointer(
5391 CGF.GetAddrOfLocalVar(&Param),
5392 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5393 llvm::Value *Size = nullptr;
5394 // If the size of the reduction item is non-constant, load it from global
5395 // threadprivate variable.
5396 if (RCG.getSizes(N).second) {
5397 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5398 CGF, CGM.getContext().getSizeType(),
5399 generateUniqueName("reduction_size", Loc, N));
5400 Size =
5401 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5402 CGM.getContext().getSizeType(), SourceLocation());
5403 }
5404 RCG.emitAggregateType(CGF, N, Size);
5405 // Emit the finalizer body:
5406 // <destroy>(<type>* %0)
5407 RCG.emitCleanups(CGF, N, PrivateAddr);
5408 CGF.FinishFunction();
5409 return Fn;
5410}
5411
5412llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
5413 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
5414 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
5415 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
5416 return nullptr;
5417
5418 // Build typedef struct:
5419 // kmp_task_red_input {
5420 // void *reduce_shar; // shared reduction item
5421 // size_t reduce_size; // size of data item
5422 // void *reduce_init; // data initialization routine
5423 // void *reduce_fini; // data finalization routine
5424 // void *reduce_comb; // data combiner routine
5425 // kmp_task_red_flags_t flags; // flags for additional info from compiler
5426 // } kmp_task_red_input_t;
5427 ASTContext &C = CGM.getContext();
5428 auto *RD = C.buildImplicitRecord("kmp_task_red_input_t");
5429 RD->startDefinition();
5430 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5431 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
5432 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5433 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5434 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5435 const FieldDecl *FlagsFD = addFieldToRecordDecl(
5436 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
5437 RD->completeDefinition();
5438 QualType RDType = C.getRecordType(RD);
5439 unsigned Size = Data.ReductionVars.size();
5440 llvm::APInt ArraySize(/*numBits=*/64, Size);
5441 QualType ArrayRDType = C.getConstantArrayType(
5442 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5443 // kmp_task_red_input_t .rd_input.[Size];
5444 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
5445 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
5446 Data.ReductionOps);
5447 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
5448 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
5449 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
5450 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
5451 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
5452 TaskRedInput.getPointer(), Idxs,
5453 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
5454 ".rd_input.gep.");
5455 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
5456 // ElemLVal.reduce_shar = &Shareds[Cnt];
5457 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
5458 RCG.emitSharedLValue(CGF, Cnt);
5459 llvm::Value *CastedShared =
5460 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
5461 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
5462 RCG.emitAggregateType(CGF, Cnt);
5463 llvm::Value *SizeValInChars;
5464 llvm::Value *SizeVal;
5465 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
5466 // We use delayed creation/initialization for VLAs, array sections and
5467 // custom reduction initializations. It is required because runtime does not
5468 // provide the way to pass the sizes of VLAs/array sections to
5469 // initializer/combiner/finalizer functions and does not pass the pointer to
5470 // original reduction item to the initializer. Instead threadprivate global
5471 // variables are used to store these values and use them in the functions.
5472 bool DelayedCreation = !!SizeVal;
5473 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
5474 /*isSigned=*/false);
5475 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
5476 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
5477 // ElemLVal.reduce_init = init;
5478 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
5479 llvm::Value *InitAddr =
5480 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
5481 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
5482 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
5483 // ElemLVal.reduce_fini = fini;
5484 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
5485 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
5486 llvm::Value *FiniAddr = Fini
5487 ? CGF.EmitCastToVoidPtr(Fini)
5488 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
5489 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
5490 // ElemLVal.reduce_comb = comb;
5491 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
5492 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
5493 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
5494 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
5495 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
5496 // ElemLVal.flags = 0;
5497 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
5498 if (DelayedCreation) {
5499 CGF.EmitStoreOfScalar(
5500 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
5501 FlagsLVal);
5502 } else
5503 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
5504 }
5505 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
5506 // *data);
5507 llvm::Value *Args[] = {
5508 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5509 /*isSigned=*/true),
5510 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
5511 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
5512 CGM.VoidPtrTy)};
5513 return CGF.EmitRuntimeCall(
5514 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
5515}
5516
5517void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
5518 SourceLocation Loc,
5519 ReductionCodeGen &RCG,
5520 unsigned N) {
5521 auto Sizes = RCG.getSizes(N);
5522 // Emit threadprivate global variable if the type is non-constant
5523 // (Sizes.second = nullptr).
5524 if (Sizes.second) {
5525 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
5526 /*isSigned=*/false);
5527 Address SizeAddr = getAddrOfArtificialThreadPrivate(
5528 CGF, CGM.getContext().getSizeType(),
5529 generateUniqueName("reduction_size", Loc, N));
5530 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
5531 }
5532 // Store address of the original reduction item if custom initializer is used.
5533 if (RCG.usesReductionInitializer(N)) {
5534 Address SharedAddr = getAddrOfArtificialThreadPrivate(
5535 CGF, CGM.getContext().VoidPtrTy,
5536 generateUniqueName("reduction", Loc, N));
5537 CGF.Builder.CreateStore(
5538 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5539 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
5540 SharedAddr, /*IsVolatile=*/false);
5541 }
5542}
5543
5544Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
5545 SourceLocation Loc,
5546 llvm::Value *ReductionsPtr,
5547 LValue SharedLVal) {
5548 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
5549 // *d);
5550 llvm::Value *Args[] = {
5551 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5552 /*isSigned=*/true),
5553 ReductionsPtr,
5554 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
5555 CGM.VoidPtrTy)};
5556 return Address(
5557 CGF.EmitRuntimeCall(
5558 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
5559 SharedLVal.getAlignment());
5560}
5561
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005562void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
5563 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005564 if (!CGF.HaveInsertPoint())
5565 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005566 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
5567 // global_tid);
5568 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
5569 // Ignore return result until untied tasks are supported.
5570 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005571 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5572 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005573}
5574
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005575void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005576 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005577 const RegionCodeGenTy &CodeGen,
5578 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005579 if (!CGF.HaveInsertPoint())
5580 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005581 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005582 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00005583}
5584
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005585namespace {
5586enum RTCancelKind {
5587 CancelNoreq = 0,
5588 CancelParallel = 1,
5589 CancelLoop = 2,
5590 CancelSections = 3,
5591 CancelTaskgroup = 4
5592};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00005593} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005594
5595static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
5596 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00005597 if (CancelRegion == OMPD_parallel)
5598 CancelKind = CancelParallel;
5599 else if (CancelRegion == OMPD_for)
5600 CancelKind = CancelLoop;
5601 else if (CancelRegion == OMPD_sections)
5602 CancelKind = CancelSections;
5603 else {
5604 assert(CancelRegion == OMPD_taskgroup);
5605 CancelKind = CancelTaskgroup;
5606 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005607 return CancelKind;
5608}
5609
5610void CGOpenMPRuntime::emitCancellationPointCall(
5611 CodeGenFunction &CGF, SourceLocation Loc,
5612 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005613 if (!CGF.HaveInsertPoint())
5614 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005615 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
5616 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005617 if (auto *OMPRegionInfo =
5618 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00005619 // For 'cancellation point taskgroup', the task region info may not have a
5620 // cancel. This may instead happen in another adjacent task.
5621 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005622 llvm::Value *Args[] = {
5623 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
5624 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005625 // Ignore return result until untied tasks are supported.
5626 auto *Result = CGF.EmitRuntimeCall(
5627 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
5628 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005629 // exit from construct;
5630 // }
5631 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5632 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5633 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5634 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5635 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005636 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005637 auto CancelDest =
5638 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005639 CGF.EmitBranchThroughCleanup(CancelDest);
5640 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5641 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005642 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005643}
5644
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005645void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00005646 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005647 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005648 if (!CGF.HaveInsertPoint())
5649 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005650 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
5651 // kmp_int32 cncl_kind);
5652 if (auto *OMPRegionInfo =
5653 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005654 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
5655 PrePostActionTy &) {
5656 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00005657 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005658 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00005659 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
5660 // Ignore return result until untied tasks are supported.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005661 auto *Result = CGF.EmitRuntimeCall(
5662 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00005663 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00005664 // exit from construct;
5665 // }
5666 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5667 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5668 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5669 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5670 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00005671 // exit from construct;
5672 auto CancelDest =
5673 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
5674 CGF.EmitBranchThroughCleanup(CancelDest);
5675 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5676 };
5677 if (IfCond)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005678 emitOMPIfClause(CGF, IfCond, ThenGen,
5679 [](CodeGenFunction &, PrePostActionTy &) {});
5680 else {
5681 RegionCodeGenTy ThenRCG(ThenGen);
5682 ThenRCG(CGF);
5683 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005684 }
5685}
Samuel Antaobed3c462015-10-02 16:14:20 +00005686
Samuel Antaoee8fb302016-01-06 13:42:12 +00005687/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00005688/// consists of the file and device IDs as well as line number associated with
5689/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005690static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
5691 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005692 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005693
5694 auto &SM = C.getSourceManager();
5695
5696 // The loc should be always valid and have a file ID (the user cannot use
5697 // #pragma directives in macros)
5698
5699 assert(Loc.isValid() && "Source location is expected to be always valid.");
5700 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
5701
5702 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
5703 assert(PLoc.isValid() && "Source location is expected to be always valid.");
5704
5705 llvm::sys::fs::UniqueID ID;
5706 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
5707 llvm_unreachable("Source file with target region no longer exists!");
5708
5709 DeviceID = ID.getDevice();
5710 FileID = ID.getFile();
5711 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00005712}
5713
5714void CGOpenMPRuntime::emitTargetOutlinedFunction(
5715 const OMPExecutableDirective &D, StringRef ParentName,
5716 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005717 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005718 assert(!ParentName.empty() && "Invalid target region parent name!");
5719
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005720 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
5721 IsOffloadEntry, CodeGen);
5722}
5723
5724void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
5725 const OMPExecutableDirective &D, StringRef ParentName,
5726 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
5727 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00005728 // Create a unique name for the entry function using the source location
5729 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00005730 //
Samuel Antao2de62b02016-02-13 23:35:10 +00005731 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00005732 //
5733 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00005734 // mangled name of the function that encloses the target region and BB is the
5735 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005736
5737 unsigned DeviceID;
5738 unsigned FileID;
5739 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005740 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005741 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005742 SmallString<64> EntryFnName;
5743 {
5744 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00005745 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
5746 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005747 }
5748
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005749 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5750
Samuel Antaobed3c462015-10-02 16:14:20 +00005751 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005752 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00005753 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005754
Samuel Antao6d004262016-06-16 18:39:34 +00005755 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005756
5757 // If this target outline function is not an offload entry, we don't need to
5758 // register it.
5759 if (!IsOffloadEntry)
5760 return;
5761
5762 // The target region ID is used by the runtime library to identify the current
5763 // target region, so it only has to be unique and not necessarily point to
5764 // anything. It could be the pointer to the outlined function that implements
5765 // the target region, but we aren't using that so that the compiler doesn't
5766 // need to keep that, and could therefore inline the host function if proven
5767 // worthwhile during optimization. In the other hand, if emitting code for the
5768 // device, the ID has to be the function address so that it can retrieved from
5769 // the offloading entry and launched by the runtime library. We also mark the
5770 // outlined function to have external linkage in case we are emitting code for
5771 // the device, because these functions will be entry points to the device.
5772
5773 if (CGM.getLangOpts().OpenMPIsDevice) {
5774 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
5775 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
5776 } else
5777 OutlinedFnID = new llvm::GlobalVariable(
5778 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
5779 llvm::GlobalValue::PrivateLinkage,
5780 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
5781
5782 // Register the information for the entry associated with this target region.
5783 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00005784 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
5785 /*Flags=*/0);
Samuel Antaobed3c462015-10-02 16:14:20 +00005786}
5787
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005788/// discard all CompoundStmts intervening between two constructs
5789static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
5790 while (auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
5791 Body = CS->body_front();
5792
5793 return Body;
5794}
5795
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005796/// Emit the number of teams for a target directive. Inspect the num_teams
5797/// clause associated with a teams construct combined or closely nested
5798/// with the target directive.
5799///
5800/// Emit a team of size one for directives such as 'target parallel' that
5801/// have no associated teams construct.
5802///
5803/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00005804static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005805emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
5806 CodeGenFunction &CGF,
5807 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005808
5809 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
5810 "teams directive expected to be "
5811 "emitted only for the host!");
5812
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005813 auto &Bld = CGF.Builder;
5814
5815 // If the target directive is combined with a teams directive:
5816 // Return the value in the num_teams clause, if any.
5817 // Otherwise, return 0 to denote the runtime default.
5818 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
5819 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
5820 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
5821 auto NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
5822 /*IgnoreResultAssign*/ true);
5823 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5824 /*IsSigned=*/true);
5825 }
5826
5827 // The default value is 0.
5828 return Bld.getInt32(0);
5829 }
5830
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005831 // If the target directive is combined with a parallel directive but not a
5832 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005833 if (isOpenMPParallelDirective(D.getDirectiveKind()))
5834 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005835
5836 // If the current target region has a teams region enclosed, we need to get
5837 // the number of teams to pass to the runtime function call. This is done
5838 // by generating the expression in a inlined region. This is required because
5839 // the expression is captured in the enclosing target environment when the
5840 // teams directive is not combined with target.
5841
5842 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5843
5844 // FIXME: Accommodate other combined directives with teams when they become
5845 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005846 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
5847 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005848 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
5849 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5850 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5851 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005852 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5853 /*IsSigned=*/true);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005854 }
5855
5856 // If we have an enclosed teams directive but no num_teams clause we use
5857 // the default value 0.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005858 return Bld.getInt32(0);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005859 }
5860
5861 // No teams associated with the directive.
5862 return nullptr;
5863}
5864
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005865/// Emit the number of threads for a target directive. Inspect the
5866/// thread_limit clause associated with a teams construct combined or closely
5867/// nested with the target directive.
5868///
5869/// Emit the num_threads clause for directives such as 'target parallel' that
5870/// have no associated teams construct.
5871///
5872/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00005873static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005874emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
5875 CodeGenFunction &CGF,
5876 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005877
5878 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
5879 "teams directive expected to be "
5880 "emitted only for the host!");
5881
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005882 auto &Bld = CGF.Builder;
5883
5884 //
5885 // If the target directive is combined with a teams directive:
5886 // Return the value in the thread_limit clause, if any.
5887 //
5888 // If the target directive is combined with a parallel directive:
5889 // Return the value in the num_threads clause, if any.
5890 //
5891 // If both clauses are set, select the minimum of the two.
5892 //
5893 // If neither teams or parallel combined directives set the number of threads
5894 // in a team, return 0 to denote the runtime default.
5895 //
5896 // If this is not a teams directive return nullptr.
5897
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005898 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
5899 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005900 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
5901 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005902 llvm::Value *ThreadLimitVal = nullptr;
5903
5904 if (const auto *ThreadLimitClause =
5905 D.getSingleClause<OMPThreadLimitClause>()) {
5906 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
5907 auto ThreadLimit = CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
5908 /*IgnoreResultAssign*/ true);
5909 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5910 /*IsSigned=*/true);
5911 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005912
5913 if (const auto *NumThreadsClause =
5914 D.getSingleClause<OMPNumThreadsClause>()) {
5915 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
5916 llvm::Value *NumThreads =
5917 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
5918 /*IgnoreResultAssign*/ true);
5919 NumThreadsVal =
5920 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
5921 }
5922
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005923 // Select the lesser of thread_limit and num_threads.
5924 if (NumThreadsVal)
5925 ThreadLimitVal = ThreadLimitVal
5926 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
5927 ThreadLimitVal),
5928 NumThreadsVal, ThreadLimitVal)
5929 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00005930
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005931 // Set default value passed to the runtime if either teams or a target
5932 // parallel type directive is found but no clause is specified.
5933 if (!ThreadLimitVal)
5934 ThreadLimitVal = DefaultThreadLimitVal;
5935
5936 return ThreadLimitVal;
5937 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00005938
Samuel Antaob68e2db2016-03-03 16:20:23 +00005939 // If the current target region has a teams region enclosed, we need to get
5940 // the thread limit to pass to the runtime function call. This is done
5941 // by generating the expression in a inlined region. This is required because
5942 // the expression is captured in the enclosing target environment when the
5943 // teams directive is not combined with target.
5944
5945 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5946
5947 // FIXME: Accommodate other combined directives with teams when they become
5948 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005949 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
5950 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005951 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
5952 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5953 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5954 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
5955 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5956 /*IsSigned=*/true);
5957 }
5958
5959 // If we have an enclosed teams directive but no thread_limit clause we use
5960 // the default value 0.
5961 return CGF.Builder.getInt32(0);
5962 }
5963
5964 // No teams associated with the directive.
5965 return nullptr;
5966}
5967
Samuel Antao86ace552016-04-27 22:40:57 +00005968namespace {
5969// \brief Utility to handle information from clauses associated with a given
5970// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
5971// It provides a convenient interface to obtain the information and generate
5972// code for that information.
5973class MappableExprsHandler {
5974public:
5975 /// \brief Values for bit flags used to specify the mapping type for
5976 /// offloading.
5977 enum OpenMPOffloadMappingFlags {
Samuel Antao86ace552016-04-27 22:40:57 +00005978 /// \brief Allocate memory on the device and move data from host to device.
5979 OMP_MAP_TO = 0x01,
5980 /// \brief Allocate memory on the device and move data from device to host.
5981 OMP_MAP_FROM = 0x02,
5982 /// \brief Always perform the requested mapping action on the element, even
5983 /// if it was already mapped before.
5984 OMP_MAP_ALWAYS = 0x04,
Samuel Antao86ace552016-04-27 22:40:57 +00005985 /// \brief Delete the element from the device environment, ignoring the
5986 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00005987 OMP_MAP_DELETE = 0x08,
George Rokos065755d2017-11-07 18:27:04 +00005988 /// \brief The element being mapped is a pointer-pointee pair; both the
5989 /// pointer and the pointee should be mapped.
5990 OMP_MAP_PTR_AND_OBJ = 0x10,
5991 /// \brief This flags signals that the base address of an entry should be
5992 /// passed to the target kernel as an argument.
5993 OMP_MAP_TARGET_PARAM = 0x20,
Samuel Antaocc10b852016-07-28 14:23:26 +00005994 /// \brief Signal that the runtime library has to return the device pointer
George Rokos065755d2017-11-07 18:27:04 +00005995 /// in the current position for the data being mapped. Used when we have the
5996 /// use_device_ptr clause.
5997 OMP_MAP_RETURN_PARAM = 0x40,
Samuel Antaod486f842016-05-26 16:53:38 +00005998 /// \brief This flag signals that the reference being passed is a pointer to
5999 /// private data.
George Rokos065755d2017-11-07 18:27:04 +00006000 OMP_MAP_PRIVATE = 0x80,
Samuel Antao86ace552016-04-27 22:40:57 +00006001 /// \brief Pass the element to the device by value.
George Rokos065755d2017-11-07 18:27:04 +00006002 OMP_MAP_LITERAL = 0x100,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006003 /// Implicit map
6004 OMP_MAP_IMPLICIT = 0x200,
Samuel Antao86ace552016-04-27 22:40:57 +00006005 };
6006
Samuel Antaocc10b852016-07-28 14:23:26 +00006007 /// Class that associates information with a base pointer to be passed to the
6008 /// runtime library.
6009 class BasePointerInfo {
6010 /// The base pointer.
6011 llvm::Value *Ptr = nullptr;
6012 /// The base declaration that refers to this device pointer, or null if
6013 /// there is none.
6014 const ValueDecl *DevPtrDecl = nullptr;
6015
6016 public:
6017 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
6018 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
6019 llvm::Value *operator*() const { return Ptr; }
6020 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
6021 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
6022 };
6023
6024 typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00006025 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
George Rokos63bc9d62017-11-21 18:25:12 +00006026 typedef SmallVector<uint64_t, 16> MapFlagsArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00006027
6028private:
6029 /// \brief Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00006030 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00006031
6032 /// \brief Function the directive is being generated for.
6033 CodeGenFunction &CGF;
6034
Samuel Antaod486f842016-05-26 16:53:38 +00006035 /// \brief Set of all first private variables in the current directive.
6036 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
6037
Samuel Antao6890b092016-07-28 14:25:09 +00006038 /// Map between device pointer declarations and their expression components.
6039 /// The key value for declarations in 'this' is null.
6040 llvm::DenseMap<
6041 const ValueDecl *,
6042 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6043 DevPointersMap;
6044
Samuel Antao86ace552016-04-27 22:40:57 +00006045 llvm::Value *getExprTypeSize(const Expr *E) const {
6046 auto ExprTy = E->getType().getCanonicalType();
6047
6048 // Reference types are ignored for mapping purposes.
6049 if (auto *RefTy = ExprTy->getAs<ReferenceType>())
6050 ExprTy = RefTy->getPointeeType().getCanonicalType();
6051
6052 // Given that an array section is considered a built-in type, we need to
6053 // do the calculation based on the length of the section instead of relying
6054 // on CGF.getTypeSize(E->getType()).
6055 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6056 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6057 OAE->getBase()->IgnoreParenImpCasts())
6058 .getCanonicalType();
6059
6060 // If there is no length associated with the expression, that means we
6061 // are using the whole length of the base.
6062 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6063 return CGF.getTypeSize(BaseTy);
6064
6065 llvm::Value *ElemSize;
6066 if (auto *PTy = BaseTy->getAs<PointerType>())
6067 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
6068 else {
6069 auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
6070 assert(ATy && "Expecting array type if not a pointer type.");
6071 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6072 }
6073
6074 // If we don't have a length at this point, that is because we have an
6075 // array section with a single element.
6076 if (!OAE->getLength())
6077 return ElemSize;
6078
6079 auto *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
6080 LengthVal =
6081 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6082 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6083 }
6084 return CGF.getTypeSize(ExprTy);
6085 }
6086
6087 /// \brief Return the corresponding bits for a given map clause modifier. Add
6088 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006089 /// map as the first one of a series of maps that relate to the same map
6090 /// expression.
George Rokos63bc9d62017-11-21 18:25:12 +00006091 uint64_t getMapTypeBits(OpenMPMapClauseKind MapType,
Samuel Antao86ace552016-04-27 22:40:57 +00006092 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
George Rokos065755d2017-11-07 18:27:04 +00006093 bool AddIsTargetParamFlag) const {
George Rokos63bc9d62017-11-21 18:25:12 +00006094 uint64_t Bits = 0u;
Samuel Antao86ace552016-04-27 22:40:57 +00006095 switch (MapType) {
6096 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006097 case OMPC_MAP_release:
6098 // alloc and release is the default behavior in the runtime library, i.e.
6099 // if we don't pass any bits alloc/release that is what the runtime is
6100 // going to do. Therefore, we don't need to signal anything for these two
6101 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006102 break;
6103 case OMPC_MAP_to:
6104 Bits = OMP_MAP_TO;
6105 break;
6106 case OMPC_MAP_from:
6107 Bits = OMP_MAP_FROM;
6108 break;
6109 case OMPC_MAP_tofrom:
6110 Bits = OMP_MAP_TO | OMP_MAP_FROM;
6111 break;
6112 case OMPC_MAP_delete:
6113 Bits = OMP_MAP_DELETE;
6114 break;
Samuel Antao86ace552016-04-27 22:40:57 +00006115 default:
6116 llvm_unreachable("Unexpected map type!");
6117 break;
6118 }
6119 if (AddPtrFlag)
George Rokos065755d2017-11-07 18:27:04 +00006120 Bits |= OMP_MAP_PTR_AND_OBJ;
6121 if (AddIsTargetParamFlag)
6122 Bits |= OMP_MAP_TARGET_PARAM;
Samuel Antao86ace552016-04-27 22:40:57 +00006123 if (MapTypeModifier == OMPC_MAP_always)
6124 Bits |= OMP_MAP_ALWAYS;
6125 return Bits;
6126 }
6127
6128 /// \brief Return true if the provided expression is a final array section. A
6129 /// final array section, is one whose length can't be proved to be one.
6130 bool isFinalArraySectionExpression(const Expr *E) const {
6131 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
6132
6133 // It is not an array section and therefore not a unity-size one.
6134 if (!OASE)
6135 return false;
6136
6137 // An array section with no colon always refer to a single element.
6138 if (OASE->getColonLoc().isInvalid())
6139 return false;
6140
6141 auto *Length = OASE->getLength();
6142
6143 // If we don't have a length we have to check if the array has size 1
6144 // for this dimension. Also, we should always expect a length if the
6145 // base type is pointer.
6146 if (!Length) {
6147 auto BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6148 OASE->getBase()->IgnoreParenImpCasts())
6149 .getCanonicalType();
6150 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
6151 return ATy->getSize().getSExtValue() != 1;
6152 // If we don't have a constant dimension length, we have to consider
6153 // the current section as having any size, so it is not necessarily
6154 // unitary. If it happen to be unity size, that's user fault.
6155 return true;
6156 }
6157
6158 // Check if the length evaluates to 1.
6159 llvm::APSInt ConstLength;
6160 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
6161 return true; // Can have more that size 1.
6162
6163 return ConstLength.getSExtValue() != 1;
6164 }
6165
6166 /// \brief Generate the base pointers, section pointers, sizes and map type
6167 /// bits for the provided map type, map modifier, and expression components.
6168 /// \a IsFirstComponent should be set to true if the provided set of
6169 /// components is the first associated with a capture.
6170 void generateInfoForComponentList(
6171 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6172 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006173 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006174 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006175 bool IsFirstComponentList, bool IsImplicit) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006176
6177 // The following summarizes what has to be generated for each map and the
6178 // types bellow. The generated information is expressed in this order:
6179 // base pointer, section pointer, size, flags
6180 // (to add to the ones that come from the map type and modifier).
6181 //
6182 // double d;
6183 // int i[100];
6184 // float *p;
6185 //
6186 // struct S1 {
6187 // int i;
6188 // float f[50];
6189 // }
6190 // struct S2 {
6191 // int i;
6192 // float f[50];
6193 // S1 s;
6194 // double *p;
6195 // struct S2 *ps;
6196 // }
6197 // S2 s;
6198 // S2 *ps;
6199 //
6200 // map(d)
6201 // &d, &d, sizeof(double), noflags
6202 //
6203 // map(i)
6204 // &i, &i, 100*sizeof(int), noflags
6205 //
6206 // map(i[1:23])
6207 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
6208 //
6209 // map(p)
6210 // &p, &p, sizeof(float*), noflags
6211 //
6212 // map(p[1:24])
6213 // p, &p[1], 24*sizeof(float), noflags
6214 //
6215 // map(s)
6216 // &s, &s, sizeof(S2), noflags
6217 //
6218 // map(s.i)
6219 // &s, &(s.i), sizeof(int), noflags
6220 //
6221 // map(s.s.f)
6222 // &s, &(s.i.f), 50*sizeof(int), noflags
6223 //
6224 // map(s.p)
6225 // &s, &(s.p), sizeof(double*), noflags
6226 //
6227 // map(s.p[:22], s.a s.b)
6228 // &s, &(s.p), sizeof(double*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006229 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006230 //
6231 // map(s.ps)
6232 // &s, &(s.ps), sizeof(S2*), noflags
6233 //
6234 // map(s.ps->s.i)
6235 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006236 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006237 //
6238 // map(s.ps->ps)
6239 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006240 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006241 //
6242 // map(s.ps->ps->ps)
6243 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006244 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
6245 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006246 //
6247 // map(s.ps->ps->s.f[:22])
6248 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006249 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
6250 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006251 //
6252 // map(ps)
6253 // &ps, &ps, sizeof(S2*), noflags
6254 //
6255 // map(ps->i)
6256 // ps, &(ps->i), sizeof(int), noflags
6257 //
6258 // map(ps->s.f)
6259 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
6260 //
6261 // map(ps->p)
6262 // ps, &(ps->p), sizeof(double*), noflags
6263 //
6264 // map(ps->p[:22])
6265 // ps, &(ps->p), sizeof(double*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006266 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006267 //
6268 // map(ps->ps)
6269 // ps, &(ps->ps), sizeof(S2*), noflags
6270 //
6271 // map(ps->ps->s.i)
6272 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006273 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006274 //
6275 // map(ps->ps->ps)
6276 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006277 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006278 //
6279 // map(ps->ps->ps->ps)
6280 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006281 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
6282 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006283 //
6284 // map(ps->ps->ps->s.f[:22])
6285 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006286 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
6287 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006288
6289 // Track if the map information being generated is the first for a capture.
6290 bool IsCaptureFirstInfo = IsFirstComponentList;
6291
6292 // Scan the components from the base to the complete expression.
6293 auto CI = Components.rbegin();
6294 auto CE = Components.rend();
6295 auto I = CI;
6296
6297 // Track if the map information being generated is the first for a list of
6298 // components.
6299 bool IsExpressionFirstInfo = true;
6300 llvm::Value *BP = nullptr;
6301
6302 if (auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
6303 // The base is the 'this' pointer. The content of the pointer is going
6304 // to be the base of the field being mapped.
6305 BP = CGF.EmitScalarExpr(ME->getBase());
6306 } else {
6307 // The base is the reference to the variable.
6308 // BP = &Var.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006309 BP = CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Samuel Antao86ace552016-04-27 22:40:57 +00006310
6311 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00006312 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00006313 // reference. References are ignored for mapping purposes.
6314 QualType Ty =
6315 I->getAssociatedDeclaration()->getType().getNonReferenceType();
6316 if (Ty->isAnyPointerType() && std::next(I) != CE) {
6317 auto PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
Samuel Antao86ace552016-04-27 22:40:57 +00006318 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
Samuel Antao403ffd42016-07-27 22:49:49 +00006319 Ty->castAs<PointerType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006320 .getPointer();
6321
6322 // We do not need to generate individual map information for the
6323 // pointer, it can be associated with the combined storage.
6324 ++I;
6325 }
6326 }
6327
George Rokos63bc9d62017-11-21 18:25:12 +00006328 uint64_t DefaultFlags = IsImplicit ? OMP_MAP_IMPLICIT : 0;
Samuel Antao86ace552016-04-27 22:40:57 +00006329 for (; I != CE; ++I) {
6330 auto Next = std::next(I);
6331
6332 // We need to generate the addresses and sizes if this is the last
6333 // component, if the component is a pointer or if it is an array section
6334 // whose length can't be proved to be one. If this is a pointer, it
6335 // becomes the base address for the following components.
6336
6337 // A final array section, is one whose length can't be proved to be one.
6338 bool IsFinalArraySection =
6339 isFinalArraySectionExpression(I->getAssociatedExpression());
6340
6341 // Get information on whether the element is a pointer. Have to do a
6342 // special treatment for array sections given that they are built-in
6343 // types.
6344 const auto *OASE =
6345 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
6346 bool IsPointer =
6347 (OASE &&
6348 OMPArraySectionExpr::getBaseOriginalType(OASE)
6349 .getCanonicalType()
6350 ->isAnyPointerType()) ||
6351 I->getAssociatedExpression()->getType()->isAnyPointerType();
6352
6353 if (Next == CE || IsPointer || IsFinalArraySection) {
6354
6355 // If this is not the last component, we expect the pointer to be
6356 // associated with an array expression or member expression.
6357 assert((Next == CE ||
6358 isa<MemberExpr>(Next->getAssociatedExpression()) ||
6359 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
6360 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
6361 "Unexpected expression");
6362
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006363 llvm::Value *LB =
6364 CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Samuel Antao86ace552016-04-27 22:40:57 +00006365 auto *Size = getExprTypeSize(I->getAssociatedExpression());
6366
Samuel Antao03a3cec2016-07-27 22:52:16 +00006367 // If we have a member expression and the current component is a
6368 // reference, we have to map the reference too. Whenever we have a
6369 // reference, the section that reference refers to is going to be a
6370 // load instruction from the storage assigned to the reference.
6371 if (isa<MemberExpr>(I->getAssociatedExpression()) &&
6372 I->getAssociatedDeclaration()->getType()->isReferenceType()) {
6373 auto *LI = cast<llvm::LoadInst>(LB);
6374 auto *RefAddr = LI->getPointerOperand();
6375
6376 BasePointers.push_back(BP);
6377 Pointers.push_back(RefAddr);
6378 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006379 Types.push_back(DefaultFlags |
6380 getMapTypeBits(
6381 /*MapType*/ OMPC_MAP_alloc,
6382 /*MapTypeModifier=*/OMPC_MAP_unknown,
6383 !IsExpressionFirstInfo, IsCaptureFirstInfo));
Samuel Antao03a3cec2016-07-27 22:52:16 +00006384 IsExpressionFirstInfo = false;
6385 IsCaptureFirstInfo = false;
6386 // The reference will be the next base address.
6387 BP = RefAddr;
6388 }
6389
6390 BasePointers.push_back(BP);
Samuel Antao86ace552016-04-27 22:40:57 +00006391 Pointers.push_back(LB);
6392 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00006393
Samuel Antao6782e942016-05-26 16:48:10 +00006394 // We need to add a pointer flag for each map that comes from the
6395 // same expression except for the first one. We also need to signal
6396 // this map is the first one that relates with the current capture
6397 // (there is a set of entries for each capture).
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006398 Types.push_back(DefaultFlags | getMapTypeBits(MapType, MapTypeModifier,
6399 !IsExpressionFirstInfo,
6400 IsCaptureFirstInfo));
Samuel Antao86ace552016-04-27 22:40:57 +00006401
6402 // If we have a final array section, we are done with this expression.
6403 if (IsFinalArraySection)
6404 break;
6405
6406 // The pointer becomes the base for the next element.
6407 if (Next != CE)
6408 BP = LB;
6409
6410 IsExpressionFirstInfo = false;
6411 IsCaptureFirstInfo = false;
Samuel Antao86ace552016-04-27 22:40:57 +00006412 }
6413 }
6414 }
6415
Samuel Antaod486f842016-05-26 16:53:38 +00006416 /// \brief Return the adjusted map modifiers if the declaration a capture
6417 /// refers to appears in a first-private clause. This is expected to be used
6418 /// only with directives that start with 'target'.
6419 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
6420 unsigned CurrentModifiers) {
6421 assert(Cap.capturesVariable() && "Expected capture by reference only!");
6422
6423 // A first private variable captured by reference will use only the
6424 // 'private ptr' and 'map to' flag. Return the right flags if the captured
6425 // declaration is known as first-private in this handler.
6426 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
George Rokos065755d2017-11-07 18:27:04 +00006427 return MappableExprsHandler::OMP_MAP_PRIVATE |
Samuel Antaod486f842016-05-26 16:53:38 +00006428 MappableExprsHandler::OMP_MAP_TO;
6429
6430 // We didn't modify anything.
6431 return CurrentModifiers;
6432 }
6433
Samuel Antao86ace552016-04-27 22:40:57 +00006434public:
6435 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
Samuel Antao44bcdb32016-07-28 15:31:29 +00006436 : CurDir(Dir), CGF(CGF) {
Samuel Antaod486f842016-05-26 16:53:38 +00006437 // Extract firstprivate clause information.
6438 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
6439 for (const auto *D : C->varlists())
6440 FirstPrivateDecls.insert(
6441 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
Samuel Antao6890b092016-07-28 14:25:09 +00006442 // Extract device pointer clause information.
6443 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
6444 for (auto L : C->component_lists())
6445 DevPointersMap[L.first].push_back(L.second);
Samuel Antaod486f842016-05-26 16:53:38 +00006446 }
Samuel Antao86ace552016-04-27 22:40:57 +00006447
6448 /// \brief Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00006449 /// types for the extracted mappable expressions. Also, for each item that
6450 /// relates with a device pointer, a pair of the relevant declaration and
6451 /// index where it occurs is appended to the device pointers info array.
6452 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006453 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
6454 MapFlagsArrayTy &Types) const {
6455 BasePointers.clear();
6456 Pointers.clear();
6457 Sizes.clear();
6458 Types.clear();
6459
6460 struct MapInfo {
Samuel Antaocc10b852016-07-28 14:23:26 +00006461 /// Kind that defines how a device pointer has to be returned.
6462 enum ReturnPointerKind {
6463 // Don't have to return any pointer.
6464 RPK_None,
6465 // Pointer is the base of the declaration.
6466 RPK_Base,
6467 // Pointer is a member of the base declaration - 'this'
6468 RPK_Member,
6469 // Pointer is a reference and a member of the base declaration - 'this'
6470 RPK_MemberReference,
6471 };
Samuel Antao86ace552016-04-27 22:40:57 +00006472 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006473 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
6474 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
6475 ReturnPointerKind ReturnDevicePointer = RPK_None;
6476 bool IsImplicit = false;
Hans Wennborgbc1b58d2016-07-30 00:41:37 +00006477
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006478 MapInfo() = default;
Samuel Antaocc10b852016-07-28 14:23:26 +00006479 MapInfo(
6480 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
6481 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006482 ReturnPointerKind ReturnDevicePointer, bool IsImplicit)
Samuel Antaocc10b852016-07-28 14:23:26 +00006483 : Components(Components), MapType(MapType),
6484 MapTypeModifier(MapTypeModifier),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006485 ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
Samuel Antao86ace552016-04-27 22:40:57 +00006486 };
6487
6488 // We have to process the component lists that relate with the same
6489 // declaration in a single chunk so that we can generate the map flags
6490 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00006491 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00006492
6493 // Helper function to fill the information map for the different supported
6494 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00006495 auto &&InfoGen = [&Info](
6496 const ValueDecl *D,
6497 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
6498 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006499 MapInfo::ReturnPointerKind ReturnDevicePointer, bool IsImplicit) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006500 const ValueDecl *VD =
6501 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006502 Info[VD].emplace_back(L, MapType, MapModifier, ReturnDevicePointer,
6503 IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00006504 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00006505
Paul Robinson78fb1322016-08-01 22:12:46 +00006506 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006507 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006508 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006509 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006510 MapInfo::RPK_None, C->isImplicit());
6511 }
Paul Robinson15c84002016-07-29 20:46:16 +00006512 for (auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006513 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006514 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006515 MapInfo::RPK_None, C->isImplicit());
6516 }
Paul Robinson15c84002016-07-29 20:46:16 +00006517 for (auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006518 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006519 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006520 MapInfo::RPK_None, C->isImplicit());
6521 }
Samuel Antao86ace552016-04-27 22:40:57 +00006522
Samuel Antaocc10b852016-07-28 14:23:26 +00006523 // Look at the use_device_ptr clause information and mark the existing map
6524 // entries as such. If there is no map information for an entry in the
6525 // use_device_ptr list, we create one with map type 'alloc' and zero size
6526 // section. It is the user fault if that was not mapped before.
Paul Robinson78fb1322016-08-01 22:12:46 +00006527 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006528 for (auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
Samuel Antaocc10b852016-07-28 14:23:26 +00006529 for (auto L : C->component_lists()) {
6530 assert(!L.second.empty() && "Not expecting empty list of components!");
6531 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
6532 VD = cast<ValueDecl>(VD->getCanonicalDecl());
6533 auto *IE = L.second.back().getAssociatedExpression();
6534 // If the first component is a member expression, we have to look into
6535 // 'this', which maps to null in the map of map information. Otherwise
6536 // look directly for the information.
6537 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
6538
6539 // We potentially have map information for this declaration already.
6540 // Look for the first set of components that refer to it.
6541 if (It != Info.end()) {
6542 auto CI = std::find_if(
6543 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
6544 return MI.Components.back().getAssociatedDeclaration() == VD;
6545 });
6546 // If we found a map entry, signal that the pointer has to be returned
6547 // and move on to the next declaration.
6548 if (CI != It->second.end()) {
6549 CI->ReturnDevicePointer = isa<MemberExpr>(IE)
6550 ? (VD->getType()->isReferenceType()
6551 ? MapInfo::RPK_MemberReference
6552 : MapInfo::RPK_Member)
6553 : MapInfo::RPK_Base;
6554 continue;
6555 }
6556 }
6557
6558 // We didn't find any match in our map information - generate a zero
6559 // size array section.
Paul Robinson78fb1322016-08-01 22:12:46 +00006560 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Samuel Antaocc10b852016-07-28 14:23:26 +00006561 llvm::Value *Ptr =
Paul Robinson15c84002016-07-29 20:46:16 +00006562 this->CGF
6563 .EmitLoadOfLValue(this->CGF.EmitLValue(IE), SourceLocation())
Samuel Antaocc10b852016-07-28 14:23:26 +00006564 .getScalarVal();
6565 BasePointers.push_back({Ptr, VD});
6566 Pointers.push_back(Ptr);
Paul Robinson15c84002016-07-29 20:46:16 +00006567 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
George Rokos065755d2017-11-07 18:27:04 +00006568 Types.push_back(OMP_MAP_RETURN_PARAM | OMP_MAP_TARGET_PARAM);
Samuel Antaocc10b852016-07-28 14:23:26 +00006569 }
6570
Samuel Antao86ace552016-04-27 22:40:57 +00006571 for (auto &M : Info) {
6572 // We need to know when we generate information for the first component
6573 // associated with a capture, because the mapping flags depend on it.
6574 bool IsFirstComponentList = true;
6575 for (MapInfo &L : M.second) {
6576 assert(!L.Components.empty() &&
6577 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00006578
6579 // Remember the current base pointer index.
6580 unsigned CurrentBasePointersIdx = BasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00006581 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006582 this->generateInfoForComponentList(
6583 L.MapType, L.MapTypeModifier, L.Components, BasePointers, Pointers,
6584 Sizes, Types, IsFirstComponentList, L.IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00006585
6586 // If this entry relates with a device pointer, set the relevant
6587 // declaration and add the 'return pointer' flag.
6588 if (IsFirstComponentList &&
6589 L.ReturnDevicePointer != MapInfo::RPK_None) {
6590 // If the pointer is not the base of the map, we need to skip the
6591 // base. If it is a reference in a member field, we also need to skip
6592 // the map of the reference.
6593 if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
6594 ++CurrentBasePointersIdx;
6595 if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
6596 ++CurrentBasePointersIdx;
6597 }
6598 assert(BasePointers.size() > CurrentBasePointersIdx &&
6599 "Unexpected number of mapped base pointers.");
6600
6601 auto *RelevantVD = L.Components.back().getAssociatedDeclaration();
6602 assert(RelevantVD &&
6603 "No relevant declaration related with device pointer??");
6604
6605 BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
George Rokos065755d2017-11-07 18:27:04 +00006606 Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PARAM;
Samuel Antaocc10b852016-07-28 14:23:26 +00006607 }
Samuel Antao86ace552016-04-27 22:40:57 +00006608 IsFirstComponentList = false;
6609 }
6610 }
6611 }
6612
6613 /// \brief Generate the base pointers, section pointers, sizes and map types
6614 /// associated to a given capture.
6615 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00006616 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006617 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006618 MapValuesArrayTy &Pointers,
6619 MapValuesArrayTy &Sizes,
6620 MapFlagsArrayTy &Types) const {
6621 assert(!Cap->capturesVariableArrayType() &&
6622 "Not expecting to generate map info for a variable array type!");
6623
6624 BasePointers.clear();
6625 Pointers.clear();
6626 Sizes.clear();
6627 Types.clear();
6628
Samuel Antao6890b092016-07-28 14:25:09 +00006629 // We need to know when we generating information for the first component
6630 // associated with a capture, because the mapping flags depend on it.
6631 bool IsFirstComponentList = true;
6632
Samuel Antao86ace552016-04-27 22:40:57 +00006633 const ValueDecl *VD =
6634 Cap->capturesThis()
6635 ? nullptr
6636 : cast<ValueDecl>(Cap->getCapturedVar()->getCanonicalDecl());
6637
Samuel Antao6890b092016-07-28 14:25:09 +00006638 // If this declaration appears in a is_device_ptr clause we just have to
6639 // pass the pointer by value. If it is a reference to a declaration, we just
6640 // pass its value, otherwise, if it is a member expression, we need to map
6641 // 'to' the field.
6642 if (!VD) {
6643 auto It = DevPointersMap.find(VD);
6644 if (It != DevPointersMap.end()) {
6645 for (auto L : It->second) {
6646 generateInfoForComponentList(
6647 /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006648 BasePointers, Pointers, Sizes, Types, IsFirstComponentList,
6649 /*IsImplicit=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +00006650 IsFirstComponentList = false;
6651 }
6652 return;
6653 }
6654 } else if (DevPointersMap.count(VD)) {
6655 BasePointers.push_back({Arg, VD});
6656 Pointers.push_back(Arg);
6657 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
George Rokos065755d2017-11-07 18:27:04 +00006658 Types.push_back(OMP_MAP_LITERAL | OMP_MAP_TARGET_PARAM);
Samuel Antao6890b092016-07-28 14:25:09 +00006659 return;
6660 }
6661
Paul Robinson78fb1322016-08-01 22:12:46 +00006662 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006663 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao86ace552016-04-27 22:40:57 +00006664 for (auto L : C->decl_component_lists(VD)) {
6665 assert(L.first == VD &&
6666 "We got information for the wrong declaration??");
6667 assert(!L.second.empty() &&
6668 "Not expecting declaration with no component lists.");
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006669 generateInfoForComponentList(
6670 C->getMapType(), C->getMapTypeModifier(), L.second, BasePointers,
6671 Pointers, Sizes, Types, IsFirstComponentList, C->isImplicit());
Samuel Antao86ace552016-04-27 22:40:57 +00006672 IsFirstComponentList = false;
6673 }
6674
6675 return;
6676 }
Samuel Antaod486f842016-05-26 16:53:38 +00006677
6678 /// \brief Generate the default map information for a given capture \a CI,
6679 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00006680 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
6681 const FieldDecl &RI, llvm::Value *CV,
6682 MapBaseValuesArrayTy &CurBasePointers,
6683 MapValuesArrayTy &CurPointers,
6684 MapValuesArrayTy &CurSizes,
6685 MapFlagsArrayTy &CurMapTypes) {
Samuel Antaod486f842016-05-26 16:53:38 +00006686
6687 // Do the default mapping.
6688 if (CI.capturesThis()) {
6689 CurBasePointers.push_back(CV);
6690 CurPointers.push_back(CV);
6691 const PointerType *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
6692 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
6693 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00006694 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00006695 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00006696 CurBasePointers.push_back(CV);
6697 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00006698 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00006699 // We have to signal to the runtime captures passed by value that are
6700 // not pointers.
George Rokos065755d2017-11-07 18:27:04 +00006701 CurMapTypes.push_back(OMP_MAP_LITERAL);
Samuel Antaod486f842016-05-26 16:53:38 +00006702 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
6703 } else {
6704 // Pointers are implicitly mapped with a zero size and no flags
6705 // (other than first map that is added for all implicit maps).
6706 CurMapTypes.push_back(0u);
Samuel Antaod486f842016-05-26 16:53:38 +00006707 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
6708 }
6709 } else {
6710 assert(CI.capturesVariable() && "Expected captured reference.");
6711 CurBasePointers.push_back(CV);
6712 CurPointers.push_back(CV);
6713
6714 const ReferenceType *PtrTy =
6715 cast<ReferenceType>(RI.getType().getTypePtr());
6716 QualType ElementType = PtrTy->getPointeeType();
6717 CurSizes.push_back(CGF.getTypeSize(ElementType));
6718 // The default map type for a scalar/complex type is 'to' because by
6719 // default the value doesn't have to be retrieved. For an aggregate
6720 // type, the default is 'tofrom'.
6721 CurMapTypes.push_back(ElementType->isAggregateType()
Samuel Antaocc10b852016-07-28 14:23:26 +00006722 ? (OMP_MAP_TO | OMP_MAP_FROM)
6723 : OMP_MAP_TO);
Samuel Antaod486f842016-05-26 16:53:38 +00006724
6725 // If we have a capture by reference we may need to add the private
6726 // pointer flag if the base declaration shows in some first-private
6727 // clause.
6728 CurMapTypes.back() =
6729 adjustMapModifiersForPrivateClauses(CI, CurMapTypes.back());
6730 }
George Rokos065755d2017-11-07 18:27:04 +00006731 // Every default map produces a single argument which is a target parameter.
6732 CurMapTypes.back() |= OMP_MAP_TARGET_PARAM;
Samuel Antaod486f842016-05-26 16:53:38 +00006733 }
Samuel Antao86ace552016-04-27 22:40:57 +00006734};
Samuel Antaodf158d52016-04-27 22:58:19 +00006735
6736enum OpenMPOffloadingReservedDeviceIDs {
6737 /// \brief Device ID if the device was not defined, runtime should get it
6738 /// from environment variables in the spec.
6739 OMP_DEVICEID_UNDEF = -1,
6740};
6741} // anonymous namespace
6742
6743/// \brief Emit the arrays used to pass the captures and map information to the
6744/// offloading runtime library. If there is no map or capture information,
6745/// return nullptr by reference.
6746static void
Samuel Antaocc10b852016-07-28 14:23:26 +00006747emitOffloadingArrays(CodeGenFunction &CGF,
6748 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00006749 MappableExprsHandler::MapValuesArrayTy &Pointers,
6750 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00006751 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
6752 CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006753 auto &CGM = CGF.CGM;
6754 auto &Ctx = CGF.getContext();
6755
Samuel Antaocc10b852016-07-28 14:23:26 +00006756 // Reset the array information.
6757 Info.clearArrayInfo();
6758 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00006759
Samuel Antaocc10b852016-07-28 14:23:26 +00006760 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006761 // Detect if we have any capture size requiring runtime evaluation of the
6762 // size so that a constant array could be eventually used.
6763 bool hasRuntimeEvaluationCaptureSize = false;
6764 for (auto *S : Sizes)
6765 if (!isa<llvm::Constant>(S)) {
6766 hasRuntimeEvaluationCaptureSize = true;
6767 break;
6768 }
6769
Samuel Antaocc10b852016-07-28 14:23:26 +00006770 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00006771 QualType PointerArrayType =
6772 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
6773 /*IndexTypeQuals=*/0);
6774
Samuel Antaocc10b852016-07-28 14:23:26 +00006775 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006776 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00006777 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006778 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
6779
6780 // If we don't have any VLA types or other types that require runtime
6781 // evaluation, we can use a constant array for the map sizes, otherwise we
6782 // need to fill up the arrays as we do for the pointers.
6783 if (hasRuntimeEvaluationCaptureSize) {
6784 QualType SizeArrayType = Ctx.getConstantArrayType(
6785 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
6786 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00006787 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006788 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
6789 } else {
6790 // We expect all the sizes to be constant, so we collect them to create
6791 // a constant array.
6792 SmallVector<llvm::Constant *, 16> ConstSizes;
6793 for (auto S : Sizes)
6794 ConstSizes.push_back(cast<llvm::Constant>(S));
6795
6796 auto *SizesArrayInit = llvm::ConstantArray::get(
6797 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
6798 auto *SizesArrayGbl = new llvm::GlobalVariable(
6799 CGM.getModule(), SizesArrayInit->getType(),
6800 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
6801 SizesArrayInit, ".offload_sizes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00006802 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00006803 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00006804 }
6805
6806 // The map types are always constant so we don't need to generate code to
6807 // fill arrays. Instead, we create an array constant.
6808 llvm::Constant *MapTypesArrayInit =
6809 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
6810 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
6811 CGM.getModule(), MapTypesArrayInit->getType(),
6812 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
6813 MapTypesArrayInit, ".offload_maptypes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00006814 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00006815 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00006816
Samuel Antaocc10b852016-07-28 14:23:26 +00006817 for (unsigned i = 0; i < Info.NumberOfPtrs; ++i) {
6818 llvm::Value *BPVal = *BasePointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00006819 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006820 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6821 Info.BasePointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00006822 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6823 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00006824 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
6825 CGF.Builder.CreateStore(BPVal, BPAddr);
6826
Samuel Antaocc10b852016-07-28 14:23:26 +00006827 if (Info.requiresDevicePointerInfo())
6828 if (auto *DevVD = BasePointers[i].getDevicePtrDecl())
6829 Info.CaptureDeviceAddrMap.insert(std::make_pair(DevVD, BPAddr));
6830
Samuel Antaodf158d52016-04-27 22:58:19 +00006831 llvm::Value *PVal = Pointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00006832 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006833 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6834 Info.PointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00006835 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6836 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00006837 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
6838 CGF.Builder.CreateStore(PVal, PAddr);
6839
6840 if (hasRuntimeEvaluationCaptureSize) {
6841 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006842 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
6843 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006844 /*Idx0=*/0,
6845 /*Idx1=*/i);
6846 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
6847 CGF.Builder.CreateStore(
6848 CGF.Builder.CreateIntCast(Sizes[i], CGM.SizeTy, /*isSigned=*/true),
6849 SAddr);
6850 }
6851 }
6852 }
6853}
6854/// \brief Emit the arguments to be passed to the runtime library based on the
6855/// arrays of pointers, sizes and map types.
6856static void emitOffloadingArraysArgument(
6857 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
6858 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006859 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006860 auto &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00006861 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006862 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006863 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6864 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006865 /*Idx0=*/0, /*Idx1=*/0);
6866 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006867 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6868 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006869 /*Idx0=*/0,
6870 /*Idx1=*/0);
6871 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006872 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006873 /*Idx0=*/0, /*Idx1=*/0);
6874 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
George Rokos63bc9d62017-11-21 18:25:12 +00006875 llvm::ArrayType::get(CGM.Int64Ty, Info.NumberOfPtrs),
Samuel Antaocc10b852016-07-28 14:23:26 +00006876 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006877 /*Idx0=*/0,
6878 /*Idx1=*/0);
6879 } else {
6880 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
6881 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
6882 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
6883 MapTypesArrayArg =
George Rokos63bc9d62017-11-21 18:25:12 +00006884 llvm::ConstantPointerNull::get(CGM.Int64Ty->getPointerTo());
Samuel Antaodf158d52016-04-27 22:58:19 +00006885 }
Samuel Antao86ace552016-04-27 22:40:57 +00006886}
6887
Samuel Antaobed3c462015-10-02 16:14:20 +00006888void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
6889 const OMPExecutableDirective &D,
6890 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00006891 llvm::Value *OutlinedFnID,
Samuel Antaobed3c462015-10-02 16:14:20 +00006892 const Expr *IfCond, const Expr *Device,
6893 ArrayRef<llvm::Value *> CapturedVars) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006894 if (!CGF.HaveInsertPoint())
6895 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00006896
Samuel Antaoee8fb302016-01-06 13:42:12 +00006897 assert(OutlinedFn && "Invalid outlined function!");
6898
Samuel Antao86ace552016-04-27 22:40:57 +00006899 // Fill up the arrays with all the captured variables.
6900 MappableExprsHandler::MapValuesArrayTy KernelArgs;
Samuel Antaocc10b852016-07-28 14:23:26 +00006901 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00006902 MappableExprsHandler::MapValuesArrayTy Pointers;
6903 MappableExprsHandler::MapValuesArrayTy Sizes;
6904 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobed3c462015-10-02 16:14:20 +00006905
Samuel Antaocc10b852016-07-28 14:23:26 +00006906 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00006907 MappableExprsHandler::MapValuesArrayTy CurPointers;
6908 MappableExprsHandler::MapValuesArrayTy CurSizes;
6909 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
6910
Samuel Antaod486f842016-05-26 16:53:38 +00006911 // Get mappable expression information.
6912 MappableExprsHandler MEHandler(D, CGF);
Samuel Antaobed3c462015-10-02 16:14:20 +00006913
6914 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
6915 auto RI = CS.getCapturedRecordDecl()->field_begin();
Samuel Antaobed3c462015-10-02 16:14:20 +00006916 auto CV = CapturedVars.begin();
6917 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
6918 CE = CS.capture_end();
6919 CI != CE; ++CI, ++RI, ++CV) {
Samuel Antao86ace552016-04-27 22:40:57 +00006920 CurBasePointers.clear();
6921 CurPointers.clear();
6922 CurSizes.clear();
6923 CurMapTypes.clear();
6924
6925 // VLA sizes are passed to the outlined region by copy and do not have map
6926 // information associated.
Samuel Antaobed3c462015-10-02 16:14:20 +00006927 if (CI->capturesVariableArrayType()) {
Samuel Antao86ace552016-04-27 22:40:57 +00006928 CurBasePointers.push_back(*CV);
6929 CurPointers.push_back(*CV);
6930 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006931 // Copy to the device as an argument. No need to retrieve it.
George Rokos065755d2017-11-07 18:27:04 +00006932 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_LITERAL |
6933 MappableExprsHandler::OMP_MAP_TARGET_PARAM);
Samuel Antaobed3c462015-10-02 16:14:20 +00006934 } else {
Samuel Antao86ace552016-04-27 22:40:57 +00006935 // If we have any information in the map clause, we use it, otherwise we
6936 // just do a default mapping.
Samuel Antao6890b092016-07-28 14:25:09 +00006937 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006938 CurSizes, CurMapTypes);
Samuel Antaod486f842016-05-26 16:53:38 +00006939 if (CurBasePointers.empty())
6940 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
6941 CurPointers, CurSizes, CurMapTypes);
Samuel Antaobed3c462015-10-02 16:14:20 +00006942 }
Samuel Antao86ace552016-04-27 22:40:57 +00006943 // We expect to have at least an element of information for this capture.
6944 assert(!CurBasePointers.empty() && "Non-existing map pointer for capture!");
6945 assert(CurBasePointers.size() == CurPointers.size() &&
6946 CurBasePointers.size() == CurSizes.size() &&
6947 CurBasePointers.size() == CurMapTypes.size() &&
6948 "Inconsistent map information sizes!");
Samuel Antaobed3c462015-10-02 16:14:20 +00006949
Samuel Antao86ace552016-04-27 22:40:57 +00006950 // The kernel args are always the first elements of the base pointers
6951 // associated with a capture.
Samuel Antaocc10b852016-07-28 14:23:26 +00006952 KernelArgs.push_back(*CurBasePointers.front());
Samuel Antao86ace552016-04-27 22:40:57 +00006953 // We need to append the results of this capture to what we already have.
6954 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
6955 Pointers.append(CurPointers.begin(), CurPointers.end());
6956 Sizes.append(CurSizes.begin(), CurSizes.end());
6957 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
Samuel Antaobed3c462015-10-02 16:14:20 +00006958 }
6959
Samuel Antaobed3c462015-10-02 16:14:20 +00006960 // Fill up the pointer arrays and transfer execution to the device.
Alexey Bataev2a007e02017-10-02 14:20:58 +00006961 auto &&ThenGen = [this, &BasePointers, &Pointers, &Sizes, &MapTypes, Device,
6962 OutlinedFn, OutlinedFnID, &D,
6963 &KernelArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006964 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antaodf158d52016-04-27 22:58:19 +00006965 // Emit the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00006966 TargetDataInfo Info;
6967 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
6968 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
6969 Info.PointersArray, Info.SizesArray,
6970 Info.MapTypesArray, Info);
Samuel Antaobed3c462015-10-02 16:14:20 +00006971
6972 // On top of the arrays that were filled up, the target offloading call
6973 // takes as arguments the device id as well as the host pointer. The host
6974 // pointer is used by the runtime library to identify the current target
6975 // region, so it only has to be unique and not necessarily point to
6976 // anything. It could be the pointer to the outlined function that
6977 // implements the target region, but we aren't using that so that the
6978 // compiler doesn't need to keep that, and could therefore inline the host
6979 // function if proven worthwhile during optimization.
6980
Samuel Antaoee8fb302016-01-06 13:42:12 +00006981 // From this point on, we need to have an ID of the target region defined.
6982 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00006983
6984 // Emit device ID if any.
6985 llvm::Value *DeviceID;
George Rokos63bc9d62017-11-21 18:25:12 +00006986 if (Device) {
Samuel Antaobed3c462015-10-02 16:14:20 +00006987 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00006988 CGF.Int64Ty, /*isSigned=*/true);
6989 } else {
6990 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
6991 }
Samuel Antaobed3c462015-10-02 16:14:20 +00006992
Samuel Antaodf158d52016-04-27 22:58:19 +00006993 // Emit the number of elements in the offloading arrays.
6994 llvm::Value *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6995
Samuel Antaob68e2db2016-03-03 16:20:23 +00006996 // Return value of the runtime offloading call.
6997 llvm::Value *Return;
6998
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006999 auto *NumTeams = emitNumTeamsForTargetDirective(RT, CGF, D);
7000 auto *NumThreads = emitNumThreadsForTargetDirective(RT, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007001
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007002 // The target region is an outlined function launched by the runtime
7003 // via calls __tgt_target() or __tgt_target_teams().
7004 //
7005 // __tgt_target() launches a target region with one team and one thread,
7006 // executing a serial region. This master thread may in turn launch
7007 // more threads within its team upon encountering a parallel region,
7008 // however, no additional teams can be launched on the device.
7009 //
7010 // __tgt_target_teams() launches a target region with one or more teams,
7011 // each with one or more threads. This call is required for target
7012 // constructs such as:
7013 // 'target teams'
7014 // 'target' / 'teams'
7015 // 'target teams distribute parallel for'
7016 // 'target parallel'
7017 // and so on.
7018 //
7019 // Note that on the host and CPU targets, the runtime implementation of
7020 // these calls simply call the outlined function without forking threads.
7021 // The outlined functions themselves have runtime calls to
7022 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
7023 // the compiler in emitTeamsCall() and emitParallelCall().
7024 //
7025 // In contrast, on the NVPTX target, the implementation of
7026 // __tgt_target_teams() launches a GPU kernel with the requested number
7027 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00007028 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007029 // If we have NumTeams defined this means that we have an enclosed teams
7030 // region. Therefore we also expect to have NumThreads defined. These two
7031 // values should be defined in the presence of a teams directive,
7032 // regardless of having any clauses associated. If the user is using teams
7033 // but no clauses, these two values will be the default that should be
7034 // passed to the runtime library - a 32-bit integer with the value zero.
7035 assert(NumThreads && "Thread limit expression should be available along "
7036 "with number of teams.");
Samuel Antaob68e2db2016-03-03 16:20:23 +00007037 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007038 DeviceID, OutlinedFnID,
7039 PointerNum, Info.BasePointersArray,
7040 Info.PointersArray, Info.SizesArray,
7041 Info.MapTypesArray, NumTeams,
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007042 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00007043 Return = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007044 RT.createRuntimeFunction(OMPRTL__tgt_target_teams), OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007045 } else {
7046 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007047 DeviceID, OutlinedFnID,
7048 PointerNum, Info.BasePointersArray,
7049 Info.PointersArray, Info.SizesArray,
7050 Info.MapTypesArray};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007051 Return = CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target),
Samuel Antaob68e2db2016-03-03 16:20:23 +00007052 OffloadingArgs);
7053 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007054
Alexey Bataev2a007e02017-10-02 14:20:58 +00007055 // Check the error code and execute the host version if required.
7056 llvm::BasicBlock *OffloadFailedBlock =
7057 CGF.createBasicBlock("omp_offload.failed");
7058 llvm::BasicBlock *OffloadContBlock =
7059 CGF.createBasicBlock("omp_offload.cont");
7060 llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
7061 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
7062
7063 CGF.EmitBlock(OffloadFailedBlock);
7064 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, KernelArgs);
7065 CGF.EmitBranch(OffloadContBlock);
7066
7067 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00007068 };
7069
Samuel Antaoee8fb302016-01-06 13:42:12 +00007070 // Notify that the host version must be executed.
Alexey Bataev2a007e02017-10-02 14:20:58 +00007071 auto &&ElseGen = [this, &D, OutlinedFn, &KernelArgs](CodeGenFunction &CGF,
7072 PrePostActionTy &) {
7073 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn,
7074 KernelArgs);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007075 };
7076
7077 // If we have a target function ID it means that we need to support
7078 // offloading, otherwise, just execute on the host. We need to execute on host
7079 // regardless of the conditional in the if clause if, e.g., the user do not
7080 // specify target triples.
7081 if (OutlinedFnID) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007082 if (IfCond)
Samuel Antaoee8fb302016-01-06 13:42:12 +00007083 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007084 else {
7085 RegionCodeGenTy ThenRCG(ThenGen);
7086 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007087 }
7088 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007089 RegionCodeGenTy ElseRCG(ElseGen);
7090 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007091 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007092}
Samuel Antaoee8fb302016-01-06 13:42:12 +00007093
7094void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
7095 StringRef ParentName) {
7096 if (!S)
7097 return;
7098
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007099 // Codegen OMP target directives that offload compute to the device.
7100 bool requiresDeviceCodegen =
7101 isa<OMPExecutableDirective>(S) &&
7102 isOpenMPTargetExecutionDirective(
7103 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00007104
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007105 if (requiresDeviceCodegen) {
7106 auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007107 unsigned DeviceID;
7108 unsigned FileID;
7109 unsigned Line;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007110 getTargetEntryUniqueInfo(CGM.getContext(), E.getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00007111 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007112
7113 // Is this a target region that should not be emitted as an entry point? If
7114 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00007115 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
7116 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007117 return;
7118
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007119 switch (S->getStmtClass()) {
7120 case Stmt::OMPTargetDirectiveClass:
7121 CodeGenFunction::EmitOMPTargetDeviceFunction(
7122 CGM, ParentName, cast<OMPTargetDirective>(*S));
7123 break;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00007124 case Stmt::OMPTargetParallelDirectiveClass:
7125 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
7126 CGM, ParentName, cast<OMPTargetParallelDirective>(*S));
7127 break;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00007128 case Stmt::OMPTargetTeamsDirectiveClass:
7129 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
7130 CGM, ParentName, cast<OMPTargetTeamsDirective>(*S));
7131 break;
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007132 case Stmt::OMPTargetParallelForDirectiveClass:
7133 CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
7134 CGM, ParentName, cast<OMPTargetParallelForDirective>(*S));
7135 break;
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007136 case Stmt::OMPTargetParallelForSimdDirectiveClass:
7137 CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
7138 CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(*S));
7139 break;
Alexey Bataevf8365372017-11-17 17:57:25 +00007140 case Stmt::OMPTargetSimdDirectiveClass:
7141 CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
7142 CGM, ParentName, cast<OMPTargetSimdDirective>(*S));
7143 break;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007144 default:
7145 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
7146 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00007147 return;
7148 }
7149
7150 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
Samuel Antaoe49645c2016-05-08 06:43:56 +00007151 if (!E->hasAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00007152 return;
7153
7154 scanForTargetRegionsFunctions(
7155 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
7156 ParentName);
7157 return;
7158 }
7159
7160 // If this is a lambda function, look into its body.
7161 if (auto *L = dyn_cast<LambdaExpr>(S))
7162 S = L->getBody();
7163
7164 // Keep looking for target regions recursively.
7165 for (auto *II : S->children())
7166 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007167}
7168
7169bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
7170 auto &FD = *cast<FunctionDecl>(GD.getDecl());
7171
7172 // If emitting code for the host, we do not process FD here. Instead we do
7173 // the normal code generation.
7174 if (!CGM.getLangOpts().OpenMPIsDevice)
7175 return false;
7176
7177 // Try to detect target regions in the function.
7178 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
7179
Samuel Antao4b75b872016-12-12 19:26:31 +00007180 // We should not emit any function other that the ones created during the
Samuel Antaoee8fb302016-01-06 13:42:12 +00007181 // scanning. Therefore, we signal that this function is completely dealt
7182 // with.
7183 return true;
7184}
7185
7186bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
7187 if (!CGM.getLangOpts().OpenMPIsDevice)
7188 return false;
7189
7190 // Check if there are Ctors/Dtors in this declaration and look for target
7191 // regions in it. We use the complete variant to produce the kernel name
7192 // mangling.
7193 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
7194 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
7195 for (auto *Ctor : RD->ctors()) {
7196 StringRef ParentName =
7197 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
7198 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
7199 }
7200 auto *Dtor = RD->getDestructor();
7201 if (Dtor) {
7202 StringRef ParentName =
7203 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
7204 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
7205 }
7206 }
7207
Gheorghe-Teodor Bercea47633db2017-06-13 15:35:27 +00007208 // If we are in target mode, we do not emit any global (declare target is not
Samuel Antaoee8fb302016-01-06 13:42:12 +00007209 // implemented yet). Therefore we signal that GD was processed in this case.
7210 return true;
7211}
7212
7213bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
7214 auto *VD = GD.getDecl();
7215 if (isa<FunctionDecl>(VD))
7216 return emitTargetFunctions(GD);
7217
7218 return emitTargetGlobalVariable(GD);
7219}
7220
7221llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
7222 // If we have offloading in the current module, we need to emit the entries
7223 // now and register the offloading descriptor.
7224 createOffloadEntriesAndInfoMetadata();
7225
7226 // Create and register the offloading binary descriptors. This is the main
7227 // entity that captures all the information about offloading in the current
7228 // compilation unit.
7229 return createOffloadingBinaryDescriptorRegistration();
7230}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007231
7232void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
7233 const OMPExecutableDirective &D,
7234 SourceLocation Loc,
7235 llvm::Value *OutlinedFn,
7236 ArrayRef<llvm::Value *> CapturedVars) {
7237 if (!CGF.HaveInsertPoint())
7238 return;
7239
7240 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7241 CodeGenFunction::RunCleanupsScope Scope(CGF);
7242
7243 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
7244 llvm::Value *Args[] = {
7245 RTLoc,
7246 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
7247 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
7248 llvm::SmallVector<llvm::Value *, 16> RealArgs;
7249 RealArgs.append(std::begin(Args), std::end(Args));
7250 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
7251
7252 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
7253 CGF.EmitRuntimeCall(RTLFn, RealArgs);
7254}
7255
7256void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00007257 const Expr *NumTeams,
7258 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007259 SourceLocation Loc) {
7260 if (!CGF.HaveInsertPoint())
7261 return;
7262
7263 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7264
Carlo Bertollic6872252016-04-04 15:55:02 +00007265 llvm::Value *NumTeamsVal =
7266 (NumTeams)
7267 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
7268 CGF.CGM.Int32Ty, /* isSigned = */ true)
7269 : CGF.Builder.getInt32(0);
7270
7271 llvm::Value *ThreadLimitVal =
7272 (ThreadLimit)
7273 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
7274 CGF.CGM.Int32Ty, /* isSigned = */ true)
7275 : CGF.Builder.getInt32(0);
7276
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007277 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00007278 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
7279 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007280 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
7281 PushNumTeamsArgs);
7282}
Samuel Antaodf158d52016-04-27 22:58:19 +00007283
Samuel Antaocc10b852016-07-28 14:23:26 +00007284void CGOpenMPRuntime::emitTargetDataCalls(
7285 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7286 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007287 if (!CGF.HaveInsertPoint())
7288 return;
7289
Samuel Antaocc10b852016-07-28 14:23:26 +00007290 // Action used to replace the default codegen action and turn privatization
7291 // off.
7292 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00007293
7294 // Generate the code for the opening of the data environment. Capture all the
7295 // arguments of the runtime call by reference because they are used in the
7296 // closing of the region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007297 auto &&BeginThenGen = [&D, Device, &Info, &CodeGen](CodeGenFunction &CGF,
7298 PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007299 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00007300 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00007301 MappableExprsHandler::MapValuesArrayTy Pointers;
7302 MappableExprsHandler::MapValuesArrayTy Sizes;
7303 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7304
7305 // Get map clause information.
7306 MappableExprsHandler MCHandler(D, CGF);
7307 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00007308
7309 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00007310 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007311
7312 llvm::Value *BasePointersArrayArg = nullptr;
7313 llvm::Value *PointersArrayArg = nullptr;
7314 llvm::Value *SizesArrayArg = nullptr;
7315 llvm::Value *MapTypesArrayArg = nullptr;
7316 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007317 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007318
7319 // Emit device ID if any.
7320 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00007321 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007322 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007323 CGF.Int64Ty, /*isSigned=*/true);
7324 } else {
7325 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7326 }
Samuel Antaodf158d52016-04-27 22:58:19 +00007327
7328 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007329 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007330
7331 llvm::Value *OffloadingArgs[] = {
7332 DeviceID, PointerNum, BasePointersArrayArg,
7333 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
7334 auto &RT = CGF.CGM.getOpenMPRuntime();
7335 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_begin),
7336 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00007337
7338 // If device pointer privatization is required, emit the body of the region
7339 // here. It will have to be duplicated: with and without privatization.
7340 if (!Info.CaptureDeviceAddrMap.empty())
7341 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007342 };
7343
7344 // Generate code for the closing of the data region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007345 auto &&EndThenGen = [Device, &Info](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007346 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00007347
7348 llvm::Value *BasePointersArrayArg = nullptr;
7349 llvm::Value *PointersArrayArg = nullptr;
7350 llvm::Value *SizesArrayArg = nullptr;
7351 llvm::Value *MapTypesArrayArg = nullptr;
7352 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007353 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007354
7355 // Emit device ID if any.
7356 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00007357 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007358 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007359 CGF.Int64Ty, /*isSigned=*/true);
7360 } else {
7361 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7362 }
Samuel Antaodf158d52016-04-27 22:58:19 +00007363
7364 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007365 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007366
7367 llvm::Value *OffloadingArgs[] = {
7368 DeviceID, PointerNum, BasePointersArrayArg,
7369 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
7370 auto &RT = CGF.CGM.getOpenMPRuntime();
7371 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_end),
7372 OffloadingArgs);
7373 };
7374
Samuel Antaocc10b852016-07-28 14:23:26 +00007375 // If we need device pointer privatization, we need to emit the body of the
7376 // region with no privatization in the 'else' branch of the conditional.
7377 // Otherwise, we don't have to do anything.
7378 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
7379 PrePostActionTy &) {
7380 if (!Info.CaptureDeviceAddrMap.empty()) {
7381 CodeGen.setAction(NoPrivAction);
7382 CodeGen(CGF);
7383 }
7384 };
7385
7386 // We don't have to do anything to close the region if the if clause evaluates
7387 // to false.
7388 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00007389
7390 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007391 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007392 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007393 RegionCodeGenTy RCG(BeginThenGen);
7394 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007395 }
7396
Samuel Antaocc10b852016-07-28 14:23:26 +00007397 // If we don't require privatization of device pointers, we emit the body in
7398 // between the runtime calls. This avoids duplicating the body code.
7399 if (Info.CaptureDeviceAddrMap.empty()) {
7400 CodeGen.setAction(NoPrivAction);
7401 CodeGen(CGF);
7402 }
Samuel Antaodf158d52016-04-27 22:58:19 +00007403
7404 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007405 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007406 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007407 RegionCodeGenTy RCG(EndThenGen);
7408 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007409 }
7410}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007411
Samuel Antao8d2d7302016-05-26 18:30:22 +00007412void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00007413 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7414 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007415 if (!CGF.HaveInsertPoint())
7416 return;
7417
Samuel Antao8dd66282016-04-27 23:14:30 +00007418 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00007419 isa<OMPTargetExitDataDirective>(D) ||
7420 isa<OMPTargetUpdateDirective>(D)) &&
7421 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00007422
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007423 // Generate the code for the opening of the data environment.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007424 auto &&ThenGen = [&D, Device](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007425 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00007426 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007427 MappableExprsHandler::MapValuesArrayTy Pointers;
7428 MappableExprsHandler::MapValuesArrayTy Sizes;
7429 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7430
7431 // Get map clause information.
Samuel Antao8d2d7302016-05-26 18:30:22 +00007432 MappableExprsHandler MEHandler(D, CGF);
7433 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007434
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007435 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00007436 TargetDataInfo Info;
7437 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
7438 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
7439 Info.PointersArray, Info.SizesArray,
7440 Info.MapTypesArray, Info);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007441
7442 // Emit device ID if any.
7443 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00007444 if (Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007445 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007446 CGF.Int64Ty, /*isSigned=*/true);
7447 } else {
7448 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7449 }
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007450
7451 // Emit the number of elements in the offloading arrays.
7452 auto *PointerNum = CGF.Builder.getInt32(BasePointers.size());
7453
7454 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007455 DeviceID, PointerNum, Info.BasePointersArray,
7456 Info.PointersArray, Info.SizesArray, Info.MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00007457
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007458 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antao8d2d7302016-05-26 18:30:22 +00007459 // Select the right runtime function call for each expected standalone
7460 // directive.
7461 OpenMPRTLFunction RTLFn;
7462 switch (D.getDirectiveKind()) {
7463 default:
7464 llvm_unreachable("Unexpected standalone target data directive.");
7465 break;
7466 case OMPD_target_enter_data:
7467 RTLFn = OMPRTL__tgt_target_data_begin;
7468 break;
7469 case OMPD_target_exit_data:
7470 RTLFn = OMPRTL__tgt_target_data_end;
7471 break;
7472 case OMPD_target_update:
7473 RTLFn = OMPRTL__tgt_target_data_update;
7474 break;
7475 }
7476 CGF.EmitRuntimeCall(RT.createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007477 };
7478
7479 // In the event we get an if clause, we don't have to take any action on the
7480 // else side.
7481 auto &&ElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
7482
7483 if (IfCond) {
7484 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
7485 } else {
7486 RegionCodeGenTy ThenGenRCG(ThenGen);
7487 ThenGenRCG(CGF);
7488 }
7489}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007490
7491namespace {
7492 /// Kind of parameter in a function with 'declare simd' directive.
7493 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
7494 /// Attribute set of the parameter.
7495 struct ParamAttrTy {
7496 ParamKindTy Kind = Vector;
7497 llvm::APSInt StrideOrArg;
7498 llvm::APSInt Alignment;
7499 };
7500} // namespace
7501
7502static unsigned evaluateCDTSize(const FunctionDecl *FD,
7503 ArrayRef<ParamAttrTy> ParamAttrs) {
7504 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
7505 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
7506 // of that clause. The VLEN value must be power of 2.
7507 // In other case the notion of the function`s "characteristic data type" (CDT)
7508 // is used to compute the vector length.
7509 // CDT is defined in the following order:
7510 // a) For non-void function, the CDT is the return type.
7511 // b) If the function has any non-uniform, non-linear parameters, then the
7512 // CDT is the type of the first such parameter.
7513 // c) If the CDT determined by a) or b) above is struct, union, or class
7514 // type which is pass-by-value (except for the type that maps to the
7515 // built-in complex data type), the characteristic data type is int.
7516 // d) If none of the above three cases is applicable, the CDT is int.
7517 // The VLEN is then determined based on the CDT and the size of vector
7518 // register of that ISA for which current vector version is generated. The
7519 // VLEN is computed using the formula below:
7520 // VLEN = sizeof(vector_register) / sizeof(CDT),
7521 // where vector register size specified in section 3.2.1 Registers and the
7522 // Stack Frame of original AMD64 ABI document.
7523 QualType RetType = FD->getReturnType();
7524 if (RetType.isNull())
7525 return 0;
7526 ASTContext &C = FD->getASTContext();
7527 QualType CDT;
7528 if (!RetType.isNull() && !RetType->isVoidType())
7529 CDT = RetType;
7530 else {
7531 unsigned Offset = 0;
7532 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
7533 if (ParamAttrs[Offset].Kind == Vector)
7534 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
7535 ++Offset;
7536 }
7537 if (CDT.isNull()) {
7538 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
7539 if (ParamAttrs[I + Offset].Kind == Vector) {
7540 CDT = FD->getParamDecl(I)->getType();
7541 break;
7542 }
7543 }
7544 }
7545 }
7546 if (CDT.isNull())
7547 CDT = C.IntTy;
7548 CDT = CDT->getCanonicalTypeUnqualified();
7549 if (CDT->isRecordType() || CDT->isUnionType())
7550 CDT = C.IntTy;
7551 return C.getTypeSize(CDT);
7552}
7553
7554static void
7555emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00007556 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007557 ArrayRef<ParamAttrTy> ParamAttrs,
7558 OMPDeclareSimdDeclAttr::BranchStateTy State) {
7559 struct ISADataTy {
7560 char ISA;
7561 unsigned VecRegSize;
7562 };
7563 ISADataTy ISAData[] = {
7564 {
7565 'b', 128
7566 }, // SSE
7567 {
7568 'c', 256
7569 }, // AVX
7570 {
7571 'd', 256
7572 }, // AVX2
7573 {
7574 'e', 512
7575 }, // AVX512
7576 };
7577 llvm::SmallVector<char, 2> Masked;
7578 switch (State) {
7579 case OMPDeclareSimdDeclAttr::BS_Undefined:
7580 Masked.push_back('N');
7581 Masked.push_back('M');
7582 break;
7583 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
7584 Masked.push_back('N');
7585 break;
7586 case OMPDeclareSimdDeclAttr::BS_Inbranch:
7587 Masked.push_back('M');
7588 break;
7589 }
7590 for (auto Mask : Masked) {
7591 for (auto &Data : ISAData) {
7592 SmallString<256> Buffer;
7593 llvm::raw_svector_ostream Out(Buffer);
7594 Out << "_ZGV" << Data.ISA << Mask;
7595 if (!VLENVal) {
7596 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
7597 evaluateCDTSize(FD, ParamAttrs));
7598 } else
7599 Out << VLENVal;
7600 for (auto &ParamAttr : ParamAttrs) {
7601 switch (ParamAttr.Kind){
7602 case LinearWithVarStride:
7603 Out << 's' << ParamAttr.StrideOrArg;
7604 break;
7605 case Linear:
7606 Out << 'l';
7607 if (!!ParamAttr.StrideOrArg)
7608 Out << ParamAttr.StrideOrArg;
7609 break;
7610 case Uniform:
7611 Out << 'u';
7612 break;
7613 case Vector:
7614 Out << 'v';
7615 break;
7616 }
7617 if (!!ParamAttr.Alignment)
7618 Out << 'a' << ParamAttr.Alignment;
7619 }
7620 Out << '_' << Fn->getName();
7621 Fn->addFnAttr(Out.str());
7622 }
7623 }
7624}
7625
7626void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
7627 llvm::Function *Fn) {
7628 ASTContext &C = CGM.getContext();
7629 FD = FD->getCanonicalDecl();
7630 // Map params to their positions in function decl.
7631 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
7632 if (isa<CXXMethodDecl>(FD))
7633 ParamPositions.insert({FD, 0});
7634 unsigned ParamPos = ParamPositions.size();
David Majnemer59f77922016-06-24 04:05:48 +00007635 for (auto *P : FD->parameters()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007636 ParamPositions.insert({P->getCanonicalDecl(), ParamPos});
7637 ++ParamPos;
7638 }
7639 for (auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
7640 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
7641 // Mark uniform parameters.
7642 for (auto *E : Attr->uniforms()) {
7643 E = E->IgnoreParenImpCasts();
7644 unsigned Pos;
7645 if (isa<CXXThisExpr>(E))
7646 Pos = ParamPositions[FD];
7647 else {
7648 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7649 ->getCanonicalDecl();
7650 Pos = ParamPositions[PVD];
7651 }
7652 ParamAttrs[Pos].Kind = Uniform;
7653 }
7654 // Get alignment info.
7655 auto NI = Attr->alignments_begin();
7656 for (auto *E : Attr->aligneds()) {
7657 E = E->IgnoreParenImpCasts();
7658 unsigned Pos;
7659 QualType ParmTy;
7660 if (isa<CXXThisExpr>(E)) {
7661 Pos = ParamPositions[FD];
7662 ParmTy = E->getType();
7663 } else {
7664 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7665 ->getCanonicalDecl();
7666 Pos = ParamPositions[PVD];
7667 ParmTy = PVD->getType();
7668 }
7669 ParamAttrs[Pos].Alignment =
7670 (*NI) ? (*NI)->EvaluateKnownConstInt(C)
7671 : llvm::APSInt::getUnsigned(
7672 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
7673 .getQuantity());
7674 ++NI;
7675 }
7676 // Mark linear parameters.
7677 auto SI = Attr->steps_begin();
7678 auto MI = Attr->modifiers_begin();
7679 for (auto *E : Attr->linears()) {
7680 E = E->IgnoreParenImpCasts();
7681 unsigned Pos;
7682 if (isa<CXXThisExpr>(E))
7683 Pos = ParamPositions[FD];
7684 else {
7685 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7686 ->getCanonicalDecl();
7687 Pos = ParamPositions[PVD];
7688 }
7689 auto &ParamAttr = ParamAttrs[Pos];
7690 ParamAttr.Kind = Linear;
7691 if (*SI) {
7692 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
7693 Expr::SE_AllowSideEffects)) {
7694 if (auto *DRE = cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
7695 if (auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
7696 ParamAttr.Kind = LinearWithVarStride;
7697 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
7698 ParamPositions[StridePVD->getCanonicalDecl()]);
7699 }
7700 }
7701 }
7702 }
7703 ++SI;
7704 ++MI;
7705 }
7706 llvm::APSInt VLENVal;
7707 if (const Expr *VLEN = Attr->getSimdlen())
7708 VLENVal = VLEN->EvaluateKnownConstInt(C);
7709 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
7710 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
7711 CGM.getTriple().getArch() == llvm::Triple::x86_64)
7712 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
7713 }
7714}
Alexey Bataev8b427062016-05-25 12:36:08 +00007715
7716namespace {
7717/// Cleanup action for doacross support.
7718class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
7719public:
7720 static const int DoacrossFinArgs = 2;
7721
7722private:
7723 llvm::Value *RTLFn;
7724 llvm::Value *Args[DoacrossFinArgs];
7725
7726public:
7727 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
7728 : RTLFn(RTLFn) {
7729 assert(CallArgs.size() == DoacrossFinArgs);
7730 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
7731 }
7732 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
7733 if (!CGF.HaveInsertPoint())
7734 return;
7735 CGF.EmitRuntimeCall(RTLFn, Args);
7736 }
7737};
7738} // namespace
7739
7740void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
7741 const OMPLoopDirective &D) {
7742 if (!CGF.HaveInsertPoint())
7743 return;
7744
7745 ASTContext &C = CGM.getContext();
7746 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
7747 RecordDecl *RD;
7748 if (KmpDimTy.isNull()) {
7749 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
7750 // kmp_int64 lo; // lower
7751 // kmp_int64 up; // upper
7752 // kmp_int64 st; // stride
7753 // };
7754 RD = C.buildImplicitRecord("kmp_dim");
7755 RD->startDefinition();
7756 addFieldToRecordDecl(C, RD, Int64Ty);
7757 addFieldToRecordDecl(C, RD, Int64Ty);
7758 addFieldToRecordDecl(C, RD, Int64Ty);
7759 RD->completeDefinition();
7760 KmpDimTy = C.getRecordType(RD);
7761 } else
7762 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
7763
7764 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
7765 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
7766 enum { LowerFD = 0, UpperFD, StrideFD };
7767 // Fill dims with data.
7768 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
7769 // dims.upper = num_iterations;
7770 LValue UpperLVal =
7771 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
7772 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
7773 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
7774 Int64Ty, D.getNumIterations()->getExprLoc());
7775 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
7776 // dims.stride = 1;
7777 LValue StrideLVal =
7778 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
7779 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
7780 StrideLVal);
7781
7782 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
7783 // kmp_int32 num_dims, struct kmp_dim * dims);
7784 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
7785 getThreadID(CGF, D.getLocStart()),
7786 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
7787 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7788 DimsAddr.getPointer(), CGM.VoidPtrTy)};
7789
7790 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
7791 CGF.EmitRuntimeCall(RTLFn, Args);
7792 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
7793 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
7794 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
7795 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
7796 llvm::makeArrayRef(FiniArgs));
7797}
7798
7799void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
7800 const OMPDependClause *C) {
7801 QualType Int64Ty =
7802 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
7803 const Expr *CounterVal = C->getCounterValue();
7804 assert(CounterVal);
7805 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
7806 CounterVal->getType(), Int64Ty,
7807 CounterVal->getExprLoc());
7808 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
7809 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
7810 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
7811 getThreadID(CGF, C->getLocStart()),
7812 CntAddr.getPointer()};
7813 llvm::Value *RTLFn;
7814 if (C->getDependencyKind() == OMPC_DEPEND_source)
7815 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
7816 else {
7817 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
7818 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
7819 }
7820 CGF.EmitRuntimeCall(RTLFn, Args);
7821}
7822
Alexey Bataev3c595a62017-08-14 15:01:03 +00007823void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, llvm::Value *Callee,
7824 ArrayRef<llvm::Value *> Args,
7825 SourceLocation Loc) const {
7826 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
7827
7828 if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007829 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00007830 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007831 return;
7832 }
7833 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00007834 CGF.EmitRuntimeCall(Callee, Args);
7835}
7836
7837void CGOpenMPRuntime::emitOutlinedFunctionCall(
7838 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
7839 ArrayRef<llvm::Value *> Args) const {
7840 assert(Loc.isValid() && "Outlined function call location must be valid.");
7841 emitCall(CGF, OutlinedFn, Args, Loc);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007842}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00007843
7844Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
7845 const VarDecl *NativeParam,
7846 const VarDecl *TargetParam) const {
7847 return CGF.GetAddrOfLocalVar(NativeParam);
7848}