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