blob: 891176b0097e7e827d74acad2a83bd7eb92127c1 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===----- CGOpenMPRuntime.cpp - Interface to OpenMP Runtimes -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides a class for OpenMP runtime code generation.
11//
12//===----------------------------------------------------------------------===//
13
Samuel Antaoee8fb302016-01-06 13:42:12 +000014#include "CGCXXABI.h"
15#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000016#include "CGOpenMPRuntime.h"
17#include "CodeGenFunction.h"
John McCall5ad74072017-03-02 20:04:19 +000018#include "clang/CodeGen/ConstantInitBuilder.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000019#include "clang/AST/Decl.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000020#include "clang/AST/StmtOpenMP.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000021#include "llvm/ADT/ArrayRef.h"
Alexey Bataev0f87dbe2017-08-14 17:56:13 +000022#include "llvm/ADT/BitmaskEnum.h"
Teresa Johnsonffc4e242016-11-11 05:35:12 +000023#include "llvm/Bitcode/BitcodeReader.h"
Alexey Bataevd74d0602014-10-13 06:02:40 +000024#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000025#include "llvm/IR/DerivedTypes.h"
26#include "llvm/IR/GlobalValue.h"
27#include "llvm/IR/Value.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000028#include "llvm/Support/Format.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000029#include "llvm/Support/raw_ostream.h"
Alexey Bataev23b69422014-06-18 07:08:49 +000030#include <cassert>
Alexey Bataev9959db52014-05-06 10:08:46 +000031
32using namespace clang;
33using namespace CodeGen;
34
Benjamin Kramerc52193f2014-10-10 13:57:57 +000035namespace {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000036/// \brief Base class for handling code generation inside OpenMP regions.
Alexey Bataev18095712014-10-10 12:19:54 +000037class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
38public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000039 /// \brief Kinds of OpenMP regions used in codegen.
40 enum CGOpenMPRegionKind {
41 /// \brief Region with outlined function for standalone 'parallel'
42 /// directive.
43 ParallelOutlinedRegion,
44 /// \brief Region with outlined function for standalone 'task' directive.
45 TaskOutlinedRegion,
46 /// \brief Region for constructs that do not require function outlining,
47 /// like 'for', 'sections', 'atomic' etc. directives.
48 InlinedRegion,
Samuel Antaobed3c462015-10-02 16:14:20 +000049 /// \brief Region with outlined function for standalone 'target' directive.
50 TargetRegion,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000051 };
Alexey Bataev18095712014-10-10 12:19:54 +000052
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000053 CGOpenMPRegionInfo(const CapturedStmt &CS,
54 const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000055 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
56 bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000057 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
Alexey Bataev25e5b442015-09-15 12:52:43 +000058 CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000059
60 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000061 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
62 bool HasCancel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +000063 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
Alexey Bataev25e5b442015-09-15 12:52:43 +000064 Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000065
66 /// \brief Get a variable or parameter for storing global thread id
Alexey Bataev18095712014-10-10 12:19:54 +000067 /// inside OpenMP construct.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000068 virtual const VarDecl *getThreadIDVariable() const = 0;
Alexey Bataev18095712014-10-10 12:19:54 +000069
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000070 /// \brief Emit the captured statement body.
Hans Wennborg7eb54642015-09-10 17:07:54 +000071 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000072
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000073 /// \brief Get an LValue for the current ThreadID variable.
Alexey Bataev62b63b12015-03-10 07:28:44 +000074 /// \return LValue for thread id variable. This LValue always has type int32*.
75 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
Alexey Bataev18095712014-10-10 12:19:54 +000076
Alexey Bataev48591dd2016-04-20 04:01:36 +000077 virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {}
78
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000079 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000080
Alexey Bataev81c7ea02015-07-03 09:56:58 +000081 OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
82
Alexey Bataev25e5b442015-09-15 12:52:43 +000083 bool hasCancel() const { return HasCancel; }
84
Alexey Bataev18095712014-10-10 12:19:54 +000085 static bool classof(const CGCapturedStmtInfo *Info) {
86 return Info->getKind() == CR_OpenMP;
87 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000088
Alexey Bataev48591dd2016-04-20 04:01:36 +000089 ~CGOpenMPRegionInfo() override = default;
90
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000091protected:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000092 CGOpenMPRegionKind RegionKind;
Hans Wennborg45c74392016-01-12 20:54:36 +000093 RegionCodeGenTy CodeGen;
Alexey Bataev81c7ea02015-07-03 09:56:58 +000094 OpenMPDirectiveKind Kind;
Alexey Bataev25e5b442015-09-15 12:52:43 +000095 bool HasCancel;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000096};
Alexey Bataev18095712014-10-10 12:19:54 +000097
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000098/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +000099class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000100public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000101 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000102 const RegionCodeGenTy &CodeGen,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000103 OpenMPDirectiveKind Kind, bool HasCancel,
104 StringRef HelperName)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000105 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
106 HasCancel),
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000107 ThreadIDVar(ThreadIDVar), HelperName(HelperName) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000108 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
109 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000110
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000111 /// \brief Get a variable or parameter for storing global thread id
112 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000113 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000114
Alexey Bataev18095712014-10-10 12:19:54 +0000115 /// \brief Get the name of the capture helper.
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000116 StringRef getHelperName() const override { return HelperName; }
Alexey Bataev18095712014-10-10 12:19:54 +0000117
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000118 static bool classof(const CGCapturedStmtInfo *Info) {
119 return CGOpenMPRegionInfo::classof(Info) &&
120 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
121 ParallelOutlinedRegion;
122 }
123
Alexey Bataev18095712014-10-10 12:19:54 +0000124private:
125 /// \brief A variable or parameter storing global thread id for OpenMP
126 /// constructs.
127 const VarDecl *ThreadIDVar;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000128 StringRef HelperName;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000129};
130
Alexey Bataev62b63b12015-03-10 07:28:44 +0000131/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000132class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000133public:
Alexey Bataev48591dd2016-04-20 04:01:36 +0000134 class UntiedTaskActionTy final : public PrePostActionTy {
135 bool Untied;
136 const VarDecl *PartIDVar;
137 const RegionCodeGenTy UntiedCodeGen;
138 llvm::SwitchInst *UntiedSwitch = nullptr;
139
140 public:
141 UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
142 const RegionCodeGenTy &UntiedCodeGen)
143 : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
144 void Enter(CodeGenFunction &CGF) override {
145 if (Untied) {
146 // Emit task switching point.
147 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
148 CGF.GetAddrOfLocalVar(PartIDVar),
149 PartIDVar->getType()->castAs<PointerType>());
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000150 auto *Res = CGF.EmitLoadOfScalar(PartIdLVal, PartIDVar->getLocation());
Alexey Bataev48591dd2016-04-20 04:01:36 +0000151 auto *DoneBB = CGF.createBasicBlock(".untied.done.");
152 UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
153 CGF.EmitBlock(DoneBB);
154 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
155 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
156 UntiedSwitch->addCase(CGF.Builder.getInt32(0),
157 CGF.Builder.GetInsertBlock());
158 emitUntiedSwitch(CGF);
159 }
160 }
161 void emitUntiedSwitch(CodeGenFunction &CGF) const {
162 if (Untied) {
163 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
164 CGF.GetAddrOfLocalVar(PartIDVar),
165 PartIDVar->getType()->castAs<PointerType>());
166 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
167 PartIdLVal);
168 UntiedCodeGen(CGF);
169 CodeGenFunction::JumpDest CurPoint =
170 CGF.getJumpDestInCurrentScope(".untied.next.");
171 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
172 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
173 UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
174 CGF.Builder.GetInsertBlock());
175 CGF.EmitBranchThroughCleanup(CurPoint);
176 CGF.EmitBlock(CurPoint.getBlock());
177 }
178 }
179 unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
180 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000181 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000182 const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000183 const RegionCodeGenTy &CodeGen,
Alexey Bataev48591dd2016-04-20 04:01:36 +0000184 OpenMPDirectiveKind Kind, bool HasCancel,
185 const UntiedTaskActionTy &Action)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000186 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
Alexey Bataev48591dd2016-04-20 04:01:36 +0000187 ThreadIDVar(ThreadIDVar), Action(Action) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000188 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
189 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000190
Alexey Bataev62b63b12015-03-10 07:28:44 +0000191 /// \brief Get a variable or parameter for storing global thread id
192 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000193 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000194
195 /// \brief Get an LValue for the current ThreadID variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000196 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000197
Alexey Bataev62b63b12015-03-10 07:28:44 +0000198 /// \brief Get the name of the capture helper.
199 StringRef getHelperName() const override { return ".omp_outlined."; }
200
Alexey Bataev48591dd2016-04-20 04:01:36 +0000201 void emitUntiedSwitch(CodeGenFunction &CGF) override {
202 Action.emitUntiedSwitch(CGF);
203 }
204
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000205 static bool classof(const CGCapturedStmtInfo *Info) {
206 return CGOpenMPRegionInfo::classof(Info) &&
207 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
208 TaskOutlinedRegion;
209 }
210
Alexey Bataev62b63b12015-03-10 07:28:44 +0000211private:
212 /// \brief A variable or parameter storing global thread id for OpenMP
213 /// constructs.
214 const VarDecl *ThreadIDVar;
Alexey Bataev48591dd2016-04-20 04:01:36 +0000215 /// Action for emitting code for untied tasks.
216 const UntiedTaskActionTy &Action;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000217};
218
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000219/// \brief API for inlined captured statement code generation in OpenMP
220/// constructs.
221class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
222public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000223 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000224 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000225 OpenMPDirectiveKind Kind, bool HasCancel)
226 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
227 OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000228 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000229
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000230 // \brief Retrieve the value of the context parameter.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000231 llvm::Value *getContextValue() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000232 if (OuterRegionInfo)
233 return OuterRegionInfo->getContextValue();
234 llvm_unreachable("No context value for inlined OpenMP region");
235 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000236
Hans Wennborg7eb54642015-09-10 17:07:54 +0000237 void setContextValue(llvm::Value *V) override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000238 if (OuterRegionInfo) {
239 OuterRegionInfo->setContextValue(V);
240 return;
241 }
242 llvm_unreachable("No context value for inlined OpenMP region");
243 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000244
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000245 /// \brief Lookup the captured field decl for a variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000246 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000247 if (OuterRegionInfo)
248 return OuterRegionInfo->lookup(VD);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000249 // If there is no outer outlined region,no need to lookup in a list of
250 // captured variables, we can use the original one.
251 return nullptr;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000252 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000253
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000254 FieldDecl *getThisFieldDecl() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000255 if (OuterRegionInfo)
256 return OuterRegionInfo->getThisFieldDecl();
257 return nullptr;
258 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000259
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000260 /// \brief Get a variable or parameter for storing global thread id
261 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000262 const VarDecl *getThreadIDVariable() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000263 if (OuterRegionInfo)
264 return OuterRegionInfo->getThreadIDVariable();
265 return nullptr;
266 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000267
Alexey Bataev311a9282017-10-12 13:51:32 +0000268 /// \brief Get an LValue for the current ThreadID variable.
269 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override {
270 if (OuterRegionInfo)
271 return OuterRegionInfo->getThreadIDVariableLValue(CGF);
272 llvm_unreachable("No LValue for inlined OpenMP construct");
273 }
274
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000275 /// \brief Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000276 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000277 if (auto *OuterRegionInfo = getOldCSI())
278 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000279 llvm_unreachable("No helper name for inlined OpenMP construct");
280 }
281
Alexey Bataev48591dd2016-04-20 04:01:36 +0000282 void emitUntiedSwitch(CodeGenFunction &CGF) override {
283 if (OuterRegionInfo)
284 OuterRegionInfo->emitUntiedSwitch(CGF);
285 }
286
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000287 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
288
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000289 static bool classof(const CGCapturedStmtInfo *Info) {
290 return CGOpenMPRegionInfo::classof(Info) &&
291 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
292 }
293
Alexey Bataev48591dd2016-04-20 04:01:36 +0000294 ~CGOpenMPInlinedRegionInfo() override = default;
295
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000296private:
297 /// \brief CodeGen info about outer OpenMP region.
298 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
299 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000300};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000301
Samuel Antaobed3c462015-10-02 16:14:20 +0000302/// \brief API for captured statement code generation in OpenMP target
303/// constructs. For this captures, implicit parameters are used instead of the
Samuel Antaoee8fb302016-01-06 13:42:12 +0000304/// captured fields. The name of the target region has to be unique in a given
305/// application so it is provided by the client, because only the client has
306/// the information to generate that.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000307class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
Samuel Antaobed3c462015-10-02 16:14:20 +0000308public:
309 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000310 const RegionCodeGenTy &CodeGen, StringRef HelperName)
Samuel Antaobed3c462015-10-02 16:14:20 +0000311 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000312 /*HasCancel=*/false),
313 HelperName(HelperName) {}
Samuel Antaobed3c462015-10-02 16:14:20 +0000314
315 /// \brief This is unused for target regions because each starts executing
316 /// with a single thread.
317 const VarDecl *getThreadIDVariable() const override { return nullptr; }
318
319 /// \brief Get the name of the capture helper.
Samuel Antaoee8fb302016-01-06 13:42:12 +0000320 StringRef getHelperName() const override { return HelperName; }
Samuel Antaobed3c462015-10-02 16:14:20 +0000321
322 static bool classof(const CGCapturedStmtInfo *Info) {
323 return CGOpenMPRegionInfo::classof(Info) &&
324 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
325 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000326
327private:
328 StringRef HelperName;
Samuel Antaobed3c462015-10-02 16:14:20 +0000329};
330
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000331static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000332 llvm_unreachable("No codegen for expressions");
333}
334/// \brief API for generation of expressions captured in a innermost OpenMP
335/// region.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000336class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000337public:
338 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
339 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
340 OMPD_unknown,
341 /*HasCancel=*/false),
342 PrivScope(CGF) {
343 // Make sure the globals captured in the provided statement are local by
344 // using the privatization logic. We assume the same variable is not
345 // captured more than once.
346 for (auto &C : CS.captures()) {
347 if (!C.capturesVariable() && !C.capturesVariableByCopy())
348 continue;
349
350 const VarDecl *VD = C.getCapturedVar();
351 if (VD->isLocalVarDeclOrParm())
352 continue;
353
354 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
355 /*RefersToEnclosingVariableOrCapture=*/false,
356 VD->getType().getNonReferenceType(), VK_LValue,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000357 C.getLocation());
Samuel Antaob68e2db2016-03-03 16:20:23 +0000358 PrivScope.addPrivate(VD, [&CGF, &DRE]() -> Address {
359 return CGF.EmitLValue(&DRE).getAddress();
360 });
361 }
362 (void)PrivScope.Privatize();
363 }
364
365 /// \brief Lookup the captured field decl for a variable.
366 const FieldDecl *lookup(const VarDecl *VD) const override {
367 if (auto *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
368 return FD;
369 return nullptr;
370 }
371
372 /// \brief Emit the captured statement body.
373 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
374 llvm_unreachable("No body for expressions");
375 }
376
377 /// \brief Get a variable or parameter for storing global thread id
378 /// inside OpenMP construct.
379 const VarDecl *getThreadIDVariable() const override {
380 llvm_unreachable("No thread id for expressions");
381 }
382
383 /// \brief Get the name of the capture helper.
384 StringRef getHelperName() const override {
385 llvm_unreachable("No helper name for expressions");
386 }
387
388 static bool classof(const CGCapturedStmtInfo *Info) { return false; }
389
390private:
391 /// Private scope to capture global variables.
392 CodeGenFunction::OMPPrivateScope PrivScope;
393};
394
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000395/// \brief RAII for emitting code of OpenMP constructs.
396class InlinedOpenMPRegionRAII {
397 CodeGenFunction &CGF;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000398 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
399 FieldDecl *LambdaThisCaptureField = nullptr;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000400 const CodeGen::CGBlockInfo *BlockInfo = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000401
402public:
403 /// \brief Constructs region for combined constructs.
404 /// \param CodeGen Code generation sequence for combined directives. Includes
405 /// a list of functions used for code generation of implicitly inlined
406 /// regions.
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000407 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000408 OpenMPDirectiveKind Kind, bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000409 : CGF(CGF) {
410 // Start emission for the construct.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000411 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
412 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000413 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
414 LambdaThisCaptureField = CGF.LambdaThisCaptureField;
415 CGF.LambdaThisCaptureField = nullptr;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000416 BlockInfo = CGF.BlockInfo;
417 CGF.BlockInfo = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000418 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000419
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000420 ~InlinedOpenMPRegionRAII() {
421 // Restore original CapturedStmtInfo only if we're done with code emission.
422 auto *OldCSI =
423 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
424 delete CGF.CapturedStmtInfo;
425 CGF.CapturedStmtInfo = OldCSI;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000426 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
427 CGF.LambdaThisCaptureField = LambdaThisCaptureField;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000428 CGF.BlockInfo = BlockInfo;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000429 }
430};
431
Alexey Bataev50b3c952016-02-19 10:38:26 +0000432/// \brief Values for bit flags used in the ident_t to describe the fields.
433/// All enumeric elements are named and described in accordance with the code
434/// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000435enum OpenMPLocationFlags : unsigned {
Alexey Bataev50b3c952016-02-19 10:38:26 +0000436 /// \brief Use trampoline for internal microtask.
437 OMP_IDENT_IMD = 0x01,
438 /// \brief Use c-style ident structure.
439 OMP_IDENT_KMPC = 0x02,
440 /// \brief Atomic reduction option for kmpc_reduce.
441 OMP_ATOMIC_REDUCE = 0x10,
442 /// \brief Explicit 'barrier' directive.
443 OMP_IDENT_BARRIER_EXPL = 0x20,
444 /// \brief Implicit barrier in code.
445 OMP_IDENT_BARRIER_IMPL = 0x40,
446 /// \brief Implicit barrier in 'for' directive.
447 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
448 /// \brief Implicit barrier in 'sections' directive.
449 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
450 /// \brief Implicit barrier in 'single' directive.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000451 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140,
452 /// Call of __kmp_for_static_init for static loop.
453 OMP_IDENT_WORK_LOOP = 0x200,
454 /// Call of __kmp_for_static_init for sections.
455 OMP_IDENT_WORK_SECTIONS = 0x400,
456 /// Call of __kmp_for_static_init for distribute.
457 OMP_IDENT_WORK_DISTRIBUTE = 0x800,
458 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_IDENT_WORK_DISTRIBUTE)
Alexey Bataev50b3c952016-02-19 10:38:26 +0000459};
460
461/// \brief Describes ident structure that describes a source location.
462/// All descriptions are taken from
463/// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
464/// Original structure:
465/// typedef struct ident {
466/// kmp_int32 reserved_1; /**< might be used in Fortran;
467/// see above */
468/// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
469/// KMP_IDENT_KMPC identifies this union
470/// member */
471/// kmp_int32 reserved_2; /**< not really used in Fortran any more;
472/// see above */
473///#if USE_ITT_BUILD
474/// /* but currently used for storing
475/// region-specific ITT */
476/// /* contextual information. */
477///#endif /* USE_ITT_BUILD */
478/// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
479/// C++ */
480/// char const *psource; /**< String describing the source location.
481/// The string is composed of semi-colon separated
482// fields which describe the source file,
483/// the function and a pair of line numbers that
484/// delimit the construct.
485/// */
486/// } ident_t;
487enum IdentFieldIndex {
488 /// \brief might be used in Fortran
489 IdentField_Reserved_1,
490 /// \brief OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
491 IdentField_Flags,
492 /// \brief Not really used in Fortran any more
493 IdentField_Reserved_2,
494 /// \brief Source[4] in Fortran, do not use for C++
495 IdentField_Reserved_3,
496 /// \brief String describing the source location. The string is composed of
497 /// semi-colon separated fields which describe the source file, the function
498 /// and a pair of line numbers that delimit the construct.
499 IdentField_PSource
500};
501
502/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
503/// the enum sched_type in kmp.h).
504enum OpenMPSchedType {
505 /// \brief Lower bound for default (unordered) versions.
506 OMP_sch_lower = 32,
507 OMP_sch_static_chunked = 33,
508 OMP_sch_static = 34,
509 OMP_sch_dynamic_chunked = 35,
510 OMP_sch_guided_chunked = 36,
511 OMP_sch_runtime = 37,
512 OMP_sch_auto = 38,
Alexey Bataev6cff6242016-05-30 13:05:14 +0000513 /// static with chunk adjustment (e.g., simd)
Samuel Antao4c8035b2016-12-12 18:00:20 +0000514 OMP_sch_static_balanced_chunked = 45,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000515 /// \brief Lower bound for 'ordered' versions.
516 OMP_ord_lower = 64,
517 OMP_ord_static_chunked = 65,
518 OMP_ord_static = 66,
519 OMP_ord_dynamic_chunked = 67,
520 OMP_ord_guided_chunked = 68,
521 OMP_ord_runtime = 69,
522 OMP_ord_auto = 70,
523 OMP_sch_default = OMP_sch_static,
Carlo Bertollifc35ad22016-03-07 16:04:49 +0000524 /// \brief dist_schedule types
525 OMP_dist_sch_static_chunked = 91,
526 OMP_dist_sch_static = 92,
Alexey Bataev9ebd7422016-05-10 09:57:36 +0000527 /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
528 /// Set if the monotonic schedule modifier was present.
529 OMP_sch_modifier_monotonic = (1 << 29),
530 /// Set if the nonmonotonic schedule modifier was present.
531 OMP_sch_modifier_nonmonotonic = (1 << 30),
Alexey Bataev50b3c952016-02-19 10:38:26 +0000532};
533
534enum OpenMPRTLFunction {
535 /// \brief Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
536 /// kmpc_micro microtask, ...);
537 OMPRTL__kmpc_fork_call,
538 /// \brief Call to void *__kmpc_threadprivate_cached(ident_t *loc,
539 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
540 OMPRTL__kmpc_threadprivate_cached,
541 /// \brief Call to void __kmpc_threadprivate_register( ident_t *,
542 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
543 OMPRTL__kmpc_threadprivate_register,
544 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
545 OMPRTL__kmpc_global_thread_num,
546 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
547 // kmp_critical_name *crit);
548 OMPRTL__kmpc_critical,
549 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
550 // global_tid, kmp_critical_name *crit, uintptr_t hint);
551 OMPRTL__kmpc_critical_with_hint,
552 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
553 // kmp_critical_name *crit);
554 OMPRTL__kmpc_end_critical,
555 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
556 // global_tid);
557 OMPRTL__kmpc_cancel_barrier,
558 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
559 OMPRTL__kmpc_barrier,
560 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
561 OMPRTL__kmpc_for_static_fini,
562 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
563 // global_tid);
564 OMPRTL__kmpc_serialized_parallel,
565 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
566 // global_tid);
567 OMPRTL__kmpc_end_serialized_parallel,
568 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
569 // kmp_int32 num_threads);
570 OMPRTL__kmpc_push_num_threads,
571 // Call to void __kmpc_flush(ident_t *loc);
572 OMPRTL__kmpc_flush,
573 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
574 OMPRTL__kmpc_master,
575 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
576 OMPRTL__kmpc_end_master,
577 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
578 // int end_part);
579 OMPRTL__kmpc_omp_taskyield,
580 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
581 OMPRTL__kmpc_single,
582 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
583 OMPRTL__kmpc_end_single,
584 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
585 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
586 // kmp_routine_entry_t *task_entry);
587 OMPRTL__kmpc_omp_task_alloc,
588 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
589 // new_task);
590 OMPRTL__kmpc_omp_task,
591 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
592 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
593 // kmp_int32 didit);
594 OMPRTL__kmpc_copyprivate,
595 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
596 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
597 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
598 OMPRTL__kmpc_reduce,
599 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
600 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
601 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
602 // *lck);
603 OMPRTL__kmpc_reduce_nowait,
604 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
605 // kmp_critical_name *lck);
606 OMPRTL__kmpc_end_reduce,
607 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
608 // kmp_critical_name *lck);
609 OMPRTL__kmpc_end_reduce_nowait,
610 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
611 // kmp_task_t * new_task);
612 OMPRTL__kmpc_omp_task_begin_if0,
613 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
614 // kmp_task_t * new_task);
615 OMPRTL__kmpc_omp_task_complete_if0,
616 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
617 OMPRTL__kmpc_ordered,
618 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
619 OMPRTL__kmpc_end_ordered,
620 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
621 // global_tid);
622 OMPRTL__kmpc_omp_taskwait,
623 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
624 OMPRTL__kmpc_taskgroup,
625 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
626 OMPRTL__kmpc_end_taskgroup,
627 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
628 // int proc_bind);
629 OMPRTL__kmpc_push_proc_bind,
630 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
631 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
632 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
633 OMPRTL__kmpc_omp_task_with_deps,
634 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
635 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
636 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
637 OMPRTL__kmpc_omp_wait_deps,
638 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
639 // global_tid, kmp_int32 cncl_kind);
640 OMPRTL__kmpc_cancellationpoint,
641 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
642 // kmp_int32 cncl_kind);
643 OMPRTL__kmpc_cancel,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000644 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
645 // kmp_int32 num_teams, kmp_int32 thread_limit);
646 OMPRTL__kmpc_push_num_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000647 // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
648 // microtask, ...);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000649 OMPRTL__kmpc_fork_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000650 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
651 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
652 // sched, kmp_uint64 grainsize, void *task_dup);
653 OMPRTL__kmpc_taskloop,
Alexey Bataev8b427062016-05-25 12:36:08 +0000654 // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
655 // num_dims, struct kmp_dim *dims);
656 OMPRTL__kmpc_doacross_init,
657 // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
658 OMPRTL__kmpc_doacross_fini,
659 // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
660 // *vec);
661 OMPRTL__kmpc_doacross_post,
662 // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
663 // *vec);
664 OMPRTL__kmpc_doacross_wait,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000665 // Call to void *__kmpc_task_reduction_init(int gtid, int num_data, void
666 // *data);
667 OMPRTL__kmpc_task_reduction_init,
668 // Call to void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
669 // *d);
670 OMPRTL__kmpc_task_reduction_get_th_data,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000671
672 //
673 // Offloading related calls
674 //
George Rokos63bc9d62017-11-21 18:25:12 +0000675 // Call to int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
676 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Alexey Bataev50b3c952016-02-19 10:38:26 +0000677 // *arg_types);
678 OMPRTL__tgt_target,
Alexey Bataeva9f77c62017-12-13 21:04:20 +0000679 // Call to int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
680 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
681 // *arg_types);
682 OMPRTL__tgt_target_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000683 // Call to int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
684 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
685 // *arg_types, int32_t num_teams, int32_t thread_limit);
Samuel Antaob68e2db2016-03-03 16:20:23 +0000686 OMPRTL__tgt_target_teams,
Alexey Bataeva9f77c62017-12-13 21:04:20 +0000687 // Call to int32_t __tgt_target_teams_nowait(int64_t device_id, void
688 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
689 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
690 OMPRTL__tgt_target_teams_nowait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000691 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
692 OMPRTL__tgt_register_lib,
693 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
694 OMPRTL__tgt_unregister_lib,
George Rokos63bc9d62017-11-21 18:25:12 +0000695 // Call to void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
696 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antaodf158d52016-04-27 22:58:19 +0000697 OMPRTL__tgt_target_data_begin,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000698 // Call to void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
699 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
700 // *arg_types);
701 OMPRTL__tgt_target_data_begin_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000702 // Call to void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
703 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antaodf158d52016-04-27 22:58:19 +0000704 OMPRTL__tgt_target_data_end,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000705 // Call to void __tgt_target_data_end_nowait(int64_t device_id, int32_t
706 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
707 // *arg_types);
708 OMPRTL__tgt_target_data_end_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000709 // Call to void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
710 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antao8d2d7302016-05-26 18:30:22 +0000711 OMPRTL__tgt_target_data_update,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000712 // Call to void __tgt_target_data_update_nowait(int64_t device_id, int32_t
713 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
714 // *arg_types);
715 OMPRTL__tgt_target_data_update_nowait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000716};
717
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000718/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
719/// region.
720class CleanupTy final : public EHScopeStack::Cleanup {
721 PrePostActionTy *Action;
722
723public:
724 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
725 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
726 if (!CGF.HaveInsertPoint())
727 return;
728 Action->Exit(CGF);
729 }
730};
731
Hans Wennborg7eb54642015-09-10 17:07:54 +0000732} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000733
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000734void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
735 CodeGenFunction::RunCleanupsScope Scope(CGF);
736 if (PrePostAction) {
737 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
738 Callback(CodeGen, CGF, *PrePostAction);
739 } else {
740 PrePostActionTy Action;
741 Callback(CodeGen, CGF, Action);
742 }
743}
744
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000745/// Check if the combiner is a call to UDR combiner and if it is so return the
746/// UDR decl used for reduction.
747static const OMPDeclareReductionDecl *
748getReductionInit(const Expr *ReductionOp) {
749 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
750 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
751 if (auto *DRE =
752 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
753 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
754 return DRD;
755 return nullptr;
756}
757
758static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
759 const OMPDeclareReductionDecl *DRD,
760 const Expr *InitOp,
761 Address Private, Address Original,
762 QualType Ty) {
763 if (DRD->getInitializer()) {
764 std::pair<llvm::Function *, llvm::Function *> Reduction =
765 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
766 auto *CE = cast<CallExpr>(InitOp);
767 auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
768 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
769 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
770 auto *LHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
771 auto *RHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
772 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
773 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
774 [=]() -> Address { return Private; });
775 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
776 [=]() -> Address { return Original; });
777 (void)PrivateScope.Privatize();
778 RValue Func = RValue::get(Reduction.second);
779 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
780 CGF.EmitIgnoredExpr(InitOp);
781 } else {
782 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
783 auto *GV = new llvm::GlobalVariable(
784 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
785 llvm::GlobalValue::PrivateLinkage, Init, ".init");
786 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
787 RValue InitRVal;
788 switch (CGF.getEvaluationKind(Ty)) {
789 case TEK_Scalar:
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000790 InitRVal = CGF.EmitLoadOfLValue(LV, DRD->getLocation());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000791 break;
792 case TEK_Complex:
793 InitRVal =
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000794 RValue::getComplex(CGF.EmitLoadOfComplex(LV, DRD->getLocation()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000795 break;
796 case TEK_Aggregate:
797 InitRVal = RValue::getAggregate(LV.getAddress());
798 break;
799 }
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000800 OpaqueValueExpr OVE(DRD->getLocation(), Ty, VK_RValue);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000801 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
802 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
803 /*IsInitializer=*/false);
804 }
805}
806
807/// \brief Emit initialization of arrays of complex types.
808/// \param DestAddr Address of the array.
809/// \param Type Type of array.
810/// \param Init Initial expression of array.
811/// \param SrcAddr Address of the original array.
812static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
Alexey Bataeva7b19152017-10-12 20:03:39 +0000813 QualType Type, bool EmitDeclareReductionInit,
814 const Expr *Init,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000815 const OMPDeclareReductionDecl *DRD,
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000816 Address SrcAddr = Address::invalid()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000817 // Perform element-by-element initialization.
818 QualType ElementTy;
819
820 // Drill down to the base element type on both arrays.
821 auto ArrayTy = Type->getAsArrayTypeUnsafe();
822 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
823 DestAddr =
824 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
825 if (DRD)
826 SrcAddr =
827 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
828
829 llvm::Value *SrcBegin = nullptr;
830 if (DRD)
831 SrcBegin = SrcAddr.getPointer();
832 auto DestBegin = DestAddr.getPointer();
833 // Cast from pointer to array type to pointer to single element.
834 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
835 // The basic structure here is a while-do loop.
836 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
837 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
838 auto IsEmpty =
839 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
840 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
841
842 // Enter the loop body, making that address the current address.
843 auto EntryBB = CGF.Builder.GetInsertBlock();
844 CGF.EmitBlock(BodyBB);
845
846 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
847
848 llvm::PHINode *SrcElementPHI = nullptr;
849 Address SrcElementCurrent = Address::invalid();
850 if (DRD) {
851 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
852 "omp.arraycpy.srcElementPast");
853 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
854 SrcElementCurrent =
855 Address(SrcElementPHI,
856 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
857 }
858 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
859 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
860 DestElementPHI->addIncoming(DestBegin, EntryBB);
861 Address DestElementCurrent =
862 Address(DestElementPHI,
863 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
864
865 // Emit copy.
866 {
867 CodeGenFunction::RunCleanupsScope InitScope(CGF);
Alexey Bataeva7b19152017-10-12 20:03:39 +0000868 if (EmitDeclareReductionInit) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000869 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
870 SrcElementCurrent, ElementTy);
871 } else
872 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
873 /*IsInitializer=*/false);
874 }
875
876 if (DRD) {
877 // Shift the address forward by one element.
878 auto SrcElementNext = CGF.Builder.CreateConstGEP1_32(
879 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
880 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
881 }
882
883 // Shift the address forward by one element.
884 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
885 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
886 // Check whether we've reached the end.
887 auto Done =
888 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
889 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
890 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
891
892 // Done.
893 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
894}
895
Alexey Bataev92327c52018-03-26 16:40:55 +0000896static llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy>
897isDeclareTargetDeclaration(const ValueDecl *VD) {
898 for (const auto *D : VD->redecls()) {
899 if (!D->hasAttrs())
900 continue;
901 if (const auto *Attr = D->getAttr<OMPDeclareTargetDeclAttr>())
902 return Attr->getMapType();
903 }
904 return llvm::None;
905}
906
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000907LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000908 return CGF.EmitOMPSharedLValue(E);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000909}
910
911LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
912 const Expr *E) {
913 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
914 return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
915 return LValue();
916}
917
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000918void ReductionCodeGen::emitAggregateInitialization(
919 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
920 const OMPDeclareReductionDecl *DRD) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000921 // Emit VarDecl with copy init for arrays.
922 // Get the address of the original variable captured in current
923 // captured region.
924 auto *PrivateVD =
925 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva7b19152017-10-12 20:03:39 +0000926 bool EmitDeclareReductionInit =
927 DRD && (DRD->getInitializer() || !PrivateVD->hasInit());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000928 EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
Alexey Bataeva7b19152017-10-12 20:03:39 +0000929 EmitDeclareReductionInit,
930 EmitDeclareReductionInit ? ClausesData[N].ReductionOp
931 : PrivateVD->getInit(),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000932 DRD, SharedLVal.getAddress());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000933}
934
935ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
936 ArrayRef<const Expr *> Privates,
937 ArrayRef<const Expr *> ReductionOps) {
938 ClausesData.reserve(Shareds.size());
939 SharedAddresses.reserve(Shareds.size());
940 Sizes.reserve(Shareds.size());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000941 BaseDecls.reserve(Shareds.size());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000942 auto IPriv = Privates.begin();
943 auto IRed = ReductionOps.begin();
944 for (const auto *Ref : Shareds) {
945 ClausesData.emplace_back(Ref, *IPriv, *IRed);
946 std::advance(IPriv, 1);
947 std::advance(IRed, 1);
948 }
949}
950
951void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
952 assert(SharedAddresses.size() == N &&
953 "Number of generated lvalues must be exactly N.");
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000954 LValue First = emitSharedLValue(CGF, ClausesData[N].Ref);
955 LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Ref);
956 SharedAddresses.emplace_back(First, Second);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000957}
958
959void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
960 auto *PrivateVD =
961 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
962 QualType PrivateType = PrivateVD->getType();
963 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000964 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000965 Sizes.emplace_back(
966 CGF.getTypeSize(
967 SharedAddresses[N].first.getType().getNonReferenceType()),
968 nullptr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000969 return;
970 }
971 llvm::Value *Size;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000972 llvm::Value *SizeInChars;
973 llvm::Type *ElemType =
974 cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
975 ->getElementType();
976 auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000977 if (AsArraySection) {
978 Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
979 SharedAddresses[N].first.getPointer());
980 Size = CGF.Builder.CreateNUWAdd(
981 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000982 SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000983 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000984 SizeInChars = CGF.getTypeSize(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000985 SharedAddresses[N].first.getType().getNonReferenceType());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000986 Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000987 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000988 Sizes.emplace_back(SizeInChars, Size);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000989 CodeGenFunction::OpaqueValueMapping OpaqueMap(
990 CGF,
991 cast<OpaqueValueExpr>(
992 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
993 RValue::get(Size));
994 CGF.EmitVariablyModifiedType(PrivateType);
995}
996
997void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
998 llvm::Value *Size) {
999 auto *PrivateVD =
1000 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1001 QualType PrivateType = PrivateVD->getType();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001002 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001003 assert(!Size && !Sizes[N].second &&
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001004 "Size should be nullptr for non-variably modified reduction "
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001005 "items.");
1006 return;
1007 }
1008 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1009 CGF,
1010 cast<OpaqueValueExpr>(
1011 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
1012 RValue::get(Size));
1013 CGF.EmitVariablyModifiedType(PrivateType);
1014}
1015
1016void ReductionCodeGen::emitInitialization(
1017 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
1018 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
1019 assert(SharedAddresses.size() > N && "No variable was generated");
1020 auto *PrivateVD =
1021 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1022 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
1023 QualType PrivateType = PrivateVD->getType();
1024 PrivateAddr = CGF.Builder.CreateElementBitCast(
1025 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1026 QualType SharedType = SharedAddresses[N].first.getType();
1027 SharedLVal = CGF.MakeAddrLValue(
1028 CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
1029 CGF.ConvertTypeForMem(SharedType)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001030 SharedType, SharedAddresses[N].first.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001031 CGF.CGM.getTBAAInfoForSubobject(SharedAddresses[N].first, SharedType));
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001032 if (CGF.getContext().getAsArrayType(PrivateVD->getType())) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001033 emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001034 } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
1035 emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
1036 PrivateAddr, SharedLVal.getAddress(),
1037 SharedLVal.getType());
1038 } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
1039 !CGF.isTrivialInitializer(PrivateVD->getInit())) {
1040 CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
1041 PrivateVD->getType().getQualifiers(),
1042 /*IsInitializer=*/false);
1043 }
1044}
1045
1046bool ReductionCodeGen::needCleanups(unsigned N) {
1047 auto *PrivateVD =
1048 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1049 QualType PrivateType = PrivateVD->getType();
1050 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1051 return DTorKind != QualType::DK_none;
1052}
1053
1054void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
1055 Address PrivateAddr) {
1056 auto *PrivateVD =
1057 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1058 QualType PrivateType = PrivateVD->getType();
1059 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1060 if (needCleanups(N)) {
1061 PrivateAddr = CGF.Builder.CreateElementBitCast(
1062 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1063 CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
1064 }
1065}
1066
1067static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1068 LValue BaseLV) {
1069 BaseTy = BaseTy.getNonReferenceType();
1070 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1071 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1072 if (auto *PtrTy = BaseTy->getAs<PointerType>())
1073 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
1074 else {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00001075 LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(), BaseTy);
1076 BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001077 }
1078 BaseTy = BaseTy->getPointeeType();
1079 }
1080 return CGF.MakeAddrLValue(
1081 CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
1082 CGF.ConvertTypeForMem(ElTy)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001083 BaseLV.getType(), BaseLV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001084 CGF.CGM.getTBAAInfoForSubobject(BaseLV, BaseLV.getType()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001085}
1086
1087static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1088 llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
1089 llvm::Value *Addr) {
1090 Address Tmp = Address::invalid();
1091 Address TopTmp = Address::invalid();
1092 Address MostTopTmp = Address::invalid();
1093 BaseTy = BaseTy.getNonReferenceType();
1094 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1095 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1096 Tmp = CGF.CreateMemTemp(BaseTy);
1097 if (TopTmp.isValid())
1098 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
1099 else
1100 MostTopTmp = Tmp;
1101 TopTmp = Tmp;
1102 BaseTy = BaseTy->getPointeeType();
1103 }
1104 llvm::Type *Ty = BaseLVType;
1105 if (Tmp.isValid())
1106 Ty = Tmp.getElementType();
1107 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
1108 if (Tmp.isValid()) {
1109 CGF.Builder.CreateStore(Addr, Tmp);
1110 return MostTopTmp;
1111 }
1112 return Address(Addr, BaseLVAlignment);
1113}
1114
Alexey Bataev1c44e152018-03-06 18:59:43 +00001115static const VarDecl *getBaseDecl(const Expr *Ref, const DeclRefExpr *&DE) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001116 const VarDecl *OrigVD = nullptr;
Alexey Bataev1c44e152018-03-06 18:59:43 +00001117 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(Ref)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001118 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
1119 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
1120 Base = TempOASE->getBase()->IgnoreParenImpCasts();
1121 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1122 Base = TempASE->getBase()->IgnoreParenImpCasts();
1123 DE = cast<DeclRefExpr>(Base);
1124 OrigVD = cast<VarDecl>(DE->getDecl());
Alexey Bataev1c44e152018-03-06 18:59:43 +00001125 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(Ref)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001126 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
1127 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1128 Base = TempASE->getBase()->IgnoreParenImpCasts();
1129 DE = cast<DeclRefExpr>(Base);
1130 OrigVD = cast<VarDecl>(DE->getDecl());
1131 }
Alexey Bataev1c44e152018-03-06 18:59:43 +00001132 return OrigVD;
1133}
1134
1135Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
1136 Address PrivateAddr) {
1137 const DeclRefExpr *DE;
1138 if (const VarDecl *OrigVD = ::getBaseDecl(ClausesData[N].Ref, DE)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001139 BaseDecls.emplace_back(OrigVD);
1140 auto OriginalBaseLValue = CGF.EmitLValue(DE);
1141 LValue BaseLValue =
1142 loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1143 OriginalBaseLValue);
1144 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1145 BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001146 llvm::Value *PrivatePointer =
1147 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1148 PrivateAddr.getPointer(),
1149 SharedAddresses[N].first.getAddress().getType());
1150 llvm::Value *Ptr = CGF.Builder.CreateGEP(PrivatePointer, Adjustment);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001151 return castToBase(CGF, OrigVD->getType(),
1152 SharedAddresses[N].first.getType(),
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001153 OriginalBaseLValue.getAddress().getType(),
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001154 OriginalBaseLValue.getAlignment(), Ptr);
1155 }
1156 BaseDecls.emplace_back(
1157 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1158 return PrivateAddr;
1159}
1160
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001161bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
1162 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
1163 return DRD && DRD->getInitializer();
1164}
1165
Alexey Bataev18095712014-10-10 12:19:54 +00001166LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00001167 return CGF.EmitLoadOfPointerLValue(
1168 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1169 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +00001170}
1171
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001172void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001173 if (!CGF.HaveInsertPoint())
1174 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001175 // 1.2.2 OpenMP Language Terminology
1176 // Structured block - An executable statement with a single entry at the
1177 // top and a single exit at the bottom.
1178 // The point of exit cannot be a branch out of the structured block.
1179 // longjmp() and throw() must not violate the entry/exit criteria.
1180 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001181 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001182 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001183}
1184
Alexey Bataev62b63b12015-03-10 07:28:44 +00001185LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1186 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001187 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1188 getThreadIDVariable()->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00001189 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001190}
1191
Alexey Bataev9959db52014-05-06 10:08:46 +00001192CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001193 : CGM(CGM), OffloadEntriesInfoManager(CGM) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001194 IdentTy = llvm::StructType::create(
1195 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
1196 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Serge Guelton1d993272017-05-09 19:31:30 +00001197 CGM.Int8PtrTy /* psource */);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001198 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +00001199
1200 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +00001201}
1202
Alexey Bataev91797552015-03-18 04:13:55 +00001203void CGOpenMPRuntime::clear() {
1204 InternalVars.clear();
1205}
1206
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001207static llvm::Function *
1208emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1209 const Expr *CombinerInitializer, const VarDecl *In,
1210 const VarDecl *Out, bool IsCombiner) {
1211 // void .omp_combiner.(Ty *in, Ty *out);
1212 auto &C = CGM.getContext();
1213 QualType PtrTy = C.getPointerType(Ty).withRestrict();
1214 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001215 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001216 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001217 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001218 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001219 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001220 Args.push_back(&OmpInParm);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001221 auto &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001222 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001223 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1224 auto *Fn = llvm::Function::Create(
1225 FnTy, llvm::GlobalValue::InternalLinkage,
1226 IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001227 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001228 Fn->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001229 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001230 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001231 CodeGenFunction CGF(CGM);
1232 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1233 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001234 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, In->getLocation(),
1235 Out->getLocation());
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001236 CodeGenFunction::OMPPrivateScope Scope(CGF);
1237 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
1238 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
1239 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1240 .getAddress();
1241 });
1242 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
1243 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
1244 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1245 .getAddress();
1246 });
1247 (void)Scope.Privatize();
Alexey Bataev070f43a2017-09-06 14:49:58 +00001248 if (!IsCombiner && Out->hasInit() &&
1249 !CGF.isTrivialInitializer(Out->getInit())) {
1250 CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
1251 Out->getType().getQualifiers(),
1252 /*IsInitializer=*/true);
1253 }
1254 if (CombinerInitializer)
1255 CGF.EmitIgnoredExpr(CombinerInitializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001256 Scope.ForceCleanup();
1257 CGF.FinishFunction();
1258 return Fn;
1259}
1260
1261void CGOpenMPRuntime::emitUserDefinedReduction(
1262 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1263 if (UDRMap.count(D) > 0)
1264 return;
1265 auto &C = CGM.getContext();
1266 if (!In || !Out) {
1267 In = &C.Idents.get("omp_in");
1268 Out = &C.Idents.get("omp_out");
1269 }
1270 llvm::Function *Combiner = emitCombinerOrInitializer(
1271 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
1272 cast<VarDecl>(D->lookup(Out).front()),
1273 /*IsCombiner=*/true);
1274 llvm::Function *Initializer = nullptr;
1275 if (auto *Init = D->getInitializer()) {
1276 if (!Priv || !Orig) {
1277 Priv = &C.Idents.get("omp_priv");
1278 Orig = &C.Idents.get("omp_orig");
1279 }
1280 Initializer = emitCombinerOrInitializer(
Alexey Bataev070f43a2017-09-06 14:49:58 +00001281 CGM, D->getType(),
1282 D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init
1283 : nullptr,
1284 cast<VarDecl>(D->lookup(Orig).front()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001285 cast<VarDecl>(D->lookup(Priv).front()),
1286 /*IsCombiner=*/false);
1287 }
1288 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
1289 if (CGF) {
1290 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1291 Decls.second.push_back(D);
1292 }
1293}
1294
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001295std::pair<llvm::Function *, llvm::Function *>
1296CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1297 auto I = UDRMap.find(D);
1298 if (I != UDRMap.end())
1299 return I->second;
1300 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1301 return UDRMap.lookup(D);
1302}
1303
John McCall7f416cc2015-09-08 08:05:57 +00001304// Layout information for ident_t.
1305static CharUnits getIdentAlign(CodeGenModule &CGM) {
1306 return CGM.getPointerAlign();
1307}
1308static CharUnits getIdentSize(CodeGenModule &CGM) {
1309 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
1310 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
1311}
Alexey Bataev50b3c952016-02-19 10:38:26 +00001312static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
John McCall7f416cc2015-09-08 08:05:57 +00001313 // All the fields except the last are i32, so this works beautifully.
1314 return unsigned(Field) * CharUnits::fromQuantity(4);
1315}
1316static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001317 IdentFieldIndex Field,
John McCall7f416cc2015-09-08 08:05:57 +00001318 const llvm::Twine &Name = "") {
1319 auto Offset = getOffsetOfIdentField(Field);
1320 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
1321}
1322
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001323static llvm::Value *emitParallelOrTeamsOutlinedFunction(
1324 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1325 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1326 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001327 assert(ThreadIDVar->getType()->isPointerType() &&
1328 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +00001329 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00001330 bool HasCancel = false;
1331 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
1332 HasCancel = OPD->hasCancel();
1333 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
1334 HasCancel = OPSD->hasCancel();
1335 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
1336 HasCancel = OPFD->hasCancel();
Alexey Bataev2139ed62017-11-16 18:20:21 +00001337 else if (auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D))
1338 HasCancel = OPFD->hasCancel();
Alexey Bataev10a54312017-11-27 16:54:08 +00001339 else if (auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&D))
1340 HasCancel = OPFD->hasCancel();
1341 else if (auto *OPFD = dyn_cast<OMPTeamsDistributeParallelForDirective>(&D))
1342 HasCancel = OPFD->hasCancel();
1343 else if (auto *OPFD =
1344 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D))
1345 HasCancel = OPFD->hasCancel();
Alexey Bataev25e5b442015-09-15 12:52:43 +00001346 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001347 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +00001348 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001349 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +00001350}
1351
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001352llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
1353 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1354 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1355 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1356 return emitParallelOrTeamsOutlinedFunction(
1357 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1358}
1359
1360llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1361 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1362 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1363 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1364 return emitParallelOrTeamsOutlinedFunction(
1365 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1366}
1367
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001368llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
1369 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +00001370 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1371 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1372 bool Tied, unsigned &NumberOfParts) {
1373 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1374 PrePostActionTy &) {
1375 auto *ThreadID = getThreadID(CGF, D.getLocStart());
1376 auto *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
1377 llvm::Value *TaskArgs[] = {
1378 UpLoc, ThreadID,
1379 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1380 TaskTVar->getType()->castAs<PointerType>())
1381 .getPointer()};
1382 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1383 };
1384 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1385 UntiedCodeGen);
1386 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001387 assert(!ThreadIDVar->getType()->isPointerType() &&
1388 "thread id variable must be of type kmp_int32 for tasks");
Alexey Bataev475a7442018-01-12 19:39:11 +00001389 const OpenMPDirectiveKind Region =
1390 isOpenMPTaskLoopDirective(D.getDirectiveKind()) ? OMPD_taskloop
1391 : OMPD_task;
1392 auto *CS = D.getCapturedStmt(Region);
Alexey Bataev7292c292016-04-25 12:22:29 +00001393 auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001394 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +00001395 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1396 InnermostKind,
1397 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +00001398 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev48591dd2016-04-20 04:01:36 +00001399 auto *Res = CGF.GenerateCapturedStmtFunction(*CS);
1400 if (!Tied)
1401 NumberOfParts = Action.getNumberOfParts();
1402 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001403}
1404
Alexey Bataev50b3c952016-02-19 10:38:26 +00001405Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +00001406 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +00001407 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +00001408 if (!Entry) {
1409 if (!DefaultOpenMPPSource) {
1410 // Initialize default location for psource field of ident_t structure of
1411 // all ident_t objects. Format is ";file;function;line;column;;".
1412 // Taken from
1413 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1414 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +00001415 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001416 DefaultOpenMPPSource =
1417 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1418 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001419
John McCall23c9dc62016-11-28 22:18:27 +00001420 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001421 auto fields = builder.beginStruct(IdentTy);
1422 fields.addInt(CGM.Int32Ty, 0);
1423 fields.addInt(CGM.Int32Ty, Flags);
1424 fields.addInt(CGM.Int32Ty, 0);
1425 fields.addInt(CGM.Int32Ty, 0);
1426 fields.add(DefaultOpenMPPSource);
1427 auto DefaultOpenMPLocation =
1428 fields.finishAndCreateGlobal("", Align, /*isConstant*/ true,
1429 llvm::GlobalValue::PrivateLinkage);
1430 DefaultOpenMPLocation->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1431
John McCall7f416cc2015-09-08 08:05:57 +00001432 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +00001433 }
John McCall7f416cc2015-09-08 08:05:57 +00001434 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +00001435}
1436
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001437llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1438 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001439 unsigned Flags) {
1440 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +00001441 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001442 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +00001443 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +00001444 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001445
1446 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1447
John McCall7f416cc2015-09-08 08:05:57 +00001448 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001449 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1450 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +00001451 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
1452
Alexander Musmanc6388682014-12-15 07:07:06 +00001453 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1454 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +00001455 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +00001456 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +00001457 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
1458 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +00001459 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +00001460 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001461 LocValue = AI;
1462
1463 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1464 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001465 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +00001466 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +00001467 }
1468
1469 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +00001470 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +00001471
Alexey Bataevf002aca2014-05-30 05:48:40 +00001472 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
1473 if (OMPDebugLoc == nullptr) {
1474 SmallString<128> Buffer2;
1475 llvm::raw_svector_ostream OS2(Buffer2);
1476 // Build debug location
1477 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1478 OS2 << ";" << PLoc.getFilename() << ";";
1479 if (const FunctionDecl *FD =
1480 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
1481 OS2 << FD->getQualifiedNameAsString();
1482 }
1483 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1484 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1485 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +00001486 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001487 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +00001488 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
1489
John McCall7f416cc2015-09-08 08:05:57 +00001490 // Our callers always pass this to a runtime function, so for
1491 // convenience, go ahead and return a naked pointer.
1492 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001493}
1494
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001495llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1496 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001497 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1498
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001499 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001500 // Check whether we've already cached a load of the thread id in this
1501 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001502 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001503 if (I != OpenMPLocThreadIDMap.end()) {
1504 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001505 if (ThreadID != nullptr)
1506 return ThreadID;
1507 }
Alexey Bataevaee18552017-08-16 14:01:00 +00001508 // If exceptions are enabled, do not use parameter to avoid possible crash.
Alexey Bataev5d2c9a42017-11-02 18:55:05 +00001509 if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions ||
1510 !CGF.getLangOpts().CXXExceptions ||
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001511 CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
Alexey Bataevaee18552017-08-16 14:01:00 +00001512 if (auto *OMPRegionInfo =
1513 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1514 if (OMPRegionInfo->getThreadIDVariable()) {
1515 // Check if this an outlined function with thread id passed as argument.
1516 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev1e491372018-01-23 18:44:14 +00001517 ThreadID = CGF.EmitLoadOfScalar(LVal, Loc);
Alexey Bataevaee18552017-08-16 14:01:00 +00001518 // If value loaded in entry block, cache it and use it everywhere in
1519 // function.
1520 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1521 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1522 Elem.second.ThreadID = ThreadID;
1523 }
1524 return ThreadID;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001525 }
Alexey Bataevd6c57552014-07-25 07:55:17 +00001526 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001527 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001528
1529 // This is not an outlined function region - need to call __kmpc_int32
1530 // kmpc_global_thread_num(ident_t *loc).
1531 // Generate thread id value and cache this value for use across the
1532 // function.
1533 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1534 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001535 auto *Call = CGF.Builder.CreateCall(
1536 createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1537 emitUpdateLocation(CGF, Loc));
1538 Call->setCallingConv(CGF.getRuntimeCC());
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001539 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001540 Elem.second.ThreadID = Call;
1541 return Call;
Alexey Bataev9959db52014-05-06 10:08:46 +00001542}
1543
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001544void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001545 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001546 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1547 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001548 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1549 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
1550 UDRMap.erase(D);
1551 }
1552 FunctionUDRMap.erase(CGF.CurFn);
1553 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001554}
1555
1556llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001557 if (!IdentTy) {
1558 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001559 return llvm::PointerType::getUnqual(IdentTy);
1560}
1561
1562llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001563 if (!Kmpc_MicroTy) {
1564 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1565 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1566 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1567 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1568 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001569 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1570}
1571
1572llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001573CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001574 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001575 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001576 case OMPRTL__kmpc_fork_call: {
1577 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1578 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001579 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1580 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001581 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001582 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001583 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1584 break;
1585 }
1586 case OMPRTL__kmpc_global_thread_num: {
1587 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001588 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001589 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001590 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001591 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1592 break;
1593 }
Alexey Bataev97720002014-11-11 04:05:39 +00001594 case OMPRTL__kmpc_threadprivate_cached: {
1595 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1596 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1597 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1598 CGM.VoidPtrTy, CGM.SizeTy,
1599 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1600 llvm::FunctionType *FnTy =
1601 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1602 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1603 break;
1604 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001605 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001606 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1607 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001608 llvm::Type *TypeParams[] = {
1609 getIdentTyPointerTy(), CGM.Int32Ty,
1610 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1611 llvm::FunctionType *FnTy =
1612 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1613 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1614 break;
1615 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001616 case OMPRTL__kmpc_critical_with_hint: {
1617 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1618 // kmp_critical_name *crit, uintptr_t hint);
1619 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1620 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1621 CGM.IntPtrTy};
1622 llvm::FunctionType *FnTy =
1623 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1624 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1625 break;
1626 }
Alexey Bataev97720002014-11-11 04:05:39 +00001627 case OMPRTL__kmpc_threadprivate_register: {
1628 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1629 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1630 // typedef void *(*kmpc_ctor)(void *);
1631 auto KmpcCtorTy =
1632 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1633 /*isVarArg*/ false)->getPointerTo();
1634 // typedef void *(*kmpc_cctor)(void *, void *);
1635 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1636 auto KmpcCopyCtorTy =
1637 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1638 /*isVarArg*/ false)->getPointerTo();
1639 // typedef void (*kmpc_dtor)(void *);
1640 auto KmpcDtorTy =
1641 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1642 ->getPointerTo();
1643 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1644 KmpcCopyCtorTy, KmpcDtorTy};
1645 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1646 /*isVarArg*/ false);
1647 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1648 break;
1649 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001650 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001651 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1652 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001653 llvm::Type *TypeParams[] = {
1654 getIdentTyPointerTy(), CGM.Int32Ty,
1655 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1656 llvm::FunctionType *FnTy =
1657 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1658 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1659 break;
1660 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001661 case OMPRTL__kmpc_cancel_barrier: {
1662 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1663 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001664 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1665 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001666 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1667 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001668 break;
1669 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001670 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001671 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001672 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1673 llvm::FunctionType *FnTy =
1674 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1675 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1676 break;
1677 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001678 case OMPRTL__kmpc_for_static_fini: {
1679 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1680 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1681 llvm::FunctionType *FnTy =
1682 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1683 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1684 break;
1685 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001686 case OMPRTL__kmpc_push_num_threads: {
1687 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1688 // kmp_int32 num_threads)
1689 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1690 CGM.Int32Ty};
1691 llvm::FunctionType *FnTy =
1692 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1693 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1694 break;
1695 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001696 case OMPRTL__kmpc_serialized_parallel: {
1697 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1698 // global_tid);
1699 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1700 llvm::FunctionType *FnTy =
1701 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1702 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1703 break;
1704 }
1705 case OMPRTL__kmpc_end_serialized_parallel: {
1706 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1707 // global_tid);
1708 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1709 llvm::FunctionType *FnTy =
1710 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1711 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1712 break;
1713 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001714 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001715 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001716 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1717 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001718 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001719 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1720 break;
1721 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001722 case OMPRTL__kmpc_master: {
1723 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1724 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1725 llvm::FunctionType *FnTy =
1726 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1727 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1728 break;
1729 }
1730 case OMPRTL__kmpc_end_master: {
1731 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1732 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1733 llvm::FunctionType *FnTy =
1734 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1735 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1736 break;
1737 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001738 case OMPRTL__kmpc_omp_taskyield: {
1739 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1740 // int end_part);
1741 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1742 llvm::FunctionType *FnTy =
1743 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1744 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1745 break;
1746 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001747 case OMPRTL__kmpc_single: {
1748 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1749 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1750 llvm::FunctionType *FnTy =
1751 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1752 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1753 break;
1754 }
1755 case OMPRTL__kmpc_end_single: {
1756 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1757 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1758 llvm::FunctionType *FnTy =
1759 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1760 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1761 break;
1762 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001763 case OMPRTL__kmpc_omp_task_alloc: {
1764 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1765 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1766 // kmp_routine_entry_t *task_entry);
1767 assert(KmpRoutineEntryPtrTy != nullptr &&
1768 "Type kmp_routine_entry_t must be created.");
1769 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1770 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1771 // Return void * and then cast to particular kmp_task_t type.
1772 llvm::FunctionType *FnTy =
1773 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1774 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1775 break;
1776 }
1777 case OMPRTL__kmpc_omp_task: {
1778 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1779 // *new_task);
1780 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1781 CGM.VoidPtrTy};
1782 llvm::FunctionType *FnTy =
1783 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1784 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1785 break;
1786 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001787 case OMPRTL__kmpc_copyprivate: {
1788 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001789 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001790 // kmp_int32 didit);
1791 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1792 auto *CpyFnTy =
1793 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001794 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001795 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1796 CGM.Int32Ty};
1797 llvm::FunctionType *FnTy =
1798 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1799 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1800 break;
1801 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001802 case OMPRTL__kmpc_reduce: {
1803 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1804 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1805 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1806 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1807 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1808 /*isVarArg=*/false);
1809 llvm::Type *TypeParams[] = {
1810 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1811 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1812 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1813 llvm::FunctionType *FnTy =
1814 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1815 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1816 break;
1817 }
1818 case OMPRTL__kmpc_reduce_nowait: {
1819 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1820 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1821 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1822 // *lck);
1823 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1824 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1825 /*isVarArg=*/false);
1826 llvm::Type *TypeParams[] = {
1827 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1828 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1829 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1830 llvm::FunctionType *FnTy =
1831 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1832 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1833 break;
1834 }
1835 case OMPRTL__kmpc_end_reduce: {
1836 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1837 // kmp_critical_name *lck);
1838 llvm::Type *TypeParams[] = {
1839 getIdentTyPointerTy(), CGM.Int32Ty,
1840 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1841 llvm::FunctionType *FnTy =
1842 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1843 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1844 break;
1845 }
1846 case OMPRTL__kmpc_end_reduce_nowait: {
1847 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1848 // kmp_critical_name *lck);
1849 llvm::Type *TypeParams[] = {
1850 getIdentTyPointerTy(), CGM.Int32Ty,
1851 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1852 llvm::FunctionType *FnTy =
1853 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1854 RTLFn =
1855 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1856 break;
1857 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001858 case OMPRTL__kmpc_omp_task_begin_if0: {
1859 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1860 // *new_task);
1861 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1862 CGM.VoidPtrTy};
1863 llvm::FunctionType *FnTy =
1864 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1865 RTLFn =
1866 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1867 break;
1868 }
1869 case OMPRTL__kmpc_omp_task_complete_if0: {
1870 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1871 // *new_task);
1872 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1873 CGM.VoidPtrTy};
1874 llvm::FunctionType *FnTy =
1875 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1876 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1877 /*Name=*/"__kmpc_omp_task_complete_if0");
1878 break;
1879 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001880 case OMPRTL__kmpc_ordered: {
1881 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1882 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1883 llvm::FunctionType *FnTy =
1884 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1885 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1886 break;
1887 }
1888 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001889 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001890 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1891 llvm::FunctionType *FnTy =
1892 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1893 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1894 break;
1895 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001896 case OMPRTL__kmpc_omp_taskwait: {
1897 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1898 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1899 llvm::FunctionType *FnTy =
1900 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1901 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1902 break;
1903 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001904 case OMPRTL__kmpc_taskgroup: {
1905 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1906 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1907 llvm::FunctionType *FnTy =
1908 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1909 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1910 break;
1911 }
1912 case OMPRTL__kmpc_end_taskgroup: {
1913 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1914 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1915 llvm::FunctionType *FnTy =
1916 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1917 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1918 break;
1919 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001920 case OMPRTL__kmpc_push_proc_bind: {
1921 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1922 // int proc_bind)
1923 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1924 llvm::FunctionType *FnTy =
1925 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1926 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1927 break;
1928 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001929 case OMPRTL__kmpc_omp_task_with_deps: {
1930 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1931 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1932 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1933 llvm::Type *TypeParams[] = {
1934 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1935 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1936 llvm::FunctionType *FnTy =
1937 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1938 RTLFn =
1939 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1940 break;
1941 }
1942 case OMPRTL__kmpc_omp_wait_deps: {
1943 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1944 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1945 // kmp_depend_info_t *noalias_dep_list);
1946 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1947 CGM.Int32Ty, CGM.VoidPtrTy,
1948 CGM.Int32Ty, CGM.VoidPtrTy};
1949 llvm::FunctionType *FnTy =
1950 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1951 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1952 break;
1953 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001954 case OMPRTL__kmpc_cancellationpoint: {
1955 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1956 // global_tid, kmp_int32 cncl_kind)
1957 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1958 llvm::FunctionType *FnTy =
1959 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1960 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1961 break;
1962 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001963 case OMPRTL__kmpc_cancel: {
1964 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1965 // kmp_int32 cncl_kind)
1966 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1967 llvm::FunctionType *FnTy =
1968 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1969 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1970 break;
1971 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001972 case OMPRTL__kmpc_push_num_teams: {
1973 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1974 // kmp_int32 num_teams, kmp_int32 num_threads)
1975 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1976 CGM.Int32Ty};
1977 llvm::FunctionType *FnTy =
1978 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1979 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1980 break;
1981 }
1982 case OMPRTL__kmpc_fork_teams: {
1983 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1984 // microtask, ...);
1985 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1986 getKmpc_MicroPointerTy()};
1987 llvm::FunctionType *FnTy =
1988 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1989 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1990 break;
1991 }
Alexey Bataev7292c292016-04-25 12:22:29 +00001992 case OMPRTL__kmpc_taskloop: {
1993 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
1994 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
1995 // sched, kmp_uint64 grainsize, void *task_dup);
1996 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1997 CGM.IntTy,
1998 CGM.VoidPtrTy,
1999 CGM.IntTy,
2000 CGM.Int64Ty->getPointerTo(),
2001 CGM.Int64Ty->getPointerTo(),
2002 CGM.Int64Ty,
2003 CGM.IntTy,
2004 CGM.IntTy,
2005 CGM.Int64Ty,
2006 CGM.VoidPtrTy};
2007 llvm::FunctionType *FnTy =
2008 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2009 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
2010 break;
2011 }
Alexey Bataev8b427062016-05-25 12:36:08 +00002012 case OMPRTL__kmpc_doacross_init: {
2013 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
2014 // num_dims, struct kmp_dim *dims);
2015 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2016 CGM.Int32Ty,
2017 CGM.Int32Ty,
2018 CGM.VoidPtrTy};
2019 llvm::FunctionType *FnTy =
2020 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2021 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
2022 break;
2023 }
2024 case OMPRTL__kmpc_doacross_fini: {
2025 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
2026 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
2027 llvm::FunctionType *FnTy =
2028 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2029 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
2030 break;
2031 }
2032 case OMPRTL__kmpc_doacross_post: {
2033 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
2034 // *vec);
2035 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2036 CGM.Int64Ty->getPointerTo()};
2037 llvm::FunctionType *FnTy =
2038 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2039 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
2040 break;
2041 }
2042 case OMPRTL__kmpc_doacross_wait: {
2043 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
2044 // *vec);
2045 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2046 CGM.Int64Ty->getPointerTo()};
2047 llvm::FunctionType *FnTy =
2048 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2049 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
2050 break;
2051 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002052 case OMPRTL__kmpc_task_reduction_init: {
2053 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
2054 // *data);
2055 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
2056 llvm::FunctionType *FnTy =
2057 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2058 RTLFn =
2059 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
2060 break;
2061 }
2062 case OMPRTL__kmpc_task_reduction_get_th_data: {
2063 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
2064 // *d);
2065 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
2066 llvm::FunctionType *FnTy =
2067 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2068 RTLFn = CGM.CreateRuntimeFunction(
2069 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2070 break;
2071 }
Samuel Antaobed3c462015-10-02 16:14:20 +00002072 case OMPRTL__tgt_target: {
George Rokos63bc9d62017-11-21 18:25:12 +00002073 // Build int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
2074 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Samuel Antaobed3c462015-10-02 16:14:20 +00002075 // *arg_types);
George Rokos63bc9d62017-11-21 18:25:12 +00002076 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaobed3c462015-10-02 16:14:20 +00002077 CGM.VoidPtrTy,
2078 CGM.Int32Ty,
2079 CGM.VoidPtrPtrTy,
2080 CGM.VoidPtrPtrTy,
2081 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002082 CGM.Int64Ty->getPointerTo()};
Samuel Antaobed3c462015-10-02 16:14:20 +00002083 llvm::FunctionType *FnTy =
2084 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2085 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2086 break;
2087 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002088 case OMPRTL__tgt_target_nowait: {
2089 // Build int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
2090 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2091 // int64_t *arg_types);
2092 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2093 CGM.VoidPtrTy,
2094 CGM.Int32Ty,
2095 CGM.VoidPtrPtrTy,
2096 CGM.VoidPtrPtrTy,
2097 CGM.SizeTy->getPointerTo(),
2098 CGM.Int64Ty->getPointerTo()};
2099 llvm::FunctionType *FnTy =
2100 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2101 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_nowait");
2102 break;
2103 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00002104 case OMPRTL__tgt_target_teams: {
George Rokos63bc9d62017-11-21 18:25:12 +00002105 // Build int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002106 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
George Rokos63bc9d62017-11-21 18:25:12 +00002107 // int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2108 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002109 CGM.VoidPtrTy,
2110 CGM.Int32Ty,
2111 CGM.VoidPtrPtrTy,
2112 CGM.VoidPtrPtrTy,
2113 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002114 CGM.Int64Ty->getPointerTo(),
Samuel Antaob68e2db2016-03-03 16:20:23 +00002115 CGM.Int32Ty,
2116 CGM.Int32Ty};
2117 llvm::FunctionType *FnTy =
2118 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2119 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2120 break;
2121 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002122 case OMPRTL__tgt_target_teams_nowait: {
2123 // Build int32_t __tgt_target_teams_nowait(int64_t device_id, void
2124 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
2125 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2126 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2127 CGM.VoidPtrTy,
2128 CGM.Int32Ty,
2129 CGM.VoidPtrPtrTy,
2130 CGM.VoidPtrPtrTy,
2131 CGM.SizeTy->getPointerTo(),
2132 CGM.Int64Ty->getPointerTo(),
2133 CGM.Int32Ty,
2134 CGM.Int32Ty};
2135 llvm::FunctionType *FnTy =
2136 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2137 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams_nowait");
2138 break;
2139 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002140 case OMPRTL__tgt_register_lib: {
2141 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2142 QualType ParamTy =
2143 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2144 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2145 llvm::FunctionType *FnTy =
2146 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2147 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2148 break;
2149 }
2150 case OMPRTL__tgt_unregister_lib: {
2151 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2152 QualType ParamTy =
2153 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2154 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2155 llvm::FunctionType *FnTy =
2156 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2157 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2158 break;
2159 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002160 case OMPRTL__tgt_target_data_begin: {
George Rokos63bc9d62017-11-21 18:25:12 +00002161 // Build void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
2162 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2163 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002164 CGM.Int32Ty,
2165 CGM.VoidPtrPtrTy,
2166 CGM.VoidPtrPtrTy,
2167 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002168 CGM.Int64Ty->getPointerTo()};
Samuel Antaodf158d52016-04-27 22:58:19 +00002169 llvm::FunctionType *FnTy =
2170 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2171 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2172 break;
2173 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002174 case OMPRTL__tgt_target_data_begin_nowait: {
2175 // Build void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
2176 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2177 // *arg_types);
2178 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2179 CGM.Int32Ty,
2180 CGM.VoidPtrPtrTy,
2181 CGM.VoidPtrPtrTy,
2182 CGM.SizeTy->getPointerTo(),
2183 CGM.Int64Ty->getPointerTo()};
2184 auto *FnTy =
2185 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2186 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin_nowait");
2187 break;
2188 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002189 case OMPRTL__tgt_target_data_end: {
George Rokos63bc9d62017-11-21 18:25:12 +00002190 // Build void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
2191 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2192 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002193 CGM.Int32Ty,
2194 CGM.VoidPtrPtrTy,
2195 CGM.VoidPtrPtrTy,
2196 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002197 CGM.Int64Ty->getPointerTo()};
Samuel Antaodf158d52016-04-27 22:58:19 +00002198 llvm::FunctionType *FnTy =
2199 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2200 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2201 break;
2202 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002203 case OMPRTL__tgt_target_data_end_nowait: {
2204 // Build void __tgt_target_data_end_nowait(int64_t device_id, int32_t
2205 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2206 // *arg_types);
2207 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2208 CGM.Int32Ty,
2209 CGM.VoidPtrPtrTy,
2210 CGM.VoidPtrPtrTy,
2211 CGM.SizeTy->getPointerTo(),
2212 CGM.Int64Ty->getPointerTo()};
2213 auto *FnTy =
2214 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2215 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end_nowait");
2216 break;
2217 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002218 case OMPRTL__tgt_target_data_update: {
George Rokos63bc9d62017-11-21 18:25:12 +00002219 // Build void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
2220 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2221 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antao8d2d7302016-05-26 18:30:22 +00002222 CGM.Int32Ty,
2223 CGM.VoidPtrPtrTy,
2224 CGM.VoidPtrPtrTy,
2225 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002226 CGM.Int64Ty->getPointerTo()};
Samuel Antao8d2d7302016-05-26 18:30:22 +00002227 llvm::FunctionType *FnTy =
2228 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2229 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2230 break;
2231 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002232 case OMPRTL__tgt_target_data_update_nowait: {
2233 // Build void __tgt_target_data_update_nowait(int64_t device_id, int32_t
2234 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2235 // *arg_types);
2236 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2237 CGM.Int32Ty,
2238 CGM.VoidPtrPtrTy,
2239 CGM.VoidPtrPtrTy,
2240 CGM.SizeTy->getPointerTo(),
2241 CGM.Int64Ty->getPointerTo()};
2242 auto *FnTy =
2243 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2244 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update_nowait");
2245 break;
2246 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002247 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002248 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002249 return RTLFn;
2250}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002251
Alexander Musman21212e42015-03-13 10:38:23 +00002252llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2253 bool IVSigned) {
2254 assert((IVSize == 32 || IVSize == 64) &&
2255 "IV size is not compatible with the omp runtime");
2256 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2257 : "__kmpc_for_static_init_4u")
2258 : (IVSigned ? "__kmpc_for_static_init_8"
2259 : "__kmpc_for_static_init_8u");
2260 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2261 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2262 llvm::Type *TypeParams[] = {
2263 getIdentTyPointerTy(), // loc
2264 CGM.Int32Ty, // tid
2265 CGM.Int32Ty, // schedtype
2266 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2267 PtrTy, // p_lower
2268 PtrTy, // p_upper
2269 PtrTy, // p_stride
2270 ITy, // incr
2271 ITy // chunk
2272 };
2273 llvm::FunctionType *FnTy =
2274 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2275 return CGM.CreateRuntimeFunction(FnTy, Name);
2276}
2277
Alexander Musman92bdaab2015-03-12 13:37:50 +00002278llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2279 bool IVSigned) {
2280 assert((IVSize == 32 || IVSize == 64) &&
2281 "IV size is not compatible with the omp runtime");
2282 auto Name =
2283 IVSize == 32
2284 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2285 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
2286 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2287 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2288 CGM.Int32Ty, // tid
2289 CGM.Int32Ty, // schedtype
2290 ITy, // lower
2291 ITy, // upper
2292 ITy, // stride
2293 ITy // chunk
2294 };
2295 llvm::FunctionType *FnTy =
2296 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2297 return CGM.CreateRuntimeFunction(FnTy, Name);
2298}
2299
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002300llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2301 bool IVSigned) {
2302 assert((IVSize == 32 || IVSize == 64) &&
2303 "IV size is not compatible with the omp runtime");
2304 auto Name =
2305 IVSize == 32
2306 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2307 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2308 llvm::Type *TypeParams[] = {
2309 getIdentTyPointerTy(), // loc
2310 CGM.Int32Ty, // tid
2311 };
2312 llvm::FunctionType *FnTy =
2313 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2314 return CGM.CreateRuntimeFunction(FnTy, Name);
2315}
2316
Alexander Musman92bdaab2015-03-12 13:37:50 +00002317llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2318 bool IVSigned) {
2319 assert((IVSize == 32 || IVSize == 64) &&
2320 "IV size is not compatible with the omp runtime");
2321 auto Name =
2322 IVSize == 32
2323 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2324 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
2325 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2326 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2327 llvm::Type *TypeParams[] = {
2328 getIdentTyPointerTy(), // loc
2329 CGM.Int32Ty, // tid
2330 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2331 PtrTy, // p_lower
2332 PtrTy, // p_upper
2333 PtrTy // p_stride
2334 };
2335 llvm::FunctionType *FnTy =
2336 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2337 return CGM.CreateRuntimeFunction(FnTy, Name);
2338}
2339
Alexey Bataev92327c52018-03-26 16:40:55 +00002340Address CGOpenMPRuntime::getAddrOfDeclareTargetLink(CodeGenFunction &CGF,
2341 const VarDecl *VD) {
2342 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2343 isDeclareTargetDeclaration(VD);
2344 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2345 SmallString<64> PtrName;
2346 {
2347 llvm::raw_svector_ostream OS(PtrName);
2348 OS << CGM.getMangledName(GlobalDecl(VD)) << "_decl_tgt_link_ptr";
2349 }
2350 llvm::Value *Ptr = CGM.getModule().getNamedValue(PtrName);
2351 if (!Ptr) {
2352 QualType PtrTy = CGM.getContext().getPointerType(VD->getType());
2353 Ptr = getOrCreateInternalVariable(CGM.getTypes().ConvertTypeForMem(PtrTy),
2354 PtrName);
2355 CGF.CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ptr));
2356 }
2357 return Address(Ptr, CGM.getContext().getDeclAlign(VD));
2358 }
2359 return Address::invalid();
2360}
2361
Alexey Bataev97720002014-11-11 04:05:39 +00002362llvm::Constant *
2363CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002364 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2365 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002366 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002367 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002368 Twine(CGM.getMangledName(VD)) + ".cache.");
2369}
2370
John McCall7f416cc2015-09-08 08:05:57 +00002371Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2372 const VarDecl *VD,
2373 Address VDAddr,
2374 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002375 if (CGM.getLangOpts().OpenMPUseTLS &&
2376 CGM.getContext().getTargetInfo().isTLSSupported())
2377 return VDAddr;
2378
John McCall7f416cc2015-09-08 08:05:57 +00002379 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002380 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002381 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2382 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002383 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2384 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002385 return Address(CGF.EmitRuntimeCall(
2386 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2387 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002388}
2389
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002390void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002391 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002392 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2393 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2394 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002395 auto OMPLoc = emitUpdateLocation(CGF, Loc);
2396 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002397 OMPLoc);
2398 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2399 // to register constructor/destructor for variable.
2400 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00002401 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2402 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002403 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002404 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002405 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002406}
2407
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002408llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002409 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002410 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002411 if (CGM.getLangOpts().OpenMPUseTLS &&
2412 CGM.getContext().getTargetInfo().isTLSSupported())
2413 return nullptr;
2414
Alexey Bataev97720002014-11-11 04:05:39 +00002415 VD = VD->getDefinition(CGM.getContext());
2416 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
2417 ThreadPrivateWithDefinition.insert(VD);
2418 QualType ASTTy = VD->getType();
2419
2420 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
2421 auto Init = VD->getAnyInitializer();
2422 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2423 // Generate function that re-emits the declaration's initializer into the
2424 // threadprivate copy of the variable VD
2425 CodeGenFunction CtorCGF(CGM);
2426 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002427 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2428 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002429 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002430 Args.push_back(&Dst);
2431
John McCallc56a8b32016-03-11 04:30:31 +00002432 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2433 CGM.getContext().VoidPtrTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002434 auto FTy = CGM.getTypes().GetFunctionType(FI);
2435 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002436 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002437 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002438 Args, Loc, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002439 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002440 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002441 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002442 Address Arg = Address(ArgVal, VDAddr.getAlignment());
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002443 Arg = CtorCGF.Builder.CreateElementBitCast(
2444 Arg, CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002445 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2446 /*IsInitializer=*/true);
2447 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002448 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002449 CGM.getContext().VoidPtrTy, Dst.getLocation());
2450 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2451 CtorCGF.FinishFunction();
2452 Ctor = Fn;
2453 }
2454 if (VD->getType().isDestructedType() != QualType::DK_none) {
2455 // Generate function that emits destructor call for the threadprivate copy
2456 // of the variable VD
2457 CodeGenFunction DtorCGF(CGM);
2458 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002459 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2460 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002461 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002462 Args.push_back(&Dst);
2463
John McCallc56a8b32016-03-11 04:30:31 +00002464 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2465 CGM.getContext().VoidTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002466 auto FTy = CGM.getTypes().GetFunctionType(FI);
2467 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002468 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002469 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002470 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002471 Loc, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002472 // Create a scope with an artificial location for the body of this function.
2473 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002474 auto ArgVal = DtorCGF.EmitLoadOfScalar(
2475 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002476 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2477 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002478 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2479 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2480 DtorCGF.FinishFunction();
2481 Dtor = Fn;
2482 }
2483 // Do not emit init function if it is not required.
2484 if (!Ctor && !Dtor)
2485 return nullptr;
2486
2487 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
2488 auto CopyCtorTy =
2489 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2490 /*isVarArg=*/false)->getPointerTo();
2491 // Copying constructor for the threadprivate variable.
2492 // Must be NULL - reserved by runtime, but currently it requires that this
2493 // parameter is always NULL. Otherwise it fires assertion.
2494 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2495 if (Ctor == nullptr) {
2496 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2497 /*isVarArg=*/false)->getPointerTo();
2498 Ctor = llvm::Constant::getNullValue(CtorTy);
2499 }
2500 if (Dtor == nullptr) {
2501 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2502 /*isVarArg=*/false)->getPointerTo();
2503 Dtor = llvm::Constant::getNullValue(DtorTy);
2504 }
2505 if (!CGF) {
2506 auto InitFunctionTy =
2507 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
2508 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002509 InitFunctionTy, ".__omp_threadprivate_init_.",
2510 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002511 CodeGenFunction InitCGF(CGM);
2512 FunctionArgList ArgList;
2513 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2514 CGM.getTypes().arrangeNullaryFunction(), ArgList,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002515 Loc, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002516 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002517 InitCGF.FinishFunction();
2518 return InitFunction;
2519 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002520 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002521 }
2522 return nullptr;
2523}
2524
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002525Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2526 QualType VarType,
2527 StringRef Name) {
2528 llvm::Twine VarName(Name, ".artificial.");
2529 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
2530 llvm::Value *GAddr = getOrCreateInternalVariable(VarLVType, VarName);
2531 llvm::Value *Args[] = {
2532 emitUpdateLocation(CGF, SourceLocation()),
2533 getThreadID(CGF, SourceLocation()),
2534 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2535 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2536 /*IsSigned=*/false),
2537 getOrCreateInternalVariable(CGM.VoidPtrPtrTy, VarName + ".cache.")};
2538 return Address(
2539 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2540 CGF.EmitRuntimeCall(
2541 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2542 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2543 CGM.getPointerAlign());
2544}
2545
Alexey Bataev1d677132015-04-22 13:57:31 +00002546/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
2547/// function. Here is the logic:
2548/// if (Cond) {
2549/// ThenGen();
2550/// } else {
2551/// ElseGen();
2552/// }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002553void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2554 const RegionCodeGenTy &ThenGen,
2555 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002556 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2557
2558 // If the condition constant folds and can be elided, try to avoid emitting
2559 // the condition and the dead arm of the if/else.
2560 bool CondConstant;
2561 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002562 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002563 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002564 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002565 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002566 return;
2567 }
2568
2569 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2570 // emit the conditional branch.
2571 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
2572 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
2573 auto ContBlock = CGF.createBasicBlock("omp_if.end");
2574 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2575
2576 // Emit the 'then' code.
2577 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002578 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002579 CGF.EmitBranch(ContBlock);
2580 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002581 // There is no need to emit line number for unconditional branch.
2582 (void)ApplyDebugLocation::CreateEmpty(CGF);
2583 CGF.EmitBlock(ElseBlock);
2584 ElseGen(CGF);
2585 // There is no need to emit line number for unconditional branch.
2586 (void)ApplyDebugLocation::CreateEmpty(CGF);
2587 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002588 // Emit the continuation block for code after the if.
2589 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002590}
2591
Alexey Bataev1d677132015-04-22 13:57:31 +00002592void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2593 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002594 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002595 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002596 if (!CGF.HaveInsertPoint())
2597 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00002598 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002599 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2600 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002601 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002602 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002603 llvm::Value *Args[] = {
2604 RTLoc,
2605 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002606 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002607 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2608 RealArgs.append(std::begin(Args), std::end(Args));
2609 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2610
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002611 auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002612 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2613 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002614 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2615 PrePostActionTy &) {
2616 auto &RT = CGF.CGM.getOpenMPRuntime();
2617 auto ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00002618 // Build calls:
2619 // __kmpc_serialized_parallel(&Loc, GTid);
2620 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002621 CGF.EmitRuntimeCall(
2622 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002623
Alexey Bataev1d677132015-04-22 13:57:31 +00002624 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002625 auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00002626 Address ZeroAddr =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002627 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
2628 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00002629 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00002630 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2631 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2632 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2633 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002634 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002635
Alexey Bataev1d677132015-04-22 13:57:31 +00002636 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002637 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00002638 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002639 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2640 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002641 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002642 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00002643 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002644 else {
2645 RegionCodeGenTy ThenRCG(ThenGen);
2646 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002647 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002648}
2649
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002650// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002651// thread-ID variable (it is passed in a first argument of the outlined function
2652// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2653// regular serial code region, get thread ID by calling kmp_int32
2654// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2655// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002656Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2657 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002658 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002659 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002660 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002661 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002662
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002663 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002664 auto Int32Ty =
2665 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2666 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2667 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002668 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002669
2670 return ThreadIDTemp;
2671}
2672
Alexey Bataev97720002014-11-11 04:05:39 +00002673llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002674CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002675 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002676 SmallString<256> Buffer;
2677 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002678 Out << Name;
2679 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00002680 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
2681 if (Elem.second) {
2682 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002683 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002684 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002685 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002686
David Blaikie13156b62014-11-19 03:06:06 +00002687 return Elem.second = new llvm::GlobalVariable(
2688 CGM.getModule(), Ty, /*IsConstant*/ false,
2689 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2690 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002691}
2692
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002693llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00002694 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002695 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002696}
2697
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002698namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002699/// Common pre(post)-action for different OpenMP constructs.
2700class CommonActionTy final : public PrePostActionTy {
2701 llvm::Value *EnterCallee;
2702 ArrayRef<llvm::Value *> EnterArgs;
2703 llvm::Value *ExitCallee;
2704 ArrayRef<llvm::Value *> ExitArgs;
2705 bool Conditional;
2706 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002707
2708public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002709 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2710 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2711 bool Conditional = false)
2712 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2713 ExitArgs(ExitArgs), Conditional(Conditional) {}
2714 void Enter(CodeGenFunction &CGF) override {
2715 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2716 if (Conditional) {
2717 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2718 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2719 ContBlock = CGF.createBasicBlock("omp_if.end");
2720 // Generate the branch (If-stmt)
2721 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2722 CGF.EmitBlock(ThenBlock);
2723 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002724 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002725 void Done(CodeGenFunction &CGF) {
2726 // Emit the rest of blocks/branches
2727 CGF.EmitBranch(ContBlock);
2728 CGF.EmitBlock(ContBlock, true);
2729 }
2730 void Exit(CodeGenFunction &CGF) override {
2731 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002732 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002733};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002734} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002735
2736void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2737 StringRef CriticalName,
2738 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002739 SourceLocation Loc, const Expr *Hint) {
2740 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002741 // CriticalOpGen();
2742 // __kmpc_end_critical(ident_t *, gtid, Lock);
2743 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002744 if (!CGF.HaveInsertPoint())
2745 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002746 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2747 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002748 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2749 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002750 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002751 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2752 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2753 }
2754 CommonActionTy Action(
2755 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2756 : OMPRTL__kmpc_critical),
2757 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2758 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002759 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002760}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002761
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002762void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002763 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002764 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002765 if (!CGF.HaveInsertPoint())
2766 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002767 // if(__kmpc_master(ident_t *, gtid)) {
2768 // MasterOpGen();
2769 // __kmpc_end_master(ident_t *, gtid);
2770 // }
2771 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002772 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002773 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2774 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2775 /*Conditional=*/true);
2776 MasterOpGen.setAction(Action);
2777 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2778 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002779}
2780
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002781void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2782 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002783 if (!CGF.HaveInsertPoint())
2784 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00002785 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2786 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002787 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00002788 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002789 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002790 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2791 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00002792}
2793
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002794void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2795 const RegionCodeGenTy &TaskgroupOpGen,
2796 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002797 if (!CGF.HaveInsertPoint())
2798 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002799 // __kmpc_taskgroup(ident_t *, gtid);
2800 // TaskgroupOpGen();
2801 // __kmpc_end_taskgroup(ident_t *, gtid);
2802 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002803 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2804 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2805 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2806 Args);
2807 TaskgroupOpGen.setAction(Action);
2808 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002809}
2810
John McCall7f416cc2015-09-08 08:05:57 +00002811/// Given an array of pointers to variables, project the address of a
2812/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002813static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2814 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00002815 // Pull out the pointer to the variable.
2816 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002817 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00002818 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2819
2820 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002821 Addr = CGF.Builder.CreateElementBitCast(
2822 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002823 return Addr;
2824}
2825
Alexey Bataeva63048e2015-03-23 06:18:07 +00002826static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00002827 CodeGenModule &CGM, llvm::Type *ArgsType,
2828 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002829 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps,
2830 SourceLocation Loc) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002831 auto &C = CGM.getContext();
2832 // void copy_func(void *LHSArg, void *RHSArg);
2833 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002834 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
2835 ImplicitParamDecl::Other);
2836 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
2837 ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002838 Args.push_back(&LHSArg);
2839 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00002840 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002841 auto *Fn = llvm::Function::Create(
2842 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2843 ".omp.copyprivate.copy_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00002844 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002845 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002846 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00002847 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002848 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00002849 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2850 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2851 ArgsType), CGF.getPointerAlign());
2852 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2853 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2854 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002855 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2856 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2857 // ...
2858 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00002859 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002860 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2861 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2862
2863 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2864 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2865
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002866 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2867 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00002868 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002869 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002870 CGF.FinishFunction();
2871 return Fn;
2872}
2873
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002874void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002875 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00002876 SourceLocation Loc,
2877 ArrayRef<const Expr *> CopyprivateVars,
2878 ArrayRef<const Expr *> SrcExprs,
2879 ArrayRef<const Expr *> DstExprs,
2880 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002881 if (!CGF.HaveInsertPoint())
2882 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002883 assert(CopyprivateVars.size() == SrcExprs.size() &&
2884 CopyprivateVars.size() == DstExprs.size() &&
2885 CopyprivateVars.size() == AssignmentOps.size());
2886 auto &C = CGM.getContext();
2887 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002888 // if(__kmpc_single(ident_t *, gtid)) {
2889 // SingleOpGen();
2890 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002891 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002892 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002893 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2894 // <copy_func>, did_it);
2895
John McCall7f416cc2015-09-08 08:05:57 +00002896 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00002897 if (!CopyprivateVars.empty()) {
2898 // int32 did_it = 0;
2899 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2900 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00002901 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002902 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002903 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002904 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002905 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
2906 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
2907 /*Conditional=*/true);
2908 SingleOpGen.setAction(Action);
2909 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2910 if (DidIt.isValid()) {
2911 // did_it = 1;
2912 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2913 }
2914 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002915 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2916 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00002917 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002918 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2919 auto CopyprivateArrayTy =
2920 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2921 /*IndexTypeQuals=*/0);
2922 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00002923 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00002924 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2925 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002926 Address Elem = CGF.Builder.CreateConstArrayGEP(
2927 CopyprivateList, I, CGF.getPointerSize());
2928 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00002929 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002930 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2931 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002932 }
2933 // Build function that copies private values from single region to all other
2934 // threads in the corresponding parallel region.
2935 auto *CpyFn = emitCopyprivateCopyFunction(
2936 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002937 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00002938 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00002939 Address CL =
2940 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2941 CGF.VoidPtrTy);
2942 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002943 llvm::Value *Args[] = {
2944 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2945 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00002946 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00002947 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00002948 CpyFn, // void (*) (void *, void *) <copy_func>
2949 DidItVal // i32 did_it
2950 };
2951 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2952 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002953}
2954
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002955void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2956 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00002957 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002958 if (!CGF.HaveInsertPoint())
2959 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002960 // __kmpc_ordered(ident_t *, gtid);
2961 // OrderedOpGen();
2962 // __kmpc_end_ordered(ident_t *, gtid);
2963 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00002964 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002965 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002966 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
2967 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2968 Args);
2969 OrderedOpGen.setAction(Action);
2970 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2971 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002972 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002973 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002974}
2975
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002976void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002977 OpenMPDirectiveKind Kind, bool EmitChecks,
2978 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002979 if (!CGF.HaveInsertPoint())
2980 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002981 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002982 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002983 unsigned Flags;
2984 if (Kind == OMPD_for)
2985 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2986 else if (Kind == OMPD_sections)
2987 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2988 else if (Kind == OMPD_single)
2989 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2990 else if (Kind == OMPD_barrier)
2991 Flags = OMP_IDENT_BARRIER_EXPL;
2992 else
2993 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002994 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2995 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002996 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2997 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002998 if (auto *OMPRegionInfo =
2999 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00003000 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003001 auto *Result = CGF.EmitRuntimeCall(
3002 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00003003 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003004 // if (__kmpc_cancel_barrier()) {
3005 // exit from construct;
3006 // }
3007 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
3008 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
3009 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
3010 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
3011 CGF.EmitBlock(ExitBB);
3012 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00003013 auto CancelDestination =
3014 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003015 CGF.EmitBranchThroughCleanup(CancelDestination);
3016 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
3017 }
3018 return;
3019 }
3020 }
3021 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00003022}
3023
Alexander Musmanc6388682014-12-15 07:07:06 +00003024/// \brief Map the OpenMP loop schedule to the runtime enumeration.
3025static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003026 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003027 switch (ScheduleKind) {
3028 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003029 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
3030 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00003031 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003032 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003033 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003034 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003035 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003036 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
3037 case OMPC_SCHEDULE_auto:
3038 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00003039 case OMPC_SCHEDULE_unknown:
3040 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003041 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00003042 }
3043 llvm_unreachable("Unexpected runtime schedule");
3044}
3045
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003046/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
3047static OpenMPSchedType
3048getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
3049 // only static is allowed for dist_schedule
3050 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
3051}
3052
Alexander Musmanc6388682014-12-15 07:07:06 +00003053bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
3054 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003055 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00003056 return Schedule == OMP_sch_static;
3057}
3058
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003059bool CGOpenMPRuntime::isStaticNonchunked(
3060 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
3061 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
3062 return Schedule == OMP_dist_sch_static;
3063}
3064
3065
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003066bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003067 auto Schedule =
3068 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003069 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
3070 return Schedule != OMP_sch_static;
3071}
3072
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003073static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
3074 OpenMPScheduleClauseModifier M1,
3075 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00003076 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003077 switch (M1) {
3078 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003079 Modifier = OMP_sch_modifier_monotonic;
3080 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003081 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003082 Modifier = OMP_sch_modifier_nonmonotonic;
3083 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003084 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003085 if (Schedule == OMP_sch_static_chunked)
3086 Schedule = OMP_sch_static_balanced_chunked;
3087 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003088 case OMPC_SCHEDULE_MODIFIER_last:
3089 case OMPC_SCHEDULE_MODIFIER_unknown:
3090 break;
3091 }
3092 switch (M2) {
3093 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003094 Modifier = OMP_sch_modifier_monotonic;
3095 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003096 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003097 Modifier = OMP_sch_modifier_nonmonotonic;
3098 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003099 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003100 if (Schedule == OMP_sch_static_chunked)
3101 Schedule = OMP_sch_static_balanced_chunked;
3102 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003103 case OMPC_SCHEDULE_MODIFIER_last:
3104 case OMPC_SCHEDULE_MODIFIER_unknown:
3105 break;
3106 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00003107 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003108}
3109
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003110void CGOpenMPRuntime::emitForDispatchInit(
3111 CodeGenFunction &CGF, SourceLocation Loc,
3112 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
3113 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003114 if (!CGF.HaveInsertPoint())
3115 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003116 OpenMPSchedType Schedule = getRuntimeSchedule(
3117 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00003118 assert(Ordered ||
3119 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00003120 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
3121 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00003122 // Call __kmpc_dispatch_init(
3123 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
3124 // kmp_int[32|64] lower, kmp_int[32|64] upper,
3125 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00003126
John McCall7f416cc2015-09-08 08:05:57 +00003127 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003128 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
3129 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00003130 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003131 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3132 CGF.Builder.getInt32(addMonoNonMonoModifier(
3133 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003134 DispatchValues.LB, // Lower
3135 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003136 CGF.Builder.getIntN(IVSize, 1), // Stride
3137 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00003138 };
3139 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
3140}
3141
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003142static void emitForStaticInitCall(
3143 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
3144 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
3145 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003146 const CGOpenMPRuntime::StaticRTInput &Values) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003147 if (!CGF.HaveInsertPoint())
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003148 return;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003149
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003150 assert(!Values.Ordered);
3151 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
3152 Schedule == OMP_sch_static_balanced_chunked ||
3153 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
3154 Schedule == OMP_dist_sch_static ||
3155 Schedule == OMP_dist_sch_static_chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003156
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003157 // Call __kmpc_for_static_init(
3158 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
3159 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
3160 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
3161 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
3162 llvm::Value *Chunk = Values.Chunk;
3163 if (Chunk == nullptr) {
3164 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
3165 Schedule == OMP_dist_sch_static) &&
3166 "expected static non-chunked schedule");
3167 // If the Chunk was not specified in the clause - use default value 1.
3168 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3169 } else {
3170 assert((Schedule == OMP_sch_static_chunked ||
3171 Schedule == OMP_sch_static_balanced_chunked ||
3172 Schedule == OMP_ord_static_chunked ||
3173 Schedule == OMP_dist_sch_static_chunked) &&
3174 "expected static chunked schedule");
3175 }
3176 llvm::Value *Args[] = {
3177 UpdateLocation,
3178 ThreadId,
3179 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3180 M2)), // Schedule type
3181 Values.IL.getPointer(), // &isLastIter
3182 Values.LB.getPointer(), // &LB
3183 Values.UB.getPointer(), // &UB
3184 Values.ST.getPointer(), // &Stride
3185 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3186 Chunk // Chunk
3187 };
3188 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003189}
3190
John McCall7f416cc2015-09-08 08:05:57 +00003191void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3192 SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003193 OpenMPDirectiveKind DKind,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003194 const OpenMPScheduleTy &ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003195 const StaticRTInput &Values) {
3196 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3197 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3198 assert(isOpenMPWorksharingDirective(DKind) &&
3199 "Expected loop-based or sections-based directive.");
3200 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc,
3201 isOpenMPLoopDirective(DKind)
3202 ? OMP_IDENT_WORK_LOOP
3203 : OMP_IDENT_WORK_SECTIONS);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003204 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003205 auto *StaticInitFunction =
3206 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003207 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003208 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003209}
John McCall7f416cc2015-09-08 08:05:57 +00003210
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003211void CGOpenMPRuntime::emitDistributeStaticInit(
3212 CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003213 OpenMPDistScheduleClauseKind SchedKind,
3214 const CGOpenMPRuntime::StaticRTInput &Values) {
3215 OpenMPSchedType ScheduleNum =
3216 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
3217 auto *UpdatedLocation =
3218 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003219 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003220 auto *StaticInitFunction =
3221 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003222 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3223 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003224 OMPC_SCHEDULE_MODIFIER_unknown, Values);
Alexander Musmanc6388682014-12-15 07:07:06 +00003225}
3226
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003227void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
Alexey Bataevf43f7142017-09-06 16:17:35 +00003228 SourceLocation Loc,
3229 OpenMPDirectiveKind DKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003230 if (!CGF.HaveInsertPoint())
3231 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003232 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataevf43f7142017-09-06 16:17:35 +00003233 llvm::Value *Args[] = {
3234 emitUpdateLocation(CGF, Loc,
3235 isOpenMPDistributeDirective(DKind)
3236 ? OMP_IDENT_WORK_DISTRIBUTE
3237 : isOpenMPLoopDirective(DKind)
3238 ? OMP_IDENT_WORK_LOOP
3239 : OMP_IDENT_WORK_SECTIONS),
3240 getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003241 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3242 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003243}
3244
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003245void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3246 SourceLocation Loc,
3247 unsigned IVSize,
3248 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003249 if (!CGF.HaveInsertPoint())
3250 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003251 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003252 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003253 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3254}
3255
Alexander Musman92bdaab2015-03-12 13:37:50 +00003256llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3257 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003258 bool IVSigned, Address IL,
3259 Address LB, Address UB,
3260 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003261 // Call __kmpc_dispatch_next(
3262 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3263 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3264 // kmp_int[32|64] *p_stride);
3265 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003266 emitUpdateLocation(CGF, Loc),
3267 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003268 IL.getPointer(), // &isLastIter
3269 LB.getPointer(), // &Lower
3270 UB.getPointer(), // &Upper
3271 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003272 };
3273 llvm::Value *Call =
3274 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3275 return CGF.EmitScalarConversion(
3276 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003277 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003278}
3279
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003280void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3281 llvm::Value *NumThreads,
3282 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003283 if (!CGF.HaveInsertPoint())
3284 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003285 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3286 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003287 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003288 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003289 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3290 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003291}
3292
Alexey Bataev7f210c62015-06-18 13:40:03 +00003293void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3294 OpenMPProcBindClauseKind ProcBind,
3295 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003296 if (!CGF.HaveInsertPoint())
3297 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003298 // Constants for proc bind value accepted by the runtime.
3299 enum ProcBindTy {
3300 ProcBindFalse = 0,
3301 ProcBindTrue,
3302 ProcBindMaster,
3303 ProcBindClose,
3304 ProcBindSpread,
3305 ProcBindIntel,
3306 ProcBindDefault
3307 } RuntimeProcBind;
3308 switch (ProcBind) {
3309 case OMPC_PROC_BIND_master:
3310 RuntimeProcBind = ProcBindMaster;
3311 break;
3312 case OMPC_PROC_BIND_close:
3313 RuntimeProcBind = ProcBindClose;
3314 break;
3315 case OMPC_PROC_BIND_spread:
3316 RuntimeProcBind = ProcBindSpread;
3317 break;
3318 case OMPC_PROC_BIND_unknown:
3319 llvm_unreachable("Unsupported proc_bind value.");
3320 }
3321 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3322 llvm::Value *Args[] = {
3323 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3324 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3325 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3326}
3327
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003328void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3329 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003330 if (!CGF.HaveInsertPoint())
3331 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003332 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003333 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3334 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003335}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003336
Alexey Bataev62b63b12015-03-10 07:28:44 +00003337namespace {
3338/// \brief Indexes of fields for type kmp_task_t.
3339enum KmpTaskTFields {
3340 /// \brief List of shared variables.
3341 KmpTaskTShareds,
3342 /// \brief Task routine.
3343 KmpTaskTRoutine,
3344 /// \brief Partition id for the untied tasks.
3345 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003346 /// Function with call of destructors for private variables.
3347 Data1,
3348 /// Task priority.
3349 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003350 /// (Taskloops only) Lower bound.
3351 KmpTaskTLowerBound,
3352 /// (Taskloops only) Upper bound.
3353 KmpTaskTUpperBound,
3354 /// (Taskloops only) Stride.
3355 KmpTaskTStride,
3356 /// (Taskloops only) Is last iteration flag.
3357 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003358 /// (Taskloops only) Reduction data.
3359 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003360};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003361} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003362
Samuel Antaoee8fb302016-01-06 13:42:12 +00003363bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
3364 // FIXME: Add other entries type when they become supported.
3365 return OffloadEntriesTargetRegion.empty();
3366}
3367
3368/// \brief Initialize target region entry.
3369void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3370 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3371 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003372 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003373 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3374 "only required for the device "
3375 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003376 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003377 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
3378 /*Flags=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003379 ++OffloadingEntriesNum;
3380}
3381
3382void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3383 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3384 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003385 llvm::Constant *Addr, llvm::Constant *ID,
3386 int32_t Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003387 // If we are emitting code for a target, the entry is already initialized,
3388 // only has to be registered.
3389 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003390 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00003391 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003392 auto &Entry =
3393 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003394 assert(Entry.isValid() && "Entry not initialized!");
3395 Entry.setAddress(Addr);
3396 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003397 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003398 return;
3399 } else {
Samuel Antaof83efdb2017-01-05 16:02:49 +00003400 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003401 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003402 }
3403}
3404
3405bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003406 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3407 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003408 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3409 if (PerDevice == OffloadEntriesTargetRegion.end())
3410 return false;
3411 auto PerFile = PerDevice->second.find(FileID);
3412 if (PerFile == PerDevice->second.end())
3413 return false;
3414 auto PerParentName = PerFile->second.find(ParentName);
3415 if (PerParentName == PerFile->second.end())
3416 return false;
3417 auto PerLine = PerParentName->second.find(LineNum);
3418 if (PerLine == PerParentName->second.end())
3419 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003420 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003421 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003422 return false;
3423 return true;
3424}
3425
3426void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3427 const OffloadTargetRegionEntryInfoActTy &Action) {
3428 // Scan all target region entries and perform the provided action.
3429 for (auto &D : OffloadEntriesTargetRegion)
3430 for (auto &F : D.second)
3431 for (auto &P : F.second)
3432 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003433 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003434}
3435
3436/// \brief Create a Ctor/Dtor-like function whose body is emitted through
3437/// \a Codegen. This is used to emit the two functions that register and
3438/// unregister the descriptor of the current compilation unit.
3439static llvm::Function *
3440createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
3441 const RegionCodeGenTy &Codegen) {
3442 auto &C = CGM.getContext();
3443 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003444 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003445 Args.push_back(&DummyPtr);
3446
3447 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003448 // Disable debug info for global (de-)initializer because they are not part of
3449 // some particular construct.
3450 CGF.disableDebugInfo();
John McCallc56a8b32016-03-11 04:30:31 +00003451 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003452 auto FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003453 auto *Fn = CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI);
3454 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003455 Codegen(CGF);
3456 CGF.FinishFunction();
3457 return Fn;
3458}
3459
3460llvm::Function *
3461CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003462 // If we don't have entries or if we are emitting code for the device, we
3463 // don't need to do anything.
3464 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3465 return nullptr;
3466
3467 auto &M = CGM.getModule();
3468 auto &C = CGM.getContext();
3469
3470 // Get list of devices we care about
3471 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
3472
3473 // We should be creating an offloading descriptor only if there are devices
3474 // specified.
3475 assert(!Devices.empty() && "No OpenMP offloading devices??");
3476
3477 // Create the external variables that will point to the begin and end of the
3478 // host entries section. These will be defined by the linker.
3479 auto *OffloadEntryTy =
3480 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
3481 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
3482 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003483 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003484 ".omp_offloading.entries_begin");
3485 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
3486 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003487 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003488 ".omp_offloading.entries_end");
3489
3490 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003491 auto *DeviceImageTy = cast<llvm::StructType>(
3492 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003493 ConstantInitBuilder DeviceImagesBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003494 auto DeviceImagesEntries = DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003495
3496 for (unsigned i = 0; i < Devices.size(); ++i) {
3497 StringRef T = Devices[i].getTriple();
3498 auto *ImgBegin = new llvm::GlobalVariable(
3499 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003500 /*Initializer=*/nullptr,
3501 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003502 auto *ImgEnd = new llvm::GlobalVariable(
3503 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003504 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003505
John McCall6c9f1fdb2016-11-19 08:17:24 +00003506 auto Dev = DeviceImagesEntries.beginStruct(DeviceImageTy);
3507 Dev.add(ImgBegin);
3508 Dev.add(ImgEnd);
3509 Dev.add(HostEntriesBegin);
3510 Dev.add(HostEntriesEnd);
John McCallf1788632016-11-28 22:18:30 +00003511 Dev.finishAndAddTo(DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003512 }
3513
3514 // Create device images global array.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003515 llvm::GlobalVariable *DeviceImages =
3516 DeviceImagesEntries.finishAndCreateGlobal(".omp_offloading.device_images",
3517 CGM.getPointerAlign(),
3518 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003519 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003520
3521 // This is a Zero array to be used in the creation of the constant expressions
3522 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3523 llvm::Constant::getNullValue(CGM.Int32Ty)};
3524
3525 // Create the target region descriptor.
3526 auto *BinaryDescriptorTy = cast<llvm::StructType>(
3527 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003528 ConstantInitBuilder DescBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003529 auto DescInit = DescBuilder.beginStruct(BinaryDescriptorTy);
3530 DescInit.addInt(CGM.Int32Ty, Devices.size());
3531 DescInit.add(llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3532 DeviceImages,
3533 Index));
3534 DescInit.add(HostEntriesBegin);
3535 DescInit.add(HostEntriesEnd);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003536
John McCall6c9f1fdb2016-11-19 08:17:24 +00003537 auto *Desc = DescInit.finishAndCreateGlobal(".omp_offloading.descriptor",
3538 CGM.getPointerAlign(),
3539 /*isConstant=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003540
3541 // Emit code to register or unregister the descriptor at execution
3542 // startup or closing, respectively.
3543
3544 // Create a variable to drive the registration and unregistration of the
3545 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3546 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
3547 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00003548 IdentInfo, C.CharTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003549
3550 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003551 CGM, ".omp_offloading.descriptor_unreg",
3552 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00003553 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3554 Desc);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003555 });
3556 auto *RegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003557 CGM, ".omp_offloading.descriptor_reg",
3558 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00003559 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib),
3560 Desc);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003561 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3562 });
George Rokos29d0f002017-05-27 03:03:13 +00003563 if (CGM.supportsCOMDAT()) {
3564 // It is sufficient to call registration function only once, so create a
3565 // COMDAT group for registration/unregistration functions and associated
3566 // data. That would reduce startup time and code size. Registration
3567 // function serves as a COMDAT group key.
3568 auto ComdatKey = M.getOrInsertComdat(RegFn->getName());
3569 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3570 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3571 RegFn->setComdat(ComdatKey);
3572 UnRegFn->setComdat(ComdatKey);
3573 DeviceImages->setComdat(ComdatKey);
3574 Desc->setComdat(ComdatKey);
3575 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003576 return RegFn;
3577}
3578
Samuel Antao2de62b02016-02-13 23:35:10 +00003579void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003580 llvm::Constant *Addr, uint64_t Size,
3581 int32_t Flags) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003582 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003583 auto *TgtOffloadEntryType = cast<llvm::StructType>(
3584 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
3585 llvm::LLVMContext &C = CGM.getModule().getContext();
3586 llvm::Module &M = CGM.getModule();
3587
3588 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00003589 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003590
3591 // Create constant string with the name.
3592 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3593
3594 llvm::GlobalVariable *Str =
3595 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
3596 llvm::GlobalValue::InternalLinkage, StrPtrInit,
3597 ".omp_offloading.entry_name");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003598 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003599 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
3600
John McCall6c9f1fdb2016-11-19 08:17:24 +00003601 // We can't have any padding between symbols, so we need to have 1-byte
3602 // alignment.
3603 auto Align = CharUnits::fromQuantity(1);
3604
Samuel Antaoee8fb302016-01-06 13:42:12 +00003605 // Create the entry struct.
John McCall23c9dc62016-11-28 22:18:27 +00003606 ConstantInitBuilder EntryBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003607 auto EntryInit = EntryBuilder.beginStruct(TgtOffloadEntryType);
3608 EntryInit.add(AddrPtr);
3609 EntryInit.add(StrPtr);
3610 EntryInit.addInt(CGM.SizeTy, Size);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003611 EntryInit.addInt(CGM.Int32Ty, Flags);
3612 EntryInit.addInt(CGM.Int32Ty, 0);
Jonas Hahnfeld5e4df282018-01-18 15:38:03 +00003613 llvm::GlobalVariable *Entry = EntryInit.finishAndCreateGlobal(
3614 Twine(".omp_offloading.entry.") + Name, Align,
3615 /*constant*/ true, llvm::GlobalValue::ExternalLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003616
3617 // The entry has to be created in the section the linker expects it to be.
3618 Entry->setSection(".omp_offloading.entries");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003619}
3620
3621void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3622 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003623 // can easily figure out what to emit. The produced metadata looks like
3624 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003625 //
3626 // !omp_offload.info = !{!1, ...}
3627 //
3628 // Right now we only generate metadata for function that contain target
3629 // regions.
3630
3631 // If we do not have entries, we dont need to do anything.
3632 if (OffloadEntriesInfoManager.empty())
3633 return;
3634
3635 llvm::Module &M = CGM.getModule();
3636 llvm::LLVMContext &C = M.getContext();
3637 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
3638 OrderedEntries(OffloadEntriesInfoManager.size());
3639
3640 // Create the offloading info metadata node.
3641 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
3642
Simon Pilgrim2c518802017-03-30 14:13:19 +00003643 // Auxiliary methods to create metadata values and strings.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003644 auto getMDInt = [&](unsigned v) {
3645 return llvm::ConstantAsMetadata::get(
3646 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
3647 };
3648
3649 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
3650
3651 // Create function that emits metadata for each target region entry;
3652 auto &&TargetRegionMetadataEmitter = [&](
3653 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003654 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3655 llvm::SmallVector<llvm::Metadata *, 32> Ops;
3656 // Generate metadata for target regions. Each entry of this metadata
3657 // contains:
3658 // - Entry 0 -> Kind of this type of metadata (0).
3659 // - Entry 1 -> Device ID of the file where the entry was identified.
3660 // - Entry 2 -> File ID of the file where the entry was identified.
3661 // - Entry 3 -> Mangled name of the function where the entry was identified.
3662 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00003663 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003664 // The first element of the metadata node is the kind.
3665 Ops.push_back(getMDInt(E.getKind()));
3666 Ops.push_back(getMDInt(DeviceID));
3667 Ops.push_back(getMDInt(FileID));
3668 Ops.push_back(getMDString(ParentName));
3669 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003670 Ops.push_back(getMDInt(E.getOrder()));
3671
3672 // Save this entry in the right position of the ordered entries array.
3673 OrderedEntries[E.getOrder()] = &E;
3674
3675 // Add metadata to the named metadata node.
3676 MD->addOperand(llvm::MDNode::get(C, Ops));
3677 };
3678
3679 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3680 TargetRegionMetadataEmitter);
3681
3682 for (auto *E : OrderedEntries) {
3683 assert(E && "All ordered entries must exist!");
3684 if (auto *CE =
3685 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3686 E)) {
3687 assert(CE->getID() && CE->getAddress() &&
3688 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00003689 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003690 } else
3691 llvm_unreachable("Unsupported entry kind.");
3692 }
3693}
3694
3695/// \brief Loads all the offload entries information from the host IR
3696/// metadata.
3697void CGOpenMPRuntime::loadOffloadInfoMetadata() {
3698 // If we are in target mode, load the metadata from the host IR. This code has
3699 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
3700
3701 if (!CGM.getLangOpts().OpenMPIsDevice)
3702 return;
3703
3704 if (CGM.getLangOpts().OMPHostIRFile.empty())
3705 return;
3706
3707 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
3708 if (Buf.getError())
3709 return;
3710
3711 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00003712 auto ME = expectedToErrorOrAndEmitErrors(
3713 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003714
3715 if (ME.getError())
3716 return;
3717
3718 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
3719 if (!MD)
3720 return;
3721
George Burgess IV00f70bd2018-03-01 05:43:23 +00003722 for (llvm::MDNode *MN : MD->operands()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003723 auto getMDInt = [&](unsigned Idx) {
3724 llvm::ConstantAsMetadata *V =
3725 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
3726 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
3727 };
3728
3729 auto getMDString = [&](unsigned Idx) {
3730 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
3731 return V->getString();
3732 };
3733
3734 switch (getMDInt(0)) {
3735 default:
3736 llvm_unreachable("Unexpected metadata!");
3737 break;
3738 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3739 OFFLOAD_ENTRY_INFO_TARGET_REGION:
3740 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
3741 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
3742 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00003743 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003744 break;
3745 }
3746 }
3747}
3748
Alexey Bataev62b63b12015-03-10 07:28:44 +00003749void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
3750 if (!KmpRoutineEntryPtrTy) {
3751 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
3752 auto &C = CGM.getContext();
3753 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
3754 FunctionProtoType::ExtProtoInfo EPI;
3755 KmpRoutineEntryPtrQTy = C.getPointerType(
3756 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
3757 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
3758 }
3759}
3760
Alexey Bataevc71a4092015-09-11 10:29:41 +00003761static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
3762 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003763 auto *Field = FieldDecl::Create(
3764 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
3765 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
3766 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
3767 Field->setAccess(AS_public);
3768 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003769 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003770}
3771
Samuel Antaoee8fb302016-01-06 13:42:12 +00003772QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
3773
3774 // Make sure the type of the entry is already created. This is the type we
3775 // have to create:
3776 // struct __tgt_offload_entry{
3777 // void *addr; // Pointer to the offload entry info.
3778 // // (function or global)
3779 // char *name; // Name of the function or global.
3780 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00003781 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
3782 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003783 // };
3784 if (TgtOffloadEntryQTy.isNull()) {
3785 ASTContext &C = CGM.getContext();
3786 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
3787 RD->startDefinition();
3788 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3789 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
3790 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00003791 addFieldToRecordDecl(
3792 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3793 addFieldToRecordDecl(
3794 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003795 RD->completeDefinition();
Jonas Hahnfeld5e4df282018-01-18 15:38:03 +00003796 RD->addAttr(PackedAttr::CreateImplicit(C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003797 TgtOffloadEntryQTy = C.getRecordType(RD);
3798 }
3799 return TgtOffloadEntryQTy;
3800}
3801
3802QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
3803 // These are the types we need to build:
3804 // struct __tgt_device_image{
3805 // void *ImageStart; // Pointer to the target code start.
3806 // void *ImageEnd; // Pointer to the target code end.
3807 // // We also add the host entries to the device image, as it may be useful
3808 // // for the target runtime to have access to that information.
3809 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
3810 // // the entries.
3811 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3812 // // entries (non inclusive).
3813 // };
3814 if (TgtDeviceImageQTy.isNull()) {
3815 ASTContext &C = CGM.getContext();
3816 auto *RD = C.buildImplicitRecord("__tgt_device_image");
3817 RD->startDefinition();
3818 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3819 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3820 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3821 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3822 RD->completeDefinition();
3823 TgtDeviceImageQTy = C.getRecordType(RD);
3824 }
3825 return TgtDeviceImageQTy;
3826}
3827
3828QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
3829 // struct __tgt_bin_desc{
3830 // int32_t NumDevices; // Number of devices supported.
3831 // __tgt_device_image *DeviceImages; // Arrays of device images
3832 // // (one per device).
3833 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
3834 // // entries.
3835 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3836 // // entries (non inclusive).
3837 // };
3838 if (TgtBinaryDescriptorQTy.isNull()) {
3839 ASTContext &C = CGM.getContext();
3840 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
3841 RD->startDefinition();
3842 addFieldToRecordDecl(
3843 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3844 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
3845 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3846 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3847 RD->completeDefinition();
3848 TgtBinaryDescriptorQTy = C.getRecordType(RD);
3849 }
3850 return TgtBinaryDescriptorQTy;
3851}
3852
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003853namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00003854struct PrivateHelpersTy {
3855 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
3856 const VarDecl *PrivateElemInit)
3857 : Original(Original), PrivateCopy(PrivateCopy),
3858 PrivateElemInit(PrivateElemInit) {}
3859 const VarDecl *Original;
3860 const VarDecl *PrivateCopy;
3861 const VarDecl *PrivateElemInit;
3862};
3863typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00003864} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003865
Alexey Bataev9e034042015-05-05 04:05:12 +00003866static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00003867createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003868 if (!Privates.empty()) {
3869 auto &C = CGM.getContext();
3870 // Build struct .kmp_privates_t. {
3871 // /* private vars */
3872 // };
3873 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
3874 RD->startDefinition();
3875 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00003876 auto *VD = Pair.second.Original;
3877 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003878 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00003879 auto *FD = addFieldToRecordDecl(C, RD, Type);
3880 if (VD->hasAttrs()) {
3881 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
3882 E(VD->getAttrs().end());
3883 I != E; ++I)
3884 FD->addAttr(*I);
3885 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003886 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003887 RD->completeDefinition();
3888 return RD;
3889 }
3890 return nullptr;
3891}
3892
Alexey Bataev9e034042015-05-05 04:05:12 +00003893static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00003894createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
3895 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003896 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003897 auto &C = CGM.getContext();
3898 // Build struct kmp_task_t {
3899 // void * shareds;
3900 // kmp_routine_entry_t routine;
3901 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00003902 // kmp_cmplrdata_t data1;
3903 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00003904 // For taskloops additional fields:
3905 // kmp_uint64 lb;
3906 // kmp_uint64 ub;
3907 // kmp_int64 st;
3908 // kmp_int32 liter;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003909 // void * reductions;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003910 // };
Alexey Bataevad537bb2016-05-30 09:06:50 +00003911 auto *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
3912 UD->startDefinition();
3913 addFieldToRecordDecl(C, UD, KmpInt32Ty);
3914 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
3915 UD->completeDefinition();
3916 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003917 auto *RD = C.buildImplicitRecord("kmp_task_t");
3918 RD->startDefinition();
3919 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3920 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
3921 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00003922 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3923 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003924 if (isOpenMPTaskLoopDirective(Kind)) {
3925 QualType KmpUInt64Ty =
3926 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3927 QualType KmpInt64Ty =
3928 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3929 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3930 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3931 addFieldToRecordDecl(C, RD, KmpInt64Ty);
3932 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003933 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003934 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003935 RD->completeDefinition();
3936 return RD;
3937}
3938
3939static RecordDecl *
3940createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003941 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003942 auto &C = CGM.getContext();
3943 // Build struct kmp_task_t_with_privates {
3944 // kmp_task_t task_data;
3945 // .kmp_privates_t. privates;
3946 // };
3947 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
3948 RD->startDefinition();
3949 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003950 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
3951 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
3952 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003953 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003954 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003955}
3956
3957/// \brief Emit a proxy function which accepts kmp_task_t as the second
3958/// argument.
3959/// \code
3960/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003961/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00003962/// For taskloops:
3963/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003964/// tt->reductions, tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003965/// return 0;
3966/// }
3967/// \endcode
3968static llvm::Value *
3969emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00003970 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
3971 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003972 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003973 QualType SharedsPtrTy, llvm::Value *TaskFunction,
3974 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003975 auto &C = CGM.getContext();
3976 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003977 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3978 ImplicitParamDecl::Other);
3979 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3980 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3981 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003982 Args.push_back(&GtidArg);
3983 Args.push_back(&TaskTypeArg);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003984 auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003985 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003986 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
3987 auto *TaskEntry =
3988 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
3989 ".omp_task_entry.", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003990 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003991 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003992 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args,
3993 Loc, Loc);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003994
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003995 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00003996 // tt,
3997 // For taskloops:
3998 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3999 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004000 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00004001 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00004002 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4003 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4004 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004005 auto *KmpTaskTWithPrivatesQTyRD =
4006 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004007 LValue Base =
4008 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004009 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
4010 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4011 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00004012 auto *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004013
4014 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
4015 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004016 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev1e491372018-01-23 18:44:14 +00004017 CGF.EmitLoadOfScalar(SharedsLVal, Loc),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004018 CGF.ConvertTypeForMem(SharedsPtrTy));
4019
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004020 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4021 llvm::Value *PrivatesParam;
4022 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
4023 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
4024 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004025 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004026 } else
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004027 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004028
Alexey Bataev7292c292016-04-25 12:22:29 +00004029 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
4030 TaskPrivatesMap,
4031 CGF.Builder
4032 .CreatePointerBitCastOrAddrSpaceCast(
4033 TDBase.getAddress(), CGF.VoidPtrTy)
4034 .getPointer()};
4035 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
4036 std::end(CommonArgs));
4037 if (isOpenMPTaskLoopDirective(Kind)) {
4038 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
4039 auto LBLVal = CGF.EmitLValueForField(Base, *LBFI);
Alexey Bataev1e491372018-01-23 18:44:14 +00004040 auto *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004041 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
4042 auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
Alexey Bataev1e491372018-01-23 18:44:14 +00004043 auto *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004044 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
4045 auto StLVal = CGF.EmitLValueForField(Base, *StFI);
Alexey Bataev1e491372018-01-23 18:44:14 +00004046 auto *StParam = CGF.EmitLoadOfScalar(StLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004047 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4048 auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
Alexey Bataev1e491372018-01-23 18:44:14 +00004049 auto *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004050 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
4051 auto RLVal = CGF.EmitLValueForField(Base, *RFI);
Alexey Bataev1e491372018-01-23 18:44:14 +00004052 auto *RParam = CGF.EmitLoadOfScalar(RLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004053 CallArgs.push_back(LBParam);
4054 CallArgs.push_back(UBParam);
4055 CallArgs.push_back(StParam);
4056 CallArgs.push_back(LIParam);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004057 CallArgs.push_back(RParam);
Alexey Bataev7292c292016-04-25 12:22:29 +00004058 }
4059 CallArgs.push_back(SharedsParam);
4060
Alexey Bataev3c595a62017-08-14 15:01:03 +00004061 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
4062 CallArgs);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004063 CGF.EmitStoreThroughLValue(
4064 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00004065 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004066 CGF.FinishFunction();
4067 return TaskEntry;
4068}
4069
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004070static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
4071 SourceLocation Loc,
4072 QualType KmpInt32Ty,
4073 QualType KmpTaskTWithPrivatesPtrQTy,
4074 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00004075 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004076 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004077 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4078 ImplicitParamDecl::Other);
4079 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4080 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4081 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004082 Args.push_back(&GtidArg);
4083 Args.push_back(&TaskTypeArg);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004084 auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004085 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004086 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
4087 auto *DestructorFn =
4088 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
4089 ".omp_task_destructor.", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004090 CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004091 DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004092 CodeGenFunction CGF(CGM);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004093 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004094 Args, Loc, Loc);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004095
Alexey Bataev31300ed2016-02-04 11:27:03 +00004096 LValue Base = CGF.EmitLoadOfPointerLValue(
4097 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4098 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004099 auto *KmpTaskTWithPrivatesQTyRD =
4100 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
4101 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004102 Base = CGF.EmitLValueForField(Base, *FI);
4103 for (auto *Field :
4104 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
4105 if (auto DtorKind = Field->getType().isDestructedType()) {
4106 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
4107 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
4108 }
4109 }
4110 CGF.FinishFunction();
4111 return DestructorFn;
4112}
4113
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004114/// \brief Emit a privates mapping function for correct handling of private and
4115/// firstprivate variables.
4116/// \code
4117/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
4118/// **noalias priv1,..., <tyn> **noalias privn) {
4119/// *priv1 = &.privates.priv1;
4120/// ...;
4121/// *privn = &.privates.privn;
4122/// }
4123/// \endcode
4124static llvm::Value *
4125emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00004126 ArrayRef<const Expr *> PrivateVars,
4127 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004128 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004129 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004130 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004131 auto &C = CGM.getContext();
4132 FunctionArgList Args;
4133 ImplicitParamDecl TaskPrivatesArg(
4134 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00004135 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
4136 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004137 Args.push_back(&TaskPrivatesArg);
4138 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
4139 unsigned Counter = 1;
4140 for (auto *E: PrivateVars) {
4141 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004142 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4143 C.getPointerType(C.getPointerType(E->getType()))
4144 .withConst()
4145 .withRestrict(),
4146 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004147 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4148 PrivateVarsPos[VD] = Counter;
4149 ++Counter;
4150 }
4151 for (auto *E : FirstprivateVars) {
4152 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004153 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4154 C.getPointerType(C.getPointerType(E->getType()))
4155 .withConst()
4156 .withRestrict(),
4157 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004158 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4159 PrivateVarsPos[VD] = Counter;
4160 ++Counter;
4161 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004162 for (auto *E: LastprivateVars) {
4163 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004164 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4165 C.getPointerType(C.getPointerType(E->getType()))
4166 .withConst()
4167 .withRestrict(),
4168 ImplicitParamDecl::Other));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004169 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4170 PrivateVarsPos[VD] = Counter;
4171 ++Counter;
4172 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004173 auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004174 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004175 auto *TaskPrivatesMapTy =
4176 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
4177 auto *TaskPrivatesMap = llvm::Function::Create(
4178 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
4179 ".omp_task_privates_map.", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004180 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004181 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00004182 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00004183 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00004184 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004185 CodeGenFunction CGF(CGM);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004186 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004187 TaskPrivatesMapFnInfo, Args, Loc, Loc);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004188
4189 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00004190 LValue Base = CGF.EmitLoadOfPointerLValue(
4191 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4192 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004193 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
4194 Counter = 0;
4195 for (auto *Field : PrivatesQTyRD->fields()) {
4196 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
4197 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00004198 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00004199 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
4200 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00004201 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004202 ++Counter;
4203 }
4204 CGF.FinishFunction();
4205 return TaskPrivatesMap;
4206}
4207
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004208static bool stable_sort_comparator(const PrivateDataTy P1,
4209 const PrivateDataTy P2) {
4210 return P1.first > P2.first;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004211}
4212
Alexey Bataevf93095a2016-05-05 08:46:22 +00004213/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00004214static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004215 const OMPExecutableDirective &D,
4216 Address KmpTaskSharedsPtr, LValue TDBase,
4217 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4218 QualType SharedsTy, QualType SharedsPtrTy,
4219 const OMPTaskDataTy &Data,
4220 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
4221 auto &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004222 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4223 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004224 OpenMPDirectiveKind Kind = isOpenMPTaskLoopDirective(D.getDirectiveKind())
4225 ? OMPD_taskloop
4226 : OMPD_task;
4227 const CapturedStmt &CS = *D.getCapturedStmt(Kind);
4228 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004229 LValue SrcBase;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004230 bool IsTargetTask =
4231 isOpenMPTargetDataManagementDirective(D.getDirectiveKind()) ||
4232 isOpenMPTargetExecutionDirective(D.getDirectiveKind());
4233 // For target-based directives skip 3 firstprivate arrays BasePointersArray,
4234 // PointersArray and SizesArray. The original variables for these arrays are
4235 // not captured and we get their addresses explicitly.
4236 if ((!IsTargetTask && !Data.FirstprivateVars.empty()) ||
Alexey Bataev8451efa2018-01-15 19:06:12 +00004237 (IsTargetTask && KmpTaskSharedsPtr.isValid())) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004238 SrcBase = CGF.MakeAddrLValue(
4239 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4240 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4241 SharedsTy);
4242 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004243 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
4244 for (auto &&Pair : Privates) {
4245 auto *VD = Pair.second.PrivateCopy;
4246 auto *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004247 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4248 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004249 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004250 if (auto *Elem = Pair.second.PrivateElemInit) {
4251 auto *OriginalVD = Pair.second.Original;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004252 // Check if the variable is the target-based BasePointersArray,
4253 // PointersArray or SizesArray.
4254 LValue SharedRefLValue;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004255 QualType Type = OriginalVD->getType();
Alexey Bataev8451efa2018-01-15 19:06:12 +00004256 auto *SharedField = CapturesInfo.lookup(OriginalVD);
4257 if (IsTargetTask && !SharedField) {
4258 assert(isa<ImplicitParamDecl>(OriginalVD) &&
4259 isa<CapturedDecl>(OriginalVD->getDeclContext()) &&
4260 cast<CapturedDecl>(OriginalVD->getDeclContext())
4261 ->getNumParams() == 0 &&
4262 isa<TranslationUnitDecl>(
4263 cast<CapturedDecl>(OriginalVD->getDeclContext())
4264 ->getDeclContext()) &&
4265 "Expected artificial target data variable.");
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004266 SharedRefLValue =
4267 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type);
4268 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004269 SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4270 SharedRefLValue = CGF.MakeAddrLValue(
4271 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
4272 SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl),
4273 SharedRefLValue.getTBAAInfo());
4274 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004275 if (Type->isArrayType()) {
4276 // Initialize firstprivate array.
4277 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4278 // Perform simple memcpy.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004279 CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004280 } else {
4281 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00004282 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00004283 CGF.EmitOMPAggregateAssign(
4284 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4285 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4286 Address SrcElement) {
4287 // Clean up any temporaries needed by the initialization.
4288 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4289 InitScope.addPrivate(
4290 Elem, [SrcElement]() -> Address { return SrcElement; });
4291 (void)InitScope.Privatize();
4292 // Emit initialization for single element.
4293 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4294 CGF, &CapturesInfo);
4295 CGF.EmitAnyExprToMem(Init, DestElement,
4296 Init->getType().getQualifiers(),
4297 /*IsInitializer=*/false);
4298 });
4299 }
4300 } else {
4301 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4302 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4303 return SharedRefLValue.getAddress();
4304 });
4305 (void)InitScope.Privatize();
4306 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4307 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4308 /*capturedByInit=*/false);
4309 }
4310 } else
4311 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
4312 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004313 ++FI;
4314 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004315}
4316
4317/// Check if duplication function is required for taskloops.
4318static bool checkInitIsRequired(CodeGenFunction &CGF,
4319 ArrayRef<PrivateDataTy> Privates) {
4320 bool InitRequired = false;
4321 for (auto &&Pair : Privates) {
4322 auto *VD = Pair.second.PrivateCopy;
4323 auto *Init = VD->getAnyInitializer();
4324 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4325 !CGF.isTrivialInitializer(Init));
4326 }
4327 return InitRequired;
4328}
4329
4330
4331/// Emit task_dup function (for initialization of
4332/// private/firstprivate/lastprivate vars and last_iter flag)
4333/// \code
4334/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4335/// lastpriv) {
4336/// // setup lastprivate flag
4337/// task_dst->last = lastpriv;
4338/// // could be constructor calls here...
4339/// }
4340/// \endcode
4341static llvm::Value *
4342emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4343 const OMPExecutableDirective &D,
4344 QualType KmpTaskTWithPrivatesPtrQTy,
4345 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4346 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4347 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4348 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
4349 auto &C = CGM.getContext();
4350 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004351 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4352 KmpTaskTWithPrivatesPtrQTy,
4353 ImplicitParamDecl::Other);
4354 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4355 KmpTaskTWithPrivatesPtrQTy,
4356 ImplicitParamDecl::Other);
4357 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4358 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004359 Args.push_back(&DstArg);
4360 Args.push_back(&SrcArg);
4361 Args.push_back(&LastprivArg);
4362 auto &TaskDupFnInfo =
4363 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
4364 auto *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
4365 auto *TaskDup =
4366 llvm::Function::Create(TaskDupTy, llvm::GlobalValue::InternalLinkage,
4367 ".omp_task_dup.", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004368 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskDup, TaskDupFnInfo);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004369 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004370 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args, Loc,
4371 Loc);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004372
4373 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4374 CGF.GetAddrOfLocalVar(&DstArg),
4375 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4376 // task_dst->liter = lastpriv;
4377 if (WithLastIter) {
4378 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4379 LValue Base = CGF.EmitLValueForField(
4380 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4381 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4382 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4383 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4384 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4385 }
4386
4387 // Emit initial values for private copies (if any).
4388 assert(!Privates.empty());
4389 Address KmpTaskSharedsPtr = Address::invalid();
4390 if (!Data.FirstprivateVars.empty()) {
4391 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4392 CGF.GetAddrOfLocalVar(&SrcArg),
4393 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4394 LValue Base = CGF.EmitLValueForField(
4395 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4396 KmpTaskSharedsPtr = Address(
4397 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4398 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4399 KmpTaskTShareds)),
4400 Loc),
4401 CGF.getNaturalTypeAlignment(SharedsTy));
4402 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004403 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4404 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004405 CGF.FinishFunction();
4406 return TaskDup;
4407}
4408
Alexey Bataev8a831592016-05-10 10:36:51 +00004409/// Checks if destructor function is required to be generated.
4410/// \return true if cleanups are required, false otherwise.
4411static bool
4412checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4413 bool NeedsCleanup = false;
4414 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4415 auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4416 for (auto *FD : PrivateRD->fields()) {
4417 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4418 if (NeedsCleanup)
4419 break;
4420 }
4421 return NeedsCleanup;
4422}
4423
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004424CGOpenMPRuntime::TaskResultTy
4425CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4426 const OMPExecutableDirective &D,
4427 llvm::Value *TaskFunction, QualType SharedsTy,
4428 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004429 auto &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004430 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004431 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004432 auto I = Data.PrivateCopies.begin();
4433 for (auto *E : Data.PrivateVars) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004434 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4435 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004436 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004437 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4438 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004439 ++I;
4440 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004441 I = Data.FirstprivateCopies.begin();
4442 auto IElemInitRef = Data.FirstprivateInits.begin();
4443 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev9e034042015-05-05 04:05:12 +00004444 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4445 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004446 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004447 PrivateHelpersTy(
4448 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4449 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
Richard Trieucc3949d2016-02-18 22:34:54 +00004450 ++I;
4451 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004452 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004453 I = Data.LastprivateCopies.begin();
4454 for (auto *E : Data.LastprivateVars) {
4455 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4456 Privates.push_back(std::make_pair(
4457 C.getDeclAlign(VD),
4458 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4459 /*PrivateElemInit=*/nullptr)));
4460 ++I;
4461 }
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004462 std::stable_sort(Privates.begin(), Privates.end(), stable_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004463 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
4464 // Build type kmp_routine_entry_t (if not built yet).
4465 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004466 // Build type kmp_task_t (if not built yet).
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004467 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
4468 if (SavedKmpTaskloopTQTy.isNull()) {
4469 SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4470 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4471 }
4472 KmpTaskTQTy = SavedKmpTaskloopTQTy;
Alexey Bataev3a03a7f2017-10-11 15:56:38 +00004473 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004474 assert((D.getDirectiveKind() == OMPD_task ||
4475 isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||
4476 isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) &&
4477 "Expected taskloop, task or target directive");
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004478 if (SavedKmpTaskTQTy.isNull()) {
4479 SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4480 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4481 }
4482 KmpTaskTQTy = SavedKmpTaskTQTy;
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004483 }
4484 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004485 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004486 auto *KmpTaskTWithPrivatesQTyRD =
4487 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
4488 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
4489 QualType KmpTaskTWithPrivatesPtrQTy =
4490 C.getPointerType(KmpTaskTWithPrivatesQTy);
4491 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4492 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004493 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004494 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4495
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004496 // Emit initial values for private copies (if any).
4497 llvm::Value *TaskPrivatesMap = nullptr;
4498 auto *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00004499 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004500 if (!Privates.empty()) {
4501 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004502 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4503 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4504 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004505 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4506 TaskPrivatesMap, TaskPrivatesMapTy);
4507 } else {
4508 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4509 cast<llvm::PointerType>(TaskPrivatesMapTy));
4510 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004511 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4512 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004513 auto *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004514 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4515 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4516 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004517
4518 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4519 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4520 // kmp_routine_entry_t *task_entry);
4521 // Task flags. Format is taken from
4522 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4523 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004524 enum {
4525 TiedFlag = 0x1,
4526 FinalFlag = 0x2,
4527 DestructorsFlag = 0x8,
4528 PriorityFlag = 0x20
4529 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004530 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004531 bool NeedsCleanup = false;
4532 if (!Privates.empty()) {
4533 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4534 if (NeedsCleanup)
4535 Flags = Flags | DestructorsFlag;
4536 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004537 if (Data.Priority.getInt())
4538 Flags = Flags | PriorityFlag;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004539 auto *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004540 Data.Final.getPointer()
4541 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00004542 CGF.Builder.getInt32(FinalFlag),
4543 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004544 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004545 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00004546 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004547 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4548 getThreadID(CGF, Loc), TaskFlags,
4549 KmpTaskTWithPrivatesTySize, SharedsSize,
4550 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4551 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00004552 auto *NewTask = CGF.EmitRuntimeCall(
4553 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004554 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4555 NewTask, KmpTaskTWithPrivatesPtrTy);
4556 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4557 KmpTaskTWithPrivatesQTy);
4558 LValue TDBase =
4559 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004560 // Fill the data in the resulting kmp_task_t record.
4561 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00004562 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004563 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00004564 KmpTaskSharedsPtr =
4565 Address(CGF.EmitLoadOfScalar(
4566 CGF.EmitLValueForField(
4567 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4568 KmpTaskTShareds)),
4569 Loc),
4570 CGF.getNaturalTypeAlignment(SharedsTy));
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004571 LValue Dest = CGF.MakeAddrLValue(KmpTaskSharedsPtr, SharedsTy);
4572 LValue Src = CGF.MakeAddrLValue(Shareds, SharedsTy);
4573 CGF.EmitAggregateCopy(Dest, Src, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004574 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004575 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00004576 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004577 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004578 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4579 SharedsTy, SharedsPtrTy, Data, Privates,
4580 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004581 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4582 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4583 Result.TaskDupFn = emitTaskDupFunction(
4584 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4585 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4586 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004587 }
4588 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00004589 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4590 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00004591 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00004592 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
4593 auto *KmpCmplrdataUD = (*FI)->getType()->getAsUnionType()->getDecl();
4594 if (NeedsCleanup) {
4595 llvm::Value *DestructorFn = emitDestructorsFunction(
4596 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4597 KmpTaskTWithPrivatesQTy);
4598 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4599 LValue DestructorsLV = CGF.EmitLValueForField(
4600 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4601 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4602 DestructorFn, KmpRoutineEntryPtrTy),
4603 DestructorsLV);
4604 }
4605 // Set priority.
4606 if (Data.Priority.getInt()) {
4607 LValue Data2LV = CGF.EmitLValueForField(
4608 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
4609 LValue PriorityLV = CGF.EmitLValueForField(
4610 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
4611 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
4612 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004613 Result.NewTask = NewTask;
4614 Result.TaskEntry = TaskEntry;
4615 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
4616 Result.TDBase = TDBase;
4617 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
4618 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00004619}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004620
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004621void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
4622 const OMPExecutableDirective &D,
4623 llvm::Value *TaskFunction,
4624 QualType SharedsTy, Address Shareds,
4625 const Expr *IfCond,
4626 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004627 if (!CGF.HaveInsertPoint())
4628 return;
4629
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004630 TaskResultTy Result =
4631 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4632 llvm::Value *NewTask = Result.NewTask;
4633 llvm::Value *TaskEntry = Result.TaskEntry;
4634 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
4635 LValue TDBase = Result.TDBase;
4636 RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
Alexey Bataev7292c292016-04-25 12:22:29 +00004637 auto &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004638 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00004639 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004640 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00004641 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004642 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00004643 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004644 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
4645 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004646 QualType FlagsTy =
4647 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004648 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
4649 if (KmpDependInfoTy.isNull()) {
4650 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
4651 KmpDependInfoRD->startDefinition();
4652 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
4653 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
4654 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
4655 KmpDependInfoRD->completeDefinition();
4656 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004657 } else
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004658 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
John McCall7f416cc2015-09-08 08:05:57 +00004659 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004660 // Define type kmp_depend_info[<Dependences.size()>];
4661 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00004662 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004663 ArrayType::Normal, /*IndexTypeQuals=*/0);
4664 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00004665 DependenciesArray =
4666 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
John McCall7f416cc2015-09-08 08:05:57 +00004667 for (unsigned i = 0; i < NumDependencies; ++i) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004668 const Expr *E = Data.Dependences[i].second;
John McCall7f416cc2015-09-08 08:05:57 +00004669 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004670 llvm::Value *Size;
4671 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004672 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
4673 LValue UpAddrLVal =
4674 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
4675 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00004676 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004677 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00004678 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004679 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
4680 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004681 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00004682 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00004683 auto Base = CGF.MakeAddrLValue(
4684 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004685 KmpDependInfoTy);
4686 // deps[i].base_addr = &<Dependences[i].second>;
4687 auto BaseAddrLVal = CGF.EmitLValueForField(
4688 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00004689 CGF.EmitStoreOfScalar(
4690 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
4691 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004692 // deps[i].len = sizeof(<Dependences[i].second>);
4693 auto LenLVal = CGF.EmitLValueForField(
4694 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
4695 CGF.EmitStoreOfScalar(Size, LenLVal);
4696 // deps[i].flags = <Dependences[i].first>;
4697 RTLDependenceKindTy DepKind;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004698 switch (Data.Dependences[i].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004699 case OMPC_DEPEND_in:
4700 DepKind = DepIn;
4701 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00004702 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004703 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004704 case OMPC_DEPEND_inout:
4705 DepKind = DepInOut;
4706 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00004707 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004708 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004709 case OMPC_DEPEND_unknown:
4710 llvm_unreachable("Unknown task dependence type");
4711 }
4712 auto FlagsLVal = CGF.EmitLValueForField(
4713 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
4714 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
4715 FlagsLVal);
4716 }
John McCall7f416cc2015-09-08 08:05:57 +00004717 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4718 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004719 CGF.VoidPtrTy);
4720 }
4721
Alexey Bataev62b63b12015-03-10 07:28:44 +00004722 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4723 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004724 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
4725 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
4726 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
4727 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00004728 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004729 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00004730 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
4731 llvm::Value *DepTaskArgs[7];
4732 if (NumDependencies) {
4733 DepTaskArgs[0] = UpLoc;
4734 DepTaskArgs[1] = ThreadID;
4735 DepTaskArgs[2] = NewTask;
4736 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
4737 DepTaskArgs[4] = DependenciesArray.getPointer();
4738 DepTaskArgs[5] = CGF.Builder.getInt32(0);
4739 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4740 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00004741 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
4742 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004743 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004744 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004745 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4746 auto PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
4747 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
4748 }
John McCall7f416cc2015-09-08 08:05:57 +00004749 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004750 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00004751 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00004752 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004753 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00004754 TaskArgs);
4755 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00004756 // Check if parent region is untied and build return for untied task;
4757 if (auto *Region =
4758 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4759 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00004760 };
John McCall7f416cc2015-09-08 08:05:57 +00004761
4762 llvm::Value *DepWaitTaskArgs[6];
4763 if (NumDependencies) {
4764 DepWaitTaskArgs[0] = UpLoc;
4765 DepWaitTaskArgs[1] = ThreadID;
4766 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
4767 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
4768 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
4769 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4770 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004771 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00004772 NumDependencies, &DepWaitTaskArgs,
4773 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004774 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004775 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
4776 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
4777 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
4778 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
4779 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00004780 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004781 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004782 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004783 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00004784 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
4785 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004786 Action.Enter(CGF);
4787 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00004788 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00004789 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004790 };
4791
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004792 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
4793 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004794 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
4795 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004796 RegionCodeGenTy RCG(CodeGen);
4797 CommonActionTy Action(
4798 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
4799 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
4800 RCG.setAction(Action);
4801 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004802 };
John McCall7f416cc2015-09-08 08:05:57 +00004803
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004804 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00004805 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004806 else {
4807 RegionCodeGenTy ThenRCG(ThenCodeGen);
4808 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00004809 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004810}
4811
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004812void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
4813 const OMPLoopDirective &D,
4814 llvm::Value *TaskFunction,
4815 QualType SharedsTy, Address Shareds,
4816 const Expr *IfCond,
4817 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004818 if (!CGF.HaveInsertPoint())
4819 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004820 TaskResultTy Result =
4821 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004822 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4823 // libcall.
4824 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
4825 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
4826 // sched, kmp_uint64 grainsize, void *task_dup);
4827 llvm::Value *ThreadID = getThreadID(CGF, Loc);
4828 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
4829 llvm::Value *IfVal;
4830 if (IfCond) {
4831 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
4832 /*isSigned=*/true);
4833 } else
4834 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
4835
4836 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004837 Result.TDBase,
4838 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004839 auto *LBVar =
4840 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
4841 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
4842 /*IsInitializer=*/true);
4843 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004844 Result.TDBase,
4845 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004846 auto *UBVar =
4847 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
4848 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
4849 /*IsInitializer=*/true);
4850 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004851 Result.TDBase,
4852 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataev7292c292016-04-25 12:22:29 +00004853 auto *StVar =
4854 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
4855 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
4856 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004857 // Store reductions address.
4858 LValue RedLVal = CGF.EmitLValueForField(
4859 Result.TDBase,
4860 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
4861 if (Data.Reductions)
4862 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
4863 else {
4864 CGF.EmitNullInitialization(RedLVal.getAddress(),
4865 CGF.getContext().VoidPtrTy);
4866 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004867 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00004868 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00004869 UpLoc,
4870 ThreadID,
4871 Result.NewTask,
4872 IfVal,
4873 LBLVal.getPointer(),
4874 UBLVal.getPointer(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00004875 CGF.EmitLoadOfScalar(StLVal, Loc),
Alexey Bataev33446032017-07-12 18:09:32 +00004876 llvm::ConstantInt::getNullValue(
4877 CGF.IntTy), // Always 0 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004878 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004879 CGF.IntTy, Data.Schedule.getPointer()
4880 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004881 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004882 Data.Schedule.getPointer()
4883 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004884 /*isSigned=*/false)
4885 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00004886 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4887 Result.TaskDupFn, CGF.VoidPtrTy)
4888 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00004889 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
4890}
4891
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004892/// \brief Emit reduction operation for each element of array (required for
4893/// array sections) LHS op = RHS.
4894/// \param Type Type of array.
4895/// \param LHSVar Variable on the left side of the reduction operation
4896/// (references element of array in original variable).
4897/// \param RHSVar Variable on the right side of the reduction operation
4898/// (references element of array in original variable).
4899/// \param RedOpGen Generator of reduction operation with use of LHSVar and
4900/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00004901static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004902 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
4903 const VarDecl *RHSVar,
4904 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
4905 const Expr *, const Expr *)> &RedOpGen,
4906 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
4907 const Expr *UpExpr = nullptr) {
4908 // Perform element-by-element initialization.
4909 QualType ElementTy;
4910 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
4911 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
4912
4913 // Drill down to the base element type on both arrays.
4914 auto ArrayTy = Type->getAsArrayTypeUnsafe();
4915 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
4916
4917 auto RHSBegin = RHSAddr.getPointer();
4918 auto LHSBegin = LHSAddr.getPointer();
4919 // Cast from pointer to array type to pointer to single element.
4920 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
4921 // The basic structure here is a while-do loop.
4922 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
4923 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
4924 auto IsEmpty =
4925 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
4926 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
4927
4928 // Enter the loop body, making that address the current address.
4929 auto EntryBB = CGF.Builder.GetInsertBlock();
4930 CGF.EmitBlock(BodyBB);
4931
4932 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
4933
4934 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
4935 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
4936 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
4937 Address RHSElementCurrent =
4938 Address(RHSElementPHI,
4939 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4940
4941 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
4942 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
4943 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
4944 Address LHSElementCurrent =
4945 Address(LHSElementPHI,
4946 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4947
4948 // Emit copy.
4949 CodeGenFunction::OMPPrivateScope Scope(CGF);
4950 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
4951 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
4952 Scope.Privatize();
4953 RedOpGen(CGF, XExpr, EExpr, UpExpr);
4954 Scope.ForceCleanup();
4955
4956 // Shift the address forward by one element.
4957 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
4958 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
4959 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
4960 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
4961 // Check whether we've reached the end.
4962 auto Done =
4963 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
4964 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
4965 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
4966 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
4967
4968 // Done.
4969 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
4970}
4971
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004972/// Emit reduction combiner. If the combiner is a simple expression emit it as
4973/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
4974/// UDR combiner function.
4975static void emitReductionCombiner(CodeGenFunction &CGF,
4976 const Expr *ReductionOp) {
4977 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
4978 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
4979 if (auto *DRE =
4980 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
4981 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
4982 std::pair<llvm::Function *, llvm::Function *> Reduction =
4983 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
4984 RValue Func = RValue::get(Reduction.first);
4985 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
4986 CGF.EmitIgnoredExpr(ReductionOp);
4987 return;
4988 }
4989 CGF.EmitIgnoredExpr(ReductionOp);
4990}
4991
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004992llvm::Value *CGOpenMPRuntime::emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004993 CodeGenModule &CGM, SourceLocation Loc, llvm::Type *ArgsType,
4994 ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs,
4995 ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004996 auto &C = CGM.getContext();
4997
4998 // void reduction_func(void *LHSArg, void *RHSArg);
4999 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005000 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5001 ImplicitParamDecl::Other);
5002 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5003 ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005004 Args.push_back(&LHSArg);
5005 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00005006 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005007 auto *Fn = llvm::Function::Create(
5008 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
5009 ".omp.reduction.reduction_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005010 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005011 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005012 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005013
5014 // Dst = (void*[n])(LHSArg);
5015 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00005016 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5017 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
5018 ArgsType), CGF.getPointerAlign());
5019 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5020 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
5021 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005022
5023 // ...
5024 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
5025 // ...
5026 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005027 auto IPriv = Privates.begin();
5028 unsigned Idx = 0;
5029 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00005030 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
5031 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005032 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005033 });
5034 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
5035 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005036 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005037 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005038 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00005039 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005040 // Get array size and emit VLA type.
5041 ++Idx;
5042 Address Elem =
5043 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
5044 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005045 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
5046 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005047 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00005048 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005049 CGF.EmitVariablyModifiedType(PrivTy);
5050 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005051 }
5052 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005053 IPriv = Privates.begin();
5054 auto ILHS = LHSExprs.begin();
5055 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005056 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005057 if ((*IPriv)->getType()->isArrayType()) {
5058 // Emit reduction for array section.
5059 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5060 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005061 EmitOMPAggregateReduction(
5062 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5063 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5064 emitReductionCombiner(CGF, E);
5065 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005066 } else
5067 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005068 emitReductionCombiner(CGF, E);
Richard Trieucc3949d2016-02-18 22:34:54 +00005069 ++IPriv;
5070 ++ILHS;
5071 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005072 }
5073 Scope.ForceCleanup();
5074 CGF.FinishFunction();
5075 return Fn;
5076}
5077
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005078void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
5079 const Expr *ReductionOp,
5080 const Expr *PrivateRef,
5081 const DeclRefExpr *LHS,
5082 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005083 if (PrivateRef->getType()->isArrayType()) {
5084 // Emit reduction for array section.
5085 auto *LHSVar = cast<VarDecl>(LHS->getDecl());
5086 auto *RHSVar = cast<VarDecl>(RHS->getDecl());
5087 EmitOMPAggregateReduction(
5088 CGF, PrivateRef->getType(), LHSVar, RHSVar,
5089 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5090 emitReductionCombiner(CGF, ReductionOp);
5091 });
5092 } else
5093 // Emit reduction for array subscript or single variable.
5094 emitReductionCombiner(CGF, ReductionOp);
5095}
5096
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005097void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005098 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005099 ArrayRef<const Expr *> LHSExprs,
5100 ArrayRef<const Expr *> RHSExprs,
5101 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005102 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005103 if (!CGF.HaveInsertPoint())
5104 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005105
5106 bool WithNowait = Options.WithNowait;
5107 bool SimpleReduction = Options.SimpleReduction;
5108
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005109 // Next code should be emitted for reduction:
5110 //
5111 // static kmp_critical_name lock = { 0 };
5112 //
5113 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
5114 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
5115 // ...
5116 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
5117 // *(Type<n>-1*)rhs[<n>-1]);
5118 // }
5119 //
5120 // ...
5121 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
5122 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5123 // RedList, reduce_func, &<lock>)) {
5124 // case 1:
5125 // ...
5126 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5127 // ...
5128 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5129 // break;
5130 // case 2:
5131 // ...
5132 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5133 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00005134 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005135 // break;
5136 // default:;
5137 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005138 //
5139 // if SimpleReduction is true, only the next code is generated:
5140 // ...
5141 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5142 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005143
5144 auto &C = CGM.getContext();
5145
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005146 if (SimpleReduction) {
5147 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005148 auto IPriv = Privates.begin();
5149 auto ILHS = LHSExprs.begin();
5150 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005151 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005152 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5153 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005154 ++IPriv;
5155 ++ILHS;
5156 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005157 }
5158 return;
5159 }
5160
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005161 // 1. Build a list of reduction variables.
5162 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005163 auto Size = RHSExprs.size();
5164 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005165 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005166 // Reserve place for array size.
5167 ++Size;
5168 }
5169 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005170 QualType ReductionArrayTy =
5171 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
5172 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00005173 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005174 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005175 auto IPriv = Privates.begin();
5176 unsigned Idx = 0;
5177 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00005178 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005179 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00005180 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005181 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00005182 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
5183 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005184 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005185 // Store array size.
5186 ++Idx;
5187 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
5188 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00005189 llvm::Value *Size = CGF.Builder.CreateIntCast(
5190 CGF.getVLASize(
5191 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
Sander de Smalen891af03a2018-02-03 13:55:59 +00005192 .NumElts,
Alexey Bataev1189bd02016-01-26 12:20:39 +00005193 CGF.SizeTy, /*isSigned=*/false);
5194 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
5195 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005196 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005197 }
5198
5199 // 2. Emit reduce_func().
5200 auto *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005201 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
5202 Privates, LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005203
5204 // 3. Create static kmp_critical_name lock = { 0 };
5205 auto *Lock = getCriticalRegionLock(".reduction");
5206
5207 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5208 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00005209 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005210 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005211 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
Samuel Antao4c8035b2016-12-12 18:00:20 +00005212 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5213 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005214 llvm::Value *Args[] = {
5215 IdentTLoc, // ident_t *<loc>
5216 ThreadId, // i32 <gtid>
5217 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5218 ReductionArrayTySize, // size_type sizeof(RedList)
5219 RL, // void *RedList
5220 ReductionFn, // void (*) (void *, void *) <reduce_func>
5221 Lock // kmp_critical_name *&<lock>
5222 };
5223 auto Res = CGF.EmitRuntimeCall(
5224 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5225 : OMPRTL__kmpc_reduce),
5226 Args);
5227
5228 // 5. Build switch(res)
5229 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5230 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
5231
5232 // 6. Build case 1:
5233 // ...
5234 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5235 // ...
5236 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5237 // break;
5238 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
5239 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5240 CGF.EmitBlock(Case1BB);
5241
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005242 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5243 llvm::Value *EndArgs[] = {
5244 IdentTLoc, // ident_t *<loc>
5245 ThreadId, // i32 <gtid>
5246 Lock // kmp_critical_name *&<lock>
5247 };
5248 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5249 CodeGenFunction &CGF, PrePostActionTy &Action) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005250 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005251 auto IPriv = Privates.begin();
5252 auto ILHS = LHSExprs.begin();
5253 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005254 for (auto *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005255 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5256 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005257 ++IPriv;
5258 ++ILHS;
5259 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005260 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005261 };
5262 RegionCodeGenTy RCG(CodeGen);
5263 CommonActionTy Action(
5264 nullptr, llvm::None,
5265 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5266 : OMPRTL__kmpc_end_reduce),
5267 EndArgs);
5268 RCG.setAction(Action);
5269 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005270
5271 CGF.EmitBranch(DefaultBB);
5272
5273 // 7. Build case 2:
5274 // ...
5275 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5276 // ...
5277 // break;
5278 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
5279 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5280 CGF.EmitBlock(Case2BB);
5281
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005282 auto &&AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5283 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005284 auto ILHS = LHSExprs.begin();
5285 auto IRHS = RHSExprs.begin();
5286 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005287 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005288 const Expr *XExpr = nullptr;
5289 const Expr *EExpr = nullptr;
5290 const Expr *UpExpr = nullptr;
5291 BinaryOperatorKind BO = BO_Comma;
5292 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
5293 if (BO->getOpcode() == BO_Assign) {
5294 XExpr = BO->getLHS();
5295 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005296 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005297 }
5298 // Try to emit update expression as a simple atomic.
5299 auto *RHSExpr = UpExpr;
5300 if (RHSExpr) {
5301 // Analyze RHS part of the whole expression.
5302 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
5303 RHSExpr->IgnoreParenImpCasts())) {
5304 // If this is a conditional operator, analyze its condition for
5305 // min/max reduction operator.
5306 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005307 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005308 if (auto *BORHS =
5309 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5310 EExpr = BORHS->getRHS();
5311 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005312 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005313 }
5314 if (XExpr) {
5315 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005316 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005317 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5318 const Expr *EExpr, const Expr *UpExpr) {
5319 LValue X = CGF.EmitLValue(XExpr);
5320 RValue E;
5321 if (EExpr)
5322 E = CGF.EmitAnyExpr(EExpr);
5323 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005324 X, E, BO, /*IsXLHSInRHSPart=*/true,
5325 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005326 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005327 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5328 PrivateScope.addPrivate(
5329 VD, [&CGF, VD, XRValue, Loc]() -> Address {
5330 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5331 CGF.emitOMPSimpleStore(
5332 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5333 VD->getType().getNonReferenceType(), Loc);
5334 return LHSTemp;
5335 });
5336 (void)PrivateScope.Privatize();
5337 return CGF.EmitAnyExpr(UpExpr);
5338 });
5339 };
5340 if ((*IPriv)->getType()->isArrayType()) {
5341 // Emit atomic reduction for array section.
5342 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5343 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5344 AtomicRedGen, XExpr, EExpr, UpExpr);
5345 } else
5346 // Emit atomic reduction for array subscript or single variable.
5347 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
5348 } else {
5349 // Emit as a critical region.
5350 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
5351 const Expr *, const Expr *) {
5352 auto &RT = CGF.CGM.getOpenMPRuntime();
5353 RT.emitCriticalRegion(
5354 CGF, ".atomic_reduction",
5355 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5356 Action.Enter(CGF);
5357 emitReductionCombiner(CGF, E);
5358 },
5359 Loc);
5360 };
5361 if ((*IPriv)->getType()->isArrayType()) {
5362 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5363 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5364 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5365 CritRedGen);
5366 } else
5367 CritRedGen(CGF, nullptr, nullptr, nullptr);
5368 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005369 ++ILHS;
5370 ++IRHS;
5371 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005372 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005373 };
5374 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5375 if (!WithNowait) {
5376 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5377 llvm::Value *EndArgs[] = {
5378 IdentTLoc, // ident_t *<loc>
5379 ThreadId, // i32 <gtid>
5380 Lock // kmp_critical_name *&<lock>
5381 };
5382 CommonActionTy Action(nullptr, llvm::None,
5383 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5384 EndArgs);
5385 AtomicRCG.setAction(Action);
5386 AtomicRCG(CGF);
5387 } else
5388 AtomicRCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005389
5390 CGF.EmitBranch(DefaultBB);
5391 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5392}
5393
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005394/// Generates unique name for artificial threadprivate variables.
Alexey Bataev1c44e152018-03-06 18:59:43 +00005395/// Format is: <Prefix> "." <Decl_mangled_name> "_" "<Decl_start_loc_raw_enc>"
5396static std::string generateUniqueName(CodeGenModule &CGM, StringRef Prefix,
5397 const Expr *Ref) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005398 SmallString<256> Buffer;
5399 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev1c44e152018-03-06 18:59:43 +00005400 const clang::DeclRefExpr *DE;
5401 const VarDecl *D = ::getBaseDecl(Ref, DE);
5402 if (!D)
5403 D = cast<VarDecl>(cast<DeclRefExpr>(Ref)->getDecl());
5404 D = D->getCanonicalDecl();
5405 Out << Prefix << "."
5406 << (D->isLocalVarDeclOrParm() ? D->getName() : CGM.getMangledName(D))
5407 << "_" << D->getCanonicalDecl()->getLocStart().getRawEncoding();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005408 return Out.str();
5409}
5410
5411/// Emits reduction initializer function:
5412/// \code
5413/// void @.red_init(void* %arg) {
5414/// %0 = bitcast void* %arg to <type>*
5415/// store <type> <init>, <type>* %0
5416/// ret void
5417/// }
5418/// \endcode
5419static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5420 SourceLocation Loc,
5421 ReductionCodeGen &RCG, unsigned N) {
5422 auto &C = CGM.getContext();
5423 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005424 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5425 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005426 Args.emplace_back(&Param);
5427 auto &FnInfo =
5428 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5429 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5430 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5431 ".red_init.", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005432 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005433 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005434 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005435 Address PrivateAddr = CGF.EmitLoadOfPointer(
5436 CGF.GetAddrOfLocalVar(&Param),
5437 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5438 llvm::Value *Size = nullptr;
5439 // If the size of the reduction item is non-constant, load it from global
5440 // threadprivate variable.
5441 if (RCG.getSizes(N).second) {
5442 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5443 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005444 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005445 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5446 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005447 }
5448 RCG.emitAggregateType(CGF, N, Size);
5449 LValue SharedLVal;
5450 // If initializer uses initializer from declare reduction construct, emit a
5451 // pointer to the address of the original reduction item (reuired by reduction
5452 // initializer)
5453 if (RCG.usesReductionInitializer(N)) {
5454 Address SharedAddr =
5455 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5456 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00005457 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataev21dab122018-03-09 15:20:30 +00005458 SharedAddr = CGF.EmitLoadOfPointer(
5459 SharedAddr,
5460 CGM.getContext().VoidPtrTy.castAs<PointerType>()->getTypePtr());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005461 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5462 } else {
5463 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5464 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5465 CGM.getContext().VoidPtrTy);
5466 }
5467 // Emit the initializer:
5468 // %0 = bitcast void* %arg to <type>*
5469 // store <type> <init>, <type>* %0
5470 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5471 [](CodeGenFunction &) { return false; });
5472 CGF.FinishFunction();
5473 return Fn;
5474}
5475
5476/// Emits reduction combiner function:
5477/// \code
5478/// void @.red_comb(void* %arg0, void* %arg1) {
5479/// %lhs = bitcast void* %arg0 to <type>*
5480/// %rhs = bitcast void* %arg1 to <type>*
5481/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5482/// store <type> %2, <type>* %lhs
5483/// ret void
5484/// }
5485/// \endcode
5486static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5487 SourceLocation Loc,
5488 ReductionCodeGen &RCG, unsigned N,
5489 const Expr *ReductionOp,
5490 const Expr *LHS, const Expr *RHS,
5491 const Expr *PrivateRef) {
5492 auto &C = CGM.getContext();
5493 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5494 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
5495 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005496 ImplicitParamDecl ParamInOut(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
5497 C.VoidPtrTy, ImplicitParamDecl::Other);
5498 ImplicitParamDecl ParamIn(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5499 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005500 Args.emplace_back(&ParamInOut);
5501 Args.emplace_back(&ParamIn);
5502 auto &FnInfo =
5503 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5504 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5505 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5506 ".red_comb.", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005507 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005508 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005509 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005510 llvm::Value *Size = nullptr;
5511 // If the size of the reduction item is non-constant, load it from global
5512 // threadprivate variable.
5513 if (RCG.getSizes(N).second) {
5514 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5515 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005516 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005517 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5518 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005519 }
5520 RCG.emitAggregateType(CGF, N, Size);
5521 // Remap lhs and rhs variables to the addresses of the function arguments.
5522 // %lhs = bitcast void* %arg0 to <type>*
5523 // %rhs = bitcast void* %arg1 to <type>*
5524 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5525 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() -> Address {
5526 // Pull out the pointer to the variable.
5527 Address PtrAddr = CGF.EmitLoadOfPointer(
5528 CGF.GetAddrOfLocalVar(&ParamInOut),
5529 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5530 return CGF.Builder.CreateElementBitCast(
5531 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
5532 });
5533 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() -> Address {
5534 // Pull out the pointer to the variable.
5535 Address PtrAddr = CGF.EmitLoadOfPointer(
5536 CGF.GetAddrOfLocalVar(&ParamIn),
5537 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5538 return CGF.Builder.CreateElementBitCast(
5539 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
5540 });
5541 PrivateScope.Privatize();
5542 // Emit the combiner body:
5543 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
5544 // store <type> %2, <type>* %lhs
5545 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
5546 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
5547 cast<DeclRefExpr>(RHS));
5548 CGF.FinishFunction();
5549 return Fn;
5550}
5551
5552/// Emits reduction finalizer function:
5553/// \code
5554/// void @.red_fini(void* %arg) {
5555/// %0 = bitcast void* %arg to <type>*
5556/// <destroy>(<type>* %0)
5557/// ret void
5558/// }
5559/// \endcode
5560static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
5561 SourceLocation Loc,
5562 ReductionCodeGen &RCG, unsigned N) {
5563 if (!RCG.needCleanups(N))
5564 return nullptr;
5565 auto &C = CGM.getContext();
5566 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005567 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5568 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005569 Args.emplace_back(&Param);
5570 auto &FnInfo =
5571 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5572 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5573 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5574 ".red_fini.", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005575 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005576 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005577 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005578 Address PrivateAddr = CGF.EmitLoadOfPointer(
5579 CGF.GetAddrOfLocalVar(&Param),
5580 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5581 llvm::Value *Size = nullptr;
5582 // If the size of the reduction item is non-constant, load it from global
5583 // threadprivate variable.
5584 if (RCG.getSizes(N).second) {
5585 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5586 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005587 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005588 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5589 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005590 }
5591 RCG.emitAggregateType(CGF, N, Size);
5592 // Emit the finalizer body:
5593 // <destroy>(<type>* %0)
5594 RCG.emitCleanups(CGF, N, PrivateAddr);
5595 CGF.FinishFunction();
5596 return Fn;
5597}
5598
5599llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
5600 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
5601 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
5602 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
5603 return nullptr;
5604
5605 // Build typedef struct:
5606 // kmp_task_red_input {
5607 // void *reduce_shar; // shared reduction item
5608 // size_t reduce_size; // size of data item
5609 // void *reduce_init; // data initialization routine
5610 // void *reduce_fini; // data finalization routine
5611 // void *reduce_comb; // data combiner routine
5612 // kmp_task_red_flags_t flags; // flags for additional info from compiler
5613 // } kmp_task_red_input_t;
5614 ASTContext &C = CGM.getContext();
5615 auto *RD = C.buildImplicitRecord("kmp_task_red_input_t");
5616 RD->startDefinition();
5617 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5618 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
5619 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5620 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5621 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5622 const FieldDecl *FlagsFD = addFieldToRecordDecl(
5623 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
5624 RD->completeDefinition();
5625 QualType RDType = C.getRecordType(RD);
5626 unsigned Size = Data.ReductionVars.size();
5627 llvm::APInt ArraySize(/*numBits=*/64, Size);
5628 QualType ArrayRDType = C.getConstantArrayType(
5629 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5630 // kmp_task_red_input_t .rd_input.[Size];
5631 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
5632 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
5633 Data.ReductionOps);
5634 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
5635 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
5636 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
5637 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
5638 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
5639 TaskRedInput.getPointer(), Idxs,
5640 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
5641 ".rd_input.gep.");
5642 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
5643 // ElemLVal.reduce_shar = &Shareds[Cnt];
5644 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
5645 RCG.emitSharedLValue(CGF, Cnt);
5646 llvm::Value *CastedShared =
5647 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
5648 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
5649 RCG.emitAggregateType(CGF, Cnt);
5650 llvm::Value *SizeValInChars;
5651 llvm::Value *SizeVal;
5652 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
5653 // We use delayed creation/initialization for VLAs, array sections and
5654 // custom reduction initializations. It is required because runtime does not
5655 // provide the way to pass the sizes of VLAs/array sections to
5656 // initializer/combiner/finalizer functions and does not pass the pointer to
5657 // original reduction item to the initializer. Instead threadprivate global
5658 // variables are used to store these values and use them in the functions.
5659 bool DelayedCreation = !!SizeVal;
5660 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
5661 /*isSigned=*/false);
5662 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
5663 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
5664 // ElemLVal.reduce_init = init;
5665 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
5666 llvm::Value *InitAddr =
5667 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
5668 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
5669 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
5670 // ElemLVal.reduce_fini = fini;
5671 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
5672 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
5673 llvm::Value *FiniAddr = Fini
5674 ? CGF.EmitCastToVoidPtr(Fini)
5675 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
5676 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
5677 // ElemLVal.reduce_comb = comb;
5678 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
5679 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
5680 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
5681 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
5682 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
5683 // ElemLVal.flags = 0;
5684 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
5685 if (DelayedCreation) {
5686 CGF.EmitStoreOfScalar(
5687 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
5688 FlagsLVal);
5689 } else
5690 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
5691 }
5692 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
5693 // *data);
5694 llvm::Value *Args[] = {
5695 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5696 /*isSigned=*/true),
5697 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
5698 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
5699 CGM.VoidPtrTy)};
5700 return CGF.EmitRuntimeCall(
5701 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
5702}
5703
5704void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
5705 SourceLocation Loc,
5706 ReductionCodeGen &RCG,
5707 unsigned N) {
5708 auto Sizes = RCG.getSizes(N);
5709 // Emit threadprivate global variable if the type is non-constant
5710 // (Sizes.second = nullptr).
5711 if (Sizes.second) {
5712 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
5713 /*isSigned=*/false);
5714 Address SizeAddr = getAddrOfArtificialThreadPrivate(
5715 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005716 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005717 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
5718 }
5719 // Store address of the original reduction item if custom initializer is used.
5720 if (RCG.usesReductionInitializer(N)) {
5721 Address SharedAddr = getAddrOfArtificialThreadPrivate(
5722 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00005723 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005724 CGF.Builder.CreateStore(
5725 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5726 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
5727 SharedAddr, /*IsVolatile=*/false);
5728 }
5729}
5730
5731Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
5732 SourceLocation Loc,
5733 llvm::Value *ReductionsPtr,
5734 LValue SharedLVal) {
5735 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
5736 // *d);
5737 llvm::Value *Args[] = {
5738 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5739 /*isSigned=*/true),
5740 ReductionsPtr,
5741 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
5742 CGM.VoidPtrTy)};
5743 return Address(
5744 CGF.EmitRuntimeCall(
5745 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
5746 SharedLVal.getAlignment());
5747}
5748
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005749void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
5750 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005751 if (!CGF.HaveInsertPoint())
5752 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005753 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
5754 // global_tid);
5755 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
5756 // Ignore return result until untied tasks are supported.
5757 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005758 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5759 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005760}
5761
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005762void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005763 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005764 const RegionCodeGenTy &CodeGen,
5765 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005766 if (!CGF.HaveInsertPoint())
5767 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005768 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005769 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00005770}
5771
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005772namespace {
5773enum RTCancelKind {
5774 CancelNoreq = 0,
5775 CancelParallel = 1,
5776 CancelLoop = 2,
5777 CancelSections = 3,
5778 CancelTaskgroup = 4
5779};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00005780} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005781
5782static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
5783 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00005784 if (CancelRegion == OMPD_parallel)
5785 CancelKind = CancelParallel;
5786 else if (CancelRegion == OMPD_for)
5787 CancelKind = CancelLoop;
5788 else if (CancelRegion == OMPD_sections)
5789 CancelKind = CancelSections;
5790 else {
5791 assert(CancelRegion == OMPD_taskgroup);
5792 CancelKind = CancelTaskgroup;
5793 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005794 return CancelKind;
5795}
5796
5797void CGOpenMPRuntime::emitCancellationPointCall(
5798 CodeGenFunction &CGF, SourceLocation Loc,
5799 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005800 if (!CGF.HaveInsertPoint())
5801 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005802 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
5803 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005804 if (auto *OMPRegionInfo =
5805 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00005806 // For 'cancellation point taskgroup', the task region info may not have a
5807 // cancel. This may instead happen in another adjacent task.
5808 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005809 llvm::Value *Args[] = {
5810 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
5811 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005812 // Ignore return result until untied tasks are supported.
5813 auto *Result = CGF.EmitRuntimeCall(
5814 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
5815 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005816 // exit from construct;
5817 // }
5818 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5819 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5820 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5821 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5822 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005823 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005824 auto CancelDest =
5825 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005826 CGF.EmitBranchThroughCleanup(CancelDest);
5827 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5828 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005829 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005830}
5831
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005832void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00005833 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005834 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005835 if (!CGF.HaveInsertPoint())
5836 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005837 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
5838 // kmp_int32 cncl_kind);
5839 if (auto *OMPRegionInfo =
5840 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005841 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
5842 PrePostActionTy &) {
5843 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00005844 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005845 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00005846 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
5847 // Ignore return result until untied tasks are supported.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005848 auto *Result = CGF.EmitRuntimeCall(
5849 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00005850 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00005851 // exit from construct;
5852 // }
5853 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5854 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5855 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5856 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5857 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00005858 // exit from construct;
5859 auto CancelDest =
5860 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
5861 CGF.EmitBranchThroughCleanup(CancelDest);
5862 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5863 };
5864 if (IfCond)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005865 emitOMPIfClause(CGF, IfCond, ThenGen,
5866 [](CodeGenFunction &, PrePostActionTy &) {});
5867 else {
5868 RegionCodeGenTy ThenRCG(ThenGen);
5869 ThenRCG(CGF);
5870 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005871 }
5872}
Samuel Antaobed3c462015-10-02 16:14:20 +00005873
Samuel Antaoee8fb302016-01-06 13:42:12 +00005874/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00005875/// consists of the file and device IDs as well as line number associated with
5876/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005877static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
5878 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005879 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005880
5881 auto &SM = C.getSourceManager();
5882
5883 // The loc should be always valid and have a file ID (the user cannot use
5884 // #pragma directives in macros)
5885
5886 assert(Loc.isValid() && "Source location is expected to be always valid.");
5887 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
5888
5889 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
5890 assert(PLoc.isValid() && "Source location is expected to be always valid.");
5891
5892 llvm::sys::fs::UniqueID ID;
5893 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
5894 llvm_unreachable("Source file with target region no longer exists!");
5895
5896 DeviceID = ID.getDevice();
5897 FileID = ID.getFile();
5898 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00005899}
5900
5901void CGOpenMPRuntime::emitTargetOutlinedFunction(
5902 const OMPExecutableDirective &D, StringRef ParentName,
5903 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005904 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005905 assert(!ParentName.empty() && "Invalid target region parent name!");
5906
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005907 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
5908 IsOffloadEntry, CodeGen);
5909}
5910
5911void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
5912 const OMPExecutableDirective &D, StringRef ParentName,
5913 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
5914 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00005915 // Create a unique name for the entry function using the source location
5916 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00005917 //
Samuel Antao2de62b02016-02-13 23:35:10 +00005918 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00005919 //
5920 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00005921 // mangled name of the function that encloses the target region and BB is the
5922 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005923
5924 unsigned DeviceID;
5925 unsigned FileID;
5926 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005927 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005928 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005929 SmallString<64> EntryFnName;
5930 {
5931 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00005932 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
5933 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005934 }
5935
Alexey Bataev475a7442018-01-12 19:39:11 +00005936 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005937
Samuel Antaobed3c462015-10-02 16:14:20 +00005938 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005939 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00005940 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005941
Samuel Antao6d004262016-06-16 18:39:34 +00005942 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005943
5944 // If this target outline function is not an offload entry, we don't need to
5945 // register it.
5946 if (!IsOffloadEntry)
5947 return;
5948
5949 // The target region ID is used by the runtime library to identify the current
5950 // target region, so it only has to be unique and not necessarily point to
5951 // anything. It could be the pointer to the outlined function that implements
5952 // the target region, but we aren't using that so that the compiler doesn't
5953 // need to keep that, and could therefore inline the host function if proven
5954 // worthwhile during optimization. In the other hand, if emitting code for the
5955 // device, the ID has to be the function address so that it can retrieved from
5956 // the offloading entry and launched by the runtime library. We also mark the
5957 // outlined function to have external linkage in case we are emitting code for
5958 // the device, because these functions will be entry points to the device.
5959
5960 if (CGM.getLangOpts().OpenMPIsDevice) {
5961 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
5962 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
Rafael Espindolacbca4872018-01-11 22:15:12 +00005963 OutlinedFn->setDSOLocal(false);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005964 } else
5965 OutlinedFnID = new llvm::GlobalVariable(
5966 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
5967 llvm::GlobalValue::PrivateLinkage,
5968 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
5969
5970 // Register the information for the entry associated with this target region.
5971 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00005972 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
5973 /*Flags=*/0);
Samuel Antaobed3c462015-10-02 16:14:20 +00005974}
5975
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005976/// discard all CompoundStmts intervening between two constructs
5977static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
5978 while (auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
5979 Body = CS->body_front();
5980
5981 return Body;
5982}
5983
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005984/// Emit the number of teams for a target directive. Inspect the num_teams
5985/// clause associated with a teams construct combined or closely nested
5986/// with the target directive.
5987///
5988/// Emit a team of size one for directives such as 'target parallel' that
5989/// have no associated teams construct.
5990///
5991/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00005992static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005993emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
5994 CodeGenFunction &CGF,
5995 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005996
5997 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
5998 "teams directive expected to be "
5999 "emitted only for the host!");
6000
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006001 auto &Bld = CGF.Builder;
6002
6003 // If the target directive is combined with a teams directive:
6004 // Return the value in the num_teams clause, if any.
6005 // Otherwise, return 0 to denote the runtime default.
6006 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
6007 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
6008 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
6009 auto NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
6010 /*IgnoreResultAssign*/ true);
6011 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6012 /*IsSigned=*/true);
6013 }
6014
6015 // The default value is 0.
6016 return Bld.getInt32(0);
6017 }
6018
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006019 // If the target directive is combined with a parallel directive but not a
6020 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006021 if (isOpenMPParallelDirective(D.getDirectiveKind()))
6022 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006023
6024 // If the current target region has a teams region enclosed, we need to get
6025 // the number of teams to pass to the runtime function call. This is done
6026 // by generating the expression in a inlined region. This is required because
6027 // the expression is captured in the enclosing target environment when the
6028 // teams directive is not combined with target.
6029
Alexey Bataev475a7442018-01-12 19:39:11 +00006030 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006031
Alexey Bataev50a1c782017-12-01 21:31:08 +00006032 if (auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006033 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006034 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
6035 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
6036 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6037 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6038 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
6039 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6040 /*IsSigned=*/true);
6041 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006042
Alexey Bataev50a1c782017-12-01 21:31:08 +00006043 // If we have an enclosed teams directive but no num_teams clause we use
6044 // the default value 0.
6045 return Bld.getInt32(0);
6046 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006047 }
6048
6049 // No teams associated with the directive.
6050 return nullptr;
6051}
6052
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006053/// Emit the number of threads for a target directive. Inspect the
6054/// thread_limit clause associated with a teams construct combined or closely
6055/// nested with the target directive.
6056///
6057/// Emit the num_threads clause for directives such as 'target parallel' that
6058/// have no associated teams construct.
6059///
6060/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006061static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006062emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6063 CodeGenFunction &CGF,
6064 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006065
6066 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6067 "teams directive expected to be "
6068 "emitted only for the host!");
6069
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006070 auto &Bld = CGF.Builder;
6071
6072 //
6073 // If the target directive is combined with a teams directive:
6074 // Return the value in the thread_limit clause, if any.
6075 //
6076 // If the target directive is combined with a parallel directive:
6077 // Return the value in the num_threads clause, if any.
6078 //
6079 // If both clauses are set, select the minimum of the two.
6080 //
6081 // If neither teams or parallel combined directives set the number of threads
6082 // in a team, return 0 to denote the runtime default.
6083 //
6084 // If this is not a teams directive return nullptr.
6085
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006086 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
6087 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006088 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
6089 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006090 llvm::Value *ThreadLimitVal = nullptr;
6091
6092 if (const auto *ThreadLimitClause =
6093 D.getSingleClause<OMPThreadLimitClause>()) {
6094 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
6095 auto ThreadLimit = CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
6096 /*IgnoreResultAssign*/ true);
6097 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6098 /*IsSigned=*/true);
6099 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006100
6101 if (const auto *NumThreadsClause =
6102 D.getSingleClause<OMPNumThreadsClause>()) {
6103 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
6104 llvm::Value *NumThreads =
6105 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
6106 /*IgnoreResultAssign*/ true);
6107 NumThreadsVal =
6108 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
6109 }
6110
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006111 // Select the lesser of thread_limit and num_threads.
6112 if (NumThreadsVal)
6113 ThreadLimitVal = ThreadLimitVal
6114 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
6115 ThreadLimitVal),
6116 NumThreadsVal, ThreadLimitVal)
6117 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00006118
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006119 // Set default value passed to the runtime if either teams or a target
6120 // parallel type directive is found but no clause is specified.
6121 if (!ThreadLimitVal)
6122 ThreadLimitVal = DefaultThreadLimitVal;
6123
6124 return ThreadLimitVal;
6125 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00006126
Samuel Antaob68e2db2016-03-03 16:20:23 +00006127 // If the current target region has a teams region enclosed, we need to get
6128 // the thread limit to pass to the runtime function call. This is done
6129 // by generating the expression in a inlined region. This is required because
6130 // the expression is captured in the enclosing target environment when the
6131 // teams directive is not combined with target.
6132
Alexey Bataev475a7442018-01-12 19:39:11 +00006133 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006134
Alexey Bataev50a1c782017-12-01 21:31:08 +00006135 if (auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006136 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006137 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
6138 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
6139 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6140 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6141 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
6142 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6143 /*IsSigned=*/true);
6144 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006145
Alexey Bataev50a1c782017-12-01 21:31:08 +00006146 // If we have an enclosed teams directive but no thread_limit clause we
6147 // use the default value 0.
6148 return CGF.Builder.getInt32(0);
6149 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006150 }
6151
6152 // No teams associated with the directive.
6153 return nullptr;
6154}
6155
Samuel Antao86ace552016-04-27 22:40:57 +00006156namespace {
6157// \brief Utility to handle information from clauses associated with a given
6158// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
6159// It provides a convenient interface to obtain the information and generate
6160// code for that information.
6161class MappableExprsHandler {
6162public:
6163 /// \brief Values for bit flags used to specify the mapping type for
6164 /// offloading.
6165 enum OpenMPOffloadMappingFlags {
Samuel Antao86ace552016-04-27 22:40:57 +00006166 /// \brief Allocate memory on the device and move data from host to device.
6167 OMP_MAP_TO = 0x01,
6168 /// \brief Allocate memory on the device and move data from device to host.
6169 OMP_MAP_FROM = 0x02,
6170 /// \brief Always perform the requested mapping action on the element, even
6171 /// if it was already mapped before.
6172 OMP_MAP_ALWAYS = 0x04,
Samuel Antao86ace552016-04-27 22:40:57 +00006173 /// \brief Delete the element from the device environment, ignoring the
6174 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00006175 OMP_MAP_DELETE = 0x08,
George Rokos065755d2017-11-07 18:27:04 +00006176 /// \brief The element being mapped is a pointer-pointee pair; both the
6177 /// pointer and the pointee should be mapped.
6178 OMP_MAP_PTR_AND_OBJ = 0x10,
6179 /// \brief This flags signals that the base address of an entry should be
6180 /// passed to the target kernel as an argument.
6181 OMP_MAP_TARGET_PARAM = 0x20,
Samuel Antaocc10b852016-07-28 14:23:26 +00006182 /// \brief Signal that the runtime library has to return the device pointer
George Rokos065755d2017-11-07 18:27:04 +00006183 /// in the current position for the data being mapped. Used when we have the
6184 /// use_device_ptr clause.
6185 OMP_MAP_RETURN_PARAM = 0x40,
Samuel Antaod486f842016-05-26 16:53:38 +00006186 /// \brief This flag signals that the reference being passed is a pointer to
6187 /// private data.
George Rokos065755d2017-11-07 18:27:04 +00006188 OMP_MAP_PRIVATE = 0x80,
Samuel Antao86ace552016-04-27 22:40:57 +00006189 /// \brief Pass the element to the device by value.
George Rokos065755d2017-11-07 18:27:04 +00006190 OMP_MAP_LITERAL = 0x100,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006191 /// Implicit map
6192 OMP_MAP_IMPLICIT = 0x200,
Samuel Antao86ace552016-04-27 22:40:57 +00006193 };
6194
Samuel Antaocc10b852016-07-28 14:23:26 +00006195 /// Class that associates information with a base pointer to be passed to the
6196 /// runtime library.
6197 class BasePointerInfo {
6198 /// The base pointer.
6199 llvm::Value *Ptr = nullptr;
6200 /// The base declaration that refers to this device pointer, or null if
6201 /// there is none.
6202 const ValueDecl *DevPtrDecl = nullptr;
6203
6204 public:
6205 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
6206 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
6207 llvm::Value *operator*() const { return Ptr; }
6208 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
6209 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
6210 };
6211
6212 typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00006213 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
George Rokos63bc9d62017-11-21 18:25:12 +00006214 typedef SmallVector<uint64_t, 16> MapFlagsArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00006215
6216private:
6217 /// \brief Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00006218 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00006219
6220 /// \brief Function the directive is being generated for.
6221 CodeGenFunction &CGF;
6222
Samuel Antaod486f842016-05-26 16:53:38 +00006223 /// \brief Set of all first private variables in the current directive.
6224 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
Alexey Bataev3f96fe62017-12-13 17:31:39 +00006225 /// Set of all reduction variables in the current directive.
6226 llvm::SmallPtrSet<const VarDecl *, 8> ReductionDecls;
Samuel Antaod486f842016-05-26 16:53:38 +00006227
Samuel Antao6890b092016-07-28 14:25:09 +00006228 /// Map between device pointer declarations and their expression components.
6229 /// The key value for declarations in 'this' is null.
6230 llvm::DenseMap<
6231 const ValueDecl *,
6232 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6233 DevPointersMap;
6234
Samuel Antao86ace552016-04-27 22:40:57 +00006235 llvm::Value *getExprTypeSize(const Expr *E) const {
6236 auto ExprTy = E->getType().getCanonicalType();
6237
6238 // Reference types are ignored for mapping purposes.
6239 if (auto *RefTy = ExprTy->getAs<ReferenceType>())
6240 ExprTy = RefTy->getPointeeType().getCanonicalType();
6241
6242 // Given that an array section is considered a built-in type, we need to
6243 // do the calculation based on the length of the section instead of relying
6244 // on CGF.getTypeSize(E->getType()).
6245 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6246 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6247 OAE->getBase()->IgnoreParenImpCasts())
6248 .getCanonicalType();
6249
6250 // If there is no length associated with the expression, that means we
6251 // are using the whole length of the base.
6252 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6253 return CGF.getTypeSize(BaseTy);
6254
6255 llvm::Value *ElemSize;
6256 if (auto *PTy = BaseTy->getAs<PointerType>())
6257 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
6258 else {
6259 auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
6260 assert(ATy && "Expecting array type if not a pointer type.");
6261 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6262 }
6263
6264 // If we don't have a length at this point, that is because we have an
6265 // array section with a single element.
6266 if (!OAE->getLength())
6267 return ElemSize;
6268
6269 auto *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
6270 LengthVal =
6271 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6272 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6273 }
6274 return CGF.getTypeSize(ExprTy);
6275 }
6276
6277 /// \brief Return the corresponding bits for a given map clause modifier. Add
6278 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006279 /// map as the first one of a series of maps that relate to the same map
6280 /// expression.
George Rokos63bc9d62017-11-21 18:25:12 +00006281 uint64_t getMapTypeBits(OpenMPMapClauseKind MapType,
Samuel Antao86ace552016-04-27 22:40:57 +00006282 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
George Rokos065755d2017-11-07 18:27:04 +00006283 bool AddIsTargetParamFlag) const {
George Rokos63bc9d62017-11-21 18:25:12 +00006284 uint64_t Bits = 0u;
Samuel Antao86ace552016-04-27 22:40:57 +00006285 switch (MapType) {
6286 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006287 case OMPC_MAP_release:
6288 // alloc and release is the default behavior in the runtime library, i.e.
6289 // if we don't pass any bits alloc/release that is what the runtime is
6290 // going to do. Therefore, we don't need to signal anything for these two
6291 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006292 break;
6293 case OMPC_MAP_to:
6294 Bits = OMP_MAP_TO;
6295 break;
6296 case OMPC_MAP_from:
6297 Bits = OMP_MAP_FROM;
6298 break;
6299 case OMPC_MAP_tofrom:
6300 Bits = OMP_MAP_TO | OMP_MAP_FROM;
6301 break;
6302 case OMPC_MAP_delete:
6303 Bits = OMP_MAP_DELETE;
6304 break;
Samuel Antao86ace552016-04-27 22:40:57 +00006305 default:
6306 llvm_unreachable("Unexpected map type!");
6307 break;
6308 }
6309 if (AddPtrFlag)
George Rokos065755d2017-11-07 18:27:04 +00006310 Bits |= OMP_MAP_PTR_AND_OBJ;
6311 if (AddIsTargetParamFlag)
6312 Bits |= OMP_MAP_TARGET_PARAM;
Samuel Antao86ace552016-04-27 22:40:57 +00006313 if (MapTypeModifier == OMPC_MAP_always)
6314 Bits |= OMP_MAP_ALWAYS;
6315 return Bits;
6316 }
6317
6318 /// \brief Return true if the provided expression is a final array section. A
6319 /// final array section, is one whose length can't be proved to be one.
6320 bool isFinalArraySectionExpression(const Expr *E) const {
6321 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
6322
6323 // It is not an array section and therefore not a unity-size one.
6324 if (!OASE)
6325 return false;
6326
6327 // An array section with no colon always refer to a single element.
6328 if (OASE->getColonLoc().isInvalid())
6329 return false;
6330
6331 auto *Length = OASE->getLength();
6332
6333 // If we don't have a length we have to check if the array has size 1
6334 // for this dimension. Also, we should always expect a length if the
6335 // base type is pointer.
6336 if (!Length) {
6337 auto BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6338 OASE->getBase()->IgnoreParenImpCasts())
6339 .getCanonicalType();
6340 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
6341 return ATy->getSize().getSExtValue() != 1;
6342 // If we don't have a constant dimension length, we have to consider
6343 // the current section as having any size, so it is not necessarily
6344 // unitary. If it happen to be unity size, that's user fault.
6345 return true;
6346 }
6347
6348 // Check if the length evaluates to 1.
6349 llvm::APSInt ConstLength;
6350 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
6351 return true; // Can have more that size 1.
6352
6353 return ConstLength.getSExtValue() != 1;
6354 }
6355
Alexey Bataev92327c52018-03-26 16:40:55 +00006356 /// \brief Return the adjusted map modifiers if the declaration a capture
6357 /// refers to appears in a first-private clause. This is expected to be used
6358 /// only with directives that start with 'target'.
6359 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
6360 unsigned CurrentModifiers) {
6361 assert(Cap.capturesVariable() && "Expected capture by reference only!");
6362
6363 // A first private variable captured by reference will use only the
6364 // 'private ptr' and 'map to' flag. Return the right flags if the captured
6365 // declaration is known as first-private in this handler.
6366 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
6367 return MappableExprsHandler::OMP_MAP_PRIVATE |
6368 MappableExprsHandler::OMP_MAP_TO;
6369 // Reduction variable will use only the 'private ptr' and 'map to_from'
6370 // flag.
6371 if (ReductionDecls.count(Cap.getCapturedVar())) {
6372 return MappableExprsHandler::OMP_MAP_TO |
6373 MappableExprsHandler::OMP_MAP_FROM;
6374 }
6375
6376 // We didn't modify anything.
6377 return CurrentModifiers;
6378 }
6379
6380public:
6381 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
6382 : CurDir(Dir), CGF(CGF) {
6383 // Extract firstprivate clause information.
6384 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
6385 for (const auto *D : C->varlists())
6386 FirstPrivateDecls.insert(
6387 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
6388 for (const auto *C : Dir.getClausesOfKind<OMPReductionClause>()) {
6389 for (const auto *D : C->varlists()) {
6390 ReductionDecls.insert(
6391 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
6392 }
6393 }
6394 // Extract device pointer clause information.
6395 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
6396 for (auto L : C->component_lists())
6397 DevPointersMap[L.first].push_back(L.second);
6398 }
6399
Samuel Antao86ace552016-04-27 22:40:57 +00006400 /// \brief Generate the base pointers, section pointers, sizes and map type
6401 /// bits for the provided map type, map modifier, and expression components.
6402 /// \a IsFirstComponent should be set to true if the provided set of
6403 /// components is the first associated with a capture.
6404 void generateInfoForComponentList(
6405 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6406 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006407 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006408 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006409 bool IsFirstComponentList, bool IsImplicit) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006410
6411 // The following summarizes what has to be generated for each map and the
6412 // types bellow. The generated information is expressed in this order:
6413 // base pointer, section pointer, size, flags
6414 // (to add to the ones that come from the map type and modifier).
6415 //
6416 // double d;
6417 // int i[100];
6418 // float *p;
6419 //
6420 // struct S1 {
6421 // int i;
6422 // float f[50];
6423 // }
6424 // struct S2 {
6425 // int i;
6426 // float f[50];
6427 // S1 s;
6428 // double *p;
6429 // struct S2 *ps;
6430 // }
6431 // S2 s;
6432 // S2 *ps;
6433 //
6434 // map(d)
6435 // &d, &d, sizeof(double), noflags
6436 //
6437 // map(i)
6438 // &i, &i, 100*sizeof(int), noflags
6439 //
6440 // map(i[1:23])
6441 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
6442 //
6443 // map(p)
6444 // &p, &p, sizeof(float*), noflags
6445 //
6446 // map(p[1:24])
6447 // p, &p[1], 24*sizeof(float), noflags
6448 //
6449 // map(s)
6450 // &s, &s, sizeof(S2), noflags
6451 //
6452 // map(s.i)
6453 // &s, &(s.i), sizeof(int), noflags
6454 //
6455 // map(s.s.f)
6456 // &s, &(s.i.f), 50*sizeof(int), noflags
6457 //
6458 // map(s.p)
6459 // &s, &(s.p), sizeof(double*), noflags
6460 //
6461 // map(s.p[:22], s.a s.b)
6462 // &s, &(s.p), sizeof(double*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006463 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006464 //
6465 // map(s.ps)
6466 // &s, &(s.ps), sizeof(S2*), noflags
6467 //
6468 // map(s.ps->s.i)
6469 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006470 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006471 //
6472 // map(s.ps->ps)
6473 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006474 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006475 //
6476 // map(s.ps->ps->ps)
6477 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006478 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
6479 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006480 //
6481 // map(s.ps->ps->s.f[:22])
6482 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006483 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
6484 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006485 //
6486 // map(ps)
6487 // &ps, &ps, sizeof(S2*), noflags
6488 //
6489 // map(ps->i)
6490 // ps, &(ps->i), sizeof(int), noflags
6491 //
6492 // map(ps->s.f)
6493 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
6494 //
6495 // map(ps->p)
6496 // ps, &(ps->p), sizeof(double*), noflags
6497 //
6498 // map(ps->p[:22])
6499 // ps, &(ps->p), sizeof(double*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006500 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006501 //
6502 // map(ps->ps)
6503 // ps, &(ps->ps), sizeof(S2*), noflags
6504 //
6505 // map(ps->ps->s.i)
6506 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006507 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006508 //
6509 // map(ps->ps->ps)
6510 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006511 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006512 //
6513 // map(ps->ps->ps->ps)
6514 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006515 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
6516 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006517 //
6518 // map(ps->ps->ps->s.f[:22])
6519 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006520 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
6521 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006522
6523 // Track if the map information being generated is the first for a capture.
6524 bool IsCaptureFirstInfo = IsFirstComponentList;
Alexey Bataev92327c52018-03-26 16:40:55 +00006525 bool IsLink = false; // Is this variable a "declare target link"?
Samuel Antao86ace552016-04-27 22:40:57 +00006526
6527 // Scan the components from the base to the complete expression.
6528 auto CI = Components.rbegin();
6529 auto CE = Components.rend();
6530 auto I = CI;
6531
6532 // Track if the map information being generated is the first for a list of
6533 // components.
6534 bool IsExpressionFirstInfo = true;
6535 llvm::Value *BP = nullptr;
6536
6537 if (auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
6538 // The base is the 'this' pointer. The content of the pointer is going
6539 // to be the base of the field being mapped.
6540 BP = CGF.EmitScalarExpr(ME->getBase());
6541 } else {
6542 // The base is the reference to the variable.
6543 // BP = &Var.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006544 BP = CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Alexey Bataev92327c52018-03-26 16:40:55 +00006545 if (const auto *VD =
6546 dyn_cast_or_null<VarDecl>(I->getAssociatedDeclaration())) {
6547 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
6548 isDeclareTargetDeclaration(VD)) {
6549 assert(*Res == OMPDeclareTargetDeclAttr::MT_Link &&
6550 "Declare target link is expected.");
6551 // Avoid warning in release build.
6552 (void)*Res;
6553 IsLink = true;
6554 BP = CGF.CGM.getOpenMPRuntime()
6555 .getAddrOfDeclareTargetLink(CGF, VD)
6556 .getPointer();
6557 }
6558 }
Samuel Antao86ace552016-04-27 22:40:57 +00006559
6560 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00006561 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00006562 // reference. References are ignored for mapping purposes.
6563 QualType Ty =
6564 I->getAssociatedDeclaration()->getType().getNonReferenceType();
6565 if (Ty->isAnyPointerType() && std::next(I) != CE) {
6566 auto PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
Samuel Antao86ace552016-04-27 22:40:57 +00006567 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
Samuel Antao403ffd42016-07-27 22:49:49 +00006568 Ty->castAs<PointerType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006569 .getPointer();
6570
6571 // We do not need to generate individual map information for the
6572 // pointer, it can be associated with the combined storage.
6573 ++I;
6574 }
6575 }
6576
George Rokos63bc9d62017-11-21 18:25:12 +00006577 uint64_t DefaultFlags = IsImplicit ? OMP_MAP_IMPLICIT : 0;
Samuel Antao86ace552016-04-27 22:40:57 +00006578 for (; I != CE; ++I) {
6579 auto Next = std::next(I);
6580
6581 // We need to generate the addresses and sizes if this is the last
6582 // component, if the component is a pointer or if it is an array section
6583 // whose length can't be proved to be one. If this is a pointer, it
6584 // becomes the base address for the following components.
6585
6586 // A final array section, is one whose length can't be proved to be one.
6587 bool IsFinalArraySection =
6588 isFinalArraySectionExpression(I->getAssociatedExpression());
6589
6590 // Get information on whether the element is a pointer. Have to do a
6591 // special treatment for array sections given that they are built-in
6592 // types.
6593 const auto *OASE =
6594 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
6595 bool IsPointer =
6596 (OASE &&
6597 OMPArraySectionExpr::getBaseOriginalType(OASE)
6598 .getCanonicalType()
6599 ->isAnyPointerType()) ||
6600 I->getAssociatedExpression()->getType()->isAnyPointerType();
6601
6602 if (Next == CE || IsPointer || IsFinalArraySection) {
6603
6604 // If this is not the last component, we expect the pointer to be
6605 // associated with an array expression or member expression.
6606 assert((Next == CE ||
6607 isa<MemberExpr>(Next->getAssociatedExpression()) ||
6608 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
6609 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
6610 "Unexpected expression");
6611
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006612 llvm::Value *LB =
6613 CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Samuel Antao86ace552016-04-27 22:40:57 +00006614 auto *Size = getExprTypeSize(I->getAssociatedExpression());
6615
Samuel Antao03a3cec2016-07-27 22:52:16 +00006616 // If we have a member expression and the current component is a
6617 // reference, we have to map the reference too. Whenever we have a
6618 // reference, the section that reference refers to is going to be a
6619 // load instruction from the storage assigned to the reference.
6620 if (isa<MemberExpr>(I->getAssociatedExpression()) &&
6621 I->getAssociatedDeclaration()->getType()->isReferenceType()) {
6622 auto *LI = cast<llvm::LoadInst>(LB);
6623 auto *RefAddr = LI->getPointerOperand();
6624
6625 BasePointers.push_back(BP);
6626 Pointers.push_back(RefAddr);
6627 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006628 Types.push_back(DefaultFlags |
6629 getMapTypeBits(
6630 /*MapType*/ OMPC_MAP_alloc,
6631 /*MapTypeModifier=*/OMPC_MAP_unknown,
6632 !IsExpressionFirstInfo, IsCaptureFirstInfo));
Samuel Antao03a3cec2016-07-27 22:52:16 +00006633 IsExpressionFirstInfo = false;
6634 IsCaptureFirstInfo = false;
6635 // The reference will be the next base address.
6636 BP = RefAddr;
6637 }
6638
6639 BasePointers.push_back(BP);
Samuel Antao86ace552016-04-27 22:40:57 +00006640 Pointers.push_back(LB);
6641 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00006642
Samuel Antao6782e942016-05-26 16:48:10 +00006643 // We need to add a pointer flag for each map that comes from the
6644 // same expression except for the first one. We also need to signal
6645 // this map is the first one that relates with the current capture
6646 // (there is a set of entries for each capture).
Alexey Bataev92327c52018-03-26 16:40:55 +00006647 Types.push_back(DefaultFlags |
6648 getMapTypeBits(MapType, MapTypeModifier,
6649 !IsExpressionFirstInfo || IsLink,
6650 IsCaptureFirstInfo && !IsLink));
Samuel Antao86ace552016-04-27 22:40:57 +00006651
6652 // If we have a final array section, we are done with this expression.
6653 if (IsFinalArraySection)
6654 break;
6655
6656 // The pointer becomes the base for the next element.
6657 if (Next != CE)
6658 BP = LB;
6659
6660 IsExpressionFirstInfo = false;
6661 IsCaptureFirstInfo = false;
Samuel Antao86ace552016-04-27 22:40:57 +00006662 }
6663 }
6664 }
6665
Samuel Antao86ace552016-04-27 22:40:57 +00006666 /// \brief Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00006667 /// types for the extracted mappable expressions. Also, for each item that
6668 /// relates with a device pointer, a pair of the relevant declaration and
6669 /// index where it occurs is appended to the device pointers info array.
6670 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006671 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
6672 MapFlagsArrayTy &Types) const {
6673 BasePointers.clear();
6674 Pointers.clear();
6675 Sizes.clear();
6676 Types.clear();
6677
6678 struct MapInfo {
Samuel Antaocc10b852016-07-28 14:23:26 +00006679 /// Kind that defines how a device pointer has to be returned.
6680 enum ReturnPointerKind {
6681 // Don't have to return any pointer.
6682 RPK_None,
6683 // Pointer is the base of the declaration.
6684 RPK_Base,
6685 // Pointer is a member of the base declaration - 'this'
6686 RPK_Member,
6687 // Pointer is a reference and a member of the base declaration - 'this'
6688 RPK_MemberReference,
6689 };
Samuel Antao86ace552016-04-27 22:40:57 +00006690 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006691 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
6692 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
6693 ReturnPointerKind ReturnDevicePointer = RPK_None;
6694 bool IsImplicit = false;
Hans Wennborgbc1b58d2016-07-30 00:41:37 +00006695
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006696 MapInfo() = default;
Samuel Antaocc10b852016-07-28 14:23:26 +00006697 MapInfo(
6698 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
6699 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006700 ReturnPointerKind ReturnDevicePointer, bool IsImplicit)
Samuel Antaocc10b852016-07-28 14:23:26 +00006701 : Components(Components), MapType(MapType),
6702 MapTypeModifier(MapTypeModifier),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006703 ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
Samuel Antao86ace552016-04-27 22:40:57 +00006704 };
6705
6706 // We have to process the component lists that relate with the same
6707 // declaration in a single chunk so that we can generate the map flags
6708 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00006709 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00006710
6711 // Helper function to fill the information map for the different supported
6712 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00006713 auto &&InfoGen = [&Info](
6714 const ValueDecl *D,
6715 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
6716 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006717 MapInfo::ReturnPointerKind ReturnDevicePointer, bool IsImplicit) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006718 const ValueDecl *VD =
6719 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006720 Info[VD].emplace_back(L, MapType, MapModifier, ReturnDevicePointer,
6721 IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00006722 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00006723
Paul Robinson78fb1322016-08-01 22:12:46 +00006724 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006725 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006726 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006727 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006728 MapInfo::RPK_None, C->isImplicit());
6729 }
Paul Robinson15c84002016-07-29 20:46:16 +00006730 for (auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006731 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006732 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006733 MapInfo::RPK_None, C->isImplicit());
6734 }
Paul Robinson15c84002016-07-29 20:46:16 +00006735 for (auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006736 for (auto L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006737 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006738 MapInfo::RPK_None, C->isImplicit());
6739 }
Samuel Antao86ace552016-04-27 22:40:57 +00006740
Samuel Antaocc10b852016-07-28 14:23:26 +00006741 // Look at the use_device_ptr clause information and mark the existing map
6742 // entries as such. If there is no map information for an entry in the
6743 // use_device_ptr list, we create one with map type 'alloc' and zero size
6744 // section. It is the user fault if that was not mapped before.
Paul Robinson78fb1322016-08-01 22:12:46 +00006745 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006746 for (auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
Samuel Antaocc10b852016-07-28 14:23:26 +00006747 for (auto L : C->component_lists()) {
6748 assert(!L.second.empty() && "Not expecting empty list of components!");
6749 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
6750 VD = cast<ValueDecl>(VD->getCanonicalDecl());
6751 auto *IE = L.second.back().getAssociatedExpression();
6752 // If the first component is a member expression, we have to look into
6753 // 'this', which maps to null in the map of map information. Otherwise
6754 // look directly for the information.
6755 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
6756
6757 // We potentially have map information for this declaration already.
6758 // Look for the first set of components that refer to it.
6759 if (It != Info.end()) {
6760 auto CI = std::find_if(
6761 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
6762 return MI.Components.back().getAssociatedDeclaration() == VD;
6763 });
6764 // If we found a map entry, signal that the pointer has to be returned
6765 // and move on to the next declaration.
6766 if (CI != It->second.end()) {
6767 CI->ReturnDevicePointer = isa<MemberExpr>(IE)
6768 ? (VD->getType()->isReferenceType()
6769 ? MapInfo::RPK_MemberReference
6770 : MapInfo::RPK_Member)
6771 : MapInfo::RPK_Base;
6772 continue;
6773 }
6774 }
6775
6776 // We didn't find any match in our map information - generate a zero
6777 // size array section.
Paul Robinson78fb1322016-08-01 22:12:46 +00006778 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Alexey Bataev1e491372018-01-23 18:44:14 +00006779 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(this->CGF.EmitLValue(IE),
6780 IE->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +00006781 BasePointers.push_back({Ptr, VD});
6782 Pointers.push_back(Ptr);
Paul Robinson15c84002016-07-29 20:46:16 +00006783 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
George Rokos065755d2017-11-07 18:27:04 +00006784 Types.push_back(OMP_MAP_RETURN_PARAM | OMP_MAP_TARGET_PARAM);
Samuel Antaocc10b852016-07-28 14:23:26 +00006785 }
6786
Samuel Antao86ace552016-04-27 22:40:57 +00006787 for (auto &M : Info) {
6788 // We need to know when we generate information for the first component
6789 // associated with a capture, because the mapping flags depend on it.
6790 bool IsFirstComponentList = true;
6791 for (MapInfo &L : M.second) {
6792 assert(!L.Components.empty() &&
6793 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00006794
6795 // Remember the current base pointer index.
6796 unsigned CurrentBasePointersIdx = BasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00006797 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006798 this->generateInfoForComponentList(
6799 L.MapType, L.MapTypeModifier, L.Components, BasePointers, Pointers,
6800 Sizes, Types, IsFirstComponentList, L.IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00006801
6802 // If this entry relates with a device pointer, set the relevant
6803 // declaration and add the 'return pointer' flag.
6804 if (IsFirstComponentList &&
6805 L.ReturnDevicePointer != MapInfo::RPK_None) {
6806 // If the pointer is not the base of the map, we need to skip the
6807 // base. If it is a reference in a member field, we also need to skip
6808 // the map of the reference.
6809 if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
6810 ++CurrentBasePointersIdx;
6811 if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
6812 ++CurrentBasePointersIdx;
6813 }
6814 assert(BasePointers.size() > CurrentBasePointersIdx &&
6815 "Unexpected number of mapped base pointers.");
6816
6817 auto *RelevantVD = L.Components.back().getAssociatedDeclaration();
6818 assert(RelevantVD &&
6819 "No relevant declaration related with device pointer??");
6820
6821 BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
George Rokos065755d2017-11-07 18:27:04 +00006822 Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PARAM;
Samuel Antaocc10b852016-07-28 14:23:26 +00006823 }
Samuel Antao86ace552016-04-27 22:40:57 +00006824 IsFirstComponentList = false;
6825 }
6826 }
6827 }
6828
6829 /// \brief Generate the base pointers, section pointers, sizes and map types
6830 /// associated to a given capture.
6831 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00006832 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006833 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006834 MapValuesArrayTy &Pointers,
6835 MapValuesArrayTy &Sizes,
6836 MapFlagsArrayTy &Types) const {
6837 assert(!Cap->capturesVariableArrayType() &&
6838 "Not expecting to generate map info for a variable array type!");
6839
6840 BasePointers.clear();
6841 Pointers.clear();
6842 Sizes.clear();
6843 Types.clear();
6844
Samuel Antao6890b092016-07-28 14:25:09 +00006845 // We need to know when we generating information for the first component
6846 // associated with a capture, because the mapping flags depend on it.
6847 bool IsFirstComponentList = true;
6848
Samuel Antao86ace552016-04-27 22:40:57 +00006849 const ValueDecl *VD =
6850 Cap->capturesThis()
6851 ? nullptr
George Burgess IV00f70bd2018-03-01 05:43:23 +00006852 : Cap->getCapturedVar()->getCanonicalDecl();
Samuel Antao86ace552016-04-27 22:40:57 +00006853
Samuel Antao6890b092016-07-28 14:25:09 +00006854 // If this declaration appears in a is_device_ptr clause we just have to
6855 // pass the pointer by value. If it is a reference to a declaration, we just
6856 // pass its value, otherwise, if it is a member expression, we need to map
6857 // 'to' the field.
6858 if (!VD) {
6859 auto It = DevPointersMap.find(VD);
6860 if (It != DevPointersMap.end()) {
6861 for (auto L : It->second) {
6862 generateInfoForComponentList(
6863 /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006864 BasePointers, Pointers, Sizes, Types, IsFirstComponentList,
6865 /*IsImplicit=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +00006866 IsFirstComponentList = false;
6867 }
6868 return;
6869 }
6870 } else if (DevPointersMap.count(VD)) {
6871 BasePointers.push_back({Arg, VD});
6872 Pointers.push_back(Arg);
6873 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
George Rokos065755d2017-11-07 18:27:04 +00006874 Types.push_back(OMP_MAP_LITERAL | OMP_MAP_TARGET_PARAM);
Samuel Antao6890b092016-07-28 14:25:09 +00006875 return;
6876 }
6877
Paul Robinson78fb1322016-08-01 22:12:46 +00006878 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006879 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao86ace552016-04-27 22:40:57 +00006880 for (auto L : C->decl_component_lists(VD)) {
6881 assert(L.first == VD &&
6882 "We got information for the wrong declaration??");
6883 assert(!L.second.empty() &&
6884 "Not expecting declaration with no component lists.");
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006885 generateInfoForComponentList(
6886 C->getMapType(), C->getMapTypeModifier(), L.second, BasePointers,
6887 Pointers, Sizes, Types, IsFirstComponentList, C->isImplicit());
Samuel Antao86ace552016-04-27 22:40:57 +00006888 IsFirstComponentList = false;
6889 }
6890
6891 return;
6892 }
Samuel Antaod486f842016-05-26 16:53:38 +00006893
6894 /// \brief Generate the default map information for a given capture \a CI,
6895 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00006896 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
6897 const FieldDecl &RI, llvm::Value *CV,
6898 MapBaseValuesArrayTy &CurBasePointers,
6899 MapValuesArrayTy &CurPointers,
6900 MapValuesArrayTy &CurSizes,
6901 MapFlagsArrayTy &CurMapTypes) {
Samuel Antaod486f842016-05-26 16:53:38 +00006902
6903 // Do the default mapping.
6904 if (CI.capturesThis()) {
6905 CurBasePointers.push_back(CV);
6906 CurPointers.push_back(CV);
6907 const PointerType *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
6908 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
6909 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00006910 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00006911 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00006912 CurBasePointers.push_back(CV);
6913 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00006914 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00006915 // We have to signal to the runtime captures passed by value that are
6916 // not pointers.
George Rokos065755d2017-11-07 18:27:04 +00006917 CurMapTypes.push_back(OMP_MAP_LITERAL);
Samuel Antaod486f842016-05-26 16:53:38 +00006918 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
6919 } else {
6920 // Pointers are implicitly mapped with a zero size and no flags
6921 // (other than first map that is added for all implicit maps).
6922 CurMapTypes.push_back(0u);
Samuel Antaod486f842016-05-26 16:53:38 +00006923 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
6924 }
6925 } else {
6926 assert(CI.capturesVariable() && "Expected captured reference.");
6927 CurBasePointers.push_back(CV);
6928 CurPointers.push_back(CV);
6929
6930 const ReferenceType *PtrTy =
6931 cast<ReferenceType>(RI.getType().getTypePtr());
6932 QualType ElementType = PtrTy->getPointeeType();
6933 CurSizes.push_back(CGF.getTypeSize(ElementType));
6934 // The default map type for a scalar/complex type is 'to' because by
6935 // default the value doesn't have to be retrieved. For an aggregate
6936 // type, the default is 'tofrom'.
Alexey Bataev3f96fe62017-12-13 17:31:39 +00006937 CurMapTypes.emplace_back(adjustMapModifiersForPrivateClauses(
6938 CI, ElementType->isAggregateType() ? (OMP_MAP_TO | OMP_MAP_FROM)
6939 : OMP_MAP_TO));
Samuel Antaod486f842016-05-26 16:53:38 +00006940 }
George Rokos065755d2017-11-07 18:27:04 +00006941 // Every default map produces a single argument which is a target parameter.
6942 CurMapTypes.back() |= OMP_MAP_TARGET_PARAM;
Samuel Antaod486f842016-05-26 16:53:38 +00006943 }
Samuel Antao86ace552016-04-27 22:40:57 +00006944};
Samuel Antaodf158d52016-04-27 22:58:19 +00006945
6946enum OpenMPOffloadingReservedDeviceIDs {
6947 /// \brief Device ID if the device was not defined, runtime should get it
6948 /// from environment variables in the spec.
6949 OMP_DEVICEID_UNDEF = -1,
6950};
6951} // anonymous namespace
6952
6953/// \brief Emit the arrays used to pass the captures and map information to the
6954/// offloading runtime library. If there is no map or capture information,
6955/// return nullptr by reference.
6956static void
Samuel Antaocc10b852016-07-28 14:23:26 +00006957emitOffloadingArrays(CodeGenFunction &CGF,
6958 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00006959 MappableExprsHandler::MapValuesArrayTy &Pointers,
6960 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00006961 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
6962 CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006963 auto &CGM = CGF.CGM;
6964 auto &Ctx = CGF.getContext();
6965
Samuel Antaocc10b852016-07-28 14:23:26 +00006966 // Reset the array information.
6967 Info.clearArrayInfo();
6968 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00006969
Samuel Antaocc10b852016-07-28 14:23:26 +00006970 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006971 // Detect if we have any capture size requiring runtime evaluation of the
6972 // size so that a constant array could be eventually used.
6973 bool hasRuntimeEvaluationCaptureSize = false;
6974 for (auto *S : Sizes)
6975 if (!isa<llvm::Constant>(S)) {
6976 hasRuntimeEvaluationCaptureSize = true;
6977 break;
6978 }
6979
Samuel Antaocc10b852016-07-28 14:23:26 +00006980 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00006981 QualType PointerArrayType =
6982 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
6983 /*IndexTypeQuals=*/0);
6984
Samuel Antaocc10b852016-07-28 14:23:26 +00006985 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006986 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00006987 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006988 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
6989
6990 // If we don't have any VLA types or other types that require runtime
6991 // evaluation, we can use a constant array for the map sizes, otherwise we
6992 // need to fill up the arrays as we do for the pointers.
6993 if (hasRuntimeEvaluationCaptureSize) {
6994 QualType SizeArrayType = Ctx.getConstantArrayType(
6995 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
6996 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00006997 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006998 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
6999 } else {
7000 // We expect all the sizes to be constant, so we collect them to create
7001 // a constant array.
7002 SmallVector<llvm::Constant *, 16> ConstSizes;
7003 for (auto S : Sizes)
7004 ConstSizes.push_back(cast<llvm::Constant>(S));
7005
7006 auto *SizesArrayInit = llvm::ConstantArray::get(
7007 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
7008 auto *SizesArrayGbl = new llvm::GlobalVariable(
7009 CGM.getModule(), SizesArrayInit->getType(),
7010 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
7011 SizesArrayInit, ".offload_sizes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00007012 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00007013 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00007014 }
7015
7016 // The map types are always constant so we don't need to generate code to
7017 // fill arrays. Instead, we create an array constant.
7018 llvm::Constant *MapTypesArrayInit =
7019 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
7020 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
7021 CGM.getModule(), MapTypesArrayInit->getType(),
7022 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
7023 MapTypesArrayInit, ".offload_maptypes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00007024 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00007025 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00007026
Samuel Antaocc10b852016-07-28 14:23:26 +00007027 for (unsigned i = 0; i < Info.NumberOfPtrs; ++i) {
7028 llvm::Value *BPVal = *BasePointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00007029 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007030 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
7031 Info.BasePointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00007032 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7033 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00007034 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
7035 CGF.Builder.CreateStore(BPVal, BPAddr);
7036
Samuel Antaocc10b852016-07-28 14:23:26 +00007037 if (Info.requiresDevicePointerInfo())
7038 if (auto *DevVD = BasePointers[i].getDevicePtrDecl())
7039 Info.CaptureDeviceAddrMap.insert(std::make_pair(DevVD, BPAddr));
7040
Samuel Antaodf158d52016-04-27 22:58:19 +00007041 llvm::Value *PVal = Pointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00007042 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007043 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
7044 Info.PointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00007045 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7046 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00007047 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
7048 CGF.Builder.CreateStore(PVal, PAddr);
7049
7050 if (hasRuntimeEvaluationCaptureSize) {
7051 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007052 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
7053 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007054 /*Idx0=*/0,
7055 /*Idx1=*/i);
7056 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
7057 CGF.Builder.CreateStore(
7058 CGF.Builder.CreateIntCast(Sizes[i], CGM.SizeTy, /*isSigned=*/true),
7059 SAddr);
7060 }
7061 }
7062 }
7063}
7064/// \brief Emit the arguments to be passed to the runtime library based on the
7065/// arrays of pointers, sizes and map types.
7066static void emitOffloadingArraysArgument(
7067 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
7068 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007069 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007070 auto &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00007071 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007072 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007073 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
7074 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007075 /*Idx0=*/0, /*Idx1=*/0);
7076 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007077 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
7078 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007079 /*Idx0=*/0,
7080 /*Idx1=*/0);
7081 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007082 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007083 /*Idx0=*/0, /*Idx1=*/0);
7084 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
George Rokos63bc9d62017-11-21 18:25:12 +00007085 llvm::ArrayType::get(CGM.Int64Ty, Info.NumberOfPtrs),
Samuel Antaocc10b852016-07-28 14:23:26 +00007086 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007087 /*Idx0=*/0,
7088 /*Idx1=*/0);
7089 } else {
7090 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
7091 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
7092 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
7093 MapTypesArrayArg =
George Rokos63bc9d62017-11-21 18:25:12 +00007094 llvm::ConstantPointerNull::get(CGM.Int64Ty->getPointerTo());
Samuel Antaodf158d52016-04-27 22:58:19 +00007095 }
Samuel Antao86ace552016-04-27 22:40:57 +00007096}
7097
Samuel Antaobed3c462015-10-02 16:14:20 +00007098void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
7099 const OMPExecutableDirective &D,
7100 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00007101 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00007102 const Expr *IfCond, const Expr *Device) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00007103 if (!CGF.HaveInsertPoint())
7104 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00007105
Samuel Antaoee8fb302016-01-06 13:42:12 +00007106 assert(OutlinedFn && "Invalid outlined function!");
7107
Alexey Bataev8451efa2018-01-15 19:06:12 +00007108 const bool RequiresOuterTask = D.hasClausesOfKind<OMPDependClause>();
7109 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Alexey Bataev475a7442018-01-12 19:39:11 +00007110 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Alexey Bataev8451efa2018-01-15 19:06:12 +00007111 auto &&ArgsCodegen = [&CS, &CapturedVars](CodeGenFunction &CGF,
7112 PrePostActionTy &) {
7113 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7114 };
7115 emitInlinedDirective(CGF, OMPD_unknown, ArgsCodegen);
Samuel Antao86ace552016-04-27 22:40:57 +00007116
Alexey Bataev8451efa2018-01-15 19:06:12 +00007117 CodeGenFunction::OMPTargetDataInfo InputInfo;
7118 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00007119 // Fill up the pointer arrays and transfer execution to the device.
Alexey Bataev8451efa2018-01-15 19:06:12 +00007120 auto &&ThenGen = [this, Device, OutlinedFn, OutlinedFnID, &D, &InputInfo,
7121 &MapTypesArray, &CS, RequiresOuterTask,
7122 &CapturedVars](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobed3c462015-10-02 16:14:20 +00007123 // On top of the arrays that were filled up, the target offloading call
7124 // takes as arguments the device id as well as the host pointer. The host
7125 // pointer is used by the runtime library to identify the current target
7126 // region, so it only has to be unique and not necessarily point to
7127 // anything. It could be the pointer to the outlined function that
7128 // implements the target region, but we aren't using that so that the
7129 // compiler doesn't need to keep that, and could therefore inline the host
7130 // function if proven worthwhile during optimization.
7131
Samuel Antaoee8fb302016-01-06 13:42:12 +00007132 // From this point on, we need to have an ID of the target region defined.
7133 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00007134
7135 // Emit device ID if any.
7136 llvm::Value *DeviceID;
George Rokos63bc9d62017-11-21 18:25:12 +00007137 if (Device) {
Samuel Antaobed3c462015-10-02 16:14:20 +00007138 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007139 CGF.Int64Ty, /*isSigned=*/true);
7140 } else {
7141 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7142 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007143
Samuel Antaodf158d52016-04-27 22:58:19 +00007144 // Emit the number of elements in the offloading arrays.
Alexey Bataev8451efa2018-01-15 19:06:12 +00007145 llvm::Value *PointerNum =
7146 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaodf158d52016-04-27 22:58:19 +00007147
Samuel Antaob68e2db2016-03-03 16:20:23 +00007148 // Return value of the runtime offloading call.
7149 llvm::Value *Return;
7150
Alexey Bataev8451efa2018-01-15 19:06:12 +00007151 auto *NumTeams = emitNumTeamsForTargetDirective(*this, CGF, D);
7152 auto *NumThreads = emitNumThreadsForTargetDirective(*this, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007153
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007154 bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007155 // The target region is an outlined function launched by the runtime
7156 // via calls __tgt_target() or __tgt_target_teams().
7157 //
7158 // __tgt_target() launches a target region with one team and one thread,
7159 // executing a serial region. This master thread may in turn launch
7160 // more threads within its team upon encountering a parallel region,
7161 // however, no additional teams can be launched on the device.
7162 //
7163 // __tgt_target_teams() launches a target region with one or more teams,
7164 // each with one or more threads. This call is required for target
7165 // constructs such as:
7166 // 'target teams'
7167 // 'target' / 'teams'
7168 // 'target teams distribute parallel for'
7169 // 'target parallel'
7170 // and so on.
7171 //
7172 // Note that on the host and CPU targets, the runtime implementation of
7173 // these calls simply call the outlined function without forking threads.
7174 // The outlined functions themselves have runtime calls to
7175 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
7176 // the compiler in emitTeamsCall() and emitParallelCall().
7177 //
7178 // In contrast, on the NVPTX target, the implementation of
7179 // __tgt_target_teams() launches a GPU kernel with the requested number
7180 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00007181 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007182 // If we have NumTeams defined this means that we have an enclosed teams
7183 // region. Therefore we also expect to have NumThreads defined. These two
7184 // values should be defined in the presence of a teams directive,
7185 // regardless of having any clauses associated. If the user is using teams
7186 // but no clauses, these two values will be the default that should be
7187 // passed to the runtime library - a 32-bit integer with the value zero.
7188 assert(NumThreads && "Thread limit expression should be available along "
7189 "with number of teams.");
Alexey Bataev8451efa2018-01-15 19:06:12 +00007190 llvm::Value *OffloadingArgs[] = {DeviceID,
7191 OutlinedFnID,
7192 PointerNum,
7193 InputInfo.BasePointersArray.getPointer(),
7194 InputInfo.PointersArray.getPointer(),
7195 InputInfo.SizesArray.getPointer(),
7196 MapTypesArray,
7197 NumTeams,
7198 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00007199 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00007200 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_teams_nowait
7201 : OMPRTL__tgt_target_teams),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007202 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007203 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00007204 llvm::Value *OffloadingArgs[] = {DeviceID,
7205 OutlinedFnID,
7206 PointerNum,
7207 InputInfo.BasePointersArray.getPointer(),
7208 InputInfo.PointersArray.getPointer(),
7209 InputInfo.SizesArray.getPointer(),
7210 MapTypesArray};
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007211 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00007212 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_nowait
7213 : OMPRTL__tgt_target),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007214 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007215 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007216
Alexey Bataev2a007e02017-10-02 14:20:58 +00007217 // Check the error code and execute the host version if required.
7218 llvm::BasicBlock *OffloadFailedBlock =
7219 CGF.createBasicBlock("omp_offload.failed");
7220 llvm::BasicBlock *OffloadContBlock =
7221 CGF.createBasicBlock("omp_offload.cont");
7222 llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
7223 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
7224
7225 CGF.EmitBlock(OffloadFailedBlock);
Alexey Bataev8451efa2018-01-15 19:06:12 +00007226 if (RequiresOuterTask) {
7227 CapturedVars.clear();
7228 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7229 }
7230 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, CapturedVars);
Alexey Bataev2a007e02017-10-02 14:20:58 +00007231 CGF.EmitBranch(OffloadContBlock);
7232
7233 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00007234 };
7235
Samuel Antaoee8fb302016-01-06 13:42:12 +00007236 // Notify that the host version must be executed.
Alexey Bataev8451efa2018-01-15 19:06:12 +00007237 auto &&ElseGen = [this, &D, OutlinedFn, &CS, &CapturedVars,
7238 RequiresOuterTask](CodeGenFunction &CGF,
7239 PrePostActionTy &) {
7240 if (RequiresOuterTask) {
7241 CapturedVars.clear();
7242 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7243 }
7244 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, CapturedVars);
7245 };
7246
7247 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray,
7248 &CapturedVars, RequiresOuterTask,
7249 &CS](CodeGenFunction &CGF, PrePostActionTy &) {
7250 // Fill up the arrays with all the captured variables.
7251 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
7252 MappableExprsHandler::MapValuesArrayTy Pointers;
7253 MappableExprsHandler::MapValuesArrayTy Sizes;
7254 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7255
7256 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
7257 MappableExprsHandler::MapValuesArrayTy CurPointers;
7258 MappableExprsHandler::MapValuesArrayTy CurSizes;
7259 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
7260
7261 // Get mappable expression information.
7262 MappableExprsHandler MEHandler(D, CGF);
7263
7264 auto RI = CS.getCapturedRecordDecl()->field_begin();
7265 auto CV = CapturedVars.begin();
7266 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
7267 CE = CS.capture_end();
7268 CI != CE; ++CI, ++RI, ++CV) {
7269 CurBasePointers.clear();
7270 CurPointers.clear();
7271 CurSizes.clear();
7272 CurMapTypes.clear();
7273
7274 // VLA sizes are passed to the outlined region by copy and do not have map
7275 // information associated.
7276 if (CI->capturesVariableArrayType()) {
7277 CurBasePointers.push_back(*CV);
7278 CurPointers.push_back(*CV);
7279 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
7280 // Copy to the device as an argument. No need to retrieve it.
7281 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_LITERAL |
7282 MappableExprsHandler::OMP_MAP_TARGET_PARAM);
7283 } else {
7284 // If we have any information in the map clause, we use it, otherwise we
7285 // just do a default mapping.
7286 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
7287 CurSizes, CurMapTypes);
7288 if (CurBasePointers.empty())
7289 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
7290 CurPointers, CurSizes, CurMapTypes);
7291 }
7292 // We expect to have at least an element of information for this capture.
7293 assert(!CurBasePointers.empty() &&
7294 "Non-existing map pointer for capture!");
7295 assert(CurBasePointers.size() == CurPointers.size() &&
7296 CurBasePointers.size() == CurSizes.size() &&
7297 CurBasePointers.size() == CurMapTypes.size() &&
7298 "Inconsistent map information sizes!");
7299
7300 // We need to append the results of this capture to what we already have.
7301 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
7302 Pointers.append(CurPointers.begin(), CurPointers.end());
7303 Sizes.append(CurSizes.begin(), CurSizes.end());
7304 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
7305 }
Alexey Bataev92327c52018-03-26 16:40:55 +00007306 // Map other list items in the map clause which are not captured variables
7307 // but "declare target link" global variables.
7308 for (const auto *C : D.getClausesOfKind<OMPMapClause>()) {
7309 for (auto L : C->component_lists()) {
7310 if (!L.first)
7311 continue;
7312 const auto *VD = dyn_cast<VarDecl>(L.first);
7313 if (!VD)
7314 continue;
7315 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
7316 isDeclareTargetDeclaration(VD);
7317 if (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link)
7318 continue;
7319 MEHandler.generateInfoForComponentList(
7320 C->getMapType(), C->getMapTypeModifier(), L.second, BasePointers,
7321 Pointers, Sizes, MapTypes, /*IsFirstComponentList=*/true,
7322 C->isImplicit());
7323 }
7324 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00007325
7326 TargetDataInfo Info;
7327 // Fill up the arrays and create the arguments.
7328 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
7329 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
7330 Info.PointersArray, Info.SizesArray,
7331 Info.MapTypesArray, Info);
7332 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
7333 InputInfo.BasePointersArray =
7334 Address(Info.BasePointersArray, CGM.getPointerAlign());
7335 InputInfo.PointersArray =
7336 Address(Info.PointersArray, CGM.getPointerAlign());
7337 InputInfo.SizesArray = Address(Info.SizesArray, CGM.getPointerAlign());
7338 MapTypesArray = Info.MapTypesArray;
7339 if (RequiresOuterTask)
7340 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
7341 else
7342 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
7343 };
7344
7345 auto &&TargetElseGen = [this, &ElseGen, &D, RequiresOuterTask](
7346 CodeGenFunction &CGF, PrePostActionTy &) {
7347 if (RequiresOuterTask) {
7348 CodeGenFunction::OMPTargetDataInfo InputInfo;
7349 CGF.EmitOMPTargetTaskBasedDirective(D, ElseGen, InputInfo);
7350 } else {
7351 emitInlinedDirective(CGF, D.getDirectiveKind(), ElseGen);
7352 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00007353 };
7354
7355 // If we have a target function ID it means that we need to support
7356 // offloading, otherwise, just execute on the host. We need to execute on host
7357 // regardless of the conditional in the if clause if, e.g., the user do not
7358 // specify target triples.
7359 if (OutlinedFnID) {
Alexey Bataev8451efa2018-01-15 19:06:12 +00007360 if (IfCond) {
7361 emitOMPIfClause(CGF, IfCond, TargetThenGen, TargetElseGen);
7362 } else {
7363 RegionCodeGenTy ThenRCG(TargetThenGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007364 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007365 }
7366 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00007367 RegionCodeGenTy ElseRCG(TargetElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007368 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007369 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007370}
Samuel Antaoee8fb302016-01-06 13:42:12 +00007371
7372void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
7373 StringRef ParentName) {
7374 if (!S)
7375 return;
7376
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007377 // Codegen OMP target directives that offload compute to the device.
7378 bool requiresDeviceCodegen =
7379 isa<OMPExecutableDirective>(S) &&
7380 isOpenMPTargetExecutionDirective(
7381 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00007382
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007383 if (requiresDeviceCodegen) {
7384 auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007385 unsigned DeviceID;
7386 unsigned FileID;
7387 unsigned Line;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007388 getTargetEntryUniqueInfo(CGM.getContext(), E.getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00007389 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007390
7391 // Is this a target region that should not be emitted as an entry point? If
7392 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00007393 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
7394 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007395 return;
7396
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007397 switch (S->getStmtClass()) {
7398 case Stmt::OMPTargetDirectiveClass:
7399 CodeGenFunction::EmitOMPTargetDeviceFunction(
7400 CGM, ParentName, cast<OMPTargetDirective>(*S));
7401 break;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00007402 case Stmt::OMPTargetParallelDirectiveClass:
7403 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
7404 CGM, ParentName, cast<OMPTargetParallelDirective>(*S));
7405 break;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00007406 case Stmt::OMPTargetTeamsDirectiveClass:
7407 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
7408 CGM, ParentName, cast<OMPTargetTeamsDirective>(*S));
7409 break;
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007410 case Stmt::OMPTargetTeamsDistributeDirectiveClass:
7411 CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
7412 CGM, ParentName, cast<OMPTargetTeamsDistributeDirective>(*S));
7413 break;
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007414 case Stmt::OMPTargetTeamsDistributeSimdDirectiveClass:
7415 CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
7416 CGM, ParentName, cast<OMPTargetTeamsDistributeSimdDirective>(*S));
7417 break;
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007418 case Stmt::OMPTargetParallelForDirectiveClass:
7419 CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
7420 CGM, ParentName, cast<OMPTargetParallelForDirective>(*S));
7421 break;
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007422 case Stmt::OMPTargetParallelForSimdDirectiveClass:
7423 CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
7424 CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(*S));
7425 break;
Alexey Bataevf8365372017-11-17 17:57:25 +00007426 case Stmt::OMPTargetSimdDirectiveClass:
7427 CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
7428 CGM, ParentName, cast<OMPTargetSimdDirective>(*S));
7429 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +00007430 case Stmt::OMPTargetTeamsDistributeParallelForDirectiveClass:
7431 CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
7432 CGM, ParentName,
7433 cast<OMPTargetTeamsDistributeParallelForDirective>(*S));
7434 break;
Alexey Bataev647dd842018-01-15 20:59:40 +00007435 case Stmt::OMPTargetTeamsDistributeParallelForSimdDirectiveClass:
7436 CodeGenFunction::
7437 EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
7438 CGM, ParentName,
7439 cast<OMPTargetTeamsDistributeParallelForSimdDirective>(*S));
7440 break;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007441 default:
7442 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
7443 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00007444 return;
7445 }
7446
7447 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
Alexey Bataev475a7442018-01-12 19:39:11 +00007448 if (!E->hasAssociatedStmt() || !E->getAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00007449 return;
7450
7451 scanForTargetRegionsFunctions(
Alexey Bataev475a7442018-01-12 19:39:11 +00007452 E->getInnermostCapturedStmt()->getCapturedStmt(), ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007453 return;
7454 }
7455
7456 // If this is a lambda function, look into its body.
7457 if (auto *L = dyn_cast<LambdaExpr>(S))
7458 S = L->getBody();
7459
7460 // Keep looking for target regions recursively.
7461 for (auto *II : S->children())
7462 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007463}
7464
7465bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
7466 auto &FD = *cast<FunctionDecl>(GD.getDecl());
7467
7468 // If emitting code for the host, we do not process FD here. Instead we do
7469 // the normal code generation.
7470 if (!CGM.getLangOpts().OpenMPIsDevice)
7471 return false;
7472
7473 // Try to detect target regions in the function.
7474 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
7475
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007476 // Do not to emit function if it is not marked as declare target.
Alexey Bataev92327c52018-03-26 16:40:55 +00007477 return !isDeclareTargetDeclaration(&FD);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007478}
7479
7480bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
7481 if (!CGM.getLangOpts().OpenMPIsDevice)
7482 return false;
7483
7484 // Check if there are Ctors/Dtors in this declaration and look for target
7485 // regions in it. We use the complete variant to produce the kernel name
7486 // mangling.
7487 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
7488 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
7489 for (auto *Ctor : RD->ctors()) {
7490 StringRef ParentName =
7491 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
7492 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
7493 }
7494 auto *Dtor = RD->getDestructor();
7495 if (Dtor) {
7496 StringRef ParentName =
7497 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
7498 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
7499 }
7500 }
7501
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007502 // Do not to emit variable if it is not marked as declare target.
Alexey Bataev92327c52018-03-26 16:40:55 +00007503 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
7504 isDeclareTargetDeclaration(cast<ValueDecl>(GD.getDecl()));
7505 return !Res || *Res == OMPDeclareTargetDeclAttr::MT_Link;
Samuel Antaoee8fb302016-01-06 13:42:12 +00007506}
7507
7508bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
7509 auto *VD = GD.getDecl();
7510 if (isa<FunctionDecl>(VD))
7511 return emitTargetFunctions(GD);
7512
7513 return emitTargetGlobalVariable(GD);
7514}
7515
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007516CGOpenMPRuntime::DisableAutoDeclareTargetRAII::DisableAutoDeclareTargetRAII(
7517 CodeGenModule &CGM)
7518 : CGM(CGM) {
7519 if (CGM.getLangOpts().OpenMPIsDevice) {
7520 SavedShouldMarkAsGlobal = CGM.getOpenMPRuntime().ShouldMarkAsGlobal;
7521 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = false;
7522 }
7523}
7524
7525CGOpenMPRuntime::DisableAutoDeclareTargetRAII::~DisableAutoDeclareTargetRAII() {
7526 if (CGM.getLangOpts().OpenMPIsDevice)
7527 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = SavedShouldMarkAsGlobal;
7528}
7529
7530bool CGOpenMPRuntime::markAsGlobalTarget(const FunctionDecl *D) {
7531 if (!CGM.getLangOpts().OpenMPIsDevice || !ShouldMarkAsGlobal)
7532 return true;
7533 // Do not to emit function if it is marked as declare target as it was already
7534 // emitted.
Alexey Bataev92327c52018-03-26 16:40:55 +00007535 if (isDeclareTargetDeclaration(D))
7536 return true;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007537
7538 const FunctionDecl *FD = D->getCanonicalDecl();
7539 // Do not mark member functions except for static.
7540 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD))
7541 if (!Method->isStatic())
7542 return true;
7543
7544 return !AlreadyEmittedTargetFunctions.insert(FD).second;
7545}
7546
Samuel Antaoee8fb302016-01-06 13:42:12 +00007547llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
7548 // If we have offloading in the current module, we need to emit the entries
7549 // now and register the offloading descriptor.
7550 createOffloadEntriesAndInfoMetadata();
7551
7552 // Create and register the offloading binary descriptors. This is the main
7553 // entity that captures all the information about offloading in the current
7554 // compilation unit.
7555 return createOffloadingBinaryDescriptorRegistration();
7556}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007557
7558void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
7559 const OMPExecutableDirective &D,
7560 SourceLocation Loc,
7561 llvm::Value *OutlinedFn,
7562 ArrayRef<llvm::Value *> CapturedVars) {
7563 if (!CGF.HaveInsertPoint())
7564 return;
7565
7566 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7567 CodeGenFunction::RunCleanupsScope Scope(CGF);
7568
7569 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
7570 llvm::Value *Args[] = {
7571 RTLoc,
7572 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
7573 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
7574 llvm::SmallVector<llvm::Value *, 16> RealArgs;
7575 RealArgs.append(std::begin(Args), std::end(Args));
7576 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
7577
7578 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
7579 CGF.EmitRuntimeCall(RTLFn, RealArgs);
7580}
7581
7582void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00007583 const Expr *NumTeams,
7584 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007585 SourceLocation Loc) {
7586 if (!CGF.HaveInsertPoint())
7587 return;
7588
7589 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7590
Carlo Bertollic6872252016-04-04 15:55:02 +00007591 llvm::Value *NumTeamsVal =
7592 (NumTeams)
7593 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
7594 CGF.CGM.Int32Ty, /* isSigned = */ true)
7595 : CGF.Builder.getInt32(0);
7596
7597 llvm::Value *ThreadLimitVal =
7598 (ThreadLimit)
7599 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
7600 CGF.CGM.Int32Ty, /* isSigned = */ true)
7601 : CGF.Builder.getInt32(0);
7602
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007603 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00007604 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
7605 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007606 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
7607 PushNumTeamsArgs);
7608}
Samuel Antaodf158d52016-04-27 22:58:19 +00007609
Samuel Antaocc10b852016-07-28 14:23:26 +00007610void CGOpenMPRuntime::emitTargetDataCalls(
7611 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7612 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007613 if (!CGF.HaveInsertPoint())
7614 return;
7615
Samuel Antaocc10b852016-07-28 14:23:26 +00007616 // Action used to replace the default codegen action and turn privatization
7617 // off.
7618 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00007619
7620 // Generate the code for the opening of the data environment. Capture all the
7621 // arguments of the runtime call by reference because they are used in the
7622 // closing of the region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007623 auto &&BeginThenGen = [this, &D, Device, &Info,
7624 &CodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007625 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00007626 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00007627 MappableExprsHandler::MapValuesArrayTy Pointers;
7628 MappableExprsHandler::MapValuesArrayTy Sizes;
7629 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7630
7631 // Get map clause information.
7632 MappableExprsHandler MCHandler(D, CGF);
7633 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00007634
7635 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00007636 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007637
7638 llvm::Value *BasePointersArrayArg = nullptr;
7639 llvm::Value *PointersArrayArg = nullptr;
7640 llvm::Value *SizesArrayArg = nullptr;
7641 llvm::Value *MapTypesArrayArg = nullptr;
7642 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007643 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007644
7645 // Emit device ID if any.
7646 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00007647 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007648 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007649 CGF.Int64Ty, /*isSigned=*/true);
7650 } else {
7651 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7652 }
Samuel Antaodf158d52016-04-27 22:58:19 +00007653
7654 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007655 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007656
7657 llvm::Value *OffloadingArgs[] = {
7658 DeviceID, PointerNum, BasePointersArrayArg,
7659 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007660 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_begin),
Samuel Antaodf158d52016-04-27 22:58:19 +00007661 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00007662
7663 // If device pointer privatization is required, emit the body of the region
7664 // here. It will have to be duplicated: with and without privatization.
7665 if (!Info.CaptureDeviceAddrMap.empty())
7666 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007667 };
7668
7669 // Generate code for the closing of the data region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007670 auto &&EndThenGen = [this, Device, &Info](CodeGenFunction &CGF,
7671 PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007672 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00007673
7674 llvm::Value *BasePointersArrayArg = nullptr;
7675 llvm::Value *PointersArrayArg = nullptr;
7676 llvm::Value *SizesArrayArg = nullptr;
7677 llvm::Value *MapTypesArrayArg = nullptr;
7678 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007679 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007680
7681 // Emit device ID if any.
7682 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00007683 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007684 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007685 CGF.Int64Ty, /*isSigned=*/true);
7686 } else {
7687 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7688 }
Samuel Antaodf158d52016-04-27 22:58:19 +00007689
7690 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007691 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007692
7693 llvm::Value *OffloadingArgs[] = {
7694 DeviceID, PointerNum, BasePointersArrayArg,
7695 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007696 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_end),
Samuel Antaodf158d52016-04-27 22:58:19 +00007697 OffloadingArgs);
7698 };
7699
Samuel Antaocc10b852016-07-28 14:23:26 +00007700 // If we need device pointer privatization, we need to emit the body of the
7701 // region with no privatization in the 'else' branch of the conditional.
7702 // Otherwise, we don't have to do anything.
7703 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
7704 PrePostActionTy &) {
7705 if (!Info.CaptureDeviceAddrMap.empty()) {
7706 CodeGen.setAction(NoPrivAction);
7707 CodeGen(CGF);
7708 }
7709 };
7710
7711 // We don't have to do anything to close the region if the if clause evaluates
7712 // to false.
7713 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00007714
7715 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007716 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007717 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007718 RegionCodeGenTy RCG(BeginThenGen);
7719 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007720 }
7721
Samuel Antaocc10b852016-07-28 14:23:26 +00007722 // If we don't require privatization of device pointers, we emit the body in
7723 // between the runtime calls. This avoids duplicating the body code.
7724 if (Info.CaptureDeviceAddrMap.empty()) {
7725 CodeGen.setAction(NoPrivAction);
7726 CodeGen(CGF);
7727 }
Samuel Antaodf158d52016-04-27 22:58:19 +00007728
7729 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007730 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007731 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007732 RegionCodeGenTy RCG(EndThenGen);
7733 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007734 }
7735}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007736
Samuel Antao8d2d7302016-05-26 18:30:22 +00007737void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00007738 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7739 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007740 if (!CGF.HaveInsertPoint())
7741 return;
7742
Samuel Antao8dd66282016-04-27 23:14:30 +00007743 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00007744 isa<OMPTargetExitDataDirective>(D) ||
7745 isa<OMPTargetUpdateDirective>(D)) &&
7746 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00007747
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007748 CodeGenFunction::OMPTargetDataInfo InputInfo;
7749 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007750 // Generate the code for the opening of the data environment.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007751 auto &&ThenGen = [this, &D, Device, &InputInfo,
7752 &MapTypesArray](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007753 // Emit device ID if any.
7754 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00007755 if (Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007756 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007757 CGF.Int64Ty, /*isSigned=*/true);
7758 } else {
7759 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7760 }
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007761
7762 // Emit the number of elements in the offloading arrays.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007763 llvm::Constant *PointerNum =
7764 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007765
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007766 llvm::Value *OffloadingArgs[] = {DeviceID,
7767 PointerNum,
7768 InputInfo.BasePointersArray.getPointer(),
7769 InputInfo.PointersArray.getPointer(),
7770 InputInfo.SizesArray.getPointer(),
7771 MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00007772
Samuel Antao8d2d7302016-05-26 18:30:22 +00007773 // Select the right runtime function call for each expected standalone
7774 // directive.
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00007775 const bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Samuel Antao8d2d7302016-05-26 18:30:22 +00007776 OpenMPRTLFunction RTLFn;
7777 switch (D.getDirectiveKind()) {
7778 default:
7779 llvm_unreachable("Unexpected standalone target data directive.");
7780 break;
7781 case OMPD_target_enter_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00007782 RTLFn = HasNowait ? OMPRTL__tgt_target_data_begin_nowait
7783 : OMPRTL__tgt_target_data_begin;
Samuel Antao8d2d7302016-05-26 18:30:22 +00007784 break;
7785 case OMPD_target_exit_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00007786 RTLFn = HasNowait ? OMPRTL__tgt_target_data_end_nowait
7787 : OMPRTL__tgt_target_data_end;
Samuel Antao8d2d7302016-05-26 18:30:22 +00007788 break;
7789 case OMPD_target_update:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00007790 RTLFn = HasNowait ? OMPRTL__tgt_target_data_update_nowait
7791 : OMPRTL__tgt_target_data_update;
Samuel Antao8d2d7302016-05-26 18:30:22 +00007792 break;
7793 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007794 CGF.EmitRuntimeCall(createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007795 };
7796
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007797 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray](
7798 CodeGenFunction &CGF, PrePostActionTy &) {
7799 // Fill up the arrays with all the mapped variables.
7800 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
7801 MappableExprsHandler::MapValuesArrayTy Pointers;
7802 MappableExprsHandler::MapValuesArrayTy Sizes;
7803 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007804
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007805 // Get map clause information.
7806 MappableExprsHandler MEHandler(D, CGF);
7807 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
7808
7809 TargetDataInfo Info;
7810 // Fill up the arrays and create the arguments.
7811 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
7812 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
7813 Info.PointersArray, Info.SizesArray,
7814 Info.MapTypesArray, Info);
7815 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
7816 InputInfo.BasePointersArray =
7817 Address(Info.BasePointersArray, CGM.getPointerAlign());
7818 InputInfo.PointersArray =
7819 Address(Info.PointersArray, CGM.getPointerAlign());
7820 InputInfo.SizesArray =
7821 Address(Info.SizesArray, CGM.getPointerAlign());
7822 MapTypesArray = Info.MapTypesArray;
7823 if (D.hasClausesOfKind<OMPDependClause>())
7824 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
7825 else
Alexey Bataev768f1f22018-01-09 19:59:25 +00007826 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007827 };
7828
7829 if (IfCond)
7830 emitOMPIfClause(CGF, IfCond, TargetThenGen,
7831 [](CodeGenFunction &CGF, PrePostActionTy &) {});
7832 else {
7833 RegionCodeGenTy ThenRCG(TargetThenGen);
7834 ThenRCG(CGF);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007835 }
7836}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007837
7838namespace {
7839 /// Kind of parameter in a function with 'declare simd' directive.
7840 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
7841 /// Attribute set of the parameter.
7842 struct ParamAttrTy {
7843 ParamKindTy Kind = Vector;
7844 llvm::APSInt StrideOrArg;
7845 llvm::APSInt Alignment;
7846 };
7847} // namespace
7848
7849static unsigned evaluateCDTSize(const FunctionDecl *FD,
7850 ArrayRef<ParamAttrTy> ParamAttrs) {
7851 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
7852 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
7853 // of that clause. The VLEN value must be power of 2.
7854 // In other case the notion of the function`s "characteristic data type" (CDT)
7855 // is used to compute the vector length.
7856 // CDT is defined in the following order:
7857 // a) For non-void function, the CDT is the return type.
7858 // b) If the function has any non-uniform, non-linear parameters, then the
7859 // CDT is the type of the first such parameter.
7860 // c) If the CDT determined by a) or b) above is struct, union, or class
7861 // type which is pass-by-value (except for the type that maps to the
7862 // built-in complex data type), the characteristic data type is int.
7863 // d) If none of the above three cases is applicable, the CDT is int.
7864 // The VLEN is then determined based on the CDT and the size of vector
7865 // register of that ISA for which current vector version is generated. The
7866 // VLEN is computed using the formula below:
7867 // VLEN = sizeof(vector_register) / sizeof(CDT),
7868 // where vector register size specified in section 3.2.1 Registers and the
7869 // Stack Frame of original AMD64 ABI document.
7870 QualType RetType = FD->getReturnType();
7871 if (RetType.isNull())
7872 return 0;
7873 ASTContext &C = FD->getASTContext();
7874 QualType CDT;
7875 if (!RetType.isNull() && !RetType->isVoidType())
7876 CDT = RetType;
7877 else {
7878 unsigned Offset = 0;
7879 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
7880 if (ParamAttrs[Offset].Kind == Vector)
7881 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
7882 ++Offset;
7883 }
7884 if (CDT.isNull()) {
7885 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
7886 if (ParamAttrs[I + Offset].Kind == Vector) {
7887 CDT = FD->getParamDecl(I)->getType();
7888 break;
7889 }
7890 }
7891 }
7892 }
7893 if (CDT.isNull())
7894 CDT = C.IntTy;
7895 CDT = CDT->getCanonicalTypeUnqualified();
7896 if (CDT->isRecordType() || CDT->isUnionType())
7897 CDT = C.IntTy;
7898 return C.getTypeSize(CDT);
7899}
7900
7901static void
7902emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00007903 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007904 ArrayRef<ParamAttrTy> ParamAttrs,
7905 OMPDeclareSimdDeclAttr::BranchStateTy State) {
7906 struct ISADataTy {
7907 char ISA;
7908 unsigned VecRegSize;
7909 };
7910 ISADataTy ISAData[] = {
7911 {
7912 'b', 128
7913 }, // SSE
7914 {
7915 'c', 256
7916 }, // AVX
7917 {
7918 'd', 256
7919 }, // AVX2
7920 {
7921 'e', 512
7922 }, // AVX512
7923 };
7924 llvm::SmallVector<char, 2> Masked;
7925 switch (State) {
7926 case OMPDeclareSimdDeclAttr::BS_Undefined:
7927 Masked.push_back('N');
7928 Masked.push_back('M');
7929 break;
7930 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
7931 Masked.push_back('N');
7932 break;
7933 case OMPDeclareSimdDeclAttr::BS_Inbranch:
7934 Masked.push_back('M');
7935 break;
7936 }
7937 for (auto Mask : Masked) {
7938 for (auto &Data : ISAData) {
7939 SmallString<256> Buffer;
7940 llvm::raw_svector_ostream Out(Buffer);
7941 Out << "_ZGV" << Data.ISA << Mask;
7942 if (!VLENVal) {
7943 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
7944 evaluateCDTSize(FD, ParamAttrs));
7945 } else
7946 Out << VLENVal;
7947 for (auto &ParamAttr : ParamAttrs) {
7948 switch (ParamAttr.Kind){
7949 case LinearWithVarStride:
7950 Out << 's' << ParamAttr.StrideOrArg;
7951 break;
7952 case Linear:
7953 Out << 'l';
7954 if (!!ParamAttr.StrideOrArg)
7955 Out << ParamAttr.StrideOrArg;
7956 break;
7957 case Uniform:
7958 Out << 'u';
7959 break;
7960 case Vector:
7961 Out << 'v';
7962 break;
7963 }
7964 if (!!ParamAttr.Alignment)
7965 Out << 'a' << ParamAttr.Alignment;
7966 }
7967 Out << '_' << Fn->getName();
7968 Fn->addFnAttr(Out.str());
7969 }
7970 }
7971}
7972
7973void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
7974 llvm::Function *Fn) {
7975 ASTContext &C = CGM.getContext();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00007976 FD = FD->getMostRecentDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007977 // Map params to their positions in function decl.
7978 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
7979 if (isa<CXXMethodDecl>(FD))
7980 ParamPositions.insert({FD, 0});
7981 unsigned ParamPos = ParamPositions.size();
David Majnemer59f77922016-06-24 04:05:48 +00007982 for (auto *P : FD->parameters()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007983 ParamPositions.insert({P->getCanonicalDecl(), ParamPos});
7984 ++ParamPos;
7985 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00007986 while (FD) {
7987 for (auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
7988 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
7989 // Mark uniform parameters.
7990 for (auto *E : Attr->uniforms()) {
7991 E = E->IgnoreParenImpCasts();
7992 unsigned Pos;
7993 if (isa<CXXThisExpr>(E))
7994 Pos = ParamPositions[FD];
7995 else {
7996 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7997 ->getCanonicalDecl();
7998 Pos = ParamPositions[PVD];
7999 }
8000 ParamAttrs[Pos].Kind = Uniform;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008001 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008002 // Get alignment info.
8003 auto NI = Attr->alignments_begin();
8004 for (auto *E : Attr->aligneds()) {
8005 E = E->IgnoreParenImpCasts();
8006 unsigned Pos;
8007 QualType ParmTy;
8008 if (isa<CXXThisExpr>(E)) {
8009 Pos = ParamPositions[FD];
8010 ParmTy = E->getType();
8011 } else {
8012 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
8013 ->getCanonicalDecl();
8014 Pos = ParamPositions[PVD];
8015 ParmTy = PVD->getType();
8016 }
8017 ParamAttrs[Pos].Alignment =
8018 (*NI)
8019 ? (*NI)->EvaluateKnownConstInt(C)
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008020 : llvm::APSInt::getUnsigned(
8021 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
8022 .getQuantity());
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008023 ++NI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008024 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008025 // Mark linear parameters.
8026 auto SI = Attr->steps_begin();
8027 auto MI = Attr->modifiers_begin();
8028 for (auto *E : Attr->linears()) {
8029 E = E->IgnoreParenImpCasts();
8030 unsigned Pos;
8031 if (isa<CXXThisExpr>(E))
8032 Pos = ParamPositions[FD];
8033 else {
8034 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
8035 ->getCanonicalDecl();
8036 Pos = ParamPositions[PVD];
8037 }
8038 auto &ParamAttr = ParamAttrs[Pos];
8039 ParamAttr.Kind = Linear;
8040 if (*SI) {
8041 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
8042 Expr::SE_AllowSideEffects)) {
8043 if (auto *DRE = cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
8044 if (auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
8045 ParamAttr.Kind = LinearWithVarStride;
8046 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
8047 ParamPositions[StridePVD->getCanonicalDecl()]);
8048 }
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008049 }
8050 }
8051 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008052 ++SI;
8053 ++MI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008054 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008055 llvm::APSInt VLENVal;
8056 if (const Expr *VLEN = Attr->getSimdlen())
8057 VLENVal = VLEN->EvaluateKnownConstInt(C);
8058 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
8059 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
8060 CGM.getTriple().getArch() == llvm::Triple::x86_64)
8061 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008062 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008063 FD = FD->getPreviousDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008064 }
8065}
Alexey Bataev8b427062016-05-25 12:36:08 +00008066
8067namespace {
8068/// Cleanup action for doacross support.
8069class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
8070public:
8071 static const int DoacrossFinArgs = 2;
8072
8073private:
8074 llvm::Value *RTLFn;
8075 llvm::Value *Args[DoacrossFinArgs];
8076
8077public:
8078 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
8079 : RTLFn(RTLFn) {
8080 assert(CallArgs.size() == DoacrossFinArgs);
8081 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
8082 }
8083 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
8084 if (!CGF.HaveInsertPoint())
8085 return;
8086 CGF.EmitRuntimeCall(RTLFn, Args);
8087 }
8088};
8089} // namespace
8090
8091void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
8092 const OMPLoopDirective &D) {
8093 if (!CGF.HaveInsertPoint())
8094 return;
8095
8096 ASTContext &C = CGM.getContext();
8097 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
8098 RecordDecl *RD;
8099 if (KmpDimTy.isNull()) {
8100 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
8101 // kmp_int64 lo; // lower
8102 // kmp_int64 up; // upper
8103 // kmp_int64 st; // stride
8104 // };
8105 RD = C.buildImplicitRecord("kmp_dim");
8106 RD->startDefinition();
8107 addFieldToRecordDecl(C, RD, Int64Ty);
8108 addFieldToRecordDecl(C, RD, Int64Ty);
8109 addFieldToRecordDecl(C, RD, Int64Ty);
8110 RD->completeDefinition();
8111 KmpDimTy = C.getRecordType(RD);
8112 } else
8113 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
8114
8115 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
8116 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
8117 enum { LowerFD = 0, UpperFD, StrideFD };
8118 // Fill dims with data.
8119 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
8120 // dims.upper = num_iterations;
8121 LValue UpperLVal =
8122 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
8123 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
8124 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
8125 Int64Ty, D.getNumIterations()->getExprLoc());
8126 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
8127 // dims.stride = 1;
8128 LValue StrideLVal =
8129 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
8130 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
8131 StrideLVal);
8132
8133 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
8134 // kmp_int32 num_dims, struct kmp_dim * dims);
8135 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
8136 getThreadID(CGF, D.getLocStart()),
8137 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
8138 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
8139 DimsAddr.getPointer(), CGM.VoidPtrTy)};
8140
8141 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
8142 CGF.EmitRuntimeCall(RTLFn, Args);
8143 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
8144 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
8145 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
8146 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
8147 llvm::makeArrayRef(FiniArgs));
8148}
8149
8150void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
8151 const OMPDependClause *C) {
8152 QualType Int64Ty =
8153 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
8154 const Expr *CounterVal = C->getCounterValue();
8155 assert(CounterVal);
8156 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
8157 CounterVal->getType(), Int64Ty,
8158 CounterVal->getExprLoc());
8159 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
8160 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
8161 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
8162 getThreadID(CGF, C->getLocStart()),
8163 CntAddr.getPointer()};
8164 llvm::Value *RTLFn;
8165 if (C->getDependencyKind() == OMPC_DEPEND_source)
8166 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
8167 else {
8168 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
8169 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
8170 }
8171 CGF.EmitRuntimeCall(RTLFn, Args);
8172}
8173
Alexey Bataev7ef47a62018-02-22 18:33:31 +00008174void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, SourceLocation Loc,
8175 llvm::Value *Callee,
8176 ArrayRef<llvm::Value *> Args) const {
8177 assert(Loc.isValid() && "Outlined function call location must be valid.");
Alexey Bataev3c595a62017-08-14 15:01:03 +00008178 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
8179
8180 if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008181 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00008182 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008183 return;
8184 }
8185 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00008186 CGF.EmitRuntimeCall(Callee, Args);
8187}
8188
8189void CGOpenMPRuntime::emitOutlinedFunctionCall(
8190 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
8191 ArrayRef<llvm::Value *> Args) const {
Alexey Bataev7ef47a62018-02-22 18:33:31 +00008192 emitCall(CGF, Loc, OutlinedFn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008193}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00008194
8195Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
8196 const VarDecl *NativeParam,
8197 const VarDecl *TargetParam) const {
8198 return CGF.GetAddrOfLocalVar(NativeParam);
8199}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00008200
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00008201Address CGOpenMPRuntime::getAddressOfLocalVariable(CodeGenFunction &CGF,
8202 const VarDecl *VD) {
8203 return Address::invalid();
8204}
8205
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00008206llvm::Value *CGOpenMPSIMDRuntime::emitParallelOutlinedFunction(
8207 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8208 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
8209 llvm_unreachable("Not supported in SIMD-only mode");
8210}
8211
8212llvm::Value *CGOpenMPSIMDRuntime::emitTeamsOutlinedFunction(
8213 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8214 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
8215 llvm_unreachable("Not supported in SIMD-only mode");
8216}
8217
8218llvm::Value *CGOpenMPSIMDRuntime::emitTaskOutlinedFunction(
8219 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8220 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
8221 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
8222 bool Tied, unsigned &NumberOfParts) {
8223 llvm_unreachable("Not supported in SIMD-only mode");
8224}
8225
8226void CGOpenMPSIMDRuntime::emitParallelCall(CodeGenFunction &CGF,
8227 SourceLocation Loc,
8228 llvm::Value *OutlinedFn,
8229 ArrayRef<llvm::Value *> CapturedVars,
8230 const Expr *IfCond) {
8231 llvm_unreachable("Not supported in SIMD-only mode");
8232}
8233
8234void CGOpenMPSIMDRuntime::emitCriticalRegion(
8235 CodeGenFunction &CGF, StringRef CriticalName,
8236 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
8237 const Expr *Hint) {
8238 llvm_unreachable("Not supported in SIMD-only mode");
8239}
8240
8241void CGOpenMPSIMDRuntime::emitMasterRegion(CodeGenFunction &CGF,
8242 const RegionCodeGenTy &MasterOpGen,
8243 SourceLocation Loc) {
8244 llvm_unreachable("Not supported in SIMD-only mode");
8245}
8246
8247void CGOpenMPSIMDRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
8248 SourceLocation Loc) {
8249 llvm_unreachable("Not supported in SIMD-only mode");
8250}
8251
8252void CGOpenMPSIMDRuntime::emitTaskgroupRegion(
8253 CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen,
8254 SourceLocation Loc) {
8255 llvm_unreachable("Not supported in SIMD-only mode");
8256}
8257
8258void CGOpenMPSIMDRuntime::emitSingleRegion(
8259 CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen,
8260 SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars,
8261 ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs,
8262 ArrayRef<const Expr *> AssignmentOps) {
8263 llvm_unreachable("Not supported in SIMD-only mode");
8264}
8265
8266void CGOpenMPSIMDRuntime::emitOrderedRegion(CodeGenFunction &CGF,
8267 const RegionCodeGenTy &OrderedOpGen,
8268 SourceLocation Loc,
8269 bool IsThreads) {
8270 llvm_unreachable("Not supported in SIMD-only mode");
8271}
8272
8273void CGOpenMPSIMDRuntime::emitBarrierCall(CodeGenFunction &CGF,
8274 SourceLocation Loc,
8275 OpenMPDirectiveKind Kind,
8276 bool EmitChecks,
8277 bool ForceSimpleCall) {
8278 llvm_unreachable("Not supported in SIMD-only mode");
8279}
8280
8281void CGOpenMPSIMDRuntime::emitForDispatchInit(
8282 CodeGenFunction &CGF, SourceLocation Loc,
8283 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
8284 bool Ordered, const DispatchRTInput &DispatchValues) {
8285 llvm_unreachable("Not supported in SIMD-only mode");
8286}
8287
8288void CGOpenMPSIMDRuntime::emitForStaticInit(
8289 CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind,
8290 const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values) {
8291 llvm_unreachable("Not supported in SIMD-only mode");
8292}
8293
8294void CGOpenMPSIMDRuntime::emitDistributeStaticInit(
8295 CodeGenFunction &CGF, SourceLocation Loc,
8296 OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values) {
8297 llvm_unreachable("Not supported in SIMD-only mode");
8298}
8299
8300void CGOpenMPSIMDRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
8301 SourceLocation Loc,
8302 unsigned IVSize,
8303 bool IVSigned) {
8304 llvm_unreachable("Not supported in SIMD-only mode");
8305}
8306
8307void CGOpenMPSIMDRuntime::emitForStaticFinish(CodeGenFunction &CGF,
8308 SourceLocation Loc,
8309 OpenMPDirectiveKind DKind) {
8310 llvm_unreachable("Not supported in SIMD-only mode");
8311}
8312
8313llvm::Value *CGOpenMPSIMDRuntime::emitForNext(CodeGenFunction &CGF,
8314 SourceLocation Loc,
8315 unsigned IVSize, bool IVSigned,
8316 Address IL, Address LB,
8317 Address UB, Address ST) {
8318 llvm_unreachable("Not supported in SIMD-only mode");
8319}
8320
8321void CGOpenMPSIMDRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
8322 llvm::Value *NumThreads,
8323 SourceLocation Loc) {
8324 llvm_unreachable("Not supported in SIMD-only mode");
8325}
8326
8327void CGOpenMPSIMDRuntime::emitProcBindClause(CodeGenFunction &CGF,
8328 OpenMPProcBindClauseKind ProcBind,
8329 SourceLocation Loc) {
8330 llvm_unreachable("Not supported in SIMD-only mode");
8331}
8332
8333Address CGOpenMPSIMDRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
8334 const VarDecl *VD,
8335 Address VDAddr,
8336 SourceLocation Loc) {
8337 llvm_unreachable("Not supported in SIMD-only mode");
8338}
8339
8340llvm::Function *CGOpenMPSIMDRuntime::emitThreadPrivateVarDefinition(
8341 const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit,
8342 CodeGenFunction *CGF) {
8343 llvm_unreachable("Not supported in SIMD-only mode");
8344}
8345
8346Address CGOpenMPSIMDRuntime::getAddrOfArtificialThreadPrivate(
8347 CodeGenFunction &CGF, QualType VarType, StringRef Name) {
8348 llvm_unreachable("Not supported in SIMD-only mode");
8349}
8350
8351void CGOpenMPSIMDRuntime::emitFlush(CodeGenFunction &CGF,
8352 ArrayRef<const Expr *> Vars,
8353 SourceLocation Loc) {
8354 llvm_unreachable("Not supported in SIMD-only mode");
8355}
8356
8357void CGOpenMPSIMDRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
8358 const OMPExecutableDirective &D,
8359 llvm::Value *TaskFunction,
8360 QualType SharedsTy, Address Shareds,
8361 const Expr *IfCond,
8362 const OMPTaskDataTy &Data) {
8363 llvm_unreachable("Not supported in SIMD-only mode");
8364}
8365
8366void CGOpenMPSIMDRuntime::emitTaskLoopCall(
8367 CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D,
8368 llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
8369 const Expr *IfCond, const OMPTaskDataTy &Data) {
8370 llvm_unreachable("Not supported in SIMD-only mode");
8371}
8372
8373void CGOpenMPSIMDRuntime::emitReduction(
8374 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
8375 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
8376 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
8377 assert(Options.SimpleReduction && "Only simple reduction is expected.");
8378 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
8379 ReductionOps, Options);
8380}
8381
8382llvm::Value *CGOpenMPSIMDRuntime::emitTaskReductionInit(
8383 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
8384 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
8385 llvm_unreachable("Not supported in SIMD-only mode");
8386}
8387
8388void CGOpenMPSIMDRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
8389 SourceLocation Loc,
8390 ReductionCodeGen &RCG,
8391 unsigned N) {
8392 llvm_unreachable("Not supported in SIMD-only mode");
8393}
8394
8395Address CGOpenMPSIMDRuntime::getTaskReductionItem(CodeGenFunction &CGF,
8396 SourceLocation Loc,
8397 llvm::Value *ReductionsPtr,
8398 LValue SharedLVal) {
8399 llvm_unreachable("Not supported in SIMD-only mode");
8400}
8401
8402void CGOpenMPSIMDRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
8403 SourceLocation Loc) {
8404 llvm_unreachable("Not supported in SIMD-only mode");
8405}
8406
8407void CGOpenMPSIMDRuntime::emitCancellationPointCall(
8408 CodeGenFunction &CGF, SourceLocation Loc,
8409 OpenMPDirectiveKind CancelRegion) {
8410 llvm_unreachable("Not supported in SIMD-only mode");
8411}
8412
8413void CGOpenMPSIMDRuntime::emitCancelCall(CodeGenFunction &CGF,
8414 SourceLocation Loc, const Expr *IfCond,
8415 OpenMPDirectiveKind CancelRegion) {
8416 llvm_unreachable("Not supported in SIMD-only mode");
8417}
8418
8419void CGOpenMPSIMDRuntime::emitTargetOutlinedFunction(
8420 const OMPExecutableDirective &D, StringRef ParentName,
8421 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
8422 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
8423 llvm_unreachable("Not supported in SIMD-only mode");
8424}
8425
8426void CGOpenMPSIMDRuntime::emitTargetCall(CodeGenFunction &CGF,
8427 const OMPExecutableDirective &D,
8428 llvm::Value *OutlinedFn,
8429 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00008430 const Expr *IfCond, const Expr *Device) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00008431 llvm_unreachable("Not supported in SIMD-only mode");
8432}
8433
8434bool CGOpenMPSIMDRuntime::emitTargetFunctions(GlobalDecl GD) {
8435 llvm_unreachable("Not supported in SIMD-only mode");
8436}
8437
8438bool CGOpenMPSIMDRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
8439 llvm_unreachable("Not supported in SIMD-only mode");
8440}
8441
8442bool CGOpenMPSIMDRuntime::emitTargetGlobal(GlobalDecl GD) {
8443 return false;
8444}
8445
8446llvm::Function *CGOpenMPSIMDRuntime::emitRegistrationFunction() {
8447 return nullptr;
8448}
8449
8450void CGOpenMPSIMDRuntime::emitTeamsCall(CodeGenFunction &CGF,
8451 const OMPExecutableDirective &D,
8452 SourceLocation Loc,
8453 llvm::Value *OutlinedFn,
8454 ArrayRef<llvm::Value *> CapturedVars) {
8455 llvm_unreachable("Not supported in SIMD-only mode");
8456}
8457
8458void CGOpenMPSIMDRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
8459 const Expr *NumTeams,
8460 const Expr *ThreadLimit,
8461 SourceLocation Loc) {
8462 llvm_unreachable("Not supported in SIMD-only mode");
8463}
8464
8465void CGOpenMPSIMDRuntime::emitTargetDataCalls(
8466 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8467 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
8468 llvm_unreachable("Not supported in SIMD-only mode");
8469}
8470
8471void CGOpenMPSIMDRuntime::emitTargetDataStandAloneCall(
8472 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8473 const Expr *Device) {
8474 llvm_unreachable("Not supported in SIMD-only mode");
8475}
8476
8477void CGOpenMPSIMDRuntime::emitDoacrossInit(CodeGenFunction &CGF,
8478 const OMPLoopDirective &D) {
8479 llvm_unreachable("Not supported in SIMD-only mode");
8480}
8481
8482void CGOpenMPSIMDRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
8483 const OMPDependClause *C) {
8484 llvm_unreachable("Not supported in SIMD-only mode");
8485}
8486
8487const VarDecl *
8488CGOpenMPSIMDRuntime::translateParameter(const FieldDecl *FD,
8489 const VarDecl *NativeParam) const {
8490 llvm_unreachable("Not supported in SIMD-only mode");
8491}
8492
8493Address
8494CGOpenMPSIMDRuntime::getParameterAddress(CodeGenFunction &CGF,
8495 const VarDecl *NativeParam,
8496 const VarDecl *TargetParam) const {
8497 llvm_unreachable("Not supported in SIMD-only mode");
8498}
8499