blob: 7a4c2a83c517090c6f47cf10334dcb33644ebfb0 [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"
Alexey Bataeva4fa0b82018-04-16 17:59:34 +000017#include "CGRecordLayout.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000018#include "CodeGenFunction.h"
John McCall5ad74072017-03-02 20:04:19 +000019#include "clang/CodeGen/ConstantInitBuilder.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000020#include "clang/AST/Decl.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000021#include "clang/AST/StmtOpenMP.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000022#include "llvm/ADT/ArrayRef.h"
Alexey Bataev0f87dbe2017-08-14 17:56:13 +000023#include "llvm/ADT/BitmaskEnum.h"
Teresa Johnsonffc4e242016-11-11 05:35:12 +000024#include "llvm/Bitcode/BitcodeReader.h"
Alexey Bataevd74d0602014-10-13 06:02:40 +000025#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000026#include "llvm/IR/DerivedTypes.h"
27#include "llvm/IR/GlobalValue.h"
28#include "llvm/IR/Value.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000029#include "llvm/Support/Format.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000030#include "llvm/Support/raw_ostream.h"
Alexey Bataev23b69422014-06-18 07:08:49 +000031#include <cassert>
Alexey Bataev9959db52014-05-06 10:08:46 +000032
33using namespace clang;
34using namespace CodeGen;
35
Benjamin Kramerc52193f2014-10-10 13:57:57 +000036namespace {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000037/// \brief Base class for handling code generation inside OpenMP regions.
Alexey Bataev18095712014-10-10 12:19:54 +000038class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
39public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000040 /// \brief Kinds of OpenMP regions used in codegen.
41 enum CGOpenMPRegionKind {
42 /// \brief Region with outlined function for standalone 'parallel'
43 /// directive.
44 ParallelOutlinedRegion,
45 /// \brief Region with outlined function for standalone 'task' directive.
46 TaskOutlinedRegion,
47 /// \brief Region for constructs that do not require function outlining,
48 /// like 'for', 'sections', 'atomic' etc. directives.
49 InlinedRegion,
Samuel Antaobed3c462015-10-02 16:14:20 +000050 /// \brief Region with outlined function for standalone 'target' directive.
51 TargetRegion,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000052 };
Alexey Bataev18095712014-10-10 12:19:54 +000053
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000054 CGOpenMPRegionInfo(const CapturedStmt &CS,
55 const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000056 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
57 bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000058 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
Alexey Bataev25e5b442015-09-15 12:52:43 +000059 CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000060
61 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000062 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
63 bool HasCancel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +000064 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
Alexey Bataev25e5b442015-09-15 12:52:43 +000065 Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000066
67 /// \brief Get a variable or parameter for storing global thread id
Alexey Bataev18095712014-10-10 12:19:54 +000068 /// inside OpenMP construct.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000069 virtual const VarDecl *getThreadIDVariable() const = 0;
Alexey Bataev18095712014-10-10 12:19:54 +000070
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000071 /// \brief Emit the captured statement body.
Hans Wennborg7eb54642015-09-10 17:07:54 +000072 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000073
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000074 /// \brief Get an LValue for the current ThreadID variable.
Alexey Bataev62b63b12015-03-10 07:28:44 +000075 /// \return LValue for thread id variable. This LValue always has type int32*.
76 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
Alexey Bataev18095712014-10-10 12:19:54 +000077
Alexey Bataev48591dd2016-04-20 04:01:36 +000078 virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {}
79
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000080 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000081
Alexey Bataev81c7ea02015-07-03 09:56:58 +000082 OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
83
Alexey Bataev25e5b442015-09-15 12:52:43 +000084 bool hasCancel() const { return HasCancel; }
85
Alexey Bataev18095712014-10-10 12:19:54 +000086 static bool classof(const CGCapturedStmtInfo *Info) {
87 return Info->getKind() == CR_OpenMP;
88 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000089
Alexey Bataev48591dd2016-04-20 04:01:36 +000090 ~CGOpenMPRegionInfo() override = default;
91
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000092protected:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000093 CGOpenMPRegionKind RegionKind;
Hans Wennborg45c74392016-01-12 20:54:36 +000094 RegionCodeGenTy CodeGen;
Alexey Bataev81c7ea02015-07-03 09:56:58 +000095 OpenMPDirectiveKind Kind;
Alexey Bataev25e5b442015-09-15 12:52:43 +000096 bool HasCancel;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000097};
Alexey Bataev18095712014-10-10 12:19:54 +000098
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000099/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000100class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000101public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000102 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000103 const RegionCodeGenTy &CodeGen,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000104 OpenMPDirectiveKind Kind, bool HasCancel,
105 StringRef HelperName)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000106 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
107 HasCancel),
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000108 ThreadIDVar(ThreadIDVar), HelperName(HelperName) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000109 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
110 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000111
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000112 /// \brief Get a variable or parameter for storing global thread id
113 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000114 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000115
Alexey Bataev18095712014-10-10 12:19:54 +0000116 /// \brief Get the name of the capture helper.
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000117 StringRef getHelperName() const override { return HelperName; }
Alexey Bataev18095712014-10-10 12:19:54 +0000118
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000119 static bool classof(const CGCapturedStmtInfo *Info) {
120 return CGOpenMPRegionInfo::classof(Info) &&
121 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
122 ParallelOutlinedRegion;
123 }
124
Alexey Bataev18095712014-10-10 12:19:54 +0000125private:
126 /// \brief A variable or parameter storing global thread id for OpenMP
127 /// constructs.
128 const VarDecl *ThreadIDVar;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000129 StringRef HelperName;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000130};
131
Alexey Bataev62b63b12015-03-10 07:28:44 +0000132/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000133class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000134public:
Alexey Bataev48591dd2016-04-20 04:01:36 +0000135 class UntiedTaskActionTy final : public PrePostActionTy {
136 bool Untied;
137 const VarDecl *PartIDVar;
138 const RegionCodeGenTy UntiedCodeGen;
139 llvm::SwitchInst *UntiedSwitch = nullptr;
140
141 public:
142 UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
143 const RegionCodeGenTy &UntiedCodeGen)
144 : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
145 void Enter(CodeGenFunction &CGF) override {
146 if (Untied) {
147 // Emit task switching point.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000148 LValue PartIdLVal = CGF.EmitLoadOfPointerLValue(
Alexey Bataev48591dd2016-04-20 04:01:36 +0000149 CGF.GetAddrOfLocalVar(PartIDVar),
150 PartIDVar->getType()->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000151 llvm::Value *Res =
152 CGF.EmitLoadOfScalar(PartIdLVal, PartIDVar->getLocation());
153 llvm::BasicBlock *DoneBB = CGF.createBasicBlock(".untied.done.");
Alexey Bataev48591dd2016-04-20 04:01:36 +0000154 UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
155 CGF.EmitBlock(DoneBB);
156 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
157 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
158 UntiedSwitch->addCase(CGF.Builder.getInt32(0),
159 CGF.Builder.GetInsertBlock());
160 emitUntiedSwitch(CGF);
161 }
162 }
163 void emitUntiedSwitch(CodeGenFunction &CGF) const {
164 if (Untied) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000165 LValue PartIdLVal = CGF.EmitLoadOfPointerLValue(
Alexey Bataev48591dd2016-04-20 04:01:36 +0000166 CGF.GetAddrOfLocalVar(PartIDVar),
167 PartIDVar->getType()->castAs<PointerType>());
168 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
169 PartIdLVal);
170 UntiedCodeGen(CGF);
171 CodeGenFunction::JumpDest CurPoint =
172 CGF.getJumpDestInCurrentScope(".untied.next.");
173 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
174 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
175 UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
176 CGF.Builder.GetInsertBlock());
177 CGF.EmitBranchThroughCleanup(CurPoint);
178 CGF.EmitBlock(CurPoint.getBlock());
179 }
180 }
181 unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
182 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000183 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000184 const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000185 const RegionCodeGenTy &CodeGen,
Alexey Bataev48591dd2016-04-20 04:01:36 +0000186 OpenMPDirectiveKind Kind, bool HasCancel,
187 const UntiedTaskActionTy &Action)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000188 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
Alexey Bataev48591dd2016-04-20 04:01:36 +0000189 ThreadIDVar(ThreadIDVar), Action(Action) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000190 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
191 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000192
Alexey Bataev62b63b12015-03-10 07:28:44 +0000193 /// \brief Get a variable or parameter for storing global thread id
194 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000195 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000196
197 /// \brief Get an LValue for the current ThreadID variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000198 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000199
Alexey Bataev62b63b12015-03-10 07:28:44 +0000200 /// \brief Get the name of the capture helper.
201 StringRef getHelperName() const override { return ".omp_outlined."; }
202
Alexey Bataev48591dd2016-04-20 04:01:36 +0000203 void emitUntiedSwitch(CodeGenFunction &CGF) override {
204 Action.emitUntiedSwitch(CGF);
205 }
206
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000207 static bool classof(const CGCapturedStmtInfo *Info) {
208 return CGOpenMPRegionInfo::classof(Info) &&
209 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
210 TaskOutlinedRegion;
211 }
212
Alexey Bataev62b63b12015-03-10 07:28:44 +0000213private:
214 /// \brief A variable or parameter storing global thread id for OpenMP
215 /// constructs.
216 const VarDecl *ThreadIDVar;
Alexey Bataev48591dd2016-04-20 04:01:36 +0000217 /// Action for emitting code for untied tasks.
218 const UntiedTaskActionTy &Action;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000219};
220
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000221/// \brief API for inlined captured statement code generation in OpenMP
222/// constructs.
223class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
224public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000225 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000226 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000227 OpenMPDirectiveKind Kind, bool HasCancel)
228 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
229 OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000230 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000231
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000232 // \brief Retrieve the value of the context parameter.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000233 llvm::Value *getContextValue() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000234 if (OuterRegionInfo)
235 return OuterRegionInfo->getContextValue();
236 llvm_unreachable("No context value for inlined OpenMP region");
237 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000238
Hans Wennborg7eb54642015-09-10 17:07:54 +0000239 void setContextValue(llvm::Value *V) override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000240 if (OuterRegionInfo) {
241 OuterRegionInfo->setContextValue(V);
242 return;
243 }
244 llvm_unreachable("No context value for inlined OpenMP region");
245 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000246
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000247 /// \brief Lookup the captured field decl for a variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000248 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000249 if (OuterRegionInfo)
250 return OuterRegionInfo->lookup(VD);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000251 // If there is no outer outlined region,no need to lookup in a list of
252 // captured variables, we can use the original one.
253 return nullptr;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000254 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000255
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000256 FieldDecl *getThisFieldDecl() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000257 if (OuterRegionInfo)
258 return OuterRegionInfo->getThisFieldDecl();
259 return nullptr;
260 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000261
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000262 /// \brief Get a variable or parameter for storing global thread id
263 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000264 const VarDecl *getThreadIDVariable() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000265 if (OuterRegionInfo)
266 return OuterRegionInfo->getThreadIDVariable();
267 return nullptr;
268 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000269
Alexey Bataev311a9282017-10-12 13:51:32 +0000270 /// \brief Get an LValue for the current ThreadID variable.
271 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override {
272 if (OuterRegionInfo)
273 return OuterRegionInfo->getThreadIDVariableLValue(CGF);
274 llvm_unreachable("No LValue for inlined OpenMP construct");
275 }
276
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000277 /// \brief Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000278 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000279 if (auto *OuterRegionInfo = getOldCSI())
280 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000281 llvm_unreachable("No helper name for inlined OpenMP construct");
282 }
283
Alexey Bataev48591dd2016-04-20 04:01:36 +0000284 void emitUntiedSwitch(CodeGenFunction &CGF) override {
285 if (OuterRegionInfo)
286 OuterRegionInfo->emitUntiedSwitch(CGF);
287 }
288
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000289 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
290
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000291 static bool classof(const CGCapturedStmtInfo *Info) {
292 return CGOpenMPRegionInfo::classof(Info) &&
293 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
294 }
295
Alexey Bataev48591dd2016-04-20 04:01:36 +0000296 ~CGOpenMPInlinedRegionInfo() override = default;
297
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000298private:
299 /// \brief CodeGen info about outer OpenMP region.
300 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
301 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000302};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000303
Samuel Antaobed3c462015-10-02 16:14:20 +0000304/// \brief API for captured statement code generation in OpenMP target
305/// constructs. For this captures, implicit parameters are used instead of the
Samuel Antaoee8fb302016-01-06 13:42:12 +0000306/// captured fields. The name of the target region has to be unique in a given
307/// application so it is provided by the client, because only the client has
308/// the information to generate that.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000309class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
Samuel Antaobed3c462015-10-02 16:14:20 +0000310public:
311 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000312 const RegionCodeGenTy &CodeGen, StringRef HelperName)
Samuel Antaobed3c462015-10-02 16:14:20 +0000313 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000314 /*HasCancel=*/false),
315 HelperName(HelperName) {}
Samuel Antaobed3c462015-10-02 16:14:20 +0000316
317 /// \brief This is unused for target regions because each starts executing
318 /// with a single thread.
319 const VarDecl *getThreadIDVariable() const override { return nullptr; }
320
321 /// \brief Get the name of the capture helper.
Samuel Antaoee8fb302016-01-06 13:42:12 +0000322 StringRef getHelperName() const override { return HelperName; }
Samuel Antaobed3c462015-10-02 16:14:20 +0000323
324 static bool classof(const CGCapturedStmtInfo *Info) {
325 return CGOpenMPRegionInfo::classof(Info) &&
326 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
327 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000328
329private:
330 StringRef HelperName;
Samuel Antaobed3c462015-10-02 16:14:20 +0000331};
332
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000333static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000334 llvm_unreachable("No codegen for expressions");
335}
336/// \brief API for generation of expressions captured in a innermost OpenMP
337/// region.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000338class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000339public:
340 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
341 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
342 OMPD_unknown,
343 /*HasCancel=*/false),
344 PrivScope(CGF) {
345 // Make sure the globals captured in the provided statement are local by
346 // using the privatization logic. We assume the same variable is not
347 // captured more than once.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000348 for (const auto &C : CS.captures()) {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000349 if (!C.capturesVariable() && !C.capturesVariableByCopy())
350 continue;
351
352 const VarDecl *VD = C.getCapturedVar();
353 if (VD->isLocalVarDeclOrParm())
354 continue;
355
356 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
357 /*RefersToEnclosingVariableOrCapture=*/false,
358 VD->getType().getNonReferenceType(), VK_LValue,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000359 C.getLocation());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000360 PrivScope.addPrivate(
361 VD, [&CGF, &DRE]() { return CGF.EmitLValue(&DRE).getAddress(); });
Samuel Antaob68e2db2016-03-03 16:20:23 +0000362 }
363 (void)PrivScope.Privatize();
364 }
365
366 /// \brief Lookup the captured field decl for a variable.
367 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000368 if (const FieldDecl *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
Samuel Antaob68e2db2016-03-03 16:20:23 +0000369 return FD;
370 return nullptr;
371 }
372
373 /// \brief Emit the captured statement body.
374 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
375 llvm_unreachable("No body for expressions");
376 }
377
378 /// \brief Get a variable or parameter for storing global thread id
379 /// inside OpenMP construct.
380 const VarDecl *getThreadIDVariable() const override {
381 llvm_unreachable("No thread id for expressions");
382 }
383
384 /// \brief Get the name of the capture helper.
385 StringRef getHelperName() const override {
386 llvm_unreachable("No helper name for expressions");
387 }
388
389 static bool classof(const CGCapturedStmtInfo *Info) { return false; }
390
391private:
392 /// Private scope to capture global variables.
393 CodeGenFunction::OMPPrivateScope PrivScope;
394};
395
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000396/// \brief RAII for emitting code of OpenMP constructs.
397class InlinedOpenMPRegionRAII {
398 CodeGenFunction &CGF;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000399 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
400 FieldDecl *LambdaThisCaptureField = nullptr;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000401 const CodeGen::CGBlockInfo *BlockInfo = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000402
403public:
404 /// \brief Constructs region for combined constructs.
405 /// \param CodeGen Code generation sequence for combined directives. Includes
406 /// a list of functions used for code generation of implicitly inlined
407 /// regions.
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000408 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000409 OpenMPDirectiveKind Kind, bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000410 : CGF(CGF) {
411 // Start emission for the construct.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000412 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
413 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000414 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
415 LambdaThisCaptureField = CGF.LambdaThisCaptureField;
416 CGF.LambdaThisCaptureField = nullptr;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000417 BlockInfo = CGF.BlockInfo;
418 CGF.BlockInfo = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000419 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000420
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000421 ~InlinedOpenMPRegionRAII() {
422 // Restore original CapturedStmtInfo only if we're done with code emission.
423 auto *OldCSI =
424 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
425 delete CGF.CapturedStmtInfo;
426 CGF.CapturedStmtInfo = OldCSI;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000427 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
428 CGF.LambdaThisCaptureField = LambdaThisCaptureField;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000429 CGF.BlockInfo = BlockInfo;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000430 }
431};
432
Alexey Bataev50b3c952016-02-19 10:38:26 +0000433/// \brief Values for bit flags used in the ident_t to describe the fields.
434/// All enumeric elements are named and described in accordance with the code
435/// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000436enum OpenMPLocationFlags : unsigned {
Alexey Bataev50b3c952016-02-19 10:38:26 +0000437 /// \brief Use trampoline for internal microtask.
438 OMP_IDENT_IMD = 0x01,
439 /// \brief Use c-style ident structure.
440 OMP_IDENT_KMPC = 0x02,
441 /// \brief Atomic reduction option for kmpc_reduce.
442 OMP_ATOMIC_REDUCE = 0x10,
443 /// \brief Explicit 'barrier' directive.
444 OMP_IDENT_BARRIER_EXPL = 0x20,
445 /// \brief Implicit barrier in code.
446 OMP_IDENT_BARRIER_IMPL = 0x40,
447 /// \brief Implicit barrier in 'for' directive.
448 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
449 /// \brief Implicit barrier in 'sections' directive.
450 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
451 /// \brief Implicit barrier in 'single' directive.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000452 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140,
453 /// Call of __kmp_for_static_init for static loop.
454 OMP_IDENT_WORK_LOOP = 0x200,
455 /// Call of __kmp_for_static_init for sections.
456 OMP_IDENT_WORK_SECTIONS = 0x400,
457 /// Call of __kmp_for_static_init for distribute.
458 OMP_IDENT_WORK_DISTRIBUTE = 0x800,
459 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_IDENT_WORK_DISTRIBUTE)
Alexey Bataev50b3c952016-02-19 10:38:26 +0000460};
461
462/// \brief Describes ident structure that describes a source location.
463/// All descriptions are taken from
464/// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
465/// Original structure:
466/// typedef struct ident {
467/// kmp_int32 reserved_1; /**< might be used in Fortran;
468/// see above */
469/// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
470/// KMP_IDENT_KMPC identifies this union
471/// member */
472/// kmp_int32 reserved_2; /**< not really used in Fortran any more;
473/// see above */
474///#if USE_ITT_BUILD
475/// /* but currently used for storing
476/// region-specific ITT */
477/// /* contextual information. */
478///#endif /* USE_ITT_BUILD */
479/// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
480/// C++ */
481/// char const *psource; /**< String describing the source location.
482/// The string is composed of semi-colon separated
483// fields which describe the source file,
484/// the function and a pair of line numbers that
485/// delimit the construct.
486/// */
487/// } ident_t;
488enum IdentFieldIndex {
489 /// \brief might be used in Fortran
490 IdentField_Reserved_1,
491 /// \brief OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
492 IdentField_Flags,
493 /// \brief Not really used in Fortran any more
494 IdentField_Reserved_2,
495 /// \brief Source[4] in Fortran, do not use for C++
496 IdentField_Reserved_3,
497 /// \brief String describing the source location. The string is composed of
498 /// semi-colon separated fields which describe the source file, the function
499 /// and a pair of line numbers that delimit the construct.
500 IdentField_PSource
501};
502
503/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
504/// the enum sched_type in kmp.h).
505enum OpenMPSchedType {
506 /// \brief Lower bound for default (unordered) versions.
507 OMP_sch_lower = 32,
508 OMP_sch_static_chunked = 33,
509 OMP_sch_static = 34,
510 OMP_sch_dynamic_chunked = 35,
511 OMP_sch_guided_chunked = 36,
512 OMP_sch_runtime = 37,
513 OMP_sch_auto = 38,
Alexey Bataev6cff6242016-05-30 13:05:14 +0000514 /// static with chunk adjustment (e.g., simd)
Samuel Antao4c8035b2016-12-12 18:00:20 +0000515 OMP_sch_static_balanced_chunked = 45,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000516 /// \brief Lower bound for 'ordered' versions.
517 OMP_ord_lower = 64,
518 OMP_ord_static_chunked = 65,
519 OMP_ord_static = 66,
520 OMP_ord_dynamic_chunked = 67,
521 OMP_ord_guided_chunked = 68,
522 OMP_ord_runtime = 69,
523 OMP_ord_auto = 70,
524 OMP_sch_default = OMP_sch_static,
Carlo Bertollifc35ad22016-03-07 16:04:49 +0000525 /// \brief dist_schedule types
526 OMP_dist_sch_static_chunked = 91,
527 OMP_dist_sch_static = 92,
Alexey Bataev9ebd7422016-05-10 09:57:36 +0000528 /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
529 /// Set if the monotonic schedule modifier was present.
530 OMP_sch_modifier_monotonic = (1 << 29),
531 /// Set if the nonmonotonic schedule modifier was present.
532 OMP_sch_modifier_nonmonotonic = (1 << 30),
Alexey Bataev50b3c952016-02-19 10:38:26 +0000533};
534
535enum OpenMPRTLFunction {
536 /// \brief Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
537 /// kmpc_micro microtask, ...);
538 OMPRTL__kmpc_fork_call,
539 /// \brief Call to void *__kmpc_threadprivate_cached(ident_t *loc,
540 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
541 OMPRTL__kmpc_threadprivate_cached,
542 /// \brief Call to void __kmpc_threadprivate_register( ident_t *,
543 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
544 OMPRTL__kmpc_threadprivate_register,
545 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
546 OMPRTL__kmpc_global_thread_num,
547 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
548 // kmp_critical_name *crit);
549 OMPRTL__kmpc_critical,
550 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
551 // global_tid, kmp_critical_name *crit, uintptr_t hint);
552 OMPRTL__kmpc_critical_with_hint,
553 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
554 // kmp_critical_name *crit);
555 OMPRTL__kmpc_end_critical,
556 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
557 // global_tid);
558 OMPRTL__kmpc_cancel_barrier,
559 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
560 OMPRTL__kmpc_barrier,
561 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
562 OMPRTL__kmpc_for_static_fini,
563 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
564 // global_tid);
565 OMPRTL__kmpc_serialized_parallel,
566 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
567 // global_tid);
568 OMPRTL__kmpc_end_serialized_parallel,
569 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
570 // kmp_int32 num_threads);
571 OMPRTL__kmpc_push_num_threads,
572 // Call to void __kmpc_flush(ident_t *loc);
573 OMPRTL__kmpc_flush,
574 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
575 OMPRTL__kmpc_master,
576 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
577 OMPRTL__kmpc_end_master,
578 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
579 // int end_part);
580 OMPRTL__kmpc_omp_taskyield,
581 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
582 OMPRTL__kmpc_single,
583 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
584 OMPRTL__kmpc_end_single,
585 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
586 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
587 // kmp_routine_entry_t *task_entry);
588 OMPRTL__kmpc_omp_task_alloc,
589 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
590 // new_task);
591 OMPRTL__kmpc_omp_task,
592 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
593 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
594 // kmp_int32 didit);
595 OMPRTL__kmpc_copyprivate,
596 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
597 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
598 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
599 OMPRTL__kmpc_reduce,
600 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
601 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
602 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
603 // *lck);
604 OMPRTL__kmpc_reduce_nowait,
605 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
606 // kmp_critical_name *lck);
607 OMPRTL__kmpc_end_reduce,
608 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
609 // kmp_critical_name *lck);
610 OMPRTL__kmpc_end_reduce_nowait,
611 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
612 // kmp_task_t * new_task);
613 OMPRTL__kmpc_omp_task_begin_if0,
614 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
615 // kmp_task_t * new_task);
616 OMPRTL__kmpc_omp_task_complete_if0,
617 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
618 OMPRTL__kmpc_ordered,
619 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
620 OMPRTL__kmpc_end_ordered,
621 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
622 // global_tid);
623 OMPRTL__kmpc_omp_taskwait,
624 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
625 OMPRTL__kmpc_taskgroup,
626 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
627 OMPRTL__kmpc_end_taskgroup,
628 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
629 // int proc_bind);
630 OMPRTL__kmpc_push_proc_bind,
631 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
632 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
633 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
634 OMPRTL__kmpc_omp_task_with_deps,
635 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
636 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
637 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
638 OMPRTL__kmpc_omp_wait_deps,
639 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
640 // global_tid, kmp_int32 cncl_kind);
641 OMPRTL__kmpc_cancellationpoint,
642 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
643 // kmp_int32 cncl_kind);
644 OMPRTL__kmpc_cancel,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000645 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
646 // kmp_int32 num_teams, kmp_int32 thread_limit);
647 OMPRTL__kmpc_push_num_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000648 // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
649 // microtask, ...);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000650 OMPRTL__kmpc_fork_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000651 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
652 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
653 // sched, kmp_uint64 grainsize, void *task_dup);
654 OMPRTL__kmpc_taskloop,
Alexey Bataev8b427062016-05-25 12:36:08 +0000655 // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
656 // num_dims, struct kmp_dim *dims);
657 OMPRTL__kmpc_doacross_init,
658 // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
659 OMPRTL__kmpc_doacross_fini,
660 // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
661 // *vec);
662 OMPRTL__kmpc_doacross_post,
663 // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
664 // *vec);
665 OMPRTL__kmpc_doacross_wait,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000666 // Call to void *__kmpc_task_reduction_init(int gtid, int num_data, void
667 // *data);
668 OMPRTL__kmpc_task_reduction_init,
669 // Call to void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
670 // *d);
671 OMPRTL__kmpc_task_reduction_get_th_data,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000672
673 //
674 // Offloading related calls
675 //
George Rokos63bc9d62017-11-21 18:25:12 +0000676 // Call to int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
677 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Alexey Bataev50b3c952016-02-19 10:38:26 +0000678 // *arg_types);
679 OMPRTL__tgt_target,
Alexey Bataeva9f77c62017-12-13 21:04:20 +0000680 // Call to int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
681 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
682 // *arg_types);
683 OMPRTL__tgt_target_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000684 // Call to int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
685 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
686 // *arg_types, int32_t num_teams, int32_t thread_limit);
Samuel Antaob68e2db2016-03-03 16:20:23 +0000687 OMPRTL__tgt_target_teams,
Alexey Bataeva9f77c62017-12-13 21:04:20 +0000688 // Call to int32_t __tgt_target_teams_nowait(int64_t device_id, void
689 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
690 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
691 OMPRTL__tgt_target_teams_nowait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000692 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
693 OMPRTL__tgt_register_lib,
694 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
695 OMPRTL__tgt_unregister_lib,
George Rokos63bc9d62017-11-21 18:25:12 +0000696 // Call to void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
697 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antaodf158d52016-04-27 22:58:19 +0000698 OMPRTL__tgt_target_data_begin,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000699 // Call to void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
700 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
701 // *arg_types);
702 OMPRTL__tgt_target_data_begin_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000703 // Call to void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
704 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antaodf158d52016-04-27 22:58:19 +0000705 OMPRTL__tgt_target_data_end,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000706 // Call to void __tgt_target_data_end_nowait(int64_t device_id, int32_t
707 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
708 // *arg_types);
709 OMPRTL__tgt_target_data_end_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000710 // Call to void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
711 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antao8d2d7302016-05-26 18:30:22 +0000712 OMPRTL__tgt_target_data_update,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000713 // Call to void __tgt_target_data_update_nowait(int64_t device_id, int32_t
714 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
715 // *arg_types);
716 OMPRTL__tgt_target_data_update_nowait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000717};
718
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000719/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
720/// region.
721class CleanupTy final : public EHScopeStack::Cleanup {
722 PrePostActionTy *Action;
723
724public:
725 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
726 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
727 if (!CGF.HaveInsertPoint())
728 return;
729 Action->Exit(CGF);
730 }
731};
732
Hans Wennborg7eb54642015-09-10 17:07:54 +0000733} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000734
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000735void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
736 CodeGenFunction::RunCleanupsScope Scope(CGF);
737 if (PrePostAction) {
738 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
739 Callback(CodeGen, CGF, *PrePostAction);
740 } else {
741 PrePostActionTy Action;
742 Callback(CodeGen, CGF, Action);
743 }
744}
745
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000746/// Check if the combiner is a call to UDR combiner and if it is so return the
747/// UDR decl used for reduction.
748static const OMPDeclareReductionDecl *
749getReductionInit(const Expr *ReductionOp) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000750 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
751 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
752 if (const auto *DRE =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000753 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000754 if (const auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000755 return DRD;
756 return nullptr;
757}
758
759static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
760 const OMPDeclareReductionDecl *DRD,
761 const Expr *InitOp,
762 Address Private, Address Original,
763 QualType Ty) {
764 if (DRD->getInitializer()) {
765 std::pair<llvm::Function *, llvm::Function *> Reduction =
766 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000767 const auto *CE = cast<CallExpr>(InitOp);
768 const auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000769 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
770 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000771 const auto *LHSDRE =
772 cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
773 const auto *RHSDRE =
774 cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000775 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
776 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000777 [=]() { return Private; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000778 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000779 [=]() { return Original; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000780 (void)PrivateScope.Privatize();
781 RValue Func = RValue::get(Reduction.second);
782 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
783 CGF.EmitIgnoredExpr(InitOp);
784 } else {
785 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
786 auto *GV = new llvm::GlobalVariable(
787 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
788 llvm::GlobalValue::PrivateLinkage, Init, ".init");
789 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
790 RValue InitRVal;
791 switch (CGF.getEvaluationKind(Ty)) {
792 case TEK_Scalar:
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000793 InitRVal = CGF.EmitLoadOfLValue(LV, DRD->getLocation());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000794 break;
795 case TEK_Complex:
796 InitRVal =
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000797 RValue::getComplex(CGF.EmitLoadOfComplex(LV, DRD->getLocation()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000798 break;
799 case TEK_Aggregate:
800 InitRVal = RValue::getAggregate(LV.getAddress());
801 break;
802 }
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000803 OpaqueValueExpr OVE(DRD->getLocation(), Ty, VK_RValue);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000804 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
805 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
806 /*IsInitializer=*/false);
807 }
808}
809
810/// \brief Emit initialization of arrays of complex types.
811/// \param DestAddr Address of the array.
812/// \param Type Type of array.
813/// \param Init Initial expression of array.
814/// \param SrcAddr Address of the original array.
815static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
Alexey Bataeva7b19152017-10-12 20:03:39 +0000816 QualType Type, bool EmitDeclareReductionInit,
817 const Expr *Init,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000818 const OMPDeclareReductionDecl *DRD,
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000819 Address SrcAddr = Address::invalid()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000820 // Perform element-by-element initialization.
821 QualType ElementTy;
822
823 // Drill down to the base element type on both arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000824 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
825 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000826 DestAddr =
827 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
828 if (DRD)
829 SrcAddr =
830 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
831
832 llvm::Value *SrcBegin = nullptr;
833 if (DRD)
834 SrcBegin = SrcAddr.getPointer();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000835 llvm::Value *DestBegin = DestAddr.getPointer();
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000836 // Cast from pointer to array type to pointer to single element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000837 llvm::Value *DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000838 // The basic structure here is a while-do loop.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000839 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
840 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
841 llvm::Value *IsEmpty =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000842 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
843 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
844
845 // Enter the loop body, making that address the current address.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000846 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000847 CGF.EmitBlock(BodyBB);
848
849 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
850
851 llvm::PHINode *SrcElementPHI = nullptr;
852 Address SrcElementCurrent = Address::invalid();
853 if (DRD) {
854 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
855 "omp.arraycpy.srcElementPast");
856 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
857 SrcElementCurrent =
858 Address(SrcElementPHI,
859 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
860 }
861 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
862 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
863 DestElementPHI->addIncoming(DestBegin, EntryBB);
864 Address DestElementCurrent =
865 Address(DestElementPHI,
866 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
867
868 // Emit copy.
869 {
870 CodeGenFunction::RunCleanupsScope InitScope(CGF);
Alexey Bataeva7b19152017-10-12 20:03:39 +0000871 if (EmitDeclareReductionInit) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000872 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
873 SrcElementCurrent, ElementTy);
874 } else
875 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
876 /*IsInitializer=*/false);
877 }
878
879 if (DRD) {
880 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000881 llvm::Value *SrcElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000882 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
883 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
884 }
885
886 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000887 llvm::Value *DestElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000888 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
889 // Check whether we've reached the end.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000890 llvm::Value *Done =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000891 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
892 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
893 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
894
895 // Done.
896 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
897}
898
Alexey Bataev92327c52018-03-26 16:40:55 +0000899static llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy>
900isDeclareTargetDeclaration(const ValueDecl *VD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000901 for (const Decl *D : VD->redecls()) {
Alexey Bataev92327c52018-03-26 16:40:55 +0000902 if (!D->hasAttrs())
903 continue;
904 if (const auto *Attr = D->getAttr<OMPDeclareTargetDeclAttr>())
905 return Attr->getMapType();
906 }
907 return llvm::None;
908}
909
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000910LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000911 return CGF.EmitOMPSharedLValue(E);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000912}
913
914LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
915 const Expr *E) {
916 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
917 return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
918 return LValue();
919}
920
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000921void ReductionCodeGen::emitAggregateInitialization(
922 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
923 const OMPDeclareReductionDecl *DRD) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000924 // Emit VarDecl with copy init for arrays.
925 // Get the address of the original variable captured in current
926 // captured region.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000927 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000928 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva7b19152017-10-12 20:03:39 +0000929 bool EmitDeclareReductionInit =
930 DRD && (DRD->getInitializer() || !PrivateVD->hasInit());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000931 EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
Alexey Bataeva7b19152017-10-12 20:03:39 +0000932 EmitDeclareReductionInit,
933 EmitDeclareReductionInit ? ClausesData[N].ReductionOp
934 : PrivateVD->getInit(),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000935 DRD, SharedLVal.getAddress());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000936}
937
938ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
939 ArrayRef<const Expr *> Privates,
940 ArrayRef<const Expr *> ReductionOps) {
941 ClausesData.reserve(Shareds.size());
942 SharedAddresses.reserve(Shareds.size());
943 Sizes.reserve(Shareds.size());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000944 BaseDecls.reserve(Shareds.size());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000945 auto IPriv = Privates.begin();
946 auto IRed = ReductionOps.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000947 for (const Expr *Ref : Shareds) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000948 ClausesData.emplace_back(Ref, *IPriv, *IRed);
949 std::advance(IPriv, 1);
950 std::advance(IRed, 1);
951 }
952}
953
954void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
955 assert(SharedAddresses.size() == N &&
956 "Number of generated lvalues must be exactly N.");
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000957 LValue First = emitSharedLValue(CGF, ClausesData[N].Ref);
958 LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Ref);
959 SharedAddresses.emplace_back(First, Second);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000960}
961
962void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000963 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000964 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
965 QualType PrivateType = PrivateVD->getType();
966 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000967 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000968 Sizes.emplace_back(
969 CGF.getTypeSize(
970 SharedAddresses[N].first.getType().getNonReferenceType()),
971 nullptr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000972 return;
973 }
974 llvm::Value *Size;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000975 llvm::Value *SizeInChars;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000976 auto *ElemType =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000977 cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
978 ->getElementType();
979 auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000980 if (AsArraySection) {
981 Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
982 SharedAddresses[N].first.getPointer());
983 Size = CGF.Builder.CreateNUWAdd(
984 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000985 SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000986 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000987 SizeInChars = CGF.getTypeSize(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000988 SharedAddresses[N].first.getType().getNonReferenceType());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000989 Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000990 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000991 Sizes.emplace_back(SizeInChars, Size);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000992 CodeGenFunction::OpaqueValueMapping OpaqueMap(
993 CGF,
994 cast<OpaqueValueExpr>(
995 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
996 RValue::get(Size));
997 CGF.EmitVariablyModifiedType(PrivateType);
998}
999
1000void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
1001 llvm::Value *Size) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001002 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001003 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1004 QualType PrivateType = PrivateVD->getType();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001005 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001006 assert(!Size && !Sizes[N].second &&
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001007 "Size should be nullptr for non-variably modified reduction "
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001008 "items.");
1009 return;
1010 }
1011 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1012 CGF,
1013 cast<OpaqueValueExpr>(
1014 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
1015 RValue::get(Size));
1016 CGF.EmitVariablyModifiedType(PrivateType);
1017}
1018
1019void ReductionCodeGen::emitInitialization(
1020 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
1021 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
1022 assert(SharedAddresses.size() > N && "No variable was generated");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001023 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001024 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001025 const OMPDeclareReductionDecl *DRD =
1026 getReductionInit(ClausesData[N].ReductionOp);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001027 QualType PrivateType = PrivateVD->getType();
1028 PrivateAddr = CGF.Builder.CreateElementBitCast(
1029 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1030 QualType SharedType = SharedAddresses[N].first.getType();
1031 SharedLVal = CGF.MakeAddrLValue(
1032 CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
1033 CGF.ConvertTypeForMem(SharedType)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001034 SharedType, SharedAddresses[N].first.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001035 CGF.CGM.getTBAAInfoForSubobject(SharedAddresses[N].first, SharedType));
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001036 if (CGF.getContext().getAsArrayType(PrivateVD->getType())) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001037 emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001038 } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
1039 emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
1040 PrivateAddr, SharedLVal.getAddress(),
1041 SharedLVal.getType());
1042 } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
1043 !CGF.isTrivialInitializer(PrivateVD->getInit())) {
1044 CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
1045 PrivateVD->getType().getQualifiers(),
1046 /*IsInitializer=*/false);
1047 }
1048}
1049
1050bool ReductionCodeGen::needCleanups(unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001051 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001052 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1053 QualType PrivateType = PrivateVD->getType();
1054 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1055 return DTorKind != QualType::DK_none;
1056}
1057
1058void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
1059 Address PrivateAddr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001060 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001061 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1062 QualType PrivateType = PrivateVD->getType();
1063 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1064 if (needCleanups(N)) {
1065 PrivateAddr = CGF.Builder.CreateElementBitCast(
1066 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1067 CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
1068 }
1069}
1070
1071static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1072 LValue BaseLV) {
1073 BaseTy = BaseTy.getNonReferenceType();
1074 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1075 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001076 if (const auto *PtrTy = BaseTy->getAs<PointerType>()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001077 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001078 } else {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00001079 LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(), BaseTy);
1080 BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001081 }
1082 BaseTy = BaseTy->getPointeeType();
1083 }
1084 return CGF.MakeAddrLValue(
1085 CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
1086 CGF.ConvertTypeForMem(ElTy)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001087 BaseLV.getType(), BaseLV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001088 CGF.CGM.getTBAAInfoForSubobject(BaseLV, BaseLV.getType()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001089}
1090
1091static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1092 llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
1093 llvm::Value *Addr) {
1094 Address Tmp = Address::invalid();
1095 Address TopTmp = Address::invalid();
1096 Address MostTopTmp = Address::invalid();
1097 BaseTy = BaseTy.getNonReferenceType();
1098 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1099 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1100 Tmp = CGF.CreateMemTemp(BaseTy);
1101 if (TopTmp.isValid())
1102 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
1103 else
1104 MostTopTmp = Tmp;
1105 TopTmp = Tmp;
1106 BaseTy = BaseTy->getPointeeType();
1107 }
1108 llvm::Type *Ty = BaseLVType;
1109 if (Tmp.isValid())
1110 Ty = Tmp.getElementType();
1111 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
1112 if (Tmp.isValid()) {
1113 CGF.Builder.CreateStore(Addr, Tmp);
1114 return MostTopTmp;
1115 }
1116 return Address(Addr, BaseLVAlignment);
1117}
1118
Alexey Bataev1c44e152018-03-06 18:59:43 +00001119static const VarDecl *getBaseDecl(const Expr *Ref, const DeclRefExpr *&DE) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001120 const VarDecl *OrigVD = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001121 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(Ref)) {
1122 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
1123 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001124 Base = TempOASE->getBase()->IgnoreParenImpCasts();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001125 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001126 Base = TempASE->getBase()->IgnoreParenImpCasts();
1127 DE = cast<DeclRefExpr>(Base);
1128 OrigVD = cast<VarDecl>(DE->getDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001129 } else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Ref)) {
1130 const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
1131 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001132 Base = TempASE->getBase()->IgnoreParenImpCasts();
1133 DE = cast<DeclRefExpr>(Base);
1134 OrigVD = cast<VarDecl>(DE->getDecl());
1135 }
Alexey Bataev1c44e152018-03-06 18:59:43 +00001136 return OrigVD;
1137}
1138
1139Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
1140 Address PrivateAddr) {
1141 const DeclRefExpr *DE;
1142 if (const VarDecl *OrigVD = ::getBaseDecl(ClausesData[N].Ref, DE)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001143 BaseDecls.emplace_back(OrigVD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001144 LValue OriginalBaseLValue = CGF.EmitLValue(DE);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001145 LValue BaseLValue =
1146 loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1147 OriginalBaseLValue);
1148 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1149 BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001150 llvm::Value *PrivatePointer =
1151 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1152 PrivateAddr.getPointer(),
1153 SharedAddresses[N].first.getAddress().getType());
1154 llvm::Value *Ptr = CGF.Builder.CreateGEP(PrivatePointer, Adjustment);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001155 return castToBase(CGF, OrigVD->getType(),
1156 SharedAddresses[N].first.getType(),
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001157 OriginalBaseLValue.getAddress().getType(),
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001158 OriginalBaseLValue.getAlignment(), Ptr);
1159 }
1160 BaseDecls.emplace_back(
1161 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1162 return PrivateAddr;
1163}
1164
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001165bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001166 const OMPDeclareReductionDecl *DRD =
1167 getReductionInit(ClausesData[N].ReductionOp);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001168 return DRD && DRD->getInitializer();
1169}
1170
Alexey Bataev18095712014-10-10 12:19:54 +00001171LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00001172 return CGF.EmitLoadOfPointerLValue(
1173 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1174 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +00001175}
1176
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001177void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001178 if (!CGF.HaveInsertPoint())
1179 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001180 // 1.2.2 OpenMP Language Terminology
1181 // Structured block - An executable statement with a single entry at the
1182 // top and a single exit at the bottom.
1183 // The point of exit cannot be a branch out of the structured block.
1184 // longjmp() and throw() must not violate the entry/exit criteria.
1185 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001186 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001187 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001188}
1189
Alexey Bataev62b63b12015-03-10 07:28:44 +00001190LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1191 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001192 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1193 getThreadIDVariable()->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00001194 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001195}
1196
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001197static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
1198 QualType FieldTy) {
1199 auto *Field = FieldDecl::Create(
1200 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
1201 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
1202 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
1203 Field->setAccess(AS_public);
1204 DC->addDecl(Field);
1205 return Field;
1206}
1207
Alexey Bataev9959db52014-05-06 10:08:46 +00001208CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001209 : CGM(CGM), OffloadEntriesInfoManager(CGM) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001210 ASTContext &C = CGM.getContext();
1211 RecordDecl *RD = C.buildImplicitRecord("ident_t");
1212 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1213 RD->startDefinition();
1214 // reserved_1
1215 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1216 // flags
1217 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1218 // reserved_2
1219 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1220 // reserved_3
1221 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1222 // psource
1223 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
1224 RD->completeDefinition();
1225 IdentQTy = C.getRecordType(RD);
1226 IdentTy = CGM.getTypes().ConvertRecordDeclType(RD);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001227 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +00001228
1229 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +00001230}
1231
Alexey Bataev91797552015-03-18 04:13:55 +00001232void CGOpenMPRuntime::clear() {
1233 InternalVars.clear();
1234}
1235
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001236static llvm::Function *
1237emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1238 const Expr *CombinerInitializer, const VarDecl *In,
1239 const VarDecl *Out, bool IsCombiner) {
1240 // void .omp_combiner.(Ty *in, Ty *out);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001241 ASTContext &C = CGM.getContext();
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001242 QualType PtrTy = C.getPointerType(Ty).withRestrict();
1243 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001244 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001245 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001246 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001247 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001248 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001249 Args.push_back(&OmpInParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001250 const CGFunctionInfo &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001251 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001252 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001253 auto *Fn = llvm::Function::Create(
1254 FnTy, llvm::GlobalValue::InternalLinkage,
1255 IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001256 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001257 Fn->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001258 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001259 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001260 CodeGenFunction CGF(CGM);
1261 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1262 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001263 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, In->getLocation(),
1264 Out->getLocation());
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001265 CodeGenFunction::OMPPrivateScope Scope(CGF);
1266 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001267 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001268 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1269 .getAddress();
1270 });
1271 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001272 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001273 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1274 .getAddress();
1275 });
1276 (void)Scope.Privatize();
Alexey Bataev070f43a2017-09-06 14:49:58 +00001277 if (!IsCombiner && Out->hasInit() &&
1278 !CGF.isTrivialInitializer(Out->getInit())) {
1279 CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
1280 Out->getType().getQualifiers(),
1281 /*IsInitializer=*/true);
1282 }
1283 if (CombinerInitializer)
1284 CGF.EmitIgnoredExpr(CombinerInitializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001285 Scope.ForceCleanup();
1286 CGF.FinishFunction();
1287 return Fn;
1288}
1289
1290void CGOpenMPRuntime::emitUserDefinedReduction(
1291 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1292 if (UDRMap.count(D) > 0)
1293 return;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001294 ASTContext &C = CGM.getContext();
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001295 if (!In || !Out) {
1296 In = &C.Idents.get("omp_in");
1297 Out = &C.Idents.get("omp_out");
1298 }
1299 llvm::Function *Combiner = emitCombinerOrInitializer(
1300 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
1301 cast<VarDecl>(D->lookup(Out).front()),
1302 /*IsCombiner=*/true);
1303 llvm::Function *Initializer = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001304 if (const Expr *Init = D->getInitializer()) {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001305 if (!Priv || !Orig) {
1306 Priv = &C.Idents.get("omp_priv");
1307 Orig = &C.Idents.get("omp_orig");
1308 }
1309 Initializer = emitCombinerOrInitializer(
Alexey Bataev070f43a2017-09-06 14:49:58 +00001310 CGM, D->getType(),
1311 D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init
1312 : nullptr,
1313 cast<VarDecl>(D->lookup(Orig).front()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001314 cast<VarDecl>(D->lookup(Priv).front()),
1315 /*IsCombiner=*/false);
1316 }
Alexey Bataev43a919f2018-04-13 17:48:43 +00001317 UDRMap.try_emplace(D, Combiner, Initializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001318 if (CGF) {
1319 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1320 Decls.second.push_back(D);
1321 }
1322}
1323
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001324std::pair<llvm::Function *, llvm::Function *>
1325CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1326 auto I = UDRMap.find(D);
1327 if (I != UDRMap.end())
1328 return I->second;
1329 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1330 return UDRMap.lookup(D);
1331}
1332
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001333static llvm::Value *emitParallelOrTeamsOutlinedFunction(
1334 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1335 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1336 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001337 assert(ThreadIDVar->getType()->isPointerType() &&
1338 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +00001339 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00001340 bool HasCancel = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001341 if (const auto *OPD = dyn_cast<OMPParallelDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001342 HasCancel = OPD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001343 else if (const auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001344 HasCancel = OPSD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001345 else if (const auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001346 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001347 else if (const auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D))
Alexey Bataev2139ed62017-11-16 18:20:21 +00001348 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001349 else if (const auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&D))
Alexey Bataev10a54312017-11-27 16:54:08 +00001350 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001351 else if (const auto *OPFD =
1352 dyn_cast<OMPTeamsDistributeParallelForDirective>(&D))
Alexey Bataev10a54312017-11-27 16:54:08 +00001353 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001354 else if (const auto *OPFD =
Alexey Bataev10a54312017-11-27 16:54:08 +00001355 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D))
1356 HasCancel = OPFD->hasCancel();
Alexey Bataev25e5b442015-09-15 12:52:43 +00001357 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001358 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +00001359 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001360 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +00001361}
1362
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001363llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
1364 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1365 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1366 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1367 return emitParallelOrTeamsOutlinedFunction(
1368 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1369}
1370
1371llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1372 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1373 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1374 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1375 return emitParallelOrTeamsOutlinedFunction(
1376 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1377}
1378
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001379llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
1380 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +00001381 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1382 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1383 bool Tied, unsigned &NumberOfParts) {
1384 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1385 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001386 llvm::Value *ThreadID = getThreadID(CGF, D.getLocStart());
1387 llvm::Value *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
Alexey Bataev48591dd2016-04-20 04:01:36 +00001388 llvm::Value *TaskArgs[] = {
1389 UpLoc, ThreadID,
1390 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1391 TaskTVar->getType()->castAs<PointerType>())
1392 .getPointer()};
1393 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1394 };
1395 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1396 UntiedCodeGen);
1397 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001398 assert(!ThreadIDVar->getType()->isPointerType() &&
1399 "thread id variable must be of type kmp_int32 for tasks");
Alexey Bataev475a7442018-01-12 19:39:11 +00001400 const OpenMPDirectiveKind Region =
1401 isOpenMPTaskLoopDirective(D.getDirectiveKind()) ? OMPD_taskloop
1402 : OMPD_task;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001403 const CapturedStmt *CS = D.getCapturedStmt(Region);
1404 const auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001405 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +00001406 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1407 InnermostKind,
1408 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +00001409 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001410 llvm::Value *Res = CGF.GenerateCapturedStmtFunction(*CS);
Alexey Bataev48591dd2016-04-20 04:01:36 +00001411 if (!Tied)
1412 NumberOfParts = Action.getNumberOfParts();
1413 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001414}
1415
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001416static void buildStructValue(ConstantStructBuilder &Fields, CodeGenModule &CGM,
1417 const RecordDecl *RD, const CGRecordLayout &RL,
1418 ArrayRef<llvm::Constant *> Data) {
1419 llvm::StructType *StructTy = RL.getLLVMType();
1420 unsigned PrevIdx = 0;
1421 ConstantInitBuilder CIBuilder(CGM);
1422 auto DI = Data.begin();
1423 for (const FieldDecl *FD : RD->fields()) {
1424 unsigned Idx = RL.getLLVMFieldNo(FD);
1425 // Fill the alignment.
1426 for (unsigned I = PrevIdx; I < Idx; ++I)
1427 Fields.add(llvm::Constant::getNullValue(StructTy->getElementType(I)));
1428 PrevIdx = Idx + 1;
1429 Fields.add(*DI);
1430 ++DI;
1431 }
1432}
1433
1434template <class... As>
1435static llvm::GlobalVariable *
1436createConstantGlobalStruct(CodeGenModule &CGM, QualType Ty,
1437 ArrayRef<llvm::Constant *> Data, const Twine &Name,
1438 As &&... Args) {
1439 const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1440 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1441 ConstantInitBuilder CIBuilder(CGM);
1442 ConstantStructBuilder Fields = CIBuilder.beginStruct(RL.getLLVMType());
1443 buildStructValue(Fields, CGM, RD, RL, Data);
1444 return Fields.finishAndCreateGlobal(
1445 Name, CGM.getContext().getAlignOfGlobalVarInChars(Ty),
1446 /*isConstant=*/true, std::forward<As>(Args)...);
1447}
1448
1449template <typename T>
1450void createConstantGlobalStructAndAddToParent(CodeGenModule &CGM, QualType Ty,
1451 ArrayRef<llvm::Constant *> Data,
1452 T &Parent) {
1453 const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1454 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1455 ConstantStructBuilder Fields = Parent.beginStruct(RL.getLLVMType());
1456 buildStructValue(Fields, CGM, RD, RL, Data);
1457 Fields.finishAndAddTo(Parent);
1458}
1459
Alexey Bataev50b3c952016-02-19 10:38:26 +00001460Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001461 CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
Alexey Bataev15007ba2014-05-07 06:18:01 +00001462 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +00001463 if (!Entry) {
1464 if (!DefaultOpenMPPSource) {
1465 // Initialize default location for psource field of ident_t structure of
1466 // all ident_t objects. Format is ";file;function;line;column;;".
1467 // Taken from
1468 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1469 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +00001470 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001471 DefaultOpenMPPSource =
1472 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1473 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001474
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001475 llvm::Constant *Data[] = {llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1476 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
1477 llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1478 llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1479 DefaultOpenMPPSource};
1480 llvm::GlobalValue *DefaultOpenMPLocation = createConstantGlobalStruct(
1481 CGM, IdentQTy, Data, "", llvm::GlobalValue::PrivateLinkage);
1482 DefaultOpenMPLocation->setUnnamedAddr(
1483 llvm::GlobalValue::UnnamedAddr::Global);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001484
John McCall7f416cc2015-09-08 08:05:57 +00001485 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +00001486 }
John McCall7f416cc2015-09-08 08:05:57 +00001487 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +00001488}
1489
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001490llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1491 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001492 unsigned Flags) {
1493 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +00001494 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001495 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +00001496 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +00001497 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001498
1499 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1500
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001501 CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
John McCall7f416cc2015-09-08 08:05:57 +00001502 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001503 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1504 if (I != OpenMPLocThreadIDMap.end())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001505 LocValue = Address(I->second.DebugLoc, Align);
John McCall7f416cc2015-09-08 08:05:57 +00001506
Alexander Musmanc6388682014-12-15 07:07:06 +00001507 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1508 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +00001509 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +00001510 // Generate "ident_t .kmpc_loc.addr;"
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001511 Address AI = CGF.CreateMemTemp(IdentQTy, ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +00001512 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +00001513 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001514 LocValue = AI;
1515
1516 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1517 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001518 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001519 CGF.getTypeSize(IdentQTy));
Alexey Bataev9959db52014-05-06 10:08:46 +00001520 }
1521
1522 // char **psource = &.kmpc_loc_<flags>.addr.psource;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001523 LValue Base = CGF.MakeAddrLValue(LocValue, IdentQTy);
1524 auto Fields = cast<RecordDecl>(IdentQTy->getAsTagDecl())->field_begin();
1525 LValue PSource =
1526 CGF.EmitLValueForField(Base, *std::next(Fields, IdentField_PSource));
Alexey Bataev9959db52014-05-06 10:08:46 +00001527
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001528 llvm::Value *OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
Alexey Bataevf002aca2014-05-30 05:48:40 +00001529 if (OMPDebugLoc == nullptr) {
1530 SmallString<128> Buffer2;
1531 llvm::raw_svector_ostream OS2(Buffer2);
1532 // Build debug location
1533 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1534 OS2 << ";" << PLoc.getFilename() << ";";
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001535 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl))
Alexey Bataevf002aca2014-05-30 05:48:40 +00001536 OS2 << FD->getQualifiedNameAsString();
Alexey Bataevf002aca2014-05-30 05:48:40 +00001537 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1538 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1539 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +00001540 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001541 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001542 CGF.EmitStoreOfScalar(OMPDebugLoc, PSource);
Alexey Bataevf002aca2014-05-30 05:48:40 +00001543
John McCall7f416cc2015-09-08 08:05:57 +00001544 // Our callers always pass this to a runtime function, so for
1545 // convenience, go ahead and return a naked pointer.
1546 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001547}
1548
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001549llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1550 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001551 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1552
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001553 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001554 // Check whether we've already cached a load of the thread id in this
1555 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001556 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001557 if (I != OpenMPLocThreadIDMap.end()) {
1558 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001559 if (ThreadID != nullptr)
1560 return ThreadID;
1561 }
Alexey Bataevaee18552017-08-16 14:01:00 +00001562 // If exceptions are enabled, do not use parameter to avoid possible crash.
Alexey Bataev5d2c9a42017-11-02 18:55:05 +00001563 if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions ||
1564 !CGF.getLangOpts().CXXExceptions ||
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001565 CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
Alexey Bataevaee18552017-08-16 14:01:00 +00001566 if (auto *OMPRegionInfo =
1567 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1568 if (OMPRegionInfo->getThreadIDVariable()) {
1569 // Check if this an outlined function with thread id passed as argument.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001570 LValue LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev1e491372018-01-23 18:44:14 +00001571 ThreadID = CGF.EmitLoadOfScalar(LVal, Loc);
Alexey Bataevaee18552017-08-16 14:01:00 +00001572 // If value loaded in entry block, cache it and use it everywhere in
1573 // function.
1574 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1575 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1576 Elem.second.ThreadID = ThreadID;
1577 }
1578 return ThreadID;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001579 }
Alexey Bataevd6c57552014-07-25 07:55:17 +00001580 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001581 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001582
1583 // This is not an outlined function region - need to call __kmpc_int32
1584 // kmpc_global_thread_num(ident_t *loc).
1585 // Generate thread id value and cache this value for use across the
1586 // function.
1587 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1588 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001589 llvm::CallInst *Call = CGF.Builder.CreateCall(
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001590 createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1591 emitUpdateLocation(CGF, Loc));
1592 Call->setCallingConv(CGF.getRuntimeCC());
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001593 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001594 Elem.second.ThreadID = Call;
1595 return Call;
Alexey Bataev9959db52014-05-06 10:08:46 +00001596}
1597
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001598void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001599 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001600 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1601 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001602 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001603 for(auto *D : FunctionUDRMap[CGF.CurFn])
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001604 UDRMap.erase(D);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001605 FunctionUDRMap.erase(CGF.CurFn);
1606 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001607}
1608
1609llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001610 return IdentTy->getPointerTo();
Alexey Bataev9959db52014-05-06 10:08:46 +00001611}
1612
1613llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001614 if (!Kmpc_MicroTy) {
1615 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1616 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1617 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1618 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1619 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001620 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1621}
1622
1623llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001624CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001625 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001626 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001627 case OMPRTL__kmpc_fork_call: {
1628 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1629 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001630 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1631 getKmpc_MicroPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001632 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001633 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001634 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1635 break;
1636 }
1637 case OMPRTL__kmpc_global_thread_num: {
1638 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001639 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001640 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001641 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001642 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1643 break;
1644 }
Alexey Bataev97720002014-11-11 04:05:39 +00001645 case OMPRTL__kmpc_threadprivate_cached: {
1646 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1647 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1648 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1649 CGM.VoidPtrTy, CGM.SizeTy,
1650 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001651 auto *FnTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001652 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1653 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1654 break;
1655 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001656 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001657 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1658 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001659 llvm::Type *TypeParams[] = {
1660 getIdentTyPointerTy(), CGM.Int32Ty,
1661 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001662 auto *FnTy =
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001663 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1664 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1665 break;
1666 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001667 case OMPRTL__kmpc_critical_with_hint: {
1668 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1669 // kmp_critical_name *crit, uintptr_t hint);
1670 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1671 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1672 CGM.IntPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001673 auto *FnTy =
Alexey Bataevfc57d162015-12-15 10:55:09 +00001674 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1675 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1676 break;
1677 }
Alexey Bataev97720002014-11-11 04:05:39 +00001678 case OMPRTL__kmpc_threadprivate_register: {
1679 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1680 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1681 // typedef void *(*kmpc_ctor)(void *);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001682 auto *KmpcCtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001683 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1684 /*isVarArg*/ false)->getPointerTo();
1685 // typedef void *(*kmpc_cctor)(void *, void *);
1686 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001687 auto *KmpcCopyCtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001688 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001689 /*isVarArg*/ false)
1690 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00001691 // typedef void (*kmpc_dtor)(void *);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001692 auto *KmpcDtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001693 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1694 ->getPointerTo();
1695 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1696 KmpcCopyCtorTy, KmpcDtorTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001697 auto *FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
Alexey Bataev97720002014-11-11 04:05:39 +00001698 /*isVarArg*/ false);
1699 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1700 break;
1701 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001702 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001703 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1704 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001705 llvm::Type *TypeParams[] = {
1706 getIdentTyPointerTy(), CGM.Int32Ty,
1707 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001708 auto *FnTy =
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001709 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1710 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1711 break;
1712 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001713 case OMPRTL__kmpc_cancel_barrier: {
1714 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1715 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001716 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001717 auto *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001718 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1719 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001720 break;
1721 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001722 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001723 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001724 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001725 auto *FnTy =
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001726 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1727 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1728 break;
1729 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001730 case OMPRTL__kmpc_for_static_fini: {
1731 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1732 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001733 auto *FnTy =
Alexander Musmanc6388682014-12-15 07:07:06 +00001734 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1735 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1736 break;
1737 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001738 case OMPRTL__kmpc_push_num_threads: {
1739 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1740 // kmp_int32 num_threads)
1741 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1742 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001743 auto *FnTy =
Alexey Bataevb2059782014-10-13 08:23:51 +00001744 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1745 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1746 break;
1747 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001748 case OMPRTL__kmpc_serialized_parallel: {
1749 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1750 // global_tid);
1751 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001752 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001753 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1754 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1755 break;
1756 }
1757 case OMPRTL__kmpc_end_serialized_parallel: {
1758 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1759 // global_tid);
1760 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001761 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001762 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1763 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1764 break;
1765 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001766 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001767 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001768 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001769 auto *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001770 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001771 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1772 break;
1773 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001774 case OMPRTL__kmpc_master: {
1775 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1776 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001777 auto *FnTy =
Alexey Bataev8d690652014-12-04 07:23:53 +00001778 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1779 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1780 break;
1781 }
1782 case OMPRTL__kmpc_end_master: {
1783 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1784 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001785 auto *FnTy =
Alexey Bataev8d690652014-12-04 07:23:53 +00001786 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1787 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1788 break;
1789 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001790 case OMPRTL__kmpc_omp_taskyield: {
1791 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1792 // int end_part);
1793 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001794 auto *FnTy =
Alexey Bataev9f797f32015-02-05 05:57:51 +00001795 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1796 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1797 break;
1798 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001799 case OMPRTL__kmpc_single: {
1800 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1801 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001802 auto *FnTy =
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001803 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1804 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1805 break;
1806 }
1807 case OMPRTL__kmpc_end_single: {
1808 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1809 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001810 auto *FnTy =
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001811 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1812 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1813 break;
1814 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001815 case OMPRTL__kmpc_omp_task_alloc: {
1816 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1817 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1818 // kmp_routine_entry_t *task_entry);
1819 assert(KmpRoutineEntryPtrTy != nullptr &&
1820 "Type kmp_routine_entry_t must be created.");
1821 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1822 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1823 // Return void * and then cast to particular kmp_task_t type.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001824 auto *FnTy =
Alexey Bataev62b63b12015-03-10 07:28:44 +00001825 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1826 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1827 break;
1828 }
1829 case OMPRTL__kmpc_omp_task: {
1830 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1831 // *new_task);
1832 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1833 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001834 auto *FnTy =
Alexey Bataev62b63b12015-03-10 07:28:44 +00001835 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1836 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1837 break;
1838 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001839 case OMPRTL__kmpc_copyprivate: {
1840 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001841 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001842 // kmp_int32 didit);
1843 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1844 auto *CpyFnTy =
1845 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001846 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001847 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1848 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001849 auto *FnTy =
Alexey Bataeva63048e2015-03-23 06:18:07 +00001850 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1851 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1852 break;
1853 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001854 case OMPRTL__kmpc_reduce: {
1855 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1856 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1857 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1858 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1859 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1860 /*isVarArg=*/false);
1861 llvm::Type *TypeParams[] = {
1862 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1863 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1864 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001865 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001866 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1867 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1868 break;
1869 }
1870 case OMPRTL__kmpc_reduce_nowait: {
1871 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1872 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1873 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1874 // *lck);
1875 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1876 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1877 /*isVarArg=*/false);
1878 llvm::Type *TypeParams[] = {
1879 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1880 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1881 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001882 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001883 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1884 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1885 break;
1886 }
1887 case OMPRTL__kmpc_end_reduce: {
1888 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1889 // kmp_critical_name *lck);
1890 llvm::Type *TypeParams[] = {
1891 getIdentTyPointerTy(), CGM.Int32Ty,
1892 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001893 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001894 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1895 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1896 break;
1897 }
1898 case OMPRTL__kmpc_end_reduce_nowait: {
1899 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1900 // kmp_critical_name *lck);
1901 llvm::Type *TypeParams[] = {
1902 getIdentTyPointerTy(), CGM.Int32Ty,
1903 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001904 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001905 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1906 RTLFn =
1907 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1908 break;
1909 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001910 case OMPRTL__kmpc_omp_task_begin_if0: {
1911 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1912 // *new_task);
1913 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1914 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001915 auto *FnTy =
Alexey Bataev1d677132015-04-22 13:57:31 +00001916 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1917 RTLFn =
1918 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1919 break;
1920 }
1921 case OMPRTL__kmpc_omp_task_complete_if0: {
1922 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1923 // *new_task);
1924 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1925 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001926 auto *FnTy =
Alexey Bataev1d677132015-04-22 13:57:31 +00001927 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1928 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1929 /*Name=*/"__kmpc_omp_task_complete_if0");
1930 break;
1931 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001932 case OMPRTL__kmpc_ordered: {
1933 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1934 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001935 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001936 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1937 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1938 break;
1939 }
1940 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001941 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001942 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001943 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001944 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1945 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1946 break;
1947 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001948 case OMPRTL__kmpc_omp_taskwait: {
1949 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1950 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001951 auto *FnTy =
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001952 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1953 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1954 break;
1955 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001956 case OMPRTL__kmpc_taskgroup: {
1957 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1958 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001959 auto *FnTy =
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001960 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1961 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1962 break;
1963 }
1964 case OMPRTL__kmpc_end_taskgroup: {
1965 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1966 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001967 auto *FnTy =
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001968 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1969 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1970 break;
1971 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001972 case OMPRTL__kmpc_push_proc_bind: {
1973 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1974 // int proc_bind)
1975 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001976 auto *FnTy =
Alexey Bataev7f210c62015-06-18 13:40:03 +00001977 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1978 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1979 break;
1980 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001981 case OMPRTL__kmpc_omp_task_with_deps: {
1982 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1983 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1984 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1985 llvm::Type *TypeParams[] = {
1986 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1987 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001988 auto *FnTy =
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001989 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1990 RTLFn =
1991 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1992 break;
1993 }
1994 case OMPRTL__kmpc_omp_wait_deps: {
1995 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1996 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1997 // kmp_depend_info_t *noalias_dep_list);
1998 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1999 CGM.Int32Ty, CGM.VoidPtrTy,
2000 CGM.Int32Ty, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002001 auto *FnTy =
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002002 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2003 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
2004 break;
2005 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00002006 case OMPRTL__kmpc_cancellationpoint: {
2007 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
2008 // global_tid, kmp_int32 cncl_kind)
2009 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002010 auto *FnTy =
Alexey Bataev0f34da12015-07-02 04:17:07 +00002011 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2012 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
2013 break;
2014 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002015 case OMPRTL__kmpc_cancel: {
2016 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
2017 // kmp_int32 cncl_kind)
2018 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002019 auto *FnTy =
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002020 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2021 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
2022 break;
2023 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002024 case OMPRTL__kmpc_push_num_teams: {
2025 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
2026 // kmp_int32 num_teams, kmp_int32 num_threads)
2027 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
2028 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002029 auto *FnTy =
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002030 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2031 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
2032 break;
2033 }
2034 case OMPRTL__kmpc_fork_teams: {
2035 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
2036 // microtask, ...);
2037 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2038 getKmpc_MicroPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002039 auto *FnTy =
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002040 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
2041 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
2042 break;
2043 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002044 case OMPRTL__kmpc_taskloop: {
2045 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
2046 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
2047 // sched, kmp_uint64 grainsize, void *task_dup);
2048 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2049 CGM.IntTy,
2050 CGM.VoidPtrTy,
2051 CGM.IntTy,
2052 CGM.Int64Ty->getPointerTo(),
2053 CGM.Int64Ty->getPointerTo(),
2054 CGM.Int64Ty,
2055 CGM.IntTy,
2056 CGM.IntTy,
2057 CGM.Int64Ty,
2058 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002059 auto *FnTy =
Alexey Bataev7292c292016-04-25 12:22:29 +00002060 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2061 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
2062 break;
2063 }
Alexey Bataev8b427062016-05-25 12:36:08 +00002064 case OMPRTL__kmpc_doacross_init: {
2065 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
2066 // num_dims, struct kmp_dim *dims);
2067 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2068 CGM.Int32Ty,
2069 CGM.Int32Ty,
2070 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002071 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002072 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2073 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
2074 break;
2075 }
2076 case OMPRTL__kmpc_doacross_fini: {
2077 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
2078 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002079 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002080 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2081 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
2082 break;
2083 }
2084 case OMPRTL__kmpc_doacross_post: {
2085 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
2086 // *vec);
2087 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2088 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002089 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002090 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2091 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
2092 break;
2093 }
2094 case OMPRTL__kmpc_doacross_wait: {
2095 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
2096 // *vec);
2097 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2098 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002099 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002100 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2101 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
2102 break;
2103 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002104 case OMPRTL__kmpc_task_reduction_init: {
2105 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
2106 // *data);
2107 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002108 auto *FnTy =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002109 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2110 RTLFn =
2111 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
2112 break;
2113 }
2114 case OMPRTL__kmpc_task_reduction_get_th_data: {
2115 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
2116 // *d);
2117 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002118 auto *FnTy =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002119 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2120 RTLFn = CGM.CreateRuntimeFunction(
2121 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2122 break;
2123 }
Samuel Antaobed3c462015-10-02 16:14:20 +00002124 case OMPRTL__tgt_target: {
George Rokos63bc9d62017-11-21 18:25:12 +00002125 // Build int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
2126 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Samuel Antaobed3c462015-10-02 16:14:20 +00002127 // *arg_types);
George Rokos63bc9d62017-11-21 18:25:12 +00002128 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaobed3c462015-10-02 16:14:20 +00002129 CGM.VoidPtrTy,
2130 CGM.Int32Ty,
2131 CGM.VoidPtrPtrTy,
2132 CGM.VoidPtrPtrTy,
2133 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002134 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002135 auto *FnTy =
Samuel Antaobed3c462015-10-02 16:14:20 +00002136 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2137 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2138 break;
2139 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002140 case OMPRTL__tgt_target_nowait: {
2141 // Build int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
2142 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2143 // int64_t *arg_types);
2144 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2145 CGM.VoidPtrTy,
2146 CGM.Int32Ty,
2147 CGM.VoidPtrPtrTy,
2148 CGM.VoidPtrPtrTy,
2149 CGM.SizeTy->getPointerTo(),
2150 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002151 auto *FnTy =
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002152 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2153 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_nowait");
2154 break;
2155 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00002156 case OMPRTL__tgt_target_teams: {
George Rokos63bc9d62017-11-21 18:25:12 +00002157 // Build int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002158 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
George Rokos63bc9d62017-11-21 18:25:12 +00002159 // int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2160 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002161 CGM.VoidPtrTy,
2162 CGM.Int32Ty,
2163 CGM.VoidPtrPtrTy,
2164 CGM.VoidPtrPtrTy,
2165 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002166 CGM.Int64Ty->getPointerTo(),
Samuel Antaob68e2db2016-03-03 16:20:23 +00002167 CGM.Int32Ty,
2168 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002169 auto *FnTy =
Samuel Antaob68e2db2016-03-03 16:20:23 +00002170 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2171 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2172 break;
2173 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002174 case OMPRTL__tgt_target_teams_nowait: {
2175 // Build int32_t __tgt_target_teams_nowait(int64_t device_id, void
2176 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
2177 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2178 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2179 CGM.VoidPtrTy,
2180 CGM.Int32Ty,
2181 CGM.VoidPtrPtrTy,
2182 CGM.VoidPtrPtrTy,
2183 CGM.SizeTy->getPointerTo(),
2184 CGM.Int64Ty->getPointerTo(),
2185 CGM.Int32Ty,
2186 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002187 auto *FnTy =
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002188 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2189 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams_nowait");
2190 break;
2191 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002192 case OMPRTL__tgt_register_lib: {
2193 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2194 QualType ParamTy =
2195 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2196 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002197 auto *FnTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002198 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2199 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2200 break;
2201 }
2202 case OMPRTL__tgt_unregister_lib: {
2203 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2204 QualType ParamTy =
2205 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2206 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002207 auto *FnTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002208 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2209 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2210 break;
2211 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002212 case OMPRTL__tgt_target_data_begin: {
George Rokos63bc9d62017-11-21 18:25:12 +00002213 // Build void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
2214 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2215 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002216 CGM.Int32Ty,
2217 CGM.VoidPtrPtrTy,
2218 CGM.VoidPtrPtrTy,
2219 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002220 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002221 auto *FnTy =
Samuel Antaodf158d52016-04-27 22:58:19 +00002222 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2223 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2224 break;
2225 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002226 case OMPRTL__tgt_target_data_begin_nowait: {
2227 // Build void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
2228 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2229 // *arg_types);
2230 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2231 CGM.Int32Ty,
2232 CGM.VoidPtrPtrTy,
2233 CGM.VoidPtrPtrTy,
2234 CGM.SizeTy->getPointerTo(),
2235 CGM.Int64Ty->getPointerTo()};
2236 auto *FnTy =
2237 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2238 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin_nowait");
2239 break;
2240 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002241 case OMPRTL__tgt_target_data_end: {
George Rokos63bc9d62017-11-21 18:25:12 +00002242 // Build void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
2243 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2244 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002245 CGM.Int32Ty,
2246 CGM.VoidPtrPtrTy,
2247 CGM.VoidPtrPtrTy,
2248 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002249 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002250 auto *FnTy =
Samuel Antaodf158d52016-04-27 22:58:19 +00002251 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2252 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2253 break;
2254 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002255 case OMPRTL__tgt_target_data_end_nowait: {
2256 // Build void __tgt_target_data_end_nowait(int64_t device_id, int32_t
2257 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2258 // *arg_types);
2259 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2260 CGM.Int32Ty,
2261 CGM.VoidPtrPtrTy,
2262 CGM.VoidPtrPtrTy,
2263 CGM.SizeTy->getPointerTo(),
2264 CGM.Int64Ty->getPointerTo()};
2265 auto *FnTy =
2266 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2267 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end_nowait");
2268 break;
2269 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002270 case OMPRTL__tgt_target_data_update: {
George Rokos63bc9d62017-11-21 18:25:12 +00002271 // Build void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
2272 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2273 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antao8d2d7302016-05-26 18:30:22 +00002274 CGM.Int32Ty,
2275 CGM.VoidPtrPtrTy,
2276 CGM.VoidPtrPtrTy,
2277 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002278 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002279 auto *FnTy =
Samuel Antao8d2d7302016-05-26 18:30:22 +00002280 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2281 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2282 break;
2283 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002284 case OMPRTL__tgt_target_data_update_nowait: {
2285 // Build void __tgt_target_data_update_nowait(int64_t device_id, int32_t
2286 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2287 // *arg_types);
2288 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2289 CGM.Int32Ty,
2290 CGM.VoidPtrPtrTy,
2291 CGM.VoidPtrPtrTy,
2292 CGM.SizeTy->getPointerTo(),
2293 CGM.Int64Ty->getPointerTo()};
2294 auto *FnTy =
2295 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2296 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update_nowait");
2297 break;
2298 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002299 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002300 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002301 return RTLFn;
2302}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002303
Alexander Musman21212e42015-03-13 10:38:23 +00002304llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2305 bool IVSigned) {
2306 assert((IVSize == 32 || IVSize == 64) &&
2307 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002308 StringRef Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2309 : "__kmpc_for_static_init_4u")
2310 : (IVSigned ? "__kmpc_for_static_init_8"
2311 : "__kmpc_for_static_init_8u");
2312 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2313 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
Alexander Musman21212e42015-03-13 10:38:23 +00002314 llvm::Type *TypeParams[] = {
2315 getIdentTyPointerTy(), // loc
2316 CGM.Int32Ty, // tid
2317 CGM.Int32Ty, // schedtype
2318 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2319 PtrTy, // p_lower
2320 PtrTy, // p_upper
2321 PtrTy, // p_stride
2322 ITy, // incr
2323 ITy // chunk
2324 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002325 auto *FnTy =
Alexander Musman21212e42015-03-13 10:38:23 +00002326 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2327 return CGM.CreateRuntimeFunction(FnTy, Name);
2328}
2329
Alexander Musman92bdaab2015-03-12 13:37:50 +00002330llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2331 bool IVSigned) {
2332 assert((IVSize == 32 || IVSize == 64) &&
2333 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002334 StringRef Name =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002335 IVSize == 32
2336 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2337 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002338 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
Alexander Musman92bdaab2015-03-12 13:37:50 +00002339 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2340 CGM.Int32Ty, // tid
2341 CGM.Int32Ty, // schedtype
2342 ITy, // lower
2343 ITy, // upper
2344 ITy, // stride
2345 ITy // chunk
2346 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002347 auto *FnTy =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002348 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2349 return CGM.CreateRuntimeFunction(FnTy, Name);
2350}
2351
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002352llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2353 bool IVSigned) {
2354 assert((IVSize == 32 || IVSize == 64) &&
2355 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002356 StringRef Name =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002357 IVSize == 32
2358 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2359 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2360 llvm::Type *TypeParams[] = {
2361 getIdentTyPointerTy(), // loc
2362 CGM.Int32Ty, // tid
2363 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002364 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002365 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2366 return CGM.CreateRuntimeFunction(FnTy, Name);
2367}
2368
Alexander Musman92bdaab2015-03-12 13:37:50 +00002369llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2370 bool IVSigned) {
2371 assert((IVSize == 32 || IVSize == 64) &&
2372 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002373 StringRef Name =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002374 IVSize == 32
2375 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2376 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002377 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2378 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002379 llvm::Type *TypeParams[] = {
2380 getIdentTyPointerTy(), // loc
2381 CGM.Int32Ty, // tid
2382 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2383 PtrTy, // p_lower
2384 PtrTy, // p_upper
2385 PtrTy // p_stride
2386 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002387 auto *FnTy =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002388 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2389 return CGM.CreateRuntimeFunction(FnTy, Name);
2390}
2391
Alexey Bataev03f270c2018-03-30 18:31:07 +00002392Address CGOpenMPRuntime::getAddrOfDeclareTargetLink(const VarDecl *VD) {
2393 if (CGM.getLangOpts().OpenMPSimd)
2394 return Address::invalid();
Alexey Bataev92327c52018-03-26 16:40:55 +00002395 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2396 isDeclareTargetDeclaration(VD);
2397 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2398 SmallString<64> PtrName;
2399 {
2400 llvm::raw_svector_ostream OS(PtrName);
2401 OS << CGM.getMangledName(GlobalDecl(VD)) << "_decl_tgt_link_ptr";
2402 }
2403 llvm::Value *Ptr = CGM.getModule().getNamedValue(PtrName);
2404 if (!Ptr) {
2405 QualType PtrTy = CGM.getContext().getPointerType(VD->getType());
2406 Ptr = getOrCreateInternalVariable(CGM.getTypes().ConvertTypeForMem(PtrTy),
2407 PtrName);
Alexey Bataev03f270c2018-03-30 18:31:07 +00002408 if (!CGM.getLangOpts().OpenMPIsDevice) {
2409 auto *GV = cast<llvm::GlobalVariable>(Ptr);
2410 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2411 GV->setInitializer(CGM.GetAddrOfGlobal(VD));
2412 }
2413 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ptr));
2414 registerTargetGlobalVariable(VD, cast<llvm::Constant>(Ptr));
Alexey Bataev92327c52018-03-26 16:40:55 +00002415 }
2416 return Address(Ptr, CGM.getContext().getDeclAlign(VD));
2417 }
2418 return Address::invalid();
2419}
2420
Alexey Bataev97720002014-11-11 04:05:39 +00002421llvm::Constant *
2422CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002423 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2424 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002425 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002426 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002427 Twine(CGM.getMangledName(VD), ".cache."));
Alexey Bataev97720002014-11-11 04:05:39 +00002428}
2429
John McCall7f416cc2015-09-08 08:05:57 +00002430Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2431 const VarDecl *VD,
2432 Address VDAddr,
2433 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002434 if (CGM.getLangOpts().OpenMPUseTLS &&
2435 CGM.getContext().getTargetInfo().isTLSSupported())
2436 return VDAddr;
2437
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002438 llvm::Type *VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002439 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002440 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2441 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002442 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2443 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002444 return Address(CGF.EmitRuntimeCall(
2445 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2446 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002447}
2448
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002449void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002450 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002451 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2452 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2453 // library.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002454 llvm::Value *OMPLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002455 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002456 OMPLoc);
2457 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2458 // to register constructor/destructor for variable.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002459 llvm::Value *Args[] = {
2460 OMPLoc, CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.VoidPtrTy),
2461 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002462 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002463 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002464}
2465
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002466llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002467 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002468 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002469 if (CGM.getLangOpts().OpenMPUseTLS &&
2470 CGM.getContext().getTargetInfo().isTLSSupported())
2471 return nullptr;
2472
Alexey Bataev97720002014-11-11 04:05:39 +00002473 VD = VD->getDefinition(CGM.getContext());
2474 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
2475 ThreadPrivateWithDefinition.insert(VD);
2476 QualType ASTTy = VD->getType();
2477
2478 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002479 const Expr *Init = VD->getAnyInitializer();
Alexey Bataev97720002014-11-11 04:05:39 +00002480 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2481 // Generate function that re-emits the declaration's initializer into the
2482 // threadprivate copy of the variable VD
2483 CodeGenFunction CtorCGF(CGM);
2484 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002485 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2486 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002487 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002488 Args.push_back(&Dst);
2489
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002490 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
John McCallc56a8b32016-03-11 04:30:31 +00002491 CGM.getContext().VoidPtrTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002492 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2493 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002494 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002495 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002496 Args, Loc, Loc);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002497 llvm::Value *ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002498 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002499 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002500 Address Arg = Address(ArgVal, VDAddr.getAlignment());
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002501 Arg = CtorCGF.Builder.CreateElementBitCast(
2502 Arg, CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002503 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2504 /*IsInitializer=*/true);
2505 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002506 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002507 CGM.getContext().VoidPtrTy, Dst.getLocation());
2508 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2509 CtorCGF.FinishFunction();
2510 Ctor = Fn;
2511 }
2512 if (VD->getType().isDestructedType() != QualType::DK_none) {
2513 // Generate function that emits destructor call for the threadprivate copy
2514 // of the variable VD
2515 CodeGenFunction DtorCGF(CGM);
2516 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002517 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2518 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002519 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002520 Args.push_back(&Dst);
2521
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002522 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
John McCallc56a8b32016-03-11 04:30:31 +00002523 CGM.getContext().VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002524 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2525 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002526 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002527 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002528 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002529 Loc, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002530 // Create a scope with an artificial location for the body of this function.
2531 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002532 llvm::Value *ArgVal = DtorCGF.EmitLoadOfScalar(
Alexey Bataev97720002014-11-11 04:05:39 +00002533 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002534 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2535 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002536 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2537 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2538 DtorCGF.FinishFunction();
2539 Dtor = Fn;
2540 }
2541 // Do not emit init function if it is not required.
2542 if (!Ctor && !Dtor)
2543 return nullptr;
2544
2545 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002546 auto *CopyCtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2547 /*isVarArg=*/false)
2548 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002549 // Copying constructor for the threadprivate variable.
2550 // Must be NULL - reserved by runtime, but currently it requires that this
2551 // parameter is always NULL. Otherwise it fires assertion.
2552 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2553 if (Ctor == nullptr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002554 auto *CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2555 /*isVarArg=*/false)
2556 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002557 Ctor = llvm::Constant::getNullValue(CtorTy);
2558 }
2559 if (Dtor == nullptr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002560 auto *DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2561 /*isVarArg=*/false)
2562 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002563 Dtor = llvm::Constant::getNullValue(DtorTy);
2564 }
2565 if (!CGF) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002566 auto *InitFunctionTy =
Alexey Bataev97720002014-11-11 04:05:39 +00002567 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002568 llvm::Function *InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002569 InitFunctionTy, ".__omp_threadprivate_init_.",
2570 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002571 CodeGenFunction InitCGF(CGM);
2572 FunctionArgList ArgList;
2573 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2574 CGM.getTypes().arrangeNullaryFunction(), ArgList,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002575 Loc, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002576 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002577 InitCGF.FinishFunction();
2578 return InitFunction;
2579 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002580 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002581 }
2582 return nullptr;
2583}
2584
Alexey Bataev34f8a702018-03-28 14:28:54 +00002585/// \brief Obtain information that uniquely identifies a target entry. This
2586/// consists of the file and device IDs as well as line number associated with
2587/// the relevant entry source location.
2588static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
2589 unsigned &DeviceID, unsigned &FileID,
2590 unsigned &LineNum) {
2591
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002592 SourceManager &SM = C.getSourceManager();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002593
2594 // The loc should be always valid and have a file ID (the user cannot use
2595 // #pragma directives in macros)
2596
2597 assert(Loc.isValid() && "Source location is expected to be always valid.");
2598 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
2599
2600 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
2601 assert(PLoc.isValid() && "Source location is expected to be always valid.");
2602
2603 llvm::sys::fs::UniqueID ID;
2604 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
2605 llvm_unreachable("Source file with target region no longer exists!");
2606
2607 DeviceID = ID.getDevice();
2608 FileID = ID.getFile();
2609 LineNum = PLoc.getLine();
2610}
2611
2612bool CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD,
2613 llvm::GlobalVariable *Addr,
2614 bool PerformInit) {
2615 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2616 isDeclareTargetDeclaration(VD);
2617 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link)
2618 return false;
2619 VD = VD->getDefinition(CGM.getContext());
2620 if (VD && !DeclareTargetWithDefinition.insert(VD).second)
2621 return CGM.getLangOpts().OpenMPIsDevice;
2622
2623 QualType ASTTy = VD->getType();
2624
2625 SourceLocation Loc = VD->getCanonicalDecl()->getLocStart();
2626 // Produce the unique prefix to identify the new target regions. We use
2627 // the source location of the variable declaration which we know to not
2628 // conflict with any target region.
2629 unsigned DeviceID;
2630 unsigned FileID;
2631 unsigned Line;
2632 getTargetEntryUniqueInfo(CGM.getContext(), Loc, DeviceID, FileID, Line);
2633 SmallString<128> Buffer, Out;
2634 {
2635 llvm::raw_svector_ostream OS(Buffer);
2636 OS << "__omp_offloading_" << llvm::format("_%x", DeviceID)
2637 << llvm::format("_%x_", FileID) << VD->getName() << "_l" << Line;
2638 }
2639
2640 const Expr *Init = VD->getAnyInitializer();
2641 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2642 llvm::Constant *Ctor;
2643 llvm::Constant *ID;
2644 if (CGM.getLangOpts().OpenMPIsDevice) {
2645 // Generate function that re-emits the declaration's initializer into
2646 // the threadprivate copy of the variable VD
2647 CodeGenFunction CtorCGF(CGM);
2648
2649 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2650 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2651 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2652 FTy, Twine(Buffer, "_ctor"), FI, Loc);
2653 auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF);
2654 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2655 FunctionArgList(), Loc, Loc);
2656 auto AL = ApplyDebugLocation::CreateArtificial(CtorCGF);
2657 CtorCGF.EmitAnyExprToMem(Init,
2658 Address(Addr, CGM.getContext().getDeclAlign(VD)),
2659 Init->getType().getQualifiers(),
2660 /*IsInitializer=*/true);
2661 CtorCGF.FinishFunction();
2662 Ctor = Fn;
2663 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
2664 } else {
2665 Ctor = new llvm::GlobalVariable(
2666 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2667 llvm::GlobalValue::PrivateLinkage,
2668 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_ctor"));
2669 ID = Ctor;
2670 }
2671
2672 // Register the information for the entry associated with the constructor.
2673 Out.clear();
2674 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2675 DeviceID, FileID, Twine(Buffer, "_ctor").toStringRef(Out), Line, Ctor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002676 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryCtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002677 }
2678 if (VD->getType().isDestructedType() != QualType::DK_none) {
2679 llvm::Constant *Dtor;
2680 llvm::Constant *ID;
2681 if (CGM.getLangOpts().OpenMPIsDevice) {
2682 // Generate function that emits destructor call for the threadprivate
2683 // copy of the variable VD
2684 CodeGenFunction DtorCGF(CGM);
2685
2686 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2687 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2688 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2689 FTy, Twine(Buffer, "_dtor"), FI, Loc);
2690 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
2691 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2692 FunctionArgList(), Loc, Loc);
2693 // Create a scope with an artificial location for the body of this
2694 // function.
2695 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
2696 DtorCGF.emitDestroy(Address(Addr, CGM.getContext().getDeclAlign(VD)),
2697 ASTTy, DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2698 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2699 DtorCGF.FinishFunction();
2700 Dtor = Fn;
2701 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
2702 } else {
2703 Dtor = new llvm::GlobalVariable(
2704 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2705 llvm::GlobalValue::PrivateLinkage,
2706 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_dtor"));
2707 ID = Dtor;
2708 }
2709 // Register the information for the entry associated with the destructor.
2710 Out.clear();
2711 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2712 DeviceID, FileID, Twine(Buffer, "_dtor").toStringRef(Out), Line, Dtor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002713 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryDtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002714 }
2715 return CGM.getLangOpts().OpenMPIsDevice;
2716}
2717
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002718Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2719 QualType VarType,
2720 StringRef Name) {
2721 llvm::Twine VarName(Name, ".artificial.");
2722 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
2723 llvm::Value *GAddr = getOrCreateInternalVariable(VarLVType, VarName);
2724 llvm::Value *Args[] = {
2725 emitUpdateLocation(CGF, SourceLocation()),
2726 getThreadID(CGF, SourceLocation()),
2727 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2728 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2729 /*IsSigned=*/false),
2730 getOrCreateInternalVariable(CGM.VoidPtrPtrTy, VarName + ".cache.")};
2731 return Address(
2732 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2733 CGF.EmitRuntimeCall(
2734 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2735 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2736 CGM.getPointerAlign());
2737}
2738
Alexey Bataev1d677132015-04-22 13:57:31 +00002739/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
2740/// function. Here is the logic:
2741/// if (Cond) {
2742/// ThenGen();
2743/// } else {
2744/// ElseGen();
2745/// }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002746void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2747 const RegionCodeGenTy &ThenGen,
2748 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002749 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2750
2751 // If the condition constant folds and can be elided, try to avoid emitting
2752 // the condition and the dead arm of the if/else.
2753 bool CondConstant;
2754 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002755 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002756 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002757 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002758 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002759 return;
2760 }
2761
2762 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2763 // emit the conditional branch.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002764 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("omp_if.then");
2765 llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else");
2766 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("omp_if.end");
Alexey Bataev1d677132015-04-22 13:57:31 +00002767 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2768
2769 // Emit the 'then' code.
2770 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002771 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002772 CGF.EmitBranch(ContBlock);
2773 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002774 // There is no need to emit line number for unconditional branch.
2775 (void)ApplyDebugLocation::CreateEmpty(CGF);
2776 CGF.EmitBlock(ElseBlock);
2777 ElseGen(CGF);
2778 // There is no need to emit line number for unconditional branch.
2779 (void)ApplyDebugLocation::CreateEmpty(CGF);
2780 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002781 // Emit the continuation block for code after the if.
2782 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002783}
2784
Alexey Bataev1d677132015-04-22 13:57:31 +00002785void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2786 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002787 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002788 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002789 if (!CGF.HaveInsertPoint())
2790 return;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002791 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002792 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2793 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002794 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002795 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002796 llvm::Value *Args[] = {
2797 RTLoc,
2798 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002799 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002800 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2801 RealArgs.append(std::begin(Args), std::end(Args));
2802 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2803
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002804 llvm::Value *RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002805 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2806 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002807 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2808 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002809 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
2810 llvm::Value *ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00002811 // Build calls:
2812 // __kmpc_serialized_parallel(&Loc, GTid);
2813 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002814 CGF.EmitRuntimeCall(
2815 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002816
Alexey Bataev1d677132015-04-22 13:57:31 +00002817 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002818 Address ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00002819 Address ZeroAddr =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002820 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
2821 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00002822 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00002823 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2824 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2825 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2826 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002827 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002828
Alexey Bataev1d677132015-04-22 13:57:31 +00002829 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002830 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00002831 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002832 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2833 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002834 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002835 if (IfCond) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002836 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002837 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002838 RegionCodeGenTy ThenRCG(ThenGen);
2839 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002840 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002841}
2842
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002843// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002844// thread-ID variable (it is passed in a first argument of the outlined function
2845// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2846// regular serial code region, get thread ID by calling kmp_int32
2847// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2848// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002849Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2850 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002851 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002852 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002853 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002854 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002855
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002856 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2857 QualType Int32Ty =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002858 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002859 Address ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
Alexey Bataevd74d0602014-10-13 06:02:40 +00002860 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002861 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002862
2863 return ThreadIDTemp;
2864}
2865
Alexey Bataev97720002014-11-11 04:05:39 +00002866llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002867CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002868 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002869 SmallString<256> Buffer;
2870 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002871 Out << Name;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002872 StringRef RuntimeName = Out.str();
Alexey Bataev43a919f2018-04-13 17:48:43 +00002873 auto &Elem = *InternalVars.try_emplace(RuntimeName, nullptr).first;
David Blaikie13156b62014-11-19 03:06:06 +00002874 if (Elem.second) {
2875 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002876 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002877 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002878 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002879
David Blaikie13156b62014-11-19 03:06:06 +00002880 return Elem.second = new llvm::GlobalVariable(
2881 CGM.getModule(), Ty, /*IsConstant*/ false,
2882 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2883 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002884}
2885
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002886llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00002887 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002888 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002889}
2890
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002891namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002892/// Common pre(post)-action for different OpenMP constructs.
2893class CommonActionTy final : public PrePostActionTy {
2894 llvm::Value *EnterCallee;
2895 ArrayRef<llvm::Value *> EnterArgs;
2896 llvm::Value *ExitCallee;
2897 ArrayRef<llvm::Value *> ExitArgs;
2898 bool Conditional;
2899 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002900
2901public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002902 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2903 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2904 bool Conditional = false)
2905 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2906 ExitArgs(ExitArgs), Conditional(Conditional) {}
2907 void Enter(CodeGenFunction &CGF) override {
2908 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2909 if (Conditional) {
2910 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2911 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2912 ContBlock = CGF.createBasicBlock("omp_if.end");
2913 // Generate the branch (If-stmt)
2914 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2915 CGF.EmitBlock(ThenBlock);
2916 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002917 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002918 void Done(CodeGenFunction &CGF) {
2919 // Emit the rest of blocks/branches
2920 CGF.EmitBranch(ContBlock);
2921 CGF.EmitBlock(ContBlock, true);
2922 }
2923 void Exit(CodeGenFunction &CGF) override {
2924 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002925 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002926};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002927} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002928
2929void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2930 StringRef CriticalName,
2931 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002932 SourceLocation Loc, const Expr *Hint) {
2933 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002934 // CriticalOpGen();
2935 // __kmpc_end_critical(ident_t *, gtid, Lock);
2936 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002937 if (!CGF.HaveInsertPoint())
2938 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002939 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2940 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002941 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2942 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002943 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002944 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2945 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2946 }
2947 CommonActionTy Action(
2948 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2949 : OMPRTL__kmpc_critical),
2950 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2951 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002952 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002953}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002954
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002955void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002956 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002957 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002958 if (!CGF.HaveInsertPoint())
2959 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002960 // if(__kmpc_master(ident_t *, gtid)) {
2961 // MasterOpGen();
2962 // __kmpc_end_master(ident_t *, gtid);
2963 // }
2964 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002965 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002966 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2967 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2968 /*Conditional=*/true);
2969 MasterOpGen.setAction(Action);
2970 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2971 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002972}
2973
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002974void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2975 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002976 if (!CGF.HaveInsertPoint())
2977 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00002978 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2979 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002980 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00002981 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002982 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002983 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2984 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00002985}
2986
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002987void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2988 const RegionCodeGenTy &TaskgroupOpGen,
2989 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002990 if (!CGF.HaveInsertPoint())
2991 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002992 // __kmpc_taskgroup(ident_t *, gtid);
2993 // TaskgroupOpGen();
2994 // __kmpc_end_taskgroup(ident_t *, gtid);
2995 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002996 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2997 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2998 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2999 Args);
3000 TaskgroupOpGen.setAction(Action);
3001 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003002}
3003
John McCall7f416cc2015-09-08 08:05:57 +00003004/// Given an array of pointers to variables, project the address of a
3005/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003006static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
3007 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00003008 // Pull out the pointer to the variable.
3009 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003010 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00003011 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
3012
3013 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003014 Addr = CGF.Builder.CreateElementBitCast(
3015 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00003016 return Addr;
3017}
3018
Alexey Bataeva63048e2015-03-23 06:18:07 +00003019static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00003020 CodeGenModule &CGM, llvm::Type *ArgsType,
3021 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003022 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps,
3023 SourceLocation Loc) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003024 ASTContext &C = CGM.getContext();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003025 // void copy_func(void *LHSArg, void *RHSArg);
3026 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003027 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3028 ImplicitParamDecl::Other);
3029 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3030 ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003031 Args.push_back(&LHSArg);
3032 Args.push_back(&RHSArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003033 const auto &CGFI =
3034 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003035 auto *Fn = llvm::Function::Create(
3036 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3037 ".omp.copyprivate.copy_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003038 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003039 Fn->setDoesNotRecurse();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003040 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003041 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00003042 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003043 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00003044 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3045 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
3046 ArgsType), CGF.getPointerAlign());
3047 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3048 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
3049 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00003050 // *(Type0*)Dst[0] = *(Type0*)Src[0];
3051 // *(Type1*)Dst[1] = *(Type1*)Src[1];
3052 // ...
3053 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00003054 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003055 const auto *DestVar =
3056 cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003057 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
3058
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003059 const auto *SrcVar =
3060 cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003061 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
3062
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003063 const auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003064 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00003065 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003066 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00003067 CGF.FinishFunction();
3068 return Fn;
3069}
3070
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003071void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003072 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00003073 SourceLocation Loc,
3074 ArrayRef<const Expr *> CopyprivateVars,
3075 ArrayRef<const Expr *> SrcExprs,
3076 ArrayRef<const Expr *> DstExprs,
3077 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003078 if (!CGF.HaveInsertPoint())
3079 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00003080 assert(CopyprivateVars.size() == SrcExprs.size() &&
3081 CopyprivateVars.size() == DstExprs.size() &&
3082 CopyprivateVars.size() == AssignmentOps.size());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003083 ASTContext &C = CGM.getContext();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003084 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003085 // if(__kmpc_single(ident_t *, gtid)) {
3086 // SingleOpGen();
3087 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003088 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003089 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00003090 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3091 // <copy_func>, did_it);
3092
John McCall7f416cc2015-09-08 08:05:57 +00003093 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003094 if (!CopyprivateVars.empty()) {
3095 // int32 did_it = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003096 QualType KmpInt32Ty =
3097 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003098 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00003099 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003100 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003101 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00003102 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003103 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
3104 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
3105 /*Conditional=*/true);
3106 SingleOpGen.setAction(Action);
3107 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
3108 if (DidIt.isValid()) {
3109 // did_it = 1;
3110 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
3111 }
3112 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003113 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3114 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00003115 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00003116 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003117 QualType CopyprivateArrayTy =
Alexey Bataeva63048e2015-03-23 06:18:07 +00003118 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3119 /*IndexTypeQuals=*/0);
3120 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00003121 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00003122 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
3123 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00003124 Address Elem = CGF.Builder.CreateConstArrayGEP(
3125 CopyprivateList, I, CGF.getPointerSize());
3126 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00003127 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003128 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
3129 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003130 }
3131 // Build function that copies private values from single region to all other
3132 // threads in the corresponding parallel region.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003133 llvm::Value *CpyFn = emitCopyprivateCopyFunction(
Alexey Bataeva63048e2015-03-23 06:18:07 +00003134 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003135 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps, Loc);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003136 llvm::Value *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00003137 Address CL =
3138 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
3139 CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003140 llvm::Value *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003141 llvm::Value *Args[] = {
3142 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
3143 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00003144 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00003145 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00003146 CpyFn, // void (*) (void *, void *) <copy_func>
3147 DidItVal // i32 did_it
3148 };
3149 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
3150 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003151}
3152
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003153void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
3154 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00003155 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003156 if (!CGF.HaveInsertPoint())
3157 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003158 // __kmpc_ordered(ident_t *, gtid);
3159 // OrderedOpGen();
3160 // __kmpc_end_ordered(ident_t *, gtid);
3161 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00003162 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003163 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003164 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
3165 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
3166 Args);
3167 OrderedOpGen.setAction(Action);
3168 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
3169 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003170 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003171 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003172}
3173
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003174void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00003175 OpenMPDirectiveKind Kind, bool EmitChecks,
3176 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003177 if (!CGF.HaveInsertPoint())
3178 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00003179 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003180 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003181 unsigned Flags;
3182 if (Kind == OMPD_for)
3183 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
3184 else if (Kind == OMPD_sections)
3185 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
3186 else if (Kind == OMPD_single)
3187 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
3188 else if (Kind == OMPD_barrier)
3189 Flags = OMP_IDENT_BARRIER_EXPL;
3190 else
3191 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003192 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
3193 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003194 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
3195 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003196 if (auto *OMPRegionInfo =
3197 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00003198 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003199 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003200 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00003201 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003202 // if (__kmpc_cancel_barrier()) {
3203 // exit from construct;
3204 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003205 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
3206 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
3207 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003208 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
3209 CGF.EmitBlock(ExitBB);
3210 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003211 CodeGenFunction::JumpDest CancelDestination =
Alexey Bataev25e5b442015-09-15 12:52:43 +00003212 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003213 CGF.EmitBranchThroughCleanup(CancelDestination);
3214 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
3215 }
3216 return;
3217 }
3218 }
3219 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00003220}
3221
Alexander Musmanc6388682014-12-15 07:07:06 +00003222/// \brief Map the OpenMP loop schedule to the runtime enumeration.
3223static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003224 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003225 switch (ScheduleKind) {
3226 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003227 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
3228 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00003229 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003230 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003231 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003232 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003233 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003234 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
3235 case OMPC_SCHEDULE_auto:
3236 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00003237 case OMPC_SCHEDULE_unknown:
3238 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003239 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00003240 }
3241 llvm_unreachable("Unexpected runtime schedule");
3242}
3243
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003244/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
3245static OpenMPSchedType
3246getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
3247 // only static is allowed for dist_schedule
3248 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
3249}
3250
Alexander Musmanc6388682014-12-15 07:07:06 +00003251bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
3252 bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003253 OpenMPSchedType Schedule =
3254 getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00003255 return Schedule == OMP_sch_static;
3256}
3257
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003258bool CGOpenMPRuntime::isStaticNonchunked(
3259 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003260 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003261 return Schedule == OMP_dist_sch_static;
3262}
3263
3264
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003265bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003266 OpenMPSchedType Schedule =
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003267 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003268 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
3269 return Schedule != OMP_sch_static;
3270}
3271
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003272static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
3273 OpenMPScheduleClauseModifier M1,
3274 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00003275 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003276 switch (M1) {
3277 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003278 Modifier = OMP_sch_modifier_monotonic;
3279 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003280 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003281 Modifier = OMP_sch_modifier_nonmonotonic;
3282 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003283 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003284 if (Schedule == OMP_sch_static_chunked)
3285 Schedule = OMP_sch_static_balanced_chunked;
3286 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003287 case OMPC_SCHEDULE_MODIFIER_last:
3288 case OMPC_SCHEDULE_MODIFIER_unknown:
3289 break;
3290 }
3291 switch (M2) {
3292 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003293 Modifier = OMP_sch_modifier_monotonic;
3294 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003295 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003296 Modifier = OMP_sch_modifier_nonmonotonic;
3297 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003298 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003299 if (Schedule == OMP_sch_static_chunked)
3300 Schedule = OMP_sch_static_balanced_chunked;
3301 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003302 case OMPC_SCHEDULE_MODIFIER_last:
3303 case OMPC_SCHEDULE_MODIFIER_unknown:
3304 break;
3305 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00003306 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003307}
3308
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003309void CGOpenMPRuntime::emitForDispatchInit(
3310 CodeGenFunction &CGF, SourceLocation Loc,
3311 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
3312 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003313 if (!CGF.HaveInsertPoint())
3314 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003315 OpenMPSchedType Schedule = getRuntimeSchedule(
3316 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00003317 assert(Ordered ||
3318 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00003319 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
3320 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00003321 // Call __kmpc_dispatch_init(
3322 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
3323 // kmp_int[32|64] lower, kmp_int[32|64] upper,
3324 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00003325
John McCall7f416cc2015-09-08 08:05:57 +00003326 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003327 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
3328 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00003329 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003330 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3331 CGF.Builder.getInt32(addMonoNonMonoModifier(
3332 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003333 DispatchValues.LB, // Lower
3334 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003335 CGF.Builder.getIntN(IVSize, 1), // Stride
3336 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00003337 };
3338 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
3339}
3340
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003341static void emitForStaticInitCall(
3342 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
3343 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
3344 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003345 const CGOpenMPRuntime::StaticRTInput &Values) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003346 if (!CGF.HaveInsertPoint())
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003347 return;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003348
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003349 assert(!Values.Ordered);
3350 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
3351 Schedule == OMP_sch_static_balanced_chunked ||
3352 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
3353 Schedule == OMP_dist_sch_static ||
3354 Schedule == OMP_dist_sch_static_chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003355
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003356 // Call __kmpc_for_static_init(
3357 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
3358 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
3359 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
3360 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
3361 llvm::Value *Chunk = Values.Chunk;
3362 if (Chunk == nullptr) {
3363 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
3364 Schedule == OMP_dist_sch_static) &&
3365 "expected static non-chunked schedule");
3366 // If the Chunk was not specified in the clause - use default value 1.
3367 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3368 } else {
3369 assert((Schedule == OMP_sch_static_chunked ||
3370 Schedule == OMP_sch_static_balanced_chunked ||
3371 Schedule == OMP_ord_static_chunked ||
3372 Schedule == OMP_dist_sch_static_chunked) &&
3373 "expected static chunked schedule");
3374 }
3375 llvm::Value *Args[] = {
3376 UpdateLocation,
3377 ThreadId,
3378 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3379 M2)), // Schedule type
3380 Values.IL.getPointer(), // &isLastIter
3381 Values.LB.getPointer(), // &LB
3382 Values.UB.getPointer(), // &UB
3383 Values.ST.getPointer(), // &Stride
3384 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3385 Chunk // Chunk
3386 };
3387 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003388}
3389
John McCall7f416cc2015-09-08 08:05:57 +00003390void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3391 SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003392 OpenMPDirectiveKind DKind,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003393 const OpenMPScheduleTy &ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003394 const StaticRTInput &Values) {
3395 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3396 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3397 assert(isOpenMPWorksharingDirective(DKind) &&
3398 "Expected loop-based or sections-based directive.");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003399 llvm::Value *UpdatedLocation = emitUpdateLocation(CGF, Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003400 isOpenMPLoopDirective(DKind)
3401 ? OMP_IDENT_WORK_LOOP
3402 : OMP_IDENT_WORK_SECTIONS);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003403 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3404 llvm::Constant *StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003405 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003406 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003407 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003408}
John McCall7f416cc2015-09-08 08:05:57 +00003409
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003410void CGOpenMPRuntime::emitDistributeStaticInit(
3411 CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003412 OpenMPDistScheduleClauseKind SchedKind,
3413 const CGOpenMPRuntime::StaticRTInput &Values) {
3414 OpenMPSchedType ScheduleNum =
3415 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003416 llvm::Value *UpdatedLocation =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003417 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003418 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3419 llvm::Constant *StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003420 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003421 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3422 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003423 OMPC_SCHEDULE_MODIFIER_unknown, Values);
Alexander Musmanc6388682014-12-15 07:07:06 +00003424}
3425
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003426void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
Alexey Bataevf43f7142017-09-06 16:17:35 +00003427 SourceLocation Loc,
3428 OpenMPDirectiveKind DKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003429 if (!CGF.HaveInsertPoint())
3430 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003431 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataevf43f7142017-09-06 16:17:35 +00003432 llvm::Value *Args[] = {
3433 emitUpdateLocation(CGF, Loc,
3434 isOpenMPDistributeDirective(DKind)
3435 ? OMP_IDENT_WORK_DISTRIBUTE
3436 : isOpenMPLoopDirective(DKind)
3437 ? OMP_IDENT_WORK_LOOP
3438 : OMP_IDENT_WORK_SECTIONS),
3439 getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003440 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3441 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003442}
3443
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003444void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3445 SourceLocation Loc,
3446 unsigned IVSize,
3447 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003448 if (!CGF.HaveInsertPoint())
3449 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003450 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003451 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003452 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3453}
3454
Alexander Musman92bdaab2015-03-12 13:37:50 +00003455llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3456 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003457 bool IVSigned, Address IL,
3458 Address LB, Address UB,
3459 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003460 // Call __kmpc_dispatch_next(
3461 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3462 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3463 // kmp_int[32|64] *p_stride);
3464 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003465 emitUpdateLocation(CGF, Loc),
3466 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003467 IL.getPointer(), // &isLastIter
3468 LB.getPointer(), // &Lower
3469 UB.getPointer(), // &Upper
3470 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003471 };
3472 llvm::Value *Call =
3473 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3474 return CGF.EmitScalarConversion(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003475 Call, CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/1),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003476 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003477}
3478
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003479void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3480 llvm::Value *NumThreads,
3481 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003482 if (!CGF.HaveInsertPoint())
3483 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003484 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3485 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003486 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003487 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003488 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3489 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003490}
3491
Alexey Bataev7f210c62015-06-18 13:40:03 +00003492void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3493 OpenMPProcBindClauseKind ProcBind,
3494 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003495 if (!CGF.HaveInsertPoint())
3496 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003497 // Constants for proc bind value accepted by the runtime.
3498 enum ProcBindTy {
3499 ProcBindFalse = 0,
3500 ProcBindTrue,
3501 ProcBindMaster,
3502 ProcBindClose,
3503 ProcBindSpread,
3504 ProcBindIntel,
3505 ProcBindDefault
3506 } RuntimeProcBind;
3507 switch (ProcBind) {
3508 case OMPC_PROC_BIND_master:
3509 RuntimeProcBind = ProcBindMaster;
3510 break;
3511 case OMPC_PROC_BIND_close:
3512 RuntimeProcBind = ProcBindClose;
3513 break;
3514 case OMPC_PROC_BIND_spread:
3515 RuntimeProcBind = ProcBindSpread;
3516 break;
3517 case OMPC_PROC_BIND_unknown:
3518 llvm_unreachable("Unsupported proc_bind value.");
3519 }
3520 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3521 llvm::Value *Args[] = {
3522 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3523 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3524 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3525}
3526
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003527void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3528 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003529 if (!CGF.HaveInsertPoint())
3530 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003531 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003532 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3533 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003534}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003535
Alexey Bataev62b63b12015-03-10 07:28:44 +00003536namespace {
3537/// \brief Indexes of fields for type kmp_task_t.
3538enum KmpTaskTFields {
3539 /// \brief List of shared variables.
3540 KmpTaskTShareds,
3541 /// \brief Task routine.
3542 KmpTaskTRoutine,
3543 /// \brief Partition id for the untied tasks.
3544 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003545 /// Function with call of destructors for private variables.
3546 Data1,
3547 /// Task priority.
3548 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003549 /// (Taskloops only) Lower bound.
3550 KmpTaskTLowerBound,
3551 /// (Taskloops only) Upper bound.
3552 KmpTaskTUpperBound,
3553 /// (Taskloops only) Stride.
3554 KmpTaskTStride,
3555 /// (Taskloops only) Is last iteration flag.
3556 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003557 /// (Taskloops only) Reduction data.
3558 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003559};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003560} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003561
Samuel Antaoee8fb302016-01-06 13:42:12 +00003562bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003563 return OffloadEntriesTargetRegion.empty() &&
3564 OffloadEntriesDeviceGlobalVar.empty();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003565}
3566
3567/// \brief Initialize target region entry.
3568void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3569 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3570 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003571 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003572 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3573 "only required for the device "
3574 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003575 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003576 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003577 OMPTargetRegionEntryTargetRegion);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003578 ++OffloadingEntriesNum;
3579}
3580
3581void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3582 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3583 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003584 llvm::Constant *Addr, llvm::Constant *ID,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003585 OMPTargetRegionEntryKind Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003586 // If we are emitting code for a target, the entry is already initialized,
3587 // only has to be registered.
3588 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003589 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00003590 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003591 auto &Entry =
3592 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003593 assert(Entry.isValid() && "Entry not initialized!");
3594 Entry.setAddress(Addr);
3595 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003596 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003597 } else {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003598 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003599 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00003600 ++OffloadingEntriesNum;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003601 }
3602}
3603
3604bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003605 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3606 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003607 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3608 if (PerDevice == OffloadEntriesTargetRegion.end())
3609 return false;
3610 auto PerFile = PerDevice->second.find(FileID);
3611 if (PerFile == PerDevice->second.end())
3612 return false;
3613 auto PerParentName = PerFile->second.find(ParentName);
3614 if (PerParentName == PerFile->second.end())
3615 return false;
3616 auto PerLine = PerParentName->second.find(LineNum);
3617 if (PerLine == PerParentName->second.end())
3618 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003619 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003620 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003621 return false;
3622 return true;
3623}
3624
3625void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3626 const OffloadTargetRegionEntryInfoActTy &Action) {
3627 // Scan all target region entries and perform the provided action.
Alexey Bataev03f270c2018-03-30 18:31:07 +00003628 for (const auto &D : OffloadEntriesTargetRegion)
3629 for (const auto &F : D.second)
3630 for (const auto &P : F.second)
3631 for (const auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003632 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003633}
3634
Alexey Bataev03f270c2018-03-30 18:31:07 +00003635void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3636 initializeDeviceGlobalVarEntryInfo(StringRef Name,
3637 OMPTargetGlobalVarEntryKind Flags,
3638 unsigned Order) {
3639 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3640 "only required for the device "
3641 "code generation.");
3642 OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags);
3643 ++OffloadingEntriesNum;
3644}
Samuel Antaoee8fb302016-01-06 13:42:12 +00003645
Alexey Bataev03f270c2018-03-30 18:31:07 +00003646void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3647 registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr,
3648 CharUnits VarSize,
3649 OMPTargetGlobalVarEntryKind Flags,
3650 llvm::GlobalValue::LinkageTypes Linkage) {
3651 if (CGM.getLangOpts().OpenMPIsDevice) {
3652 auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
3653 assert(Entry.isValid() && Entry.getFlags() == Flags &&
3654 "Entry not initialized!");
3655 assert((!Entry.getAddress() || Entry.getAddress() == Addr) &&
3656 "Resetting with the new address.");
3657 if (Entry.getAddress() && hasDeviceGlobalVarEntryInfo(VarName))
3658 return;
3659 Entry.setAddress(Addr);
3660 Entry.setVarSize(VarSize);
3661 Entry.setLinkage(Linkage);
3662 } else {
3663 if (hasDeviceGlobalVarEntryInfo(VarName))
3664 return;
3665 OffloadEntriesDeviceGlobalVar.try_emplace(
3666 VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage);
3667 ++OffloadingEntriesNum;
3668 }
3669}
3670
3671void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3672 actOnDeviceGlobalVarEntriesInfo(
3673 const OffloadDeviceGlobalVarEntryInfoActTy &Action) {
3674 // Scan all target region entries and perform the provided action.
3675 for (const auto &E : OffloadEntriesDeviceGlobalVar)
3676 Action(E.getKey(), E.getValue());
Samuel Antaoee8fb302016-01-06 13:42:12 +00003677}
3678
3679llvm::Function *
3680CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003681 // If we don't have entries or if we are emitting code for the device, we
3682 // don't need to do anything.
3683 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3684 return nullptr;
3685
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003686 llvm::Module &M = CGM.getModule();
3687 ASTContext &C = CGM.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003688
3689 // Get list of devices we care about
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003690 const std::vector<llvm::Triple> &Devices = CGM.getLangOpts().OMPTargetTriples;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003691
3692 // We should be creating an offloading descriptor only if there are devices
3693 // specified.
3694 assert(!Devices.empty() && "No OpenMP offloading devices??");
3695
3696 // Create the external variables that will point to the begin and end of the
3697 // host entries section. These will be defined by the linker.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003698 llvm::Type *OffloadEntryTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00003699 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003700 auto *HostEntriesBegin = new llvm::GlobalVariable(
Samuel Antaoee8fb302016-01-06 13:42:12 +00003701 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003702 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003703 ".omp_offloading.entries_begin");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003704 auto *HostEntriesEnd = new llvm::GlobalVariable(
Samuel Antaoee8fb302016-01-06 13:42:12 +00003705 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003706 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003707 ".omp_offloading.entries_end");
3708
3709 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003710 auto *DeviceImageTy = cast<llvm::StructType>(
3711 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003712 ConstantInitBuilder DeviceImagesBuilder(CGM);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003713 ConstantArrayBuilder DeviceImagesEntries =
3714 DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003715
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003716 for (const llvm::Triple &Device : Devices) {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003717 StringRef T = Device.getTriple();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003718 auto *ImgBegin = new llvm::GlobalVariable(
3719 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003720 /*Initializer=*/nullptr, Twine(".omp_offloading.img_start.", T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003721 auto *ImgEnd = new llvm::GlobalVariable(
3722 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003723 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.", T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003724
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003725 llvm::Constant *Data[] = {ImgBegin, ImgEnd, HostEntriesBegin,
3726 HostEntriesEnd};
3727 createConstantGlobalStructAndAddToParent(CGM, getTgtDeviceImageQTy(), Data,
3728 DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003729 }
3730
3731 // Create device images global array.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003732 llvm::GlobalVariable *DeviceImages =
3733 DeviceImagesEntries.finishAndCreateGlobal(".omp_offloading.device_images",
3734 CGM.getPointerAlign(),
3735 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003736 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003737
3738 // This is a Zero array to be used in the creation of the constant expressions
3739 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3740 llvm::Constant::getNullValue(CGM.Int32Ty)};
3741
3742 // Create the target region descriptor.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003743 llvm::Constant *Data[] = {
3744 llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
3745 llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3746 DeviceImages, Index),
3747 HostEntriesBegin, HostEntriesEnd};
3748 llvm::GlobalVariable *Desc = createConstantGlobalStruct(
3749 CGM, getTgtBinaryDescriptorQTy(), Data, ".omp_offloading.descriptor");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003750
3751 // Emit code to register or unregister the descriptor at execution
3752 // startup or closing, respectively.
3753
Alexey Bataev03f270c2018-03-30 18:31:07 +00003754 llvm::Function *UnRegFn;
3755 {
3756 FunctionArgList Args;
3757 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
3758 Args.push_back(&DummyPtr);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003759
Alexey Bataev03f270c2018-03-30 18:31:07 +00003760 CodeGenFunction CGF(CGM);
3761 // Disable debug info for global (de-)initializer because they are not part
3762 // of some particular construct.
3763 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003764 const auto &FI =
3765 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3766 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003767 UnRegFn = CGM.CreateGlobalInitOrDestructFunction(
3768 FTy, ".omp_offloading.descriptor_unreg", FI);
3769 CGF.StartFunction(GlobalDecl(), C.VoidTy, UnRegFn, FI, Args);
3770 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3771 Desc);
3772 CGF.FinishFunction();
3773 }
3774 llvm::Function *RegFn;
3775 {
3776 CodeGenFunction CGF(CGM);
3777 // Disable debug info for global (de-)initializer because they are not part
3778 // of some particular construct.
3779 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003780 const auto &FI = CGM.getTypes().arrangeNullaryFunction();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003781 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
3782 RegFn = CGM.CreateGlobalInitOrDestructFunction(
3783 FTy, ".omp_offloading.descriptor_reg", FI);
3784 CGF.StartFunction(GlobalDecl(), C.VoidTy, RegFn, FI, FunctionArgList());
3785 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib), Desc);
3786 // Create a variable to drive the registration and unregistration of the
3787 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3788 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(),
3789 SourceLocation(), nullptr, C.CharTy,
3790 ImplicitParamDecl::Other);
3791 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3792 CGF.FinishFunction();
3793 }
George Rokos29d0f002017-05-27 03:03:13 +00003794 if (CGM.supportsCOMDAT()) {
3795 // It is sufficient to call registration function only once, so create a
3796 // COMDAT group for registration/unregistration functions and associated
3797 // data. That would reduce startup time and code size. Registration
3798 // function serves as a COMDAT group key.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003799 llvm::Comdat *ComdatKey = M.getOrInsertComdat(RegFn->getName());
George Rokos29d0f002017-05-27 03:03:13 +00003800 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3801 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3802 RegFn->setComdat(ComdatKey);
3803 UnRegFn->setComdat(ComdatKey);
3804 DeviceImages->setComdat(ComdatKey);
3805 Desc->setComdat(ComdatKey);
3806 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003807 return RegFn;
3808}
3809
Alexey Bataev03f270c2018-03-30 18:31:07 +00003810void CGOpenMPRuntime::createOffloadEntry(
3811 llvm::Constant *ID, llvm::Constant *Addr, uint64_t Size, int32_t Flags,
3812 llvm::GlobalValue::LinkageTypes Linkage) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003813 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003814 llvm::Module &M = CGM.getModule();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003815 llvm::LLVMContext &C = M.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003816
3817 // Create constant string with the name.
3818 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3819
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003820 auto *Str =
Samuel Antaoee8fb302016-01-06 13:42:12 +00003821 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
3822 llvm::GlobalValue::InternalLinkage, StrPtrInit,
3823 ".omp_offloading.entry_name");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003824 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003825
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003826 llvm::Constant *Data[] = {llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy),
3827 llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy),
3828 llvm::ConstantInt::get(CGM.SizeTy, Size),
3829 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
3830 llvm::ConstantInt::get(CGM.Int32Ty, 0)};
3831 llvm::GlobalVariable *Entry = createConstantGlobalStruct(
3832 CGM, getTgtOffloadEntryQTy(), Data, Twine(".omp_offloading.entry.", Name),
3833 Linkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003834
3835 // The entry has to be created in the section the linker expects it to be.
3836 Entry->setSection(".omp_offloading.entries");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003837}
3838
3839void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3840 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003841 // can easily figure out what to emit. The produced metadata looks like
3842 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003843 //
3844 // !omp_offload.info = !{!1, ...}
3845 //
3846 // Right now we only generate metadata for function that contain target
3847 // regions.
3848
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003849 // If we do not have entries, we don't need to do anything.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003850 if (OffloadEntriesInfoManager.empty())
3851 return;
3852
3853 llvm::Module &M = CGM.getModule();
3854 llvm::LLVMContext &C = M.getContext();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003855 SmallVector<const OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
Samuel Antaoee8fb302016-01-06 13:42:12 +00003856 OrderedEntries(OffloadEntriesInfoManager.size());
3857
Simon Pilgrim2c518802017-03-30 14:13:19 +00003858 // Auxiliary methods to create metadata values and strings.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003859 auto &&GetMDInt = [this](unsigned V) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003860 return llvm::ConstantAsMetadata::get(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003861 llvm::ConstantInt::get(CGM.Int32Ty, V));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003862 };
3863
Alexey Bataev03f270c2018-03-30 18:31:07 +00003864 auto &&GetMDString = [&C](StringRef V) { return llvm::MDString::get(C, V); };
3865
3866 // Create the offloading info metadata node.
3867 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003868
3869 // Create function that emits metadata for each target region entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00003870 auto &&TargetRegionMetadataEmitter =
3871 [&C, MD, &OrderedEntries, &GetMDInt, &GetMDString](
3872 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3873 unsigned Line,
3874 const OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3875 // Generate metadata for target regions. Each entry of this metadata
3876 // contains:
3877 // - Entry 0 -> Kind of this type of metadata (0).
3878 // - Entry 1 -> Device ID of the file where the entry was identified.
3879 // - Entry 2 -> File ID of the file where the entry was identified.
3880 // - Entry 3 -> Mangled name of the function where the entry was
3881 // identified.
3882 // - Entry 4 -> Line in the file where the entry was identified.
3883 // - Entry 5 -> Order the entry was created.
3884 // The first element of the metadata node is the kind.
3885 llvm::Metadata *Ops[] = {GetMDInt(E.getKind()), GetMDInt(DeviceID),
3886 GetMDInt(FileID), GetMDString(ParentName),
3887 GetMDInt(Line), GetMDInt(E.getOrder())};
Samuel Antaoee8fb302016-01-06 13:42:12 +00003888
Alexey Bataev03f270c2018-03-30 18:31:07 +00003889 // Save this entry in the right position of the ordered entries array.
3890 OrderedEntries[E.getOrder()] = &E;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003891
Alexey Bataev03f270c2018-03-30 18:31:07 +00003892 // Add metadata to the named metadata node.
3893 MD->addOperand(llvm::MDNode::get(C, Ops));
3894 };
Samuel Antaoee8fb302016-01-06 13:42:12 +00003895
3896 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3897 TargetRegionMetadataEmitter);
3898
Alexey Bataev03f270c2018-03-30 18:31:07 +00003899 // Create function that emits metadata for each device global variable entry;
3900 auto &&DeviceGlobalVarMetadataEmitter =
3901 [&C, &OrderedEntries, &GetMDInt, &GetMDString,
3902 MD](StringRef MangledName,
3903 const OffloadEntriesInfoManagerTy::OffloadEntryInfoDeviceGlobalVar
3904 &E) {
3905 // Generate metadata for global variables. Each entry of this metadata
3906 // contains:
3907 // - Entry 0 -> Kind of this type of metadata (1).
3908 // - Entry 1 -> Mangled name of the variable.
3909 // - Entry 2 -> Declare target kind.
3910 // - Entry 3 -> Order the entry was created.
3911 // The first element of the metadata node is the kind.
3912 llvm::Metadata *Ops[] = {
3913 GetMDInt(E.getKind()), GetMDString(MangledName),
3914 GetMDInt(E.getFlags()), GetMDInt(E.getOrder())};
3915
3916 // Save this entry in the right position of the ordered entries array.
3917 OrderedEntries[E.getOrder()] = &E;
3918
3919 // Add metadata to the named metadata node.
3920 MD->addOperand(llvm::MDNode::get(C, Ops));
3921 };
3922
3923 OffloadEntriesInfoManager.actOnDeviceGlobalVarEntriesInfo(
3924 DeviceGlobalVarMetadataEmitter);
3925
3926 for (const auto *E : OrderedEntries) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003927 assert(E && "All ordered entries must exist!");
Alexey Bataev03f270c2018-03-30 18:31:07 +00003928 if (const auto *CE =
Samuel Antaoee8fb302016-01-06 13:42:12 +00003929 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3930 E)) {
3931 assert(CE->getID() && CE->getAddress() &&
3932 "Entry ID and Addr are invalid!");
Alexey Bataev34f8a702018-03-28 14:28:54 +00003933 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0,
Alexey Bataev03f270c2018-03-30 18:31:07 +00003934 CE->getFlags(), llvm::GlobalValue::WeakAnyLinkage);
3935 } else if (const auto *CE =
3936 dyn_cast<OffloadEntriesInfoManagerTy::
3937 OffloadEntryInfoDeviceGlobalVar>(E)) {
3938 assert(CE->getAddress() && "Entry Addr is invalid!");
3939 createOffloadEntry(CE->getAddress(), CE->getAddress(),
3940 CE->getVarSize().getQuantity(), CE->getFlags(),
3941 CE->getLinkage());
3942 } else {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003943 llvm_unreachable("Unsupported entry kind.");
Alexey Bataev03f270c2018-03-30 18:31:07 +00003944 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003945 }
3946}
3947
3948/// \brief Loads all the offload entries information from the host IR
3949/// metadata.
3950void CGOpenMPRuntime::loadOffloadInfoMetadata() {
3951 // If we are in target mode, load the metadata from the host IR. This code has
3952 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
3953
3954 if (!CGM.getLangOpts().OpenMPIsDevice)
3955 return;
3956
3957 if (CGM.getLangOpts().OMPHostIRFile.empty())
3958 return;
3959
3960 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
3961 if (Buf.getError())
3962 return;
3963
3964 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00003965 auto ME = expectedToErrorOrAndEmitErrors(
3966 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003967
3968 if (ME.getError())
3969 return;
3970
3971 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
3972 if (!MD)
3973 return;
3974
George Burgess IV00f70bd2018-03-01 05:43:23 +00003975 for (llvm::MDNode *MN : MD->operands()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003976 auto &&GetMDInt = [MN](unsigned Idx) {
3977 auto *V = cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003978 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
3979 };
3980
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003981 auto &&GetMDString = [MN](unsigned Idx) {
3982 auto *V = cast<llvm::MDString>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003983 return V->getString();
3984 };
3985
Alexey Bataev03f270c2018-03-30 18:31:07 +00003986 switch (GetMDInt(0)) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003987 default:
3988 llvm_unreachable("Unexpected metadata!");
3989 break;
3990 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
Alexey Bataev34f8a702018-03-28 14:28:54 +00003991 OffloadingEntryInfoTargetRegion:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003992 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
Alexey Bataev03f270c2018-03-30 18:31:07 +00003993 /*DeviceID=*/GetMDInt(1), /*FileID=*/GetMDInt(2),
3994 /*ParentName=*/GetMDString(3), /*Line=*/GetMDInt(4),
3995 /*Order=*/GetMDInt(5));
3996 break;
3997 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3998 OffloadingEntryInfoDeviceGlobalVar:
3999 OffloadEntriesInfoManager.initializeDeviceGlobalVarEntryInfo(
4000 /*MangledName=*/GetMDString(1),
4001 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
4002 /*Flags=*/GetMDInt(2)),
4003 /*Order=*/GetMDInt(3));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004004 break;
4005 }
4006 }
4007}
4008
Alexey Bataev62b63b12015-03-10 07:28:44 +00004009void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
4010 if (!KmpRoutineEntryPtrTy) {
4011 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004012 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004013 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
4014 FunctionProtoType::ExtProtoInfo EPI;
4015 KmpRoutineEntryPtrQTy = C.getPointerType(
4016 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
4017 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
4018 }
4019}
4020
Samuel Antaoee8fb302016-01-06 13:42:12 +00004021QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004022 // Make sure the type of the entry is already created. This is the type we
4023 // have to create:
4024 // struct __tgt_offload_entry{
4025 // void *addr; // Pointer to the offload entry info.
4026 // // (function or global)
4027 // char *name; // Name of the function or global.
4028 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00004029 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
4030 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004031 // };
4032 if (TgtOffloadEntryQTy.isNull()) {
4033 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004034 RecordDecl *RD = C.buildImplicitRecord("__tgt_offload_entry");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004035 RD->startDefinition();
4036 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4037 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
4038 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00004039 addFieldToRecordDecl(
4040 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4041 addFieldToRecordDecl(
4042 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004043 RD->completeDefinition();
Jonas Hahnfeld5e4df282018-01-18 15:38:03 +00004044 RD->addAttr(PackedAttr::CreateImplicit(C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004045 TgtOffloadEntryQTy = C.getRecordType(RD);
4046 }
4047 return TgtOffloadEntryQTy;
4048}
4049
4050QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
4051 // These are the types we need to build:
4052 // struct __tgt_device_image{
4053 // void *ImageStart; // Pointer to the target code start.
4054 // void *ImageEnd; // Pointer to the target code end.
4055 // // We also add the host entries to the device image, as it may be useful
4056 // // for the target runtime to have access to that information.
4057 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
4058 // // the entries.
4059 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4060 // // entries (non inclusive).
4061 // };
4062 if (TgtDeviceImageQTy.isNull()) {
4063 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004064 RecordDecl *RD = C.buildImplicitRecord("__tgt_device_image");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004065 RD->startDefinition();
4066 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4067 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4068 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4069 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4070 RD->completeDefinition();
4071 TgtDeviceImageQTy = C.getRecordType(RD);
4072 }
4073 return TgtDeviceImageQTy;
4074}
4075
4076QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
4077 // struct __tgt_bin_desc{
4078 // int32_t NumDevices; // Number of devices supported.
4079 // __tgt_device_image *DeviceImages; // Arrays of device images
4080 // // (one per device).
4081 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
4082 // // entries.
4083 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4084 // // entries (non inclusive).
4085 // };
4086 if (TgtBinaryDescriptorQTy.isNull()) {
4087 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004088 RecordDecl *RD = C.buildImplicitRecord("__tgt_bin_desc");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004089 RD->startDefinition();
4090 addFieldToRecordDecl(
4091 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4092 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
4093 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4094 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4095 RD->completeDefinition();
4096 TgtBinaryDescriptorQTy = C.getRecordType(RD);
4097 }
4098 return TgtBinaryDescriptorQTy;
4099}
4100
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004101namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00004102struct PrivateHelpersTy {
4103 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
4104 const VarDecl *PrivateElemInit)
4105 : Original(Original), PrivateCopy(PrivateCopy),
4106 PrivateElemInit(PrivateElemInit) {}
4107 const VarDecl *Original;
4108 const VarDecl *PrivateCopy;
4109 const VarDecl *PrivateElemInit;
4110};
4111typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00004112} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004113
Alexey Bataev9e034042015-05-05 04:05:12 +00004114static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00004115createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004116 if (!Privates.empty()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004117 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004118 // Build struct .kmp_privates_t. {
4119 // /* private vars */
4120 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004121 RecordDecl *RD = C.buildImplicitRecord(".kmp_privates.t");
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004122 RD->startDefinition();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004123 for (const auto &Pair : Privates) {
4124 const VarDecl *VD = Pair.second.Original;
4125 QualType Type = VD->getType().getNonReferenceType();
4126 FieldDecl *FD = addFieldToRecordDecl(C, RD, Type);
Alexey Bataevc71a4092015-09-11 10:29:41 +00004127 if (VD->hasAttrs()) {
4128 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
4129 E(VD->getAttrs().end());
4130 I != E; ++I)
4131 FD->addAttr(*I);
4132 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004133 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004134 RD->completeDefinition();
4135 return RD;
4136 }
4137 return nullptr;
4138}
4139
Alexey Bataev9e034042015-05-05 04:05:12 +00004140static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00004141createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
4142 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004143 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004144 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004145 // Build struct kmp_task_t {
4146 // void * shareds;
4147 // kmp_routine_entry_t routine;
4148 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00004149 // kmp_cmplrdata_t data1;
4150 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00004151 // For taskloops additional fields:
4152 // kmp_uint64 lb;
4153 // kmp_uint64 ub;
4154 // kmp_int64 st;
4155 // kmp_int32 liter;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004156 // void * reductions;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004157 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004158 RecordDecl *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004159 UD->startDefinition();
4160 addFieldToRecordDecl(C, UD, KmpInt32Ty);
4161 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
4162 UD->completeDefinition();
4163 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004164 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t");
Alexey Bataev62b63b12015-03-10 07:28:44 +00004165 RD->startDefinition();
4166 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4167 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
4168 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004169 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
4170 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004171 if (isOpenMPTaskLoopDirective(Kind)) {
4172 QualType KmpUInt64Ty =
4173 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4174 QualType KmpInt64Ty =
4175 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4176 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4177 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4178 addFieldToRecordDecl(C, RD, KmpInt64Ty);
4179 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004180 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004181 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004182 RD->completeDefinition();
4183 return RD;
4184}
4185
4186static RecordDecl *
4187createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004188 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004189 ASTContext &C = CGM.getContext();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004190 // Build struct kmp_task_t_with_privates {
4191 // kmp_task_t task_data;
4192 // .kmp_privates_t. privates;
4193 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004194 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004195 RD->startDefinition();
4196 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004197 if (const RecordDecl *PrivateRD = createPrivatesRecordDecl(CGM, Privates))
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004198 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004199 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004200 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004201}
4202
4203/// \brief Emit a proxy function which accepts kmp_task_t as the second
4204/// argument.
4205/// \code
4206/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004207/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00004208/// For taskloops:
4209/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004210/// tt->reductions, tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004211/// return 0;
4212/// }
4213/// \endcode
4214static llvm::Value *
4215emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00004216 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
4217 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004218 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004219 QualType SharedsPtrTy, llvm::Value *TaskFunction,
4220 llvm::Value *TaskPrivatesMap) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004221 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004222 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004223 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4224 ImplicitParamDecl::Other);
4225 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4226 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4227 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004228 Args.push_back(&GtidArg);
4229 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004230 const auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004231 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004232 llvm::FunctionType *TaskEntryTy =
4233 CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004234 auto *TaskEntry =
4235 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
4236 ".omp_task_entry.", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004237 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskEntry, TaskEntryFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004238 TaskEntry->setDoesNotRecurse();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004239 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004240 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args,
4241 Loc, Loc);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004242
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004243 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00004244 // tt,
4245 // For taskloops:
4246 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
4247 // tt->task_data.shareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004248 llvm::Value *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00004249 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00004250 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4251 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4252 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004253 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004254 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004255 LValue Base =
4256 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004257 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004258 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004259 LValue PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
4260 llvm::Value *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004261
4262 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004263 LValue SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
4264 llvm::Value *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev1e491372018-01-23 18:44:14 +00004265 CGF.EmitLoadOfScalar(SharedsLVal, Loc),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004266 CGF.ConvertTypeForMem(SharedsPtrTy));
4267
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004268 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4269 llvm::Value *PrivatesParam;
4270 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004271 LValue PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004272 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004273 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004274 } else {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004275 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004276 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004277
Alexey Bataev7292c292016-04-25 12:22:29 +00004278 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
4279 TaskPrivatesMap,
4280 CGF.Builder
4281 .CreatePointerBitCastOrAddrSpaceCast(
4282 TDBase.getAddress(), CGF.VoidPtrTy)
4283 .getPointer()};
4284 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
4285 std::end(CommonArgs));
4286 if (isOpenMPTaskLoopDirective(Kind)) {
4287 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004288 LValue LBLVal = CGF.EmitLValueForField(Base, *LBFI);
4289 llvm::Value *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004290 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004291 LValue UBLVal = CGF.EmitLValueForField(Base, *UBFI);
4292 llvm::Value *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004293 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004294 LValue StLVal = CGF.EmitLValueForField(Base, *StFI);
4295 llvm::Value *StParam = CGF.EmitLoadOfScalar(StLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004296 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004297 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4298 llvm::Value *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004299 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004300 LValue RLVal = CGF.EmitLValueForField(Base, *RFI);
4301 llvm::Value *RParam = CGF.EmitLoadOfScalar(RLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004302 CallArgs.push_back(LBParam);
4303 CallArgs.push_back(UBParam);
4304 CallArgs.push_back(StParam);
4305 CallArgs.push_back(LIParam);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004306 CallArgs.push_back(RParam);
Alexey Bataev7292c292016-04-25 12:22:29 +00004307 }
4308 CallArgs.push_back(SharedsParam);
4309
Alexey Bataev3c595a62017-08-14 15:01:03 +00004310 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
4311 CallArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004312 CGF.EmitStoreThroughLValue(RValue::get(CGF.Builder.getInt32(/*C=*/0)),
4313 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004314 CGF.FinishFunction();
4315 return TaskEntry;
4316}
4317
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004318static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
4319 SourceLocation Loc,
4320 QualType KmpInt32Ty,
4321 QualType KmpTaskTWithPrivatesPtrQTy,
4322 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004323 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004324 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004325 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4326 ImplicitParamDecl::Other);
4327 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4328 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4329 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004330 Args.push_back(&GtidArg);
4331 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004332 const auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004333 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004334 llvm::FunctionType *DestructorFnTy =
4335 CGM.getTypes().GetFunctionType(DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004336 auto *DestructorFn =
4337 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
4338 ".omp_task_destructor.", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004339 CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004340 DestructorFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004341 DestructorFn->setDoesNotRecurse();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004342 CodeGenFunction CGF(CGM);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004343 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004344 Args, Loc, Loc);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004345
Alexey Bataev31300ed2016-02-04 11:27:03 +00004346 LValue Base = CGF.EmitLoadOfPointerLValue(
4347 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4348 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004349 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004350 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
4351 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004352 Base = CGF.EmitLValueForField(Base, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004353 for (const auto *Field :
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004354 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004355 if (QualType::DestructionKind DtorKind =
4356 Field->getType().isDestructedType()) {
4357 LValue FieldLValue = CGF.EmitLValueForField(Base, Field);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004358 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
4359 }
4360 }
4361 CGF.FinishFunction();
4362 return DestructorFn;
4363}
4364
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004365/// \brief Emit a privates mapping function for correct handling of private and
4366/// firstprivate variables.
4367/// \code
4368/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
4369/// **noalias priv1,..., <tyn> **noalias privn) {
4370/// *priv1 = &.privates.priv1;
4371/// ...;
4372/// *privn = &.privates.privn;
4373/// }
4374/// \endcode
4375static llvm::Value *
4376emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00004377 ArrayRef<const Expr *> PrivateVars,
4378 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004379 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004380 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004381 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004382 ASTContext &C = CGM.getContext();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004383 FunctionArgList Args;
4384 ImplicitParamDecl TaskPrivatesArg(
4385 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00004386 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
4387 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004388 Args.push_back(&TaskPrivatesArg);
4389 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
4390 unsigned Counter = 1;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004391 for (const Expr *E : PrivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004392 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004393 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4394 C.getPointerType(C.getPointerType(E->getType()))
4395 .withConst()
4396 .withRestrict(),
4397 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004398 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004399 PrivateVarsPos[VD] = Counter;
4400 ++Counter;
4401 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004402 for (const Expr *E : FirstprivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004403 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004404 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4405 C.getPointerType(C.getPointerType(E->getType()))
4406 .withConst()
4407 .withRestrict(),
4408 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004409 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004410 PrivateVarsPos[VD] = Counter;
4411 ++Counter;
4412 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004413 for (const Expr *E : LastprivateVars) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004414 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004415 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4416 C.getPointerType(C.getPointerType(E->getType()))
4417 .withConst()
4418 .withRestrict(),
4419 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004420 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004421 PrivateVarsPos[VD] = Counter;
4422 ++Counter;
4423 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004424 const auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004425 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004426 llvm::FunctionType *TaskPrivatesMapTy =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004427 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
4428 auto *TaskPrivatesMap = llvm::Function::Create(
4429 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
4430 ".omp_task_privates_map.", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004431 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004432 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00004433 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00004434 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00004435 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004436 CodeGenFunction CGF(CGM);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004437 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004438 TaskPrivatesMapFnInfo, Args, Loc, Loc);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004439
4440 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00004441 LValue Base = CGF.EmitLoadOfPointerLValue(
4442 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4443 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004444 const auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004445 Counter = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004446 for (const FieldDecl *Field : PrivatesQTyRD->fields()) {
4447 LValue FieldLVal = CGF.EmitLValueForField(Base, Field);
4448 const VarDecl *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
4449 LValue RefLVal =
4450 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
4451 LValue RefLoadLVal = CGF.EmitLoadOfPointerLValue(
Alexey Bataev31300ed2016-02-04 11:27:03 +00004452 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00004453 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004454 ++Counter;
4455 }
4456 CGF.FinishFunction();
4457 return TaskPrivatesMap;
4458}
4459
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004460static bool stable_sort_comparator(const PrivateDataTy P1,
4461 const PrivateDataTy P2) {
4462 return P1.first > P2.first;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004463}
4464
Alexey Bataevf93095a2016-05-05 08:46:22 +00004465/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00004466static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004467 const OMPExecutableDirective &D,
4468 Address KmpTaskSharedsPtr, LValue TDBase,
4469 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4470 QualType SharedsTy, QualType SharedsPtrTy,
4471 const OMPTaskDataTy &Data,
4472 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004473 ASTContext &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004474 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4475 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004476 OpenMPDirectiveKind Kind = isOpenMPTaskLoopDirective(D.getDirectiveKind())
4477 ? OMPD_taskloop
4478 : OMPD_task;
4479 const CapturedStmt &CS = *D.getCapturedStmt(Kind);
4480 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004481 LValue SrcBase;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004482 bool IsTargetTask =
4483 isOpenMPTargetDataManagementDirective(D.getDirectiveKind()) ||
4484 isOpenMPTargetExecutionDirective(D.getDirectiveKind());
4485 // For target-based directives skip 3 firstprivate arrays BasePointersArray,
4486 // PointersArray and SizesArray. The original variables for these arrays are
4487 // not captured and we get their addresses explicitly.
4488 if ((!IsTargetTask && !Data.FirstprivateVars.empty()) ||
Alexey Bataev8451efa2018-01-15 19:06:12 +00004489 (IsTargetTask && KmpTaskSharedsPtr.isValid())) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004490 SrcBase = CGF.MakeAddrLValue(
4491 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4492 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4493 SharedsTy);
4494 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004495 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004496 for (const PrivateDataTy &Pair : Privates) {
4497 const VarDecl *VD = Pair.second.PrivateCopy;
4498 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004499 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4500 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004501 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004502 if (const VarDecl *Elem = Pair.second.PrivateElemInit) {
4503 const VarDecl *OriginalVD = Pair.second.Original;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004504 // Check if the variable is the target-based BasePointersArray,
4505 // PointersArray or SizesArray.
4506 LValue SharedRefLValue;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004507 QualType Type = OriginalVD->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004508 const FieldDecl *SharedField = CapturesInfo.lookup(OriginalVD);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004509 if (IsTargetTask && !SharedField) {
4510 assert(isa<ImplicitParamDecl>(OriginalVD) &&
4511 isa<CapturedDecl>(OriginalVD->getDeclContext()) &&
4512 cast<CapturedDecl>(OriginalVD->getDeclContext())
4513 ->getNumParams() == 0 &&
4514 isa<TranslationUnitDecl>(
4515 cast<CapturedDecl>(OriginalVD->getDeclContext())
4516 ->getDeclContext()) &&
4517 "Expected artificial target data variable.");
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004518 SharedRefLValue =
4519 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type);
4520 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004521 SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4522 SharedRefLValue = CGF.MakeAddrLValue(
4523 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
4524 SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl),
4525 SharedRefLValue.getTBAAInfo());
4526 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004527 if (Type->isArrayType()) {
4528 // Initialize firstprivate array.
4529 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4530 // Perform simple memcpy.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004531 CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004532 } else {
4533 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00004534 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00004535 CGF.EmitOMPAggregateAssign(
4536 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4537 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4538 Address SrcElement) {
4539 // Clean up any temporaries needed by the initialization.
4540 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4541 InitScope.addPrivate(
4542 Elem, [SrcElement]() -> Address { return SrcElement; });
4543 (void)InitScope.Privatize();
4544 // Emit initialization for single element.
4545 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4546 CGF, &CapturesInfo);
4547 CGF.EmitAnyExprToMem(Init, DestElement,
4548 Init->getType().getQualifiers(),
4549 /*IsInitializer=*/false);
4550 });
4551 }
4552 } else {
4553 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4554 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4555 return SharedRefLValue.getAddress();
4556 });
4557 (void)InitScope.Privatize();
4558 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4559 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4560 /*capturedByInit=*/false);
4561 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004562 } else {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004563 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004564 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004565 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004566 ++FI;
4567 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004568}
4569
4570/// Check if duplication function is required for taskloops.
4571static bool checkInitIsRequired(CodeGenFunction &CGF,
4572 ArrayRef<PrivateDataTy> Privates) {
4573 bool InitRequired = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004574 for (const PrivateDataTy &Pair : Privates) {
4575 const VarDecl *VD = Pair.second.PrivateCopy;
4576 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004577 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4578 !CGF.isTrivialInitializer(Init));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004579 if (InitRequired)
4580 break;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004581 }
4582 return InitRequired;
4583}
4584
4585
4586/// Emit task_dup function (for initialization of
4587/// private/firstprivate/lastprivate vars and last_iter flag)
4588/// \code
4589/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4590/// lastpriv) {
4591/// // setup lastprivate flag
4592/// task_dst->last = lastpriv;
4593/// // could be constructor calls here...
4594/// }
4595/// \endcode
4596static llvm::Value *
4597emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4598 const OMPExecutableDirective &D,
4599 QualType KmpTaskTWithPrivatesPtrQTy,
4600 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4601 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4602 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4603 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004604 ASTContext &C = CGM.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004605 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004606 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4607 KmpTaskTWithPrivatesPtrQTy,
4608 ImplicitParamDecl::Other);
4609 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4610 KmpTaskTWithPrivatesPtrQTy,
4611 ImplicitParamDecl::Other);
4612 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4613 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004614 Args.push_back(&DstArg);
4615 Args.push_back(&SrcArg);
4616 Args.push_back(&LastprivArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004617 const auto &TaskDupFnInfo =
Alexey Bataevf93095a2016-05-05 08:46:22 +00004618 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004619 llvm::FunctionType *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004620 auto *TaskDup =
4621 llvm::Function::Create(TaskDupTy, llvm::GlobalValue::InternalLinkage,
4622 ".omp_task_dup.", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004623 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskDup, TaskDupFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004624 TaskDup->setDoesNotRecurse();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004625 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004626 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args, Loc,
4627 Loc);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004628
4629 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4630 CGF.GetAddrOfLocalVar(&DstArg),
4631 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4632 // task_dst->liter = lastpriv;
4633 if (WithLastIter) {
4634 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4635 LValue Base = CGF.EmitLValueForField(
4636 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4637 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4638 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4639 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4640 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4641 }
4642
4643 // Emit initial values for private copies (if any).
4644 assert(!Privates.empty());
4645 Address KmpTaskSharedsPtr = Address::invalid();
4646 if (!Data.FirstprivateVars.empty()) {
4647 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4648 CGF.GetAddrOfLocalVar(&SrcArg),
4649 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4650 LValue Base = CGF.EmitLValueForField(
4651 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4652 KmpTaskSharedsPtr = Address(
4653 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4654 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4655 KmpTaskTShareds)),
4656 Loc),
4657 CGF.getNaturalTypeAlignment(SharedsTy));
4658 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004659 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4660 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004661 CGF.FinishFunction();
4662 return TaskDup;
4663}
4664
Alexey Bataev8a831592016-05-10 10:36:51 +00004665/// Checks if destructor function is required to be generated.
4666/// \return true if cleanups are required, false otherwise.
4667static bool
4668checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4669 bool NeedsCleanup = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004670 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4671 const auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4672 for (const FieldDecl *FD : PrivateRD->fields()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004673 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4674 if (NeedsCleanup)
4675 break;
4676 }
4677 return NeedsCleanup;
4678}
4679
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004680CGOpenMPRuntime::TaskResultTy
4681CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4682 const OMPExecutableDirective &D,
4683 llvm::Value *TaskFunction, QualType SharedsTy,
4684 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004685 ASTContext &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004686 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004687 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004688 auto I = Data.PrivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004689 for (const Expr *E : Data.PrivateVars) {
4690 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004691 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004692 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004693 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004694 /*PrivateElemInit=*/nullptr));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004695 ++I;
4696 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004697 I = Data.FirstprivateCopies.begin();
4698 auto IElemInitRef = Data.FirstprivateInits.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004699 for (const Expr *E : Data.FirstprivateVars) {
4700 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004701 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004702 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004703 PrivateHelpersTy(
4704 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004705 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl())));
Richard Trieucc3949d2016-02-18 22:34:54 +00004706 ++I;
4707 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004708 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004709 I = Data.LastprivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004710 for (const Expr *E : Data.LastprivateVars) {
4711 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004712 Privates.emplace_back(
Alexey Bataevf93095a2016-05-05 08:46:22 +00004713 C.getDeclAlign(VD),
4714 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004715 /*PrivateElemInit=*/nullptr));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004716 ++I;
4717 }
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004718 std::stable_sort(Privates.begin(), Privates.end(), stable_sort_comparator);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004719 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004720 // Build type kmp_routine_entry_t (if not built yet).
4721 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004722 // Build type kmp_task_t (if not built yet).
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004723 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
4724 if (SavedKmpTaskloopTQTy.isNull()) {
4725 SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4726 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4727 }
4728 KmpTaskTQTy = SavedKmpTaskloopTQTy;
Alexey Bataev3a03a7f2017-10-11 15:56:38 +00004729 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004730 assert((D.getDirectiveKind() == OMPD_task ||
4731 isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||
4732 isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) &&
4733 "Expected taskloop, task or target directive");
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004734 if (SavedKmpTaskTQTy.isNull()) {
4735 SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4736 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4737 }
4738 KmpTaskTQTy = SavedKmpTaskTQTy;
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004739 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004740 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004741 // Build particular struct kmp_task_t for the given task.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004742 const RecordDecl *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004743 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004744 QualType KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004745 QualType KmpTaskTWithPrivatesPtrQTy =
4746 C.getPointerType(KmpTaskTWithPrivatesQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004747 llvm::Type *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4748 llvm::Type *KmpTaskTWithPrivatesPtrTy =
4749 KmpTaskTWithPrivatesTy->getPointerTo();
4750 llvm::Value *KmpTaskTWithPrivatesTySize =
4751 CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004752 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4753
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004754 // Emit initial values for private copies (if any).
4755 llvm::Value *TaskPrivatesMap = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004756 llvm::Type *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00004757 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004758 if (!Privates.empty()) {
4759 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004760 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4761 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4762 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004763 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4764 TaskPrivatesMap, TaskPrivatesMapTy);
4765 } else {
4766 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4767 cast<llvm::PointerType>(TaskPrivatesMapTy));
4768 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004769 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4770 // kmp_task_t *tt);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004771 llvm::Value *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004772 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4773 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4774 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004775
4776 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4777 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4778 // kmp_routine_entry_t *task_entry);
4779 // Task flags. Format is taken from
4780 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4781 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004782 enum {
4783 TiedFlag = 0x1,
4784 FinalFlag = 0x2,
4785 DestructorsFlag = 0x8,
4786 PriorityFlag = 0x20
4787 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004788 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004789 bool NeedsCleanup = false;
4790 if (!Privates.empty()) {
4791 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4792 if (NeedsCleanup)
4793 Flags = Flags | DestructorsFlag;
4794 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004795 if (Data.Priority.getInt())
4796 Flags = Flags | PriorityFlag;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004797 llvm::Value *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004798 Data.Final.getPointer()
4799 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00004800 CGF.Builder.getInt32(FinalFlag),
4801 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004802 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004803 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004804 llvm::Value *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004805 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4806 getThreadID(CGF, Loc), TaskFlags,
4807 KmpTaskTWithPrivatesTySize, SharedsSize,
4808 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4809 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004810 llvm::Value *NewTask = CGF.EmitRuntimeCall(
Alexey Bataev62b63b12015-03-10 07:28:44 +00004811 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004812 llvm::Value *NewTaskNewTaskTTy =
4813 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4814 NewTask, KmpTaskTWithPrivatesPtrTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004815 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4816 KmpTaskTWithPrivatesQTy);
4817 LValue TDBase =
4818 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004819 // Fill the data in the resulting kmp_task_t record.
4820 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00004821 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004822 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00004823 KmpTaskSharedsPtr =
4824 Address(CGF.EmitLoadOfScalar(
4825 CGF.EmitLValueForField(
4826 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4827 KmpTaskTShareds)),
4828 Loc),
4829 CGF.getNaturalTypeAlignment(SharedsTy));
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004830 LValue Dest = CGF.MakeAddrLValue(KmpTaskSharedsPtr, SharedsTy);
4831 LValue Src = CGF.MakeAddrLValue(Shareds, SharedsTy);
Richard Smithe78fac52018-04-05 20:52:58 +00004832 CGF.EmitAggregateCopy(Dest, Src, SharedsTy, AggValueSlot::DoesNotOverlap);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004833 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004834 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00004835 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004836 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004837 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4838 SharedsTy, SharedsPtrTy, Data, Privates,
4839 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004840 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4841 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4842 Result.TaskDupFn = emitTaskDupFunction(
4843 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4844 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4845 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004846 }
4847 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00004848 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4849 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00004850 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00004851 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004852 const RecordDecl *KmpCmplrdataUD =
4853 (*FI)->getType()->getAsUnionType()->getDecl();
Alexey Bataevad537bb2016-05-30 09:06:50 +00004854 if (NeedsCleanup) {
4855 llvm::Value *DestructorFn = emitDestructorsFunction(
4856 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4857 KmpTaskTWithPrivatesQTy);
4858 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4859 LValue DestructorsLV = CGF.EmitLValueForField(
4860 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4861 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4862 DestructorFn, KmpRoutineEntryPtrTy),
4863 DestructorsLV);
4864 }
4865 // Set priority.
4866 if (Data.Priority.getInt()) {
4867 LValue Data2LV = CGF.EmitLValueForField(
4868 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
4869 LValue PriorityLV = CGF.EmitLValueForField(
4870 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
4871 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
4872 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004873 Result.NewTask = NewTask;
4874 Result.TaskEntry = TaskEntry;
4875 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
4876 Result.TDBase = TDBase;
4877 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
4878 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00004879}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004880
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004881void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
4882 const OMPExecutableDirective &D,
4883 llvm::Value *TaskFunction,
4884 QualType SharedsTy, Address Shareds,
4885 const Expr *IfCond,
4886 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004887 if (!CGF.HaveInsertPoint())
4888 return;
4889
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004890 TaskResultTy Result =
4891 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4892 llvm::Value *NewTask = Result.NewTask;
4893 llvm::Value *TaskEntry = Result.TaskEntry;
4894 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
4895 LValue TDBase = Result.TDBase;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004896 const RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
4897 ASTContext &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004898 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00004899 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004900 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00004901 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004902 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00004903 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004904 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
4905 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004906 QualType FlagsTy =
4907 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004908 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
4909 if (KmpDependInfoTy.isNull()) {
4910 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
4911 KmpDependInfoRD->startDefinition();
4912 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
4913 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
4914 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
4915 KmpDependInfoRD->completeDefinition();
4916 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004917 } else {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004918 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004919 }
John McCall7f416cc2015-09-08 08:05:57 +00004920 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004921 // Define type kmp_depend_info[<Dependences.size()>];
4922 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00004923 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004924 ArrayType::Normal, /*IndexTypeQuals=*/0);
4925 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00004926 DependenciesArray =
4927 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004928 for (unsigned I = 0; I < NumDependencies; ++I) {
4929 const Expr *E = Data.Dependences[I].second;
4930 LValue Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004931 llvm::Value *Size;
4932 QualType Ty = E->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004933 if (const auto *ASE =
4934 dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004935 LValue UpAddrLVal =
4936 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
4937 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00004938 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004939 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00004940 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004941 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
4942 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004943 } else {
Alexey Bataev1189bd02016-01-26 12:20:39 +00004944 Size = CGF.getTypeSize(Ty);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004945 }
4946 LValue Base = CGF.MakeAddrLValue(
4947 CGF.Builder.CreateConstArrayGEP(DependenciesArray, I, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004948 KmpDependInfoTy);
4949 // deps[i].base_addr = &<Dependences[i].second>;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004950 LValue BaseAddrLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004951 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00004952 CGF.EmitStoreOfScalar(
4953 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
4954 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004955 // deps[i].len = sizeof(<Dependences[i].second>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004956 LValue LenLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004957 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
4958 CGF.EmitStoreOfScalar(Size, LenLVal);
4959 // deps[i].flags = <Dependences[i].first>;
4960 RTLDependenceKindTy DepKind;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004961 switch (Data.Dependences[I].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004962 case OMPC_DEPEND_in:
4963 DepKind = DepIn;
4964 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00004965 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004966 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004967 case OMPC_DEPEND_inout:
4968 DepKind = DepInOut;
4969 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00004970 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004971 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004972 case OMPC_DEPEND_unknown:
4973 llvm_unreachable("Unknown task dependence type");
4974 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004975 LValue FlagsLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004976 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
4977 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
4978 FlagsLVal);
4979 }
John McCall7f416cc2015-09-08 08:05:57 +00004980 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4981 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004982 CGF.VoidPtrTy);
4983 }
4984
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00004985 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev62b63b12015-03-10 07:28:44 +00004986 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004987 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
4988 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
4989 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
4990 // list is not empty
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004991 llvm::Value *ThreadID = getThreadID(CGF, Loc);
4992 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00004993 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
4994 llvm::Value *DepTaskArgs[7];
4995 if (NumDependencies) {
4996 DepTaskArgs[0] = UpLoc;
4997 DepTaskArgs[1] = ThreadID;
4998 DepTaskArgs[2] = NewTask;
4999 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
5000 DepTaskArgs[4] = DependenciesArray.getPointer();
5001 DepTaskArgs[5] = CGF.Builder.getInt32(0);
5002 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5003 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005004 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
5005 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005006 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005007 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005008 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005009 LValue PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005010 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
5011 }
John McCall7f416cc2015-09-08 08:05:57 +00005012 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005013 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00005014 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00005015 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005016 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00005017 TaskArgs);
5018 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00005019 // Check if parent region is untied and build return for untied task;
5020 if (auto *Region =
5021 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5022 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00005023 };
John McCall7f416cc2015-09-08 08:05:57 +00005024
5025 llvm::Value *DepWaitTaskArgs[6];
5026 if (NumDependencies) {
5027 DepWaitTaskArgs[0] = UpLoc;
5028 DepWaitTaskArgs[1] = ThreadID;
5029 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
5030 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
5031 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
5032 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5033 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005034 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00005035 NumDependencies, &DepWaitTaskArgs,
5036 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005037 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005038 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
5039 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
5040 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
5041 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
5042 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00005043 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005044 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005045 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005046 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00005047 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
5048 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005049 Action.Enter(CGF);
5050 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00005051 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00005052 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005053 };
5054
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005055 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
5056 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005057 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
5058 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005059 RegionCodeGenTy RCG(CodeGen);
5060 CommonActionTy Action(
5061 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
5062 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
5063 RCG.setAction(Action);
5064 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005065 };
John McCall7f416cc2015-09-08 08:05:57 +00005066
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005067 if (IfCond) {
Alexey Bataev1d677132015-04-22 13:57:31 +00005068 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005069 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005070 RegionCodeGenTy ThenRCG(ThenCodeGen);
5071 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00005072 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00005073}
5074
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005075void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
5076 const OMPLoopDirective &D,
5077 llvm::Value *TaskFunction,
5078 QualType SharedsTy, Address Shareds,
5079 const Expr *IfCond,
5080 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005081 if (!CGF.HaveInsertPoint())
5082 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005083 TaskResultTy Result =
5084 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005085 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev7292c292016-04-25 12:22:29 +00005086 // libcall.
5087 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
5088 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
5089 // sched, kmp_uint64 grainsize, void *task_dup);
5090 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5091 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
5092 llvm::Value *IfVal;
5093 if (IfCond) {
5094 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
5095 /*isSigned=*/true);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005096 } else {
Alexey Bataev7292c292016-04-25 12:22:29 +00005097 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005098 }
Alexey Bataev7292c292016-04-25 12:22:29 +00005099
5100 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005101 Result.TDBase,
5102 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005103 const auto *LBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005104 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
5105 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
5106 /*IsInitializer=*/true);
5107 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005108 Result.TDBase,
5109 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005110 const auto *UBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005111 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
5112 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
5113 /*IsInitializer=*/true);
5114 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005115 Result.TDBase,
5116 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005117 const auto *StVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005118 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
5119 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
5120 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005121 // Store reductions address.
5122 LValue RedLVal = CGF.EmitLValueForField(
5123 Result.TDBase,
5124 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005125 if (Data.Reductions) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005126 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005127 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005128 CGF.EmitNullInitialization(RedLVal.getAddress(),
5129 CGF.getContext().VoidPtrTy);
5130 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005131 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00005132 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00005133 UpLoc,
5134 ThreadID,
5135 Result.NewTask,
5136 IfVal,
5137 LBLVal.getPointer(),
5138 UBLVal.getPointer(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005139 CGF.EmitLoadOfScalar(StLVal, Loc),
Alexey Bataev33446032017-07-12 18:09:32 +00005140 llvm::ConstantInt::getNullValue(
5141 CGF.IntTy), // Always 0 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005142 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005143 CGF.IntTy, Data.Schedule.getPointer()
5144 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005145 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005146 Data.Schedule.getPointer()
5147 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005148 /*isSigned=*/false)
5149 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00005150 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5151 Result.TaskDupFn, CGF.VoidPtrTy)
5152 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00005153 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
5154}
5155
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005156/// \brief Emit reduction operation for each element of array (required for
5157/// array sections) LHS op = RHS.
5158/// \param Type Type of array.
5159/// \param LHSVar Variable on the left side of the reduction operation
5160/// (references element of array in original variable).
5161/// \param RHSVar Variable on the right side of the reduction operation
5162/// (references element of array in original variable).
5163/// \param RedOpGen Generator of reduction operation with use of LHSVar and
5164/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00005165static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005166 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
5167 const VarDecl *RHSVar,
5168 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
5169 const Expr *, const Expr *)> &RedOpGen,
5170 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
5171 const Expr *UpExpr = nullptr) {
5172 // Perform element-by-element initialization.
5173 QualType ElementTy;
5174 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
5175 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
5176
5177 // Drill down to the base element type on both arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005178 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
5179 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005180
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005181 llvm::Value *RHSBegin = RHSAddr.getPointer();
5182 llvm::Value *LHSBegin = LHSAddr.getPointer();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005183 // Cast from pointer to array type to pointer to single element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005184 llvm::Value *LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005185 // The basic structure here is a while-do loop.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005186 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
5187 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
5188 llvm::Value *IsEmpty =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005189 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
5190 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
5191
5192 // Enter the loop body, making that address the current address.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005193 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005194 CGF.EmitBlock(BodyBB);
5195
5196 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
5197
5198 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
5199 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
5200 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
5201 Address RHSElementCurrent =
5202 Address(RHSElementPHI,
5203 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5204
5205 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
5206 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
5207 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
5208 Address LHSElementCurrent =
5209 Address(LHSElementPHI,
5210 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5211
5212 // Emit copy.
5213 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005214 Scope.addPrivate(LHSVar, [=]() { return LHSElementCurrent; });
5215 Scope.addPrivate(RHSVar, [=]() { return RHSElementCurrent; });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005216 Scope.Privatize();
5217 RedOpGen(CGF, XExpr, EExpr, UpExpr);
5218 Scope.ForceCleanup();
5219
5220 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005221 llvm::Value *LHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005222 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005223 llvm::Value *RHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005224 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
5225 // Check whether we've reached the end.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005226 llvm::Value *Done =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005227 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
5228 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
5229 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
5230 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
5231
5232 // Done.
5233 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
5234}
5235
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005236/// Emit reduction combiner. If the combiner is a simple expression emit it as
5237/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
5238/// UDR combiner function.
5239static void emitReductionCombiner(CodeGenFunction &CGF,
5240 const Expr *ReductionOp) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005241 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
5242 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
5243 if (const auto *DRE =
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005244 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005245 if (const auto *DRD =
5246 dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005247 std::pair<llvm::Function *, llvm::Function *> Reduction =
5248 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
5249 RValue Func = RValue::get(Reduction.first);
5250 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
5251 CGF.EmitIgnoredExpr(ReductionOp);
5252 return;
5253 }
5254 CGF.EmitIgnoredExpr(ReductionOp);
5255}
5256
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005257llvm::Value *CGOpenMPRuntime::emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005258 CodeGenModule &CGM, SourceLocation Loc, llvm::Type *ArgsType,
5259 ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs,
5260 ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005261 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005262
5263 // void reduction_func(void *LHSArg, void *RHSArg);
5264 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005265 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5266 ImplicitParamDecl::Other);
5267 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5268 ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005269 Args.push_back(&LHSArg);
5270 Args.push_back(&RHSArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005271 const auto &CGFI =
5272 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005273 auto *Fn = llvm::Function::Create(
5274 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
5275 ".omp.reduction.reduction_func", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005276 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005277 Fn->setDoesNotRecurse();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005278 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005279 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005280
5281 // Dst = (void*[n])(LHSArg);
5282 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00005283 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5284 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
5285 ArgsType), CGF.getPointerAlign());
5286 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5287 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
5288 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005289
5290 // ...
5291 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
5292 // ...
5293 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005294 auto IPriv = Privates.begin();
5295 unsigned Idx = 0;
5296 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005297 const auto *RHSVar =
5298 cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
5299 Scope.addPrivate(RHSVar, [&CGF, RHS, Idx, RHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005300 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005301 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005302 const auto *LHSVar =
5303 cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
5304 Scope.addPrivate(LHSVar, [&CGF, LHS, Idx, LHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005305 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005306 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005307 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00005308 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005309 // Get array size and emit VLA type.
5310 ++Idx;
5311 Address Elem =
5312 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
5313 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005314 const VariableArrayType *VLA =
5315 CGF.getContext().getAsVariableArrayType(PrivTy);
5316 const auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005317 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00005318 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005319 CGF.EmitVariablyModifiedType(PrivTy);
5320 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005321 }
5322 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005323 IPriv = Privates.begin();
5324 auto ILHS = LHSExprs.begin();
5325 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005326 for (const Expr *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005327 if ((*IPriv)->getType()->isArrayType()) {
5328 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005329 const auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5330 const auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005331 EmitOMPAggregateReduction(
5332 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5333 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5334 emitReductionCombiner(CGF, E);
5335 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005336 } else {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005337 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005338 emitReductionCombiner(CGF, E);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005339 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005340 ++IPriv;
5341 ++ILHS;
5342 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005343 }
5344 Scope.ForceCleanup();
5345 CGF.FinishFunction();
5346 return Fn;
5347}
5348
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005349void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
5350 const Expr *ReductionOp,
5351 const Expr *PrivateRef,
5352 const DeclRefExpr *LHS,
5353 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005354 if (PrivateRef->getType()->isArrayType()) {
5355 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005356 const auto *LHSVar = cast<VarDecl>(LHS->getDecl());
5357 const auto *RHSVar = cast<VarDecl>(RHS->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005358 EmitOMPAggregateReduction(
5359 CGF, PrivateRef->getType(), LHSVar, RHSVar,
5360 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5361 emitReductionCombiner(CGF, ReductionOp);
5362 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005363 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005364 // Emit reduction for array subscript or single variable.
5365 emitReductionCombiner(CGF, ReductionOp);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005366 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005367}
5368
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005369void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005370 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005371 ArrayRef<const Expr *> LHSExprs,
5372 ArrayRef<const Expr *> RHSExprs,
5373 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005374 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005375 if (!CGF.HaveInsertPoint())
5376 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005377
5378 bool WithNowait = Options.WithNowait;
5379 bool SimpleReduction = Options.SimpleReduction;
5380
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005381 // Next code should be emitted for reduction:
5382 //
5383 // static kmp_critical_name lock = { 0 };
5384 //
5385 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
5386 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
5387 // ...
5388 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
5389 // *(Type<n>-1*)rhs[<n>-1]);
5390 // }
5391 //
5392 // ...
5393 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
5394 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5395 // RedList, reduce_func, &<lock>)) {
5396 // case 1:
5397 // ...
5398 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5399 // ...
5400 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5401 // break;
5402 // case 2:
5403 // ...
5404 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5405 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00005406 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005407 // break;
5408 // default:;
5409 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005410 //
5411 // if SimpleReduction is true, only the next code is generated:
5412 // ...
5413 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5414 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005415
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005416 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005417
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005418 if (SimpleReduction) {
5419 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005420 auto IPriv = Privates.begin();
5421 auto ILHS = LHSExprs.begin();
5422 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005423 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005424 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5425 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005426 ++IPriv;
5427 ++ILHS;
5428 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005429 }
5430 return;
5431 }
5432
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005433 // 1. Build a list of reduction variables.
5434 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005435 auto Size = RHSExprs.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005436 for (const Expr *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005437 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005438 // Reserve place for array size.
5439 ++Size;
5440 }
5441 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005442 QualType ReductionArrayTy =
5443 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
5444 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00005445 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005446 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005447 auto IPriv = Privates.begin();
5448 unsigned Idx = 0;
5449 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00005450 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005451 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00005452 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005453 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00005454 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
5455 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005456 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005457 // Store array size.
5458 ++Idx;
5459 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
5460 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00005461 llvm::Value *Size = CGF.Builder.CreateIntCast(
5462 CGF.getVLASize(
5463 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
Sander de Smalen891af03a2018-02-03 13:55:59 +00005464 .NumElts,
Alexey Bataev1189bd02016-01-26 12:20:39 +00005465 CGF.SizeTy, /*isSigned=*/false);
5466 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
5467 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005468 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005469 }
5470
5471 // 2. Emit reduce_func().
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005472 llvm::Value *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005473 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
5474 Privates, LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005475
5476 // 3. Create static kmp_critical_name lock = { 0 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005477 llvm::Value *Lock = getCriticalRegionLock(".reduction");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005478
5479 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5480 // RedList, reduce_func, &<lock>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005481 llvm::Value *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
5482 llvm::Value *ThreadId = getThreadID(CGF, Loc);
5483 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
5484 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Samuel Antao4c8035b2016-12-12 18:00:20 +00005485 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005486 llvm::Value *Args[] = {
5487 IdentTLoc, // ident_t *<loc>
5488 ThreadId, // i32 <gtid>
5489 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5490 ReductionArrayTySize, // size_type sizeof(RedList)
5491 RL, // void *RedList
5492 ReductionFn, // void (*) (void *, void *) <reduce_func>
5493 Lock // kmp_critical_name *&<lock>
5494 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005495 llvm::Value *Res = CGF.EmitRuntimeCall(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005496 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5497 : OMPRTL__kmpc_reduce),
5498 Args);
5499
5500 // 5. Build switch(res)
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005501 llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5502 llvm::SwitchInst *SwInst =
5503 CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005504
5505 // 6. Build case 1:
5506 // ...
5507 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5508 // ...
5509 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5510 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005511 llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005512 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5513 CGF.EmitBlock(Case1BB);
5514
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005515 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5516 llvm::Value *EndArgs[] = {
5517 IdentTLoc, // ident_t *<loc>
5518 ThreadId, // i32 <gtid>
5519 Lock // kmp_critical_name *&<lock>
5520 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005521 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps](
5522 CodeGenFunction &CGF, PrePostActionTy &Action) {
5523 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005524 auto IPriv = Privates.begin();
5525 auto ILHS = LHSExprs.begin();
5526 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005527 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005528 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5529 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005530 ++IPriv;
5531 ++ILHS;
5532 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005533 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005534 };
5535 RegionCodeGenTy RCG(CodeGen);
5536 CommonActionTy Action(
5537 nullptr, llvm::None,
5538 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5539 : OMPRTL__kmpc_end_reduce),
5540 EndArgs);
5541 RCG.setAction(Action);
5542 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005543
5544 CGF.EmitBranch(DefaultBB);
5545
5546 // 7. Build case 2:
5547 // ...
5548 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5549 // ...
5550 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005551 llvm::BasicBlock *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005552 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5553 CGF.EmitBlock(Case2BB);
5554
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005555 auto &&AtomicCodeGen = [Loc, Privates, LHSExprs, RHSExprs, ReductionOps](
5556 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005557 auto ILHS = LHSExprs.begin();
5558 auto IRHS = RHSExprs.begin();
5559 auto IPriv = Privates.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005560 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005561 const Expr *XExpr = nullptr;
5562 const Expr *EExpr = nullptr;
5563 const Expr *UpExpr = nullptr;
5564 BinaryOperatorKind BO = BO_Comma;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005565 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005566 if (BO->getOpcode() == BO_Assign) {
5567 XExpr = BO->getLHS();
5568 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005569 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005570 }
5571 // Try to emit update expression as a simple atomic.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005572 const Expr *RHSExpr = UpExpr;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005573 if (RHSExpr) {
5574 // Analyze RHS part of the whole expression.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005575 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005576 RHSExpr->IgnoreParenImpCasts())) {
5577 // If this is a conditional operator, analyze its condition for
5578 // min/max reduction operator.
5579 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005580 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005581 if (const auto *BORHS =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005582 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5583 EExpr = BORHS->getRHS();
5584 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005585 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005586 }
5587 if (XExpr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005588 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005589 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005590 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5591 const Expr *EExpr, const Expr *UpExpr) {
5592 LValue X = CGF.EmitLValue(XExpr);
5593 RValue E;
5594 if (EExpr)
5595 E = CGF.EmitAnyExpr(EExpr);
5596 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005597 X, E, BO, /*IsXLHSInRHSPart=*/true,
5598 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005599 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005600 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5601 PrivateScope.addPrivate(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005602 VD, [&CGF, VD, XRValue, Loc]() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005603 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5604 CGF.emitOMPSimpleStore(
5605 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5606 VD->getType().getNonReferenceType(), Loc);
5607 return LHSTemp;
5608 });
5609 (void)PrivateScope.Privatize();
5610 return CGF.EmitAnyExpr(UpExpr);
5611 });
5612 };
5613 if ((*IPriv)->getType()->isArrayType()) {
5614 // Emit atomic reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005615 const auto *RHSVar =
5616 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005617 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5618 AtomicRedGen, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005619 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005620 // Emit atomic reduction for array subscript or single variable.
5621 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005622 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005623 } else {
5624 // Emit as a critical region.
5625 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
5626 const Expr *, const Expr *) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005627 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005628 RT.emitCriticalRegion(
5629 CGF, ".atomic_reduction",
5630 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5631 Action.Enter(CGF);
5632 emitReductionCombiner(CGF, E);
5633 },
5634 Loc);
5635 };
5636 if ((*IPriv)->getType()->isArrayType()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005637 const auto *LHSVar =
5638 cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5639 const auto *RHSVar =
5640 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005641 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5642 CritRedGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005643 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005644 CritRedGen(CGF, nullptr, nullptr, nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005645 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005646 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005647 ++ILHS;
5648 ++IRHS;
5649 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005650 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005651 };
5652 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5653 if (!WithNowait) {
5654 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5655 llvm::Value *EndArgs[] = {
5656 IdentTLoc, // ident_t *<loc>
5657 ThreadId, // i32 <gtid>
5658 Lock // kmp_critical_name *&<lock>
5659 };
5660 CommonActionTy Action(nullptr, llvm::None,
5661 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5662 EndArgs);
5663 AtomicRCG.setAction(Action);
5664 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005665 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005666 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005667 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005668
5669 CGF.EmitBranch(DefaultBB);
5670 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5671}
5672
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005673/// Generates unique name for artificial threadprivate variables.
Alexey Bataev1c44e152018-03-06 18:59:43 +00005674/// Format is: <Prefix> "." <Decl_mangled_name> "_" "<Decl_start_loc_raw_enc>"
5675static std::string generateUniqueName(CodeGenModule &CGM, StringRef Prefix,
5676 const Expr *Ref) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005677 SmallString<256> Buffer;
5678 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev1c44e152018-03-06 18:59:43 +00005679 const clang::DeclRefExpr *DE;
5680 const VarDecl *D = ::getBaseDecl(Ref, DE);
5681 if (!D)
5682 D = cast<VarDecl>(cast<DeclRefExpr>(Ref)->getDecl());
5683 D = D->getCanonicalDecl();
5684 Out << Prefix << "."
5685 << (D->isLocalVarDeclOrParm() ? D->getName() : CGM.getMangledName(D))
5686 << "_" << D->getCanonicalDecl()->getLocStart().getRawEncoding();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005687 return Out.str();
5688}
5689
5690/// Emits reduction initializer function:
5691/// \code
5692/// void @.red_init(void* %arg) {
5693/// %0 = bitcast void* %arg to <type>*
5694/// store <type> <init>, <type>* %0
5695/// ret void
5696/// }
5697/// \endcode
5698static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5699 SourceLocation Loc,
5700 ReductionCodeGen &RCG, unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005701 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005702 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005703 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5704 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005705 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005706 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005707 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005708 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005709 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5710 ".red_init.", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005711 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005712 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005713 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005714 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005715 Address PrivateAddr = CGF.EmitLoadOfPointer(
5716 CGF.GetAddrOfLocalVar(&Param),
5717 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5718 llvm::Value *Size = nullptr;
5719 // If the size of the reduction item is non-constant, load it from global
5720 // threadprivate variable.
5721 if (RCG.getSizes(N).second) {
5722 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5723 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005724 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005725 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5726 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005727 }
5728 RCG.emitAggregateType(CGF, N, Size);
5729 LValue SharedLVal;
5730 // If initializer uses initializer from declare reduction construct, emit a
5731 // pointer to the address of the original reduction item (reuired by reduction
5732 // initializer)
5733 if (RCG.usesReductionInitializer(N)) {
5734 Address SharedAddr =
5735 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5736 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00005737 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataev21dab122018-03-09 15:20:30 +00005738 SharedAddr = CGF.EmitLoadOfPointer(
5739 SharedAddr,
5740 CGM.getContext().VoidPtrTy.castAs<PointerType>()->getTypePtr());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005741 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5742 } else {
5743 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5744 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5745 CGM.getContext().VoidPtrTy);
5746 }
5747 // Emit the initializer:
5748 // %0 = bitcast void* %arg to <type>*
5749 // store <type> <init>, <type>* %0
5750 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5751 [](CodeGenFunction &) { return false; });
5752 CGF.FinishFunction();
5753 return Fn;
5754}
5755
5756/// Emits reduction combiner function:
5757/// \code
5758/// void @.red_comb(void* %arg0, void* %arg1) {
5759/// %lhs = bitcast void* %arg0 to <type>*
5760/// %rhs = bitcast void* %arg1 to <type>*
5761/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5762/// store <type> %2, <type>* %lhs
5763/// ret void
5764/// }
5765/// \endcode
5766static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5767 SourceLocation Loc,
5768 ReductionCodeGen &RCG, unsigned N,
5769 const Expr *ReductionOp,
5770 const Expr *LHS, const Expr *RHS,
5771 const Expr *PrivateRef) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005772 ASTContext &C = CGM.getContext();
5773 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5774 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005775 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005776 ImplicitParamDecl ParamInOut(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
5777 C.VoidPtrTy, ImplicitParamDecl::Other);
5778 ImplicitParamDecl ParamIn(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5779 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005780 Args.emplace_back(&ParamInOut);
5781 Args.emplace_back(&ParamIn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005782 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005783 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005784 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005785 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5786 ".red_comb.", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005787 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005788 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005789 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005790 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005791 llvm::Value *Size = nullptr;
5792 // If the size of the reduction item is non-constant, load it from global
5793 // threadprivate variable.
5794 if (RCG.getSizes(N).second) {
5795 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5796 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005797 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005798 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5799 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005800 }
5801 RCG.emitAggregateType(CGF, N, Size);
5802 // Remap lhs and rhs variables to the addresses of the function arguments.
5803 // %lhs = bitcast void* %arg0 to <type>*
5804 // %rhs = bitcast void* %arg1 to <type>*
5805 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005806 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005807 // Pull out the pointer to the variable.
5808 Address PtrAddr = CGF.EmitLoadOfPointer(
5809 CGF.GetAddrOfLocalVar(&ParamInOut),
5810 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5811 return CGF.Builder.CreateElementBitCast(
5812 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
5813 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005814 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005815 // Pull out the pointer to the variable.
5816 Address PtrAddr = CGF.EmitLoadOfPointer(
5817 CGF.GetAddrOfLocalVar(&ParamIn),
5818 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5819 return CGF.Builder.CreateElementBitCast(
5820 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
5821 });
5822 PrivateScope.Privatize();
5823 // Emit the combiner body:
5824 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
5825 // store <type> %2, <type>* %lhs
5826 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
5827 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
5828 cast<DeclRefExpr>(RHS));
5829 CGF.FinishFunction();
5830 return Fn;
5831}
5832
5833/// Emits reduction finalizer function:
5834/// \code
5835/// void @.red_fini(void* %arg) {
5836/// %0 = bitcast void* %arg to <type>*
5837/// <destroy>(<type>* %0)
5838/// ret void
5839/// }
5840/// \endcode
5841static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
5842 SourceLocation Loc,
5843 ReductionCodeGen &RCG, unsigned N) {
5844 if (!RCG.needCleanups(N))
5845 return nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005846 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005847 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005848 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5849 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005850 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005851 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005852 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005853 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005854 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5855 ".red_fini.", &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005856 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005857 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005858 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005859 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005860 Address PrivateAddr = CGF.EmitLoadOfPointer(
5861 CGF.GetAddrOfLocalVar(&Param),
5862 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5863 llvm::Value *Size = nullptr;
5864 // If the size of the reduction item is non-constant, load it from global
5865 // threadprivate variable.
5866 if (RCG.getSizes(N).second) {
5867 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5868 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005869 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005870 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5871 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005872 }
5873 RCG.emitAggregateType(CGF, N, Size);
5874 // Emit the finalizer body:
5875 // <destroy>(<type>* %0)
5876 RCG.emitCleanups(CGF, N, PrivateAddr);
5877 CGF.FinishFunction();
5878 return Fn;
5879}
5880
5881llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
5882 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
5883 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
5884 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
5885 return nullptr;
5886
5887 // Build typedef struct:
5888 // kmp_task_red_input {
5889 // void *reduce_shar; // shared reduction item
5890 // size_t reduce_size; // size of data item
5891 // void *reduce_init; // data initialization routine
5892 // void *reduce_fini; // data finalization routine
5893 // void *reduce_comb; // data combiner routine
5894 // kmp_task_red_flags_t flags; // flags for additional info from compiler
5895 // } kmp_task_red_input_t;
5896 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005897 RecordDecl *RD = C.buildImplicitRecord("kmp_task_red_input_t");
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005898 RD->startDefinition();
5899 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5900 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
5901 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5902 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5903 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5904 const FieldDecl *FlagsFD = addFieldToRecordDecl(
5905 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
5906 RD->completeDefinition();
5907 QualType RDType = C.getRecordType(RD);
5908 unsigned Size = Data.ReductionVars.size();
5909 llvm::APInt ArraySize(/*numBits=*/64, Size);
5910 QualType ArrayRDType = C.getConstantArrayType(
5911 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5912 // kmp_task_red_input_t .rd_input.[Size];
5913 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
5914 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
5915 Data.ReductionOps);
5916 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
5917 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
5918 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
5919 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
5920 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
5921 TaskRedInput.getPointer(), Idxs,
5922 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
5923 ".rd_input.gep.");
5924 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
5925 // ElemLVal.reduce_shar = &Shareds[Cnt];
5926 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
5927 RCG.emitSharedLValue(CGF, Cnt);
5928 llvm::Value *CastedShared =
5929 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
5930 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
5931 RCG.emitAggregateType(CGF, Cnt);
5932 llvm::Value *SizeValInChars;
5933 llvm::Value *SizeVal;
5934 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
5935 // We use delayed creation/initialization for VLAs, array sections and
5936 // custom reduction initializations. It is required because runtime does not
5937 // provide the way to pass the sizes of VLAs/array sections to
5938 // initializer/combiner/finalizer functions and does not pass the pointer to
5939 // original reduction item to the initializer. Instead threadprivate global
5940 // variables are used to store these values and use them in the functions.
5941 bool DelayedCreation = !!SizeVal;
5942 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
5943 /*isSigned=*/false);
5944 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
5945 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
5946 // ElemLVal.reduce_init = init;
5947 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
5948 llvm::Value *InitAddr =
5949 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
5950 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
5951 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
5952 // ElemLVal.reduce_fini = fini;
5953 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
5954 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
5955 llvm::Value *FiniAddr = Fini
5956 ? CGF.EmitCastToVoidPtr(Fini)
5957 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
5958 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
5959 // ElemLVal.reduce_comb = comb;
5960 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
5961 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
5962 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
5963 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
5964 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
5965 // ElemLVal.flags = 0;
5966 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
5967 if (DelayedCreation) {
5968 CGF.EmitStoreOfScalar(
5969 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
5970 FlagsLVal);
5971 } else
5972 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
5973 }
5974 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
5975 // *data);
5976 llvm::Value *Args[] = {
5977 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5978 /*isSigned=*/true),
5979 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
5980 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
5981 CGM.VoidPtrTy)};
5982 return CGF.EmitRuntimeCall(
5983 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
5984}
5985
5986void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
5987 SourceLocation Loc,
5988 ReductionCodeGen &RCG,
5989 unsigned N) {
5990 auto Sizes = RCG.getSizes(N);
5991 // Emit threadprivate global variable if the type is non-constant
5992 // (Sizes.second = nullptr).
5993 if (Sizes.second) {
5994 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
5995 /*isSigned=*/false);
5996 Address SizeAddr = getAddrOfArtificialThreadPrivate(
5997 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005998 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005999 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
6000 }
6001 // Store address of the original reduction item if custom initializer is used.
6002 if (RCG.usesReductionInitializer(N)) {
6003 Address SharedAddr = getAddrOfArtificialThreadPrivate(
6004 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00006005 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006006 CGF.Builder.CreateStore(
6007 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6008 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
6009 SharedAddr, /*IsVolatile=*/false);
6010 }
6011}
6012
6013Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
6014 SourceLocation Loc,
6015 llvm::Value *ReductionsPtr,
6016 LValue SharedLVal) {
6017 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
6018 // *d);
6019 llvm::Value *Args[] = {
6020 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6021 /*isSigned=*/true),
6022 ReductionsPtr,
6023 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
6024 CGM.VoidPtrTy)};
6025 return Address(
6026 CGF.EmitRuntimeCall(
6027 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
6028 SharedLVal.getAlignment());
6029}
6030
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006031void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
6032 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006033 if (!CGF.HaveInsertPoint())
6034 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006035 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
6036 // global_tid);
6037 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
6038 // Ignore return result until untied tasks are supported.
6039 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00006040 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
6041 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006042}
6043
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006044void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006045 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006046 const RegionCodeGenTy &CodeGen,
6047 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006048 if (!CGF.HaveInsertPoint())
6049 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00006050 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006051 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00006052}
6053
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006054namespace {
6055enum RTCancelKind {
6056 CancelNoreq = 0,
6057 CancelParallel = 1,
6058 CancelLoop = 2,
6059 CancelSections = 3,
6060 CancelTaskgroup = 4
6061};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00006062} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006063
6064static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
6065 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00006066 if (CancelRegion == OMPD_parallel)
6067 CancelKind = CancelParallel;
6068 else if (CancelRegion == OMPD_for)
6069 CancelKind = CancelLoop;
6070 else if (CancelRegion == OMPD_sections)
6071 CancelKind = CancelSections;
6072 else {
6073 assert(CancelRegion == OMPD_taskgroup);
6074 CancelKind = CancelTaskgroup;
6075 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006076 return CancelKind;
6077}
6078
6079void CGOpenMPRuntime::emitCancellationPointCall(
6080 CodeGenFunction &CGF, SourceLocation Loc,
6081 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006082 if (!CGF.HaveInsertPoint())
6083 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006084 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
6085 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006086 if (auto *OMPRegionInfo =
6087 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00006088 // For 'cancellation point taskgroup', the task region info may not have a
6089 // cancel. This may instead happen in another adjacent task.
6090 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006091 llvm::Value *Args[] = {
6092 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
6093 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006094 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006095 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006096 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
6097 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006098 // exit from construct;
6099 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006100 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6101 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6102 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006103 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6104 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006105 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006106 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev25e5b442015-09-15 12:52:43 +00006107 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006108 CGF.EmitBranchThroughCleanup(CancelDest);
6109 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6110 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006111 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006112}
6113
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006114void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00006115 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006116 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006117 if (!CGF.HaveInsertPoint())
6118 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006119 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
6120 // kmp_int32 cncl_kind);
6121 if (auto *OMPRegionInfo =
6122 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006123 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
6124 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006125 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00006126 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006127 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00006128 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
6129 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006130 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006131 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00006132 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00006133 // exit from construct;
6134 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006135 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6136 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6137 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev87933c72015-09-18 08:07:34 +00006138 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6139 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00006140 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006141 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev87933c72015-09-18 08:07:34 +00006142 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
6143 CGF.EmitBranchThroughCleanup(CancelDest);
6144 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6145 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006146 if (IfCond) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006147 emitOMPIfClause(CGF, IfCond, ThenGen,
6148 [](CodeGenFunction &, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006149 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006150 RegionCodeGenTy ThenRCG(ThenGen);
6151 ThenRCG(CGF);
6152 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006153 }
6154}
Samuel Antaobed3c462015-10-02 16:14:20 +00006155
Samuel Antaoee8fb302016-01-06 13:42:12 +00006156void CGOpenMPRuntime::emitTargetOutlinedFunction(
6157 const OMPExecutableDirective &D, StringRef ParentName,
6158 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006159 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00006160 assert(!ParentName.empty() && "Invalid target region parent name!");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006161 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
6162 IsOffloadEntry, CodeGen);
6163}
6164
6165void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
6166 const OMPExecutableDirective &D, StringRef ParentName,
6167 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
6168 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00006169 // Create a unique name for the entry function using the source location
6170 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00006171 //
Samuel Antao2de62b02016-02-13 23:35:10 +00006172 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00006173 //
6174 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00006175 // mangled name of the function that encloses the target region and BB is the
6176 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00006177
6178 unsigned DeviceID;
6179 unsigned FileID;
6180 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00006181 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00006182 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006183 SmallString<64> EntryFnName;
6184 {
6185 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00006186 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
6187 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00006188 }
6189
Alexey Bataev475a7442018-01-12 19:39:11 +00006190 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006191
Samuel Antaobed3c462015-10-02 16:14:20 +00006192 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006193 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00006194 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006195
Samuel Antao6d004262016-06-16 18:39:34 +00006196 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006197
6198 // If this target outline function is not an offload entry, we don't need to
6199 // register it.
6200 if (!IsOffloadEntry)
6201 return;
6202
6203 // The target region ID is used by the runtime library to identify the current
6204 // target region, so it only has to be unique and not necessarily point to
6205 // anything. It could be the pointer to the outlined function that implements
6206 // the target region, but we aren't using that so that the compiler doesn't
6207 // need to keep that, and could therefore inline the host function if proven
6208 // worthwhile during optimization. In the other hand, if emitting code for the
6209 // device, the ID has to be the function address so that it can retrieved from
6210 // the offloading entry and launched by the runtime library. We also mark the
6211 // outlined function to have external linkage in case we are emitting code for
6212 // the device, because these functions will be entry points to the device.
6213
6214 if (CGM.getLangOpts().OpenMPIsDevice) {
6215 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
6216 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
Rafael Espindolacbca4872018-01-11 22:15:12 +00006217 OutlinedFn->setDSOLocal(false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006218 } else {
Samuel Antaoee8fb302016-01-06 13:42:12 +00006219 OutlinedFnID = new llvm::GlobalVariable(
6220 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
6221 llvm::GlobalValue::PrivateLinkage,
6222 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006223 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00006224
6225 // Register the information for the entry associated with this target region.
6226 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00006227 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
Alexey Bataev03f270c2018-03-30 18:31:07 +00006228 OffloadEntriesInfoManagerTy::OMPTargetRegionEntryTargetRegion);
Samuel Antaobed3c462015-10-02 16:14:20 +00006229}
6230
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006231/// discard all CompoundStmts intervening between two constructs
6232static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006233 while (const auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006234 Body = CS->body_front();
6235
6236 return Body;
6237}
6238
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006239/// Emit the number of teams for a target directive. Inspect the num_teams
6240/// clause associated with a teams construct combined or closely nested
6241/// with the target directive.
6242///
6243/// Emit a team of size one for directives such as 'target parallel' that
6244/// have no associated teams construct.
6245///
6246/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006247static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006248emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6249 CodeGenFunction &CGF,
6250 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006251 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6252 "teams directive expected to be "
6253 "emitted only for the host!");
6254
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006255 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006256
6257 // If the target directive is combined with a teams directive:
6258 // Return the value in the num_teams clause, if any.
6259 // Otherwise, return 0 to denote the runtime default.
6260 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
6261 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
6262 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006263 llvm::Value *NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
6264 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006265 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6266 /*IsSigned=*/true);
6267 }
6268
6269 // The default value is 0.
6270 return Bld.getInt32(0);
6271 }
6272
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006273 // If the target directive is combined with a parallel directive but not a
6274 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006275 if (isOpenMPParallelDirective(D.getDirectiveKind()))
6276 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006277
6278 // If the current target region has a teams region enclosed, we need to get
6279 // the number of teams to pass to the runtime function call. This is done
6280 // by generating the expression in a inlined region. This is required because
6281 // the expression is captured in the enclosing target environment when the
6282 // teams directive is not combined with target.
6283
Alexey Bataev475a7442018-01-12 19:39:11 +00006284 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006285
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006286 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006287 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006288 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006289 if (const auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006290 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6291 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6292 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
6293 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6294 /*IsSigned=*/true);
6295 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006296
Alexey Bataev50a1c782017-12-01 21:31:08 +00006297 // If we have an enclosed teams directive but no num_teams clause we use
6298 // the default value 0.
6299 return Bld.getInt32(0);
6300 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006301 }
6302
6303 // No teams associated with the directive.
6304 return nullptr;
6305}
6306
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006307/// Emit the number of threads for a target directive. Inspect the
6308/// thread_limit clause associated with a teams construct combined or closely
6309/// nested with the target directive.
6310///
6311/// Emit the num_threads clause for directives such as 'target parallel' that
6312/// have no associated teams construct.
6313///
6314/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006315static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006316emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6317 CodeGenFunction &CGF,
6318 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006319 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6320 "teams directive expected to be "
6321 "emitted only for the host!");
6322
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006323 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006324
6325 //
6326 // If the target directive is combined with a teams directive:
6327 // Return the value in the thread_limit clause, if any.
6328 //
6329 // If the target directive is combined with a parallel directive:
6330 // Return the value in the num_threads clause, if any.
6331 //
6332 // If both clauses are set, select the minimum of the two.
6333 //
6334 // If neither teams or parallel combined directives set the number of threads
6335 // in a team, return 0 to denote the runtime default.
6336 //
6337 // If this is not a teams directive return nullptr.
6338
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006339 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
6340 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006341 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
6342 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006343 llvm::Value *ThreadLimitVal = nullptr;
6344
6345 if (const auto *ThreadLimitClause =
6346 D.getSingleClause<OMPThreadLimitClause>()) {
6347 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006348 llvm::Value *ThreadLimit =
6349 CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
6350 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006351 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6352 /*IsSigned=*/true);
6353 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006354
6355 if (const auto *NumThreadsClause =
6356 D.getSingleClause<OMPNumThreadsClause>()) {
6357 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
6358 llvm::Value *NumThreads =
6359 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
6360 /*IgnoreResultAssign*/ true);
6361 NumThreadsVal =
6362 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
6363 }
6364
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006365 // Select the lesser of thread_limit and num_threads.
6366 if (NumThreadsVal)
6367 ThreadLimitVal = ThreadLimitVal
6368 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
6369 ThreadLimitVal),
6370 NumThreadsVal, ThreadLimitVal)
6371 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00006372
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006373 // Set default value passed to the runtime if either teams or a target
6374 // parallel type directive is found but no clause is specified.
6375 if (!ThreadLimitVal)
6376 ThreadLimitVal = DefaultThreadLimitVal;
6377
6378 return ThreadLimitVal;
6379 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00006380
Samuel Antaob68e2db2016-03-03 16:20:23 +00006381 // If the current target region has a teams region enclosed, we need to get
6382 // the thread limit to pass to the runtime function call. This is done
6383 // by generating the expression in a inlined region. This is required because
6384 // the expression is captured in the enclosing target environment when the
6385 // teams directive is not combined with target.
6386
Alexey Bataev475a7442018-01-12 19:39:11 +00006387 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006388
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006389 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006390 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006391 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006392 if (const auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006393 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6394 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6395 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
6396 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6397 /*IsSigned=*/true);
6398 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006399
Alexey Bataev50a1c782017-12-01 21:31:08 +00006400 // If we have an enclosed teams directive but no thread_limit clause we
6401 // use the default value 0.
6402 return CGF.Builder.getInt32(0);
6403 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006404 }
6405
6406 // No teams associated with the directive.
6407 return nullptr;
6408}
6409
Samuel Antao86ace552016-04-27 22:40:57 +00006410namespace {
6411// \brief Utility to handle information from clauses associated with a given
6412// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
6413// It provides a convenient interface to obtain the information and generate
6414// code for that information.
6415class MappableExprsHandler {
6416public:
6417 /// \brief Values for bit flags used to specify the mapping type for
6418 /// offloading.
6419 enum OpenMPOffloadMappingFlags {
Samuel Antao86ace552016-04-27 22:40:57 +00006420 /// \brief Allocate memory on the device and move data from host to device.
6421 OMP_MAP_TO = 0x01,
6422 /// \brief Allocate memory on the device and move data from device to host.
6423 OMP_MAP_FROM = 0x02,
6424 /// \brief Always perform the requested mapping action on the element, even
6425 /// if it was already mapped before.
6426 OMP_MAP_ALWAYS = 0x04,
Samuel Antao86ace552016-04-27 22:40:57 +00006427 /// \brief Delete the element from the device environment, ignoring the
6428 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00006429 OMP_MAP_DELETE = 0x08,
George Rokos065755d2017-11-07 18:27:04 +00006430 /// \brief The element being mapped is a pointer-pointee pair; both the
6431 /// pointer and the pointee should be mapped.
6432 OMP_MAP_PTR_AND_OBJ = 0x10,
6433 /// \brief This flags signals that the base address of an entry should be
6434 /// passed to the target kernel as an argument.
6435 OMP_MAP_TARGET_PARAM = 0x20,
Samuel Antaocc10b852016-07-28 14:23:26 +00006436 /// \brief Signal that the runtime library has to return the device pointer
George Rokos065755d2017-11-07 18:27:04 +00006437 /// in the current position for the data being mapped. Used when we have the
6438 /// use_device_ptr clause.
6439 OMP_MAP_RETURN_PARAM = 0x40,
Samuel Antaod486f842016-05-26 16:53:38 +00006440 /// \brief This flag signals that the reference being passed is a pointer to
6441 /// private data.
George Rokos065755d2017-11-07 18:27:04 +00006442 OMP_MAP_PRIVATE = 0x80,
Samuel Antao86ace552016-04-27 22:40:57 +00006443 /// \brief Pass the element to the device by value.
George Rokos065755d2017-11-07 18:27:04 +00006444 OMP_MAP_LITERAL = 0x100,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006445 /// Implicit map
6446 OMP_MAP_IMPLICIT = 0x200,
Samuel Antao86ace552016-04-27 22:40:57 +00006447 };
6448
Samuel Antaocc10b852016-07-28 14:23:26 +00006449 /// Class that associates information with a base pointer to be passed to the
6450 /// runtime library.
6451 class BasePointerInfo {
6452 /// The base pointer.
6453 llvm::Value *Ptr = nullptr;
6454 /// The base declaration that refers to this device pointer, or null if
6455 /// there is none.
6456 const ValueDecl *DevPtrDecl = nullptr;
6457
6458 public:
6459 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
6460 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
6461 llvm::Value *operator*() const { return Ptr; }
6462 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
6463 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
6464 };
6465
6466 typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00006467 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
George Rokos63bc9d62017-11-21 18:25:12 +00006468 typedef SmallVector<uint64_t, 16> MapFlagsArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00006469
6470private:
6471 /// \brief Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00006472 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00006473
6474 /// \brief Function the directive is being generated for.
6475 CodeGenFunction &CGF;
6476
Samuel Antaod486f842016-05-26 16:53:38 +00006477 /// \brief Set of all first private variables in the current directive.
6478 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
Alexey Bataev3f96fe62017-12-13 17:31:39 +00006479 /// Set of all reduction variables in the current directive.
6480 llvm::SmallPtrSet<const VarDecl *, 8> ReductionDecls;
Samuel Antaod486f842016-05-26 16:53:38 +00006481
Samuel Antao6890b092016-07-28 14:25:09 +00006482 /// Map between device pointer declarations and their expression components.
6483 /// The key value for declarations in 'this' is null.
6484 llvm::DenseMap<
6485 const ValueDecl *,
6486 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6487 DevPointersMap;
6488
Samuel Antao86ace552016-04-27 22:40:57 +00006489 llvm::Value *getExprTypeSize(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006490 QualType ExprTy = E->getType().getCanonicalType();
Samuel Antao86ace552016-04-27 22:40:57 +00006491
6492 // Reference types are ignored for mapping purposes.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006493 if (const auto *RefTy = ExprTy->getAs<ReferenceType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006494 ExprTy = RefTy->getPointeeType().getCanonicalType();
6495
6496 // Given that an array section is considered a built-in type, we need to
6497 // do the calculation based on the length of the section instead of relying
6498 // on CGF.getTypeSize(E->getType()).
6499 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6500 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6501 OAE->getBase()->IgnoreParenImpCasts())
6502 .getCanonicalType();
6503
6504 // If there is no length associated with the expression, that means we
6505 // are using the whole length of the base.
6506 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6507 return CGF.getTypeSize(BaseTy);
6508
6509 llvm::Value *ElemSize;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006510 if (const auto *PTy = BaseTy->getAs<PointerType>()) {
Samuel Antao86ace552016-04-27 22:40:57 +00006511 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006512 } else {
6513 const auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
Samuel Antao86ace552016-04-27 22:40:57 +00006514 assert(ATy && "Expecting array type if not a pointer type.");
6515 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6516 }
6517
6518 // If we don't have a length at this point, that is because we have an
6519 // array section with a single element.
6520 if (!OAE->getLength())
6521 return ElemSize;
6522
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006523 llvm::Value *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
Samuel Antao86ace552016-04-27 22:40:57 +00006524 LengthVal =
6525 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6526 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6527 }
6528 return CGF.getTypeSize(ExprTy);
6529 }
6530
6531 /// \brief Return the corresponding bits for a given map clause modifier. Add
6532 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006533 /// map as the first one of a series of maps that relate to the same map
6534 /// expression.
George Rokos63bc9d62017-11-21 18:25:12 +00006535 uint64_t getMapTypeBits(OpenMPMapClauseKind MapType,
Samuel Antao86ace552016-04-27 22:40:57 +00006536 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
George Rokos065755d2017-11-07 18:27:04 +00006537 bool AddIsTargetParamFlag) const {
George Rokos63bc9d62017-11-21 18:25:12 +00006538 uint64_t Bits = 0u;
Samuel Antao86ace552016-04-27 22:40:57 +00006539 switch (MapType) {
6540 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006541 case OMPC_MAP_release:
6542 // alloc and release is the default behavior in the runtime library, i.e.
6543 // if we don't pass any bits alloc/release that is what the runtime is
6544 // going to do. Therefore, we don't need to signal anything for these two
6545 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006546 break;
6547 case OMPC_MAP_to:
6548 Bits = OMP_MAP_TO;
6549 break;
6550 case OMPC_MAP_from:
6551 Bits = OMP_MAP_FROM;
6552 break;
6553 case OMPC_MAP_tofrom:
6554 Bits = OMP_MAP_TO | OMP_MAP_FROM;
6555 break;
6556 case OMPC_MAP_delete:
6557 Bits = OMP_MAP_DELETE;
6558 break;
Samuel Antao86ace552016-04-27 22:40:57 +00006559 default:
6560 llvm_unreachable("Unexpected map type!");
6561 break;
6562 }
6563 if (AddPtrFlag)
George Rokos065755d2017-11-07 18:27:04 +00006564 Bits |= OMP_MAP_PTR_AND_OBJ;
6565 if (AddIsTargetParamFlag)
6566 Bits |= OMP_MAP_TARGET_PARAM;
Samuel Antao86ace552016-04-27 22:40:57 +00006567 if (MapTypeModifier == OMPC_MAP_always)
6568 Bits |= OMP_MAP_ALWAYS;
6569 return Bits;
6570 }
6571
6572 /// \brief Return true if the provided expression is a final array section. A
6573 /// final array section, is one whose length can't be proved to be one.
6574 bool isFinalArraySectionExpression(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006575 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antao86ace552016-04-27 22:40:57 +00006576
6577 // It is not an array section and therefore not a unity-size one.
6578 if (!OASE)
6579 return false;
6580
6581 // An array section with no colon always refer to a single element.
6582 if (OASE->getColonLoc().isInvalid())
6583 return false;
6584
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006585 const Expr *Length = OASE->getLength();
Samuel Antao86ace552016-04-27 22:40:57 +00006586
6587 // If we don't have a length we have to check if the array has size 1
6588 // for this dimension. Also, we should always expect a length if the
6589 // base type is pointer.
6590 if (!Length) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006591 QualType BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6592 OASE->getBase()->IgnoreParenImpCasts())
6593 .getCanonicalType();
6594 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antao86ace552016-04-27 22:40:57 +00006595 return ATy->getSize().getSExtValue() != 1;
6596 // If we don't have a constant dimension length, we have to consider
6597 // the current section as having any size, so it is not necessarily
6598 // unitary. If it happen to be unity size, that's user fault.
6599 return true;
6600 }
6601
6602 // Check if the length evaluates to 1.
6603 llvm::APSInt ConstLength;
6604 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
6605 return true; // Can have more that size 1.
6606
6607 return ConstLength.getSExtValue() != 1;
6608 }
6609
Alexey Bataev92327c52018-03-26 16:40:55 +00006610 /// \brief Return the adjusted map modifiers if the declaration a capture
6611 /// refers to appears in a first-private clause. This is expected to be used
6612 /// only with directives that start with 'target'.
6613 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
6614 unsigned CurrentModifiers) {
6615 assert(Cap.capturesVariable() && "Expected capture by reference only!");
6616
6617 // A first private variable captured by reference will use only the
6618 // 'private ptr' and 'map to' flag. Return the right flags if the captured
6619 // declaration is known as first-private in this handler.
6620 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
6621 return MappableExprsHandler::OMP_MAP_PRIVATE |
6622 MappableExprsHandler::OMP_MAP_TO;
6623 // Reduction variable will use only the 'private ptr' and 'map to_from'
6624 // flag.
6625 if (ReductionDecls.count(Cap.getCapturedVar())) {
6626 return MappableExprsHandler::OMP_MAP_TO |
6627 MappableExprsHandler::OMP_MAP_FROM;
6628 }
6629
6630 // We didn't modify anything.
6631 return CurrentModifiers;
6632 }
6633
6634public:
6635 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
6636 : CurDir(Dir), CGF(CGF) {
6637 // Extract firstprivate clause information.
6638 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006639 for (const Expr *D : C->varlists())
Alexey Bataev92327c52018-03-26 16:40:55 +00006640 FirstPrivateDecls.insert(
6641 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
6642 for (const auto *C : Dir.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006643 for (const Expr *D : C->varlists()) {
Alexey Bataev92327c52018-03-26 16:40:55 +00006644 ReductionDecls.insert(
6645 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
6646 }
6647 }
6648 // Extract device pointer clause information.
6649 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006650 for (const auto &L : C->component_lists())
Alexey Bataev92327c52018-03-26 16:40:55 +00006651 DevPointersMap[L.first].push_back(L.second);
6652 }
6653
Samuel Antao86ace552016-04-27 22:40:57 +00006654 /// \brief Generate the base pointers, section pointers, sizes and map type
6655 /// bits for the provided map type, map modifier, and expression components.
6656 /// \a IsFirstComponent should be set to true if the provided set of
6657 /// components is the first associated with a capture.
6658 void generateInfoForComponentList(
6659 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6660 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006661 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006662 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006663 bool IsFirstComponentList, bool IsImplicit) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006664
6665 // The following summarizes what has to be generated for each map and the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006666 // types below. The generated information is expressed in this order:
Samuel Antao86ace552016-04-27 22:40:57 +00006667 // base pointer, section pointer, size, flags
6668 // (to add to the ones that come from the map type and modifier).
6669 //
6670 // double d;
6671 // int i[100];
6672 // float *p;
6673 //
6674 // struct S1 {
6675 // int i;
6676 // float f[50];
6677 // }
6678 // struct S2 {
6679 // int i;
6680 // float f[50];
6681 // S1 s;
6682 // double *p;
6683 // struct S2 *ps;
6684 // }
6685 // S2 s;
6686 // S2 *ps;
6687 //
6688 // map(d)
6689 // &d, &d, sizeof(double), noflags
6690 //
6691 // map(i)
6692 // &i, &i, 100*sizeof(int), noflags
6693 //
6694 // map(i[1:23])
6695 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
6696 //
6697 // map(p)
6698 // &p, &p, sizeof(float*), noflags
6699 //
6700 // map(p[1:24])
6701 // p, &p[1], 24*sizeof(float), noflags
6702 //
6703 // map(s)
6704 // &s, &s, sizeof(S2), noflags
6705 //
6706 // map(s.i)
6707 // &s, &(s.i), sizeof(int), noflags
6708 //
6709 // map(s.s.f)
6710 // &s, &(s.i.f), 50*sizeof(int), noflags
6711 //
6712 // map(s.p)
6713 // &s, &(s.p), sizeof(double*), noflags
6714 //
6715 // map(s.p[:22], s.a s.b)
6716 // &s, &(s.p), sizeof(double*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006717 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006718 //
6719 // map(s.ps)
6720 // &s, &(s.ps), sizeof(S2*), noflags
6721 //
6722 // map(s.ps->s.i)
6723 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006724 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006725 //
6726 // map(s.ps->ps)
6727 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006728 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006729 //
6730 // map(s.ps->ps->ps)
6731 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006732 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
6733 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006734 //
6735 // map(s.ps->ps->s.f[:22])
6736 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006737 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
6738 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006739 //
6740 // map(ps)
6741 // &ps, &ps, sizeof(S2*), noflags
6742 //
6743 // map(ps->i)
6744 // ps, &(ps->i), sizeof(int), noflags
6745 //
6746 // map(ps->s.f)
6747 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
6748 //
6749 // map(ps->p)
6750 // ps, &(ps->p), sizeof(double*), noflags
6751 //
6752 // map(ps->p[:22])
6753 // ps, &(ps->p), sizeof(double*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006754 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006755 //
6756 // map(ps->ps)
6757 // ps, &(ps->ps), sizeof(S2*), noflags
6758 //
6759 // map(ps->ps->s.i)
6760 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006761 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006762 //
6763 // map(ps->ps->ps)
6764 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006765 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006766 //
6767 // map(ps->ps->ps->ps)
6768 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006769 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
6770 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006771 //
6772 // map(ps->ps->ps->s.f[:22])
6773 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006774 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
6775 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006776
6777 // Track if the map information being generated is the first for a capture.
6778 bool IsCaptureFirstInfo = IsFirstComponentList;
Alexey Bataev92327c52018-03-26 16:40:55 +00006779 bool IsLink = false; // Is this variable a "declare target link"?
Samuel Antao86ace552016-04-27 22:40:57 +00006780
6781 // Scan the components from the base to the complete expression.
6782 auto CI = Components.rbegin();
6783 auto CE = Components.rend();
6784 auto I = CI;
6785
6786 // Track if the map information being generated is the first for a list of
6787 // components.
6788 bool IsExpressionFirstInfo = true;
6789 llvm::Value *BP = nullptr;
6790
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006791 if (const auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
Samuel Antao86ace552016-04-27 22:40:57 +00006792 // The base is the 'this' pointer. The content of the pointer is going
6793 // to be the base of the field being mapped.
6794 BP = CGF.EmitScalarExpr(ME->getBase());
6795 } else {
6796 // The base is the reference to the variable.
6797 // BP = &Var.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006798 BP = CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Alexey Bataev92327c52018-03-26 16:40:55 +00006799 if (const auto *VD =
6800 dyn_cast_or_null<VarDecl>(I->getAssociatedDeclaration())) {
6801 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
6802 isDeclareTargetDeclaration(VD)) {
6803 assert(*Res == OMPDeclareTargetDeclAttr::MT_Link &&
6804 "Declare target link is expected.");
6805 // Avoid warning in release build.
6806 (void)*Res;
6807 IsLink = true;
6808 BP = CGF.CGM.getOpenMPRuntime()
Alexey Bataev03f270c2018-03-30 18:31:07 +00006809 .getAddrOfDeclareTargetLink(VD)
Alexey Bataev92327c52018-03-26 16:40:55 +00006810 .getPointer();
6811 }
6812 }
Samuel Antao86ace552016-04-27 22:40:57 +00006813
6814 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00006815 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00006816 // reference. References are ignored for mapping purposes.
6817 QualType Ty =
6818 I->getAssociatedDeclaration()->getType().getNonReferenceType();
6819 if (Ty->isAnyPointerType() && std::next(I) != CE) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006820 LValue PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
Samuel Antao86ace552016-04-27 22:40:57 +00006821 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
Samuel Antao403ffd42016-07-27 22:49:49 +00006822 Ty->castAs<PointerType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006823 .getPointer();
6824
6825 // We do not need to generate individual map information for the
6826 // pointer, it can be associated with the combined storage.
6827 ++I;
6828 }
6829 }
6830
George Rokos63bc9d62017-11-21 18:25:12 +00006831 uint64_t DefaultFlags = IsImplicit ? OMP_MAP_IMPLICIT : 0;
Samuel Antao86ace552016-04-27 22:40:57 +00006832 for (; I != CE; ++I) {
6833 auto Next = std::next(I);
6834
6835 // We need to generate the addresses and sizes if this is the last
6836 // component, if the component is a pointer or if it is an array section
6837 // whose length can't be proved to be one. If this is a pointer, it
6838 // becomes the base address for the following components.
6839
6840 // A final array section, is one whose length can't be proved to be one.
6841 bool IsFinalArraySection =
6842 isFinalArraySectionExpression(I->getAssociatedExpression());
6843
6844 // Get information on whether the element is a pointer. Have to do a
6845 // special treatment for array sections given that they are built-in
6846 // types.
6847 const auto *OASE =
6848 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
6849 bool IsPointer =
6850 (OASE &&
6851 OMPArraySectionExpr::getBaseOriginalType(OASE)
6852 .getCanonicalType()
6853 ->isAnyPointerType()) ||
6854 I->getAssociatedExpression()->getType()->isAnyPointerType();
6855
6856 if (Next == CE || IsPointer || IsFinalArraySection) {
Samuel Antao86ace552016-04-27 22:40:57 +00006857 // If this is not the last component, we expect the pointer to be
6858 // associated with an array expression or member expression.
6859 assert((Next == CE ||
6860 isa<MemberExpr>(Next->getAssociatedExpression()) ||
6861 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
6862 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
6863 "Unexpected expression");
6864
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006865 llvm::Value *LB =
6866 CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006867 llvm::Value *Size = getExprTypeSize(I->getAssociatedExpression());
Samuel Antao86ace552016-04-27 22:40:57 +00006868
Samuel Antao03a3cec2016-07-27 22:52:16 +00006869 // If we have a member expression and the current component is a
6870 // reference, we have to map the reference too. Whenever we have a
6871 // reference, the section that reference refers to is going to be a
6872 // load instruction from the storage assigned to the reference.
6873 if (isa<MemberExpr>(I->getAssociatedExpression()) &&
6874 I->getAssociatedDeclaration()->getType()->isReferenceType()) {
6875 auto *LI = cast<llvm::LoadInst>(LB);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006876 llvm::Value *RefAddr = LI->getPointerOperand();
Samuel Antao03a3cec2016-07-27 22:52:16 +00006877
6878 BasePointers.push_back(BP);
6879 Pointers.push_back(RefAddr);
6880 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006881 Types.push_back(DefaultFlags |
6882 getMapTypeBits(
6883 /*MapType*/ OMPC_MAP_alloc,
6884 /*MapTypeModifier=*/OMPC_MAP_unknown,
6885 !IsExpressionFirstInfo, IsCaptureFirstInfo));
Samuel Antao03a3cec2016-07-27 22:52:16 +00006886 IsExpressionFirstInfo = false;
6887 IsCaptureFirstInfo = false;
6888 // The reference will be the next base address.
6889 BP = RefAddr;
6890 }
6891
6892 BasePointers.push_back(BP);
Samuel Antao86ace552016-04-27 22:40:57 +00006893 Pointers.push_back(LB);
6894 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00006895
Samuel Antao6782e942016-05-26 16:48:10 +00006896 // We need to add a pointer flag for each map that comes from the
6897 // same expression except for the first one. We also need to signal
6898 // this map is the first one that relates with the current capture
6899 // (there is a set of entries for each capture).
Alexey Bataev92327c52018-03-26 16:40:55 +00006900 Types.push_back(DefaultFlags |
6901 getMapTypeBits(MapType, MapTypeModifier,
6902 !IsExpressionFirstInfo || IsLink,
6903 IsCaptureFirstInfo && !IsLink));
Samuel Antao86ace552016-04-27 22:40:57 +00006904
6905 // If we have a final array section, we are done with this expression.
6906 if (IsFinalArraySection)
6907 break;
6908
6909 // The pointer becomes the base for the next element.
6910 if (Next != CE)
6911 BP = LB;
6912
6913 IsExpressionFirstInfo = false;
6914 IsCaptureFirstInfo = false;
Samuel Antao86ace552016-04-27 22:40:57 +00006915 }
6916 }
6917 }
6918
Samuel Antao86ace552016-04-27 22:40:57 +00006919 /// \brief Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00006920 /// types for the extracted mappable expressions. Also, for each item that
6921 /// relates with a device pointer, a pair of the relevant declaration and
6922 /// index where it occurs is appended to the device pointers info array.
6923 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006924 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
6925 MapFlagsArrayTy &Types) const {
6926 BasePointers.clear();
6927 Pointers.clear();
6928 Sizes.clear();
6929 Types.clear();
6930
6931 struct MapInfo {
Samuel Antaocc10b852016-07-28 14:23:26 +00006932 /// Kind that defines how a device pointer has to be returned.
6933 enum ReturnPointerKind {
6934 // Don't have to return any pointer.
6935 RPK_None,
6936 // Pointer is the base of the declaration.
6937 RPK_Base,
6938 // Pointer is a member of the base declaration - 'this'
6939 RPK_Member,
6940 // Pointer is a reference and a member of the base declaration - 'this'
6941 RPK_MemberReference,
6942 };
Samuel Antao86ace552016-04-27 22:40:57 +00006943 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006944 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
6945 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
6946 ReturnPointerKind ReturnDevicePointer = RPK_None;
6947 bool IsImplicit = false;
Hans Wennborgbc1b58d2016-07-30 00:41:37 +00006948
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006949 MapInfo() = default;
Samuel Antaocc10b852016-07-28 14:23:26 +00006950 MapInfo(
6951 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
6952 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006953 ReturnPointerKind ReturnDevicePointer, bool IsImplicit)
Samuel Antaocc10b852016-07-28 14:23:26 +00006954 : Components(Components), MapType(MapType),
6955 MapTypeModifier(MapTypeModifier),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006956 ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
Samuel Antao86ace552016-04-27 22:40:57 +00006957 };
6958
6959 // We have to process the component lists that relate with the same
6960 // declaration in a single chunk so that we can generate the map flags
6961 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00006962 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00006963
6964 // Helper function to fill the information map for the different supported
6965 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00006966 auto &&InfoGen = [&Info](
6967 const ValueDecl *D,
6968 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
6969 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006970 MapInfo::ReturnPointerKind ReturnDevicePointer, bool IsImplicit) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006971 const ValueDecl *VD =
6972 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006973 Info[VD].emplace_back(L, MapType, MapModifier, ReturnDevicePointer,
6974 IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00006975 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00006976
Paul Robinson78fb1322016-08-01 22:12:46 +00006977 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006978 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
6979 for (const auto &L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006980 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006981 MapInfo::RPK_None, C->isImplicit());
6982 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006983 for (const auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
6984 for (const auto &L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006985 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006986 MapInfo::RPK_None, C->isImplicit());
6987 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006988 for (const auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
6989 for (const auto &L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006990 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006991 MapInfo::RPK_None, C->isImplicit());
6992 }
Samuel Antao86ace552016-04-27 22:40:57 +00006993
Samuel Antaocc10b852016-07-28 14:23:26 +00006994 // Look at the use_device_ptr clause information and mark the existing map
6995 // entries as such. If there is no map information for an entry in the
6996 // use_device_ptr list, we create one with map type 'alloc' and zero size
6997 // section. It is the user fault if that was not mapped before.
Paul Robinson78fb1322016-08-01 22:12:46 +00006998 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006999 for (const auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
7000 for (const auto &L : C->component_lists()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007001 assert(!L.second.empty() && "Not expecting empty list of components!");
7002 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
7003 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007004 const Expr *IE = L.second.back().getAssociatedExpression();
Samuel Antaocc10b852016-07-28 14:23:26 +00007005 // If the first component is a member expression, we have to look into
7006 // 'this', which maps to null in the map of map information. Otherwise
7007 // look directly for the information.
7008 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
7009
7010 // We potentially have map information for this declaration already.
7011 // Look for the first set of components that refer to it.
7012 if (It != Info.end()) {
7013 auto CI = std::find_if(
7014 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
7015 return MI.Components.back().getAssociatedDeclaration() == VD;
7016 });
7017 // If we found a map entry, signal that the pointer has to be returned
7018 // and move on to the next declaration.
7019 if (CI != It->second.end()) {
7020 CI->ReturnDevicePointer = isa<MemberExpr>(IE)
7021 ? (VD->getType()->isReferenceType()
7022 ? MapInfo::RPK_MemberReference
7023 : MapInfo::RPK_Member)
7024 : MapInfo::RPK_Base;
7025 continue;
7026 }
7027 }
7028
7029 // We didn't find any match in our map information - generate a zero
7030 // size array section.
Paul Robinson78fb1322016-08-01 22:12:46 +00007031 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Alexey Bataev1e491372018-01-23 18:44:14 +00007032 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(this->CGF.EmitLValue(IE),
7033 IE->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +00007034 BasePointers.push_back({Ptr, VD});
7035 Pointers.push_back(Ptr);
Paul Robinson15c84002016-07-29 20:46:16 +00007036 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
George Rokos065755d2017-11-07 18:27:04 +00007037 Types.push_back(OMP_MAP_RETURN_PARAM | OMP_MAP_TARGET_PARAM);
Samuel Antaocc10b852016-07-28 14:23:26 +00007038 }
7039
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007040 for (const auto &M : Info) {
Samuel Antao86ace552016-04-27 22:40:57 +00007041 // We need to know when we generate information for the first component
7042 // associated with a capture, because the mapping flags depend on it.
7043 bool IsFirstComponentList = true;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007044 for (const MapInfo &L : M.second) {
Samuel Antao86ace552016-04-27 22:40:57 +00007045 assert(!L.Components.empty() &&
7046 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00007047
7048 // Remember the current base pointer index.
7049 unsigned CurrentBasePointersIdx = BasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00007050 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007051 this->generateInfoForComponentList(
7052 L.MapType, L.MapTypeModifier, L.Components, BasePointers, Pointers,
7053 Sizes, Types, IsFirstComponentList, L.IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007054
7055 // If this entry relates with a device pointer, set the relevant
7056 // declaration and add the 'return pointer' flag.
7057 if (IsFirstComponentList &&
7058 L.ReturnDevicePointer != MapInfo::RPK_None) {
7059 // If the pointer is not the base of the map, we need to skip the
7060 // base. If it is a reference in a member field, we also need to skip
7061 // the map of the reference.
7062 if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
7063 ++CurrentBasePointersIdx;
7064 if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
7065 ++CurrentBasePointersIdx;
7066 }
7067 assert(BasePointers.size() > CurrentBasePointersIdx &&
7068 "Unexpected number of mapped base pointers.");
7069
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007070 const ValueDecl *RelevantVD =
7071 L.Components.back().getAssociatedDeclaration();
Samuel Antaocc10b852016-07-28 14:23:26 +00007072 assert(RelevantVD &&
7073 "No relevant declaration related with device pointer??");
7074
7075 BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
George Rokos065755d2017-11-07 18:27:04 +00007076 Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PARAM;
Samuel Antaocc10b852016-07-28 14:23:26 +00007077 }
Samuel Antao86ace552016-04-27 22:40:57 +00007078 IsFirstComponentList = false;
7079 }
7080 }
7081 }
7082
7083 /// \brief Generate the base pointers, section pointers, sizes and map types
7084 /// associated to a given capture.
7085 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00007086 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007087 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007088 MapValuesArrayTy &Pointers,
7089 MapValuesArrayTy &Sizes,
7090 MapFlagsArrayTy &Types) const {
7091 assert(!Cap->capturesVariableArrayType() &&
7092 "Not expecting to generate map info for a variable array type!");
7093
7094 BasePointers.clear();
7095 Pointers.clear();
7096 Sizes.clear();
7097 Types.clear();
7098
Samuel Antao6890b092016-07-28 14:25:09 +00007099 // We need to know when we generating information for the first component
7100 // associated with a capture, because the mapping flags depend on it.
7101 bool IsFirstComponentList = true;
7102
Samuel Antao86ace552016-04-27 22:40:57 +00007103 const ValueDecl *VD =
7104 Cap->capturesThis()
7105 ? nullptr
George Burgess IV00f70bd2018-03-01 05:43:23 +00007106 : Cap->getCapturedVar()->getCanonicalDecl();
Samuel Antao86ace552016-04-27 22:40:57 +00007107
Samuel Antao6890b092016-07-28 14:25:09 +00007108 // If this declaration appears in a is_device_ptr clause we just have to
7109 // pass the pointer by value. If it is a reference to a declaration, we just
7110 // pass its value, otherwise, if it is a member expression, we need to map
7111 // 'to' the field.
7112 if (!VD) {
7113 auto It = DevPointersMap.find(VD);
7114 if (It != DevPointersMap.end()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007115 for (ArrayRef<OMPClauseMappableExprCommon::MappableComponent> L :
7116 It->second) {
Samuel Antao6890b092016-07-28 14:25:09 +00007117 generateInfoForComponentList(
7118 /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007119 BasePointers, Pointers, Sizes, Types, IsFirstComponentList,
7120 /*IsImplicit=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +00007121 IsFirstComponentList = false;
7122 }
7123 return;
7124 }
7125 } else if (DevPointersMap.count(VD)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007126 BasePointers.emplace_back(Arg, VD);
Samuel Antao6890b092016-07-28 14:25:09 +00007127 Pointers.push_back(Arg);
7128 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
George Rokos065755d2017-11-07 18:27:04 +00007129 Types.push_back(OMP_MAP_LITERAL | OMP_MAP_TARGET_PARAM);
Samuel Antao6890b092016-07-28 14:25:09 +00007130 return;
7131 }
7132
Paul Robinson78fb1322016-08-01 22:12:46 +00007133 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007134 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
7135 for (const auto &L : C->decl_component_lists(VD)) {
Samuel Antao86ace552016-04-27 22:40:57 +00007136 assert(L.first == VD &&
7137 "We got information for the wrong declaration??");
7138 assert(!L.second.empty() &&
7139 "Not expecting declaration with no component lists.");
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007140 generateInfoForComponentList(
7141 C->getMapType(), C->getMapTypeModifier(), L.second, BasePointers,
7142 Pointers, Sizes, Types, IsFirstComponentList, C->isImplicit());
Samuel Antao86ace552016-04-27 22:40:57 +00007143 IsFirstComponentList = false;
7144 }
7145
7146 return;
7147 }
Samuel Antaod486f842016-05-26 16:53:38 +00007148
7149 /// \brief Generate the default map information for a given capture \a CI,
7150 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00007151 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
7152 const FieldDecl &RI, llvm::Value *CV,
7153 MapBaseValuesArrayTy &CurBasePointers,
7154 MapValuesArrayTy &CurPointers,
7155 MapValuesArrayTy &CurSizes,
7156 MapFlagsArrayTy &CurMapTypes) {
Samuel Antaod486f842016-05-26 16:53:38 +00007157
7158 // Do the default mapping.
7159 if (CI.capturesThis()) {
7160 CurBasePointers.push_back(CV);
7161 CurPointers.push_back(CV);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007162 const auto *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007163 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
7164 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00007165 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00007166 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007167 CurBasePointers.push_back(CV);
7168 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00007169 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007170 // We have to signal to the runtime captures passed by value that are
7171 // not pointers.
George Rokos065755d2017-11-07 18:27:04 +00007172 CurMapTypes.push_back(OMP_MAP_LITERAL);
Samuel Antaod486f842016-05-26 16:53:38 +00007173 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
7174 } else {
7175 // Pointers are implicitly mapped with a zero size and no flags
7176 // (other than first map that is added for all implicit maps).
7177 CurMapTypes.push_back(0u);
Samuel Antaod486f842016-05-26 16:53:38 +00007178 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
7179 }
7180 } else {
7181 assert(CI.capturesVariable() && "Expected captured reference.");
7182 CurBasePointers.push_back(CV);
7183 CurPointers.push_back(CV);
7184
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007185 const auto *PtrTy = cast<ReferenceType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007186 QualType ElementType = PtrTy->getPointeeType();
7187 CurSizes.push_back(CGF.getTypeSize(ElementType));
7188 // The default map type for a scalar/complex type is 'to' because by
7189 // default the value doesn't have to be retrieved. For an aggregate
7190 // type, the default is 'tofrom'.
Alexey Bataev3f96fe62017-12-13 17:31:39 +00007191 CurMapTypes.emplace_back(adjustMapModifiersForPrivateClauses(
7192 CI, ElementType->isAggregateType() ? (OMP_MAP_TO | OMP_MAP_FROM)
7193 : OMP_MAP_TO));
Samuel Antaod486f842016-05-26 16:53:38 +00007194 }
George Rokos065755d2017-11-07 18:27:04 +00007195 // Every default map produces a single argument which is a target parameter.
7196 CurMapTypes.back() |= OMP_MAP_TARGET_PARAM;
Samuel Antaod486f842016-05-26 16:53:38 +00007197 }
Samuel Antao86ace552016-04-27 22:40:57 +00007198};
Samuel Antaodf158d52016-04-27 22:58:19 +00007199
7200enum OpenMPOffloadingReservedDeviceIDs {
7201 /// \brief Device ID if the device was not defined, runtime should get it
7202 /// from environment variables in the spec.
7203 OMP_DEVICEID_UNDEF = -1,
7204};
7205} // anonymous namespace
7206
7207/// \brief Emit the arrays used to pass the captures and map information to the
7208/// offloading runtime library. If there is no map or capture information,
7209/// return nullptr by reference.
7210static void
Samuel Antaocc10b852016-07-28 14:23:26 +00007211emitOffloadingArrays(CodeGenFunction &CGF,
7212 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00007213 MappableExprsHandler::MapValuesArrayTy &Pointers,
7214 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00007215 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
7216 CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007217 CodeGenModule &CGM = CGF.CGM;
7218 ASTContext &Ctx = CGF.getContext();
Samuel Antaodf158d52016-04-27 22:58:19 +00007219
Samuel Antaocc10b852016-07-28 14:23:26 +00007220 // Reset the array information.
7221 Info.clearArrayInfo();
7222 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00007223
Samuel Antaocc10b852016-07-28 14:23:26 +00007224 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007225 // Detect if we have any capture size requiring runtime evaluation of the
7226 // size so that a constant array could be eventually used.
7227 bool hasRuntimeEvaluationCaptureSize = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007228 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00007229 if (!isa<llvm::Constant>(S)) {
7230 hasRuntimeEvaluationCaptureSize = true;
7231 break;
7232 }
7233
Samuel Antaocc10b852016-07-28 14:23:26 +00007234 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00007235 QualType PointerArrayType =
7236 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
7237 /*IndexTypeQuals=*/0);
7238
Samuel Antaocc10b852016-07-28 14:23:26 +00007239 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007240 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00007241 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007242 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
7243
7244 // If we don't have any VLA types or other types that require runtime
7245 // evaluation, we can use a constant array for the map sizes, otherwise we
7246 // need to fill up the arrays as we do for the pointers.
7247 if (hasRuntimeEvaluationCaptureSize) {
7248 QualType SizeArrayType = Ctx.getConstantArrayType(
7249 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
7250 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00007251 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007252 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
7253 } else {
7254 // We expect all the sizes to be constant, so we collect them to create
7255 // a constant array.
7256 SmallVector<llvm::Constant *, 16> ConstSizes;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007257 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00007258 ConstSizes.push_back(cast<llvm::Constant>(S));
7259
7260 auto *SizesArrayInit = llvm::ConstantArray::get(
7261 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
7262 auto *SizesArrayGbl = new llvm::GlobalVariable(
7263 CGM.getModule(), SizesArrayInit->getType(),
7264 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
7265 SizesArrayInit, ".offload_sizes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00007266 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00007267 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00007268 }
7269
7270 // The map types are always constant so we don't need to generate code to
7271 // fill arrays. Instead, we create an array constant.
7272 llvm::Constant *MapTypesArrayInit =
7273 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
7274 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
7275 CGM.getModule(), MapTypesArrayInit->getType(),
7276 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
7277 MapTypesArrayInit, ".offload_maptypes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00007278 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00007279 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00007280
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007281 for (unsigned I = 0; I < Info.NumberOfPtrs; ++I) {
7282 llvm::Value *BPVal = *BasePointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00007283 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007284 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007285 Info.BasePointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00007286 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7287 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00007288 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
7289 CGF.Builder.CreateStore(BPVal, BPAddr);
7290
Samuel Antaocc10b852016-07-28 14:23:26 +00007291 if (Info.requiresDevicePointerInfo())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007292 if (const ValueDecl *DevVD = BasePointers[I].getDevicePtrDecl())
Alexey Bataev43a919f2018-04-13 17:48:43 +00007293 Info.CaptureDeviceAddrMap.try_emplace(DevVD, BPAddr);
Samuel Antaocc10b852016-07-28 14:23:26 +00007294
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007295 llvm::Value *PVal = Pointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00007296 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007297 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007298 Info.PointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00007299 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7300 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00007301 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
7302 CGF.Builder.CreateStore(PVal, PAddr);
7303
7304 if (hasRuntimeEvaluationCaptureSize) {
7305 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007306 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
7307 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007308 /*Idx0=*/0,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007309 /*Idx1=*/I);
Samuel Antaodf158d52016-04-27 22:58:19 +00007310 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
7311 CGF.Builder.CreateStore(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007312 CGF.Builder.CreateIntCast(Sizes[I], CGM.SizeTy, /*isSigned=*/true),
Samuel Antaodf158d52016-04-27 22:58:19 +00007313 SAddr);
7314 }
7315 }
7316 }
7317}
7318/// \brief Emit the arguments to be passed to the runtime library based on the
7319/// arrays of pointers, sizes and map types.
7320static void emitOffloadingArraysArgument(
7321 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
7322 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007323 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007324 CodeGenModule &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00007325 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007326 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007327 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
7328 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007329 /*Idx0=*/0, /*Idx1=*/0);
7330 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007331 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
7332 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007333 /*Idx0=*/0,
7334 /*Idx1=*/0);
7335 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007336 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007337 /*Idx0=*/0, /*Idx1=*/0);
7338 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
George Rokos63bc9d62017-11-21 18:25:12 +00007339 llvm::ArrayType::get(CGM.Int64Ty, Info.NumberOfPtrs),
Samuel Antaocc10b852016-07-28 14:23:26 +00007340 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007341 /*Idx0=*/0,
7342 /*Idx1=*/0);
7343 } else {
7344 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
7345 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
7346 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
7347 MapTypesArrayArg =
George Rokos63bc9d62017-11-21 18:25:12 +00007348 llvm::ConstantPointerNull::get(CGM.Int64Ty->getPointerTo());
Samuel Antaodf158d52016-04-27 22:58:19 +00007349 }
Samuel Antao86ace552016-04-27 22:40:57 +00007350}
7351
Samuel Antaobed3c462015-10-02 16:14:20 +00007352void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
7353 const OMPExecutableDirective &D,
7354 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00007355 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00007356 const Expr *IfCond, const Expr *Device) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00007357 if (!CGF.HaveInsertPoint())
7358 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00007359
Samuel Antaoee8fb302016-01-06 13:42:12 +00007360 assert(OutlinedFn && "Invalid outlined function!");
7361
Alexey Bataev8451efa2018-01-15 19:06:12 +00007362 const bool RequiresOuterTask = D.hasClausesOfKind<OMPDependClause>();
7363 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Alexey Bataev475a7442018-01-12 19:39:11 +00007364 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Alexey Bataev8451efa2018-01-15 19:06:12 +00007365 auto &&ArgsCodegen = [&CS, &CapturedVars](CodeGenFunction &CGF,
7366 PrePostActionTy &) {
7367 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7368 };
7369 emitInlinedDirective(CGF, OMPD_unknown, ArgsCodegen);
Samuel Antao86ace552016-04-27 22:40:57 +00007370
Alexey Bataev8451efa2018-01-15 19:06:12 +00007371 CodeGenFunction::OMPTargetDataInfo InputInfo;
7372 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00007373 // Fill up the pointer arrays and transfer execution to the device.
Alexey Bataev8451efa2018-01-15 19:06:12 +00007374 auto &&ThenGen = [this, Device, OutlinedFn, OutlinedFnID, &D, &InputInfo,
7375 &MapTypesArray, &CS, RequiresOuterTask,
7376 &CapturedVars](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobed3c462015-10-02 16:14:20 +00007377 // On top of the arrays that were filled up, the target offloading call
7378 // takes as arguments the device id as well as the host pointer. The host
7379 // pointer is used by the runtime library to identify the current target
7380 // region, so it only has to be unique and not necessarily point to
7381 // anything. It could be the pointer to the outlined function that
7382 // implements the target region, but we aren't using that so that the
7383 // compiler doesn't need to keep that, and could therefore inline the host
7384 // function if proven worthwhile during optimization.
7385
Samuel Antaoee8fb302016-01-06 13:42:12 +00007386 // From this point on, we need to have an ID of the target region defined.
7387 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00007388
7389 // Emit device ID if any.
7390 llvm::Value *DeviceID;
George Rokos63bc9d62017-11-21 18:25:12 +00007391 if (Device) {
Samuel Antaobed3c462015-10-02 16:14:20 +00007392 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007393 CGF.Int64Ty, /*isSigned=*/true);
7394 } else {
7395 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7396 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007397
Samuel Antaodf158d52016-04-27 22:58:19 +00007398 // Emit the number of elements in the offloading arrays.
Alexey Bataev8451efa2018-01-15 19:06:12 +00007399 llvm::Value *PointerNum =
7400 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaodf158d52016-04-27 22:58:19 +00007401
Samuel Antaob68e2db2016-03-03 16:20:23 +00007402 // Return value of the runtime offloading call.
7403 llvm::Value *Return;
7404
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007405 llvm::Value *NumTeams = emitNumTeamsForTargetDirective(*this, CGF, D);
7406 llvm::Value *NumThreads = emitNumThreadsForTargetDirective(*this, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007407
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007408 bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007409 // The target region is an outlined function launched by the runtime
7410 // via calls __tgt_target() or __tgt_target_teams().
7411 //
7412 // __tgt_target() launches a target region with one team and one thread,
7413 // executing a serial region. This master thread may in turn launch
7414 // more threads within its team upon encountering a parallel region,
7415 // however, no additional teams can be launched on the device.
7416 //
7417 // __tgt_target_teams() launches a target region with one or more teams,
7418 // each with one or more threads. This call is required for target
7419 // constructs such as:
7420 // 'target teams'
7421 // 'target' / 'teams'
7422 // 'target teams distribute parallel for'
7423 // 'target parallel'
7424 // and so on.
7425 //
7426 // Note that on the host and CPU targets, the runtime implementation of
7427 // these calls simply call the outlined function without forking threads.
7428 // The outlined functions themselves have runtime calls to
7429 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
7430 // the compiler in emitTeamsCall() and emitParallelCall().
7431 //
7432 // In contrast, on the NVPTX target, the implementation of
7433 // __tgt_target_teams() launches a GPU kernel with the requested number
7434 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00007435 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007436 // If we have NumTeams defined this means that we have an enclosed teams
7437 // region. Therefore we also expect to have NumThreads defined. These two
7438 // values should be defined in the presence of a teams directive,
7439 // regardless of having any clauses associated. If the user is using teams
7440 // but no clauses, these two values will be the default that should be
7441 // passed to the runtime library - a 32-bit integer with the value zero.
7442 assert(NumThreads && "Thread limit expression should be available along "
7443 "with number of teams.");
Alexey Bataev8451efa2018-01-15 19:06:12 +00007444 llvm::Value *OffloadingArgs[] = {DeviceID,
7445 OutlinedFnID,
7446 PointerNum,
7447 InputInfo.BasePointersArray.getPointer(),
7448 InputInfo.PointersArray.getPointer(),
7449 InputInfo.SizesArray.getPointer(),
7450 MapTypesArray,
7451 NumTeams,
7452 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00007453 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00007454 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_teams_nowait
7455 : OMPRTL__tgt_target_teams),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007456 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007457 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00007458 llvm::Value *OffloadingArgs[] = {DeviceID,
7459 OutlinedFnID,
7460 PointerNum,
7461 InputInfo.BasePointersArray.getPointer(),
7462 InputInfo.PointersArray.getPointer(),
7463 InputInfo.SizesArray.getPointer(),
7464 MapTypesArray};
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007465 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00007466 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_nowait
7467 : OMPRTL__tgt_target),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007468 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007469 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007470
Alexey Bataev2a007e02017-10-02 14:20:58 +00007471 // Check the error code and execute the host version if required.
7472 llvm::BasicBlock *OffloadFailedBlock =
7473 CGF.createBasicBlock("omp_offload.failed");
7474 llvm::BasicBlock *OffloadContBlock =
7475 CGF.createBasicBlock("omp_offload.cont");
7476 llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
7477 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
7478
7479 CGF.EmitBlock(OffloadFailedBlock);
Alexey Bataev8451efa2018-01-15 19:06:12 +00007480 if (RequiresOuterTask) {
7481 CapturedVars.clear();
7482 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7483 }
7484 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, CapturedVars);
Alexey Bataev2a007e02017-10-02 14:20:58 +00007485 CGF.EmitBranch(OffloadContBlock);
7486
7487 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00007488 };
7489
Samuel Antaoee8fb302016-01-06 13:42:12 +00007490 // Notify that the host version must be executed.
Alexey Bataev8451efa2018-01-15 19:06:12 +00007491 auto &&ElseGen = [this, &D, OutlinedFn, &CS, &CapturedVars,
7492 RequiresOuterTask](CodeGenFunction &CGF,
7493 PrePostActionTy &) {
7494 if (RequiresOuterTask) {
7495 CapturedVars.clear();
7496 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7497 }
7498 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, CapturedVars);
7499 };
7500
7501 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray,
7502 &CapturedVars, RequiresOuterTask,
7503 &CS](CodeGenFunction &CGF, PrePostActionTy &) {
7504 // Fill up the arrays with all the captured variables.
7505 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
7506 MappableExprsHandler::MapValuesArrayTy Pointers;
7507 MappableExprsHandler::MapValuesArrayTy Sizes;
7508 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7509
7510 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
7511 MappableExprsHandler::MapValuesArrayTy CurPointers;
7512 MappableExprsHandler::MapValuesArrayTy CurSizes;
7513 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
7514
7515 // Get mappable expression information.
7516 MappableExprsHandler MEHandler(D, CGF);
7517
7518 auto RI = CS.getCapturedRecordDecl()->field_begin();
7519 auto CV = CapturedVars.begin();
7520 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
7521 CE = CS.capture_end();
7522 CI != CE; ++CI, ++RI, ++CV) {
7523 CurBasePointers.clear();
7524 CurPointers.clear();
7525 CurSizes.clear();
7526 CurMapTypes.clear();
7527
7528 // VLA sizes are passed to the outlined region by copy and do not have map
7529 // information associated.
7530 if (CI->capturesVariableArrayType()) {
7531 CurBasePointers.push_back(*CV);
7532 CurPointers.push_back(*CV);
7533 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
7534 // Copy to the device as an argument. No need to retrieve it.
7535 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_LITERAL |
7536 MappableExprsHandler::OMP_MAP_TARGET_PARAM);
7537 } else {
7538 // If we have any information in the map clause, we use it, otherwise we
7539 // just do a default mapping.
7540 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
7541 CurSizes, CurMapTypes);
7542 if (CurBasePointers.empty())
7543 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
7544 CurPointers, CurSizes, CurMapTypes);
7545 }
7546 // We expect to have at least an element of information for this capture.
7547 assert(!CurBasePointers.empty() &&
7548 "Non-existing map pointer for capture!");
7549 assert(CurBasePointers.size() == CurPointers.size() &&
7550 CurBasePointers.size() == CurSizes.size() &&
7551 CurBasePointers.size() == CurMapTypes.size() &&
7552 "Inconsistent map information sizes!");
7553
7554 // We need to append the results of this capture to what we already have.
7555 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
7556 Pointers.append(CurPointers.begin(), CurPointers.end());
7557 Sizes.append(CurSizes.begin(), CurSizes.end());
7558 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
7559 }
Alexey Bataev92327c52018-03-26 16:40:55 +00007560 // Map other list items in the map clause which are not captured variables
7561 // but "declare target link" global variables.
7562 for (const auto *C : D.getClausesOfKind<OMPMapClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007563 for (const auto &L : C->component_lists()) {
Alexey Bataev92327c52018-03-26 16:40:55 +00007564 if (!L.first)
7565 continue;
7566 const auto *VD = dyn_cast<VarDecl>(L.first);
7567 if (!VD)
7568 continue;
7569 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
7570 isDeclareTargetDeclaration(VD);
7571 if (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link)
7572 continue;
7573 MEHandler.generateInfoForComponentList(
7574 C->getMapType(), C->getMapTypeModifier(), L.second, BasePointers,
7575 Pointers, Sizes, MapTypes, /*IsFirstComponentList=*/true,
7576 C->isImplicit());
7577 }
7578 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00007579
7580 TargetDataInfo Info;
7581 // Fill up the arrays and create the arguments.
7582 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
7583 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
7584 Info.PointersArray, Info.SizesArray,
7585 Info.MapTypesArray, Info);
7586 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
7587 InputInfo.BasePointersArray =
7588 Address(Info.BasePointersArray, CGM.getPointerAlign());
7589 InputInfo.PointersArray =
7590 Address(Info.PointersArray, CGM.getPointerAlign());
7591 InputInfo.SizesArray = Address(Info.SizesArray, CGM.getPointerAlign());
7592 MapTypesArray = Info.MapTypesArray;
7593 if (RequiresOuterTask)
7594 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
7595 else
7596 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
7597 };
7598
7599 auto &&TargetElseGen = [this, &ElseGen, &D, RequiresOuterTask](
7600 CodeGenFunction &CGF, PrePostActionTy &) {
7601 if (RequiresOuterTask) {
7602 CodeGenFunction::OMPTargetDataInfo InputInfo;
7603 CGF.EmitOMPTargetTaskBasedDirective(D, ElseGen, InputInfo);
7604 } else {
7605 emitInlinedDirective(CGF, D.getDirectiveKind(), ElseGen);
7606 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00007607 };
7608
7609 // If we have a target function ID it means that we need to support
7610 // offloading, otherwise, just execute on the host. We need to execute on host
7611 // regardless of the conditional in the if clause if, e.g., the user do not
7612 // specify target triples.
7613 if (OutlinedFnID) {
Alexey Bataev8451efa2018-01-15 19:06:12 +00007614 if (IfCond) {
7615 emitOMPIfClause(CGF, IfCond, TargetThenGen, TargetElseGen);
7616 } else {
7617 RegionCodeGenTy ThenRCG(TargetThenGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007618 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007619 }
7620 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00007621 RegionCodeGenTy ElseRCG(TargetElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007622 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007623 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007624}
Samuel Antaoee8fb302016-01-06 13:42:12 +00007625
7626void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
7627 StringRef ParentName) {
7628 if (!S)
7629 return;
7630
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007631 // Codegen OMP target directives that offload compute to the device.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007632 bool RequiresDeviceCodegen =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007633 isa<OMPExecutableDirective>(S) &&
7634 isOpenMPTargetExecutionDirective(
7635 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00007636
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007637 if (RequiresDeviceCodegen) {
7638 const auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007639 unsigned DeviceID;
7640 unsigned FileID;
7641 unsigned Line;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007642 getTargetEntryUniqueInfo(CGM.getContext(), E.getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00007643 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007644
7645 // Is this a target region that should not be emitted as an entry point? If
7646 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00007647 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
7648 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007649 return;
7650
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007651 switch (E.getDirectiveKind()) {
7652 case OMPD_target:
7653 CodeGenFunction::EmitOMPTargetDeviceFunction(CGM, ParentName,
7654 cast<OMPTargetDirective>(E));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007655 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007656 case OMPD_target_parallel:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00007657 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007658 CGM, ParentName, cast<OMPTargetParallelDirective>(E));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00007659 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007660 case OMPD_target_teams:
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00007661 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007662 CGM, ParentName, cast<OMPTargetTeamsDirective>(E));
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00007663 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007664 case OMPD_target_teams_distribute:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007665 CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007666 CGM, ParentName, cast<OMPTargetTeamsDistributeDirective>(E));
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007667 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007668 case OMPD_target_teams_distribute_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007669 CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007670 CGM, ParentName, cast<OMPTargetTeamsDistributeSimdDirective>(E));
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007671 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007672 case OMPD_target_parallel_for:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007673 CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007674 CGM, ParentName, cast<OMPTargetParallelForDirective>(E));
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007675 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007676 case OMPD_target_parallel_for_simd:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007677 CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007678 CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(E));
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007679 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007680 case OMPD_target_simd:
Alexey Bataevf8365372017-11-17 17:57:25 +00007681 CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007682 CGM, ParentName, cast<OMPTargetSimdDirective>(E));
Alexey Bataevf8365372017-11-17 17:57:25 +00007683 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007684 case OMPD_target_teams_distribute_parallel_for:
Carlo Bertolli52978c32018-01-03 21:12:44 +00007685 CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
7686 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007687 cast<OMPTargetTeamsDistributeParallelForDirective>(E));
Carlo Bertolli52978c32018-01-03 21:12:44 +00007688 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007689 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00007690 CodeGenFunction::
7691 EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
7692 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007693 cast<OMPTargetTeamsDistributeParallelForSimdDirective>(E));
Alexey Bataev647dd842018-01-15 20:59:40 +00007694 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007695 case OMPD_parallel:
7696 case OMPD_for:
7697 case OMPD_parallel_for:
7698 case OMPD_parallel_sections:
7699 case OMPD_for_simd:
7700 case OMPD_parallel_for_simd:
7701 case OMPD_cancel:
7702 case OMPD_cancellation_point:
7703 case OMPD_ordered:
7704 case OMPD_threadprivate:
7705 case OMPD_task:
7706 case OMPD_simd:
7707 case OMPD_sections:
7708 case OMPD_section:
7709 case OMPD_single:
7710 case OMPD_master:
7711 case OMPD_critical:
7712 case OMPD_taskyield:
7713 case OMPD_barrier:
7714 case OMPD_taskwait:
7715 case OMPD_taskgroup:
7716 case OMPD_atomic:
7717 case OMPD_flush:
7718 case OMPD_teams:
7719 case OMPD_target_data:
7720 case OMPD_target_exit_data:
7721 case OMPD_target_enter_data:
7722 case OMPD_distribute:
7723 case OMPD_distribute_simd:
7724 case OMPD_distribute_parallel_for:
7725 case OMPD_distribute_parallel_for_simd:
7726 case OMPD_teams_distribute:
7727 case OMPD_teams_distribute_simd:
7728 case OMPD_teams_distribute_parallel_for:
7729 case OMPD_teams_distribute_parallel_for_simd:
7730 case OMPD_target_update:
7731 case OMPD_declare_simd:
7732 case OMPD_declare_target:
7733 case OMPD_end_declare_target:
7734 case OMPD_declare_reduction:
7735 case OMPD_taskloop:
7736 case OMPD_taskloop_simd:
7737 case OMPD_unknown:
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007738 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
7739 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00007740 return;
7741 }
7742
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007743 if (const auto *E = dyn_cast<OMPExecutableDirective>(S)) {
Alexey Bataev475a7442018-01-12 19:39:11 +00007744 if (!E->hasAssociatedStmt() || !E->getAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00007745 return;
7746
7747 scanForTargetRegionsFunctions(
Alexey Bataev475a7442018-01-12 19:39:11 +00007748 E->getInnermostCapturedStmt()->getCapturedStmt(), ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007749 return;
7750 }
7751
7752 // If this is a lambda function, look into its body.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007753 if (const auto *L = dyn_cast<LambdaExpr>(S))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007754 S = L->getBody();
7755
7756 // Keep looking for target regions recursively.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007757 for (const Stmt *II : S->children())
Samuel Antaoee8fb302016-01-06 13:42:12 +00007758 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007759}
7760
7761bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007762 const auto *FD = cast<FunctionDecl>(GD.getDecl());
Samuel Antaoee8fb302016-01-06 13:42:12 +00007763
7764 // If emitting code for the host, we do not process FD here. Instead we do
7765 // the normal code generation.
7766 if (!CGM.getLangOpts().OpenMPIsDevice)
7767 return false;
7768
7769 // Try to detect target regions in the function.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007770 scanForTargetRegionsFunctions(FD->getBody(), CGM.getMangledName(GD));
Samuel Antaoee8fb302016-01-06 13:42:12 +00007771
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007772 // Do not to emit function if it is not marked as declare target.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007773 return !isDeclareTargetDeclaration(FD);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007774}
7775
7776bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
7777 if (!CGM.getLangOpts().OpenMPIsDevice)
7778 return false;
7779
7780 // Check if there are Ctors/Dtors in this declaration and look for target
7781 // regions in it. We use the complete variant to produce the kernel name
7782 // mangling.
7783 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007784 if (const auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
7785 for (const CXXConstructorDecl *Ctor : RD->ctors()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00007786 StringRef ParentName =
7787 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
7788 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
7789 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007790 if (const CXXDestructorDecl *Dtor = RD->getDestructor()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00007791 StringRef ParentName =
7792 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
7793 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
7794 }
7795 }
7796
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007797 // Do not to emit variable if it is not marked as declare target.
Alexey Bataev92327c52018-03-26 16:40:55 +00007798 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev03f270c2018-03-30 18:31:07 +00007799 isDeclareTargetDeclaration(cast<VarDecl>(GD.getDecl()));
Alexey Bataev92327c52018-03-26 16:40:55 +00007800 return !Res || *Res == OMPDeclareTargetDeclAttr::MT_Link;
Samuel Antaoee8fb302016-01-06 13:42:12 +00007801}
7802
Alexey Bataev03f270c2018-03-30 18:31:07 +00007803void CGOpenMPRuntime::registerTargetGlobalVariable(const VarDecl *VD,
7804 llvm::Constant *Addr) {
7805 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
7806 isDeclareTargetDeclaration(VD)) {
7807 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags;
7808 StringRef VarName;
7809 CharUnits VarSize;
7810 llvm::GlobalValue::LinkageTypes Linkage;
7811 switch (*Res) {
7812 case OMPDeclareTargetDeclAttr::MT_To:
7813 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo;
7814 VarName = CGM.getMangledName(VD);
7815 VarSize = CGM.getContext().getTypeSizeInChars(VD->getType());
7816 Linkage = CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false);
7817 break;
7818 case OMPDeclareTargetDeclAttr::MT_Link:
7819 // Map type 'to' because we do not map the original variable but the
7820 // reference.
7821 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo;
7822 if (!CGM.getLangOpts().OpenMPIsDevice) {
7823 Addr =
7824 cast<llvm::Constant>(getAddrOfDeclareTargetLink(VD).getPointer());
7825 }
7826 VarName = Addr->getName();
7827 VarSize = CGM.getPointerSize();
7828 Linkage = llvm::GlobalValue::WeakAnyLinkage;
7829 break;
7830 }
7831 OffloadEntriesInfoManager.registerDeviceGlobalVarEntryInfo(
7832 VarName, Addr, VarSize, Flags, Linkage);
7833 }
7834}
7835
Samuel Antaoee8fb302016-01-06 13:42:12 +00007836bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007837 if (isa<FunctionDecl>(GD.getDecl()))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007838 return emitTargetFunctions(GD);
7839
7840 return emitTargetGlobalVariable(GD);
7841}
7842
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007843CGOpenMPRuntime::DisableAutoDeclareTargetRAII::DisableAutoDeclareTargetRAII(
7844 CodeGenModule &CGM)
7845 : CGM(CGM) {
7846 if (CGM.getLangOpts().OpenMPIsDevice) {
7847 SavedShouldMarkAsGlobal = CGM.getOpenMPRuntime().ShouldMarkAsGlobal;
7848 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = false;
7849 }
7850}
7851
7852CGOpenMPRuntime::DisableAutoDeclareTargetRAII::~DisableAutoDeclareTargetRAII() {
7853 if (CGM.getLangOpts().OpenMPIsDevice)
7854 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = SavedShouldMarkAsGlobal;
7855}
7856
7857bool CGOpenMPRuntime::markAsGlobalTarget(const FunctionDecl *D) {
7858 if (!CGM.getLangOpts().OpenMPIsDevice || !ShouldMarkAsGlobal)
7859 return true;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007860
7861 const FunctionDecl *FD = D->getCanonicalDecl();
Alexey Bataev34f8a702018-03-28 14:28:54 +00007862 // Do not to emit function if it is marked as declare target as it was already
7863 // emitted.
7864 if (isDeclareTargetDeclaration(D)) {
7865 if (D->hasBody() && AlreadyEmittedTargetFunctions.count(FD) == 0) {
7866 if (auto *F = dyn_cast_or_null<llvm::Function>(
7867 CGM.GetGlobalValue(CGM.getMangledName(D))))
7868 return !F->isDeclaration();
7869 return false;
7870 }
7871 return true;
7872 }
7873
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007874 // Do not mark member functions except for static.
7875 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD))
7876 if (!Method->isStatic())
7877 return true;
7878
7879 return !AlreadyEmittedTargetFunctions.insert(FD).second;
7880}
7881
Samuel Antaoee8fb302016-01-06 13:42:12 +00007882llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
7883 // If we have offloading in the current module, we need to emit the entries
7884 // now and register the offloading descriptor.
7885 createOffloadEntriesAndInfoMetadata();
7886
7887 // Create and register the offloading binary descriptors. This is the main
7888 // entity that captures all the information about offloading in the current
7889 // compilation unit.
7890 return createOffloadingBinaryDescriptorRegistration();
7891}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007892
7893void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
7894 const OMPExecutableDirective &D,
7895 SourceLocation Loc,
7896 llvm::Value *OutlinedFn,
7897 ArrayRef<llvm::Value *> CapturedVars) {
7898 if (!CGF.HaveInsertPoint())
7899 return;
7900
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007901 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007902 CodeGenFunction::RunCleanupsScope Scope(CGF);
7903
7904 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
7905 llvm::Value *Args[] = {
7906 RTLoc,
7907 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
7908 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
7909 llvm::SmallVector<llvm::Value *, 16> RealArgs;
7910 RealArgs.append(std::begin(Args), std::end(Args));
7911 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
7912
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007913 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007914 CGF.EmitRuntimeCall(RTLFn, RealArgs);
7915}
7916
7917void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00007918 const Expr *NumTeams,
7919 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007920 SourceLocation Loc) {
7921 if (!CGF.HaveInsertPoint())
7922 return;
7923
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007924 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007925
Carlo Bertollic6872252016-04-04 15:55:02 +00007926 llvm::Value *NumTeamsVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007927 NumTeams
Carlo Bertollic6872252016-04-04 15:55:02 +00007928 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
7929 CGF.CGM.Int32Ty, /* isSigned = */ true)
7930 : CGF.Builder.getInt32(0);
7931
7932 llvm::Value *ThreadLimitVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007933 ThreadLimit
Carlo Bertollic6872252016-04-04 15:55:02 +00007934 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
7935 CGF.CGM.Int32Ty, /* isSigned = */ true)
7936 : CGF.Builder.getInt32(0);
7937
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007938 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00007939 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
7940 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007941 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
7942 PushNumTeamsArgs);
7943}
Samuel Antaodf158d52016-04-27 22:58:19 +00007944
Samuel Antaocc10b852016-07-28 14:23:26 +00007945void CGOpenMPRuntime::emitTargetDataCalls(
7946 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7947 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007948 if (!CGF.HaveInsertPoint())
7949 return;
7950
Samuel Antaocc10b852016-07-28 14:23:26 +00007951 // Action used to replace the default codegen action and turn privatization
7952 // off.
7953 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00007954
7955 // Generate the code for the opening of the data environment. Capture all the
7956 // arguments of the runtime call by reference because they are used in the
7957 // closing of the region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007958 auto &&BeginThenGen = [this, &D, Device, &Info,
7959 &CodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007960 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00007961 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00007962 MappableExprsHandler::MapValuesArrayTy Pointers;
7963 MappableExprsHandler::MapValuesArrayTy Sizes;
7964 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7965
7966 // Get map clause information.
7967 MappableExprsHandler MCHandler(D, CGF);
7968 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00007969
7970 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00007971 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007972
7973 llvm::Value *BasePointersArrayArg = nullptr;
7974 llvm::Value *PointersArrayArg = nullptr;
7975 llvm::Value *SizesArrayArg = nullptr;
7976 llvm::Value *MapTypesArrayArg = nullptr;
7977 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007978 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007979
7980 // Emit device ID if any.
7981 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00007982 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007983 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007984 CGF.Int64Ty, /*isSigned=*/true);
7985 } else {
7986 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7987 }
Samuel Antaodf158d52016-04-27 22:58:19 +00007988
7989 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007990 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007991
7992 llvm::Value *OffloadingArgs[] = {
7993 DeviceID, PointerNum, BasePointersArrayArg,
7994 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007995 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_begin),
Samuel Antaodf158d52016-04-27 22:58:19 +00007996 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00007997
7998 // If device pointer privatization is required, emit the body of the region
7999 // here. It will have to be duplicated: with and without privatization.
8000 if (!Info.CaptureDeviceAddrMap.empty())
8001 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008002 };
8003
8004 // Generate code for the closing of the data region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008005 auto &&EndThenGen = [this, Device, &Info](CodeGenFunction &CGF,
8006 PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008007 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00008008
8009 llvm::Value *BasePointersArrayArg = nullptr;
8010 llvm::Value *PointersArrayArg = nullptr;
8011 llvm::Value *SizesArrayArg = nullptr;
8012 llvm::Value *MapTypesArrayArg = nullptr;
8013 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008014 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008015
8016 // Emit device ID if any.
8017 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008018 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008019 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008020 CGF.Int64Ty, /*isSigned=*/true);
8021 } else {
8022 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8023 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008024
8025 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008026 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00008027
8028 llvm::Value *OffloadingArgs[] = {
8029 DeviceID, PointerNum, BasePointersArrayArg,
8030 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008031 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_end),
Samuel Antaodf158d52016-04-27 22:58:19 +00008032 OffloadingArgs);
8033 };
8034
Samuel Antaocc10b852016-07-28 14:23:26 +00008035 // If we need device pointer privatization, we need to emit the body of the
8036 // region with no privatization in the 'else' branch of the conditional.
8037 // Otherwise, we don't have to do anything.
8038 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
8039 PrePostActionTy &) {
8040 if (!Info.CaptureDeviceAddrMap.empty()) {
8041 CodeGen.setAction(NoPrivAction);
8042 CodeGen(CGF);
8043 }
8044 };
8045
8046 // We don't have to do anything to close the region if the if clause evaluates
8047 // to false.
8048 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00008049
8050 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008051 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00008052 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00008053 RegionCodeGenTy RCG(BeginThenGen);
8054 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008055 }
8056
Samuel Antaocc10b852016-07-28 14:23:26 +00008057 // If we don't require privatization of device pointers, we emit the body in
8058 // between the runtime calls. This avoids duplicating the body code.
8059 if (Info.CaptureDeviceAddrMap.empty()) {
8060 CodeGen.setAction(NoPrivAction);
8061 CodeGen(CGF);
8062 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008063
8064 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008065 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00008066 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00008067 RegionCodeGenTy RCG(EndThenGen);
8068 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008069 }
8070}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008071
Samuel Antao8d2d7302016-05-26 18:30:22 +00008072void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00008073 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8074 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008075 if (!CGF.HaveInsertPoint())
8076 return;
8077
Samuel Antao8dd66282016-04-27 23:14:30 +00008078 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00008079 isa<OMPTargetExitDataDirective>(D) ||
8080 isa<OMPTargetUpdateDirective>(D)) &&
8081 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00008082
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008083 CodeGenFunction::OMPTargetDataInfo InputInfo;
8084 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008085 // Generate the code for the opening of the data environment.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008086 auto &&ThenGen = [this, &D, Device, &InputInfo,
8087 &MapTypesArray](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008088 // Emit device ID if any.
8089 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008090 if (Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008091 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008092 CGF.Int64Ty, /*isSigned=*/true);
8093 } else {
8094 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8095 }
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008096
8097 // Emit the number of elements in the offloading arrays.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008098 llvm::Constant *PointerNum =
8099 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008100
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008101 llvm::Value *OffloadingArgs[] = {DeviceID,
8102 PointerNum,
8103 InputInfo.BasePointersArray.getPointer(),
8104 InputInfo.PointersArray.getPointer(),
8105 InputInfo.SizesArray.getPointer(),
8106 MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00008107
Samuel Antao8d2d7302016-05-26 18:30:22 +00008108 // Select the right runtime function call for each expected standalone
8109 // directive.
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008110 const bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Samuel Antao8d2d7302016-05-26 18:30:22 +00008111 OpenMPRTLFunction RTLFn;
8112 switch (D.getDirectiveKind()) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00008113 case OMPD_target_enter_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008114 RTLFn = HasNowait ? OMPRTL__tgt_target_data_begin_nowait
8115 : OMPRTL__tgt_target_data_begin;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008116 break;
8117 case OMPD_target_exit_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008118 RTLFn = HasNowait ? OMPRTL__tgt_target_data_end_nowait
8119 : OMPRTL__tgt_target_data_end;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008120 break;
8121 case OMPD_target_update:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008122 RTLFn = HasNowait ? OMPRTL__tgt_target_data_update_nowait
8123 : OMPRTL__tgt_target_data_update;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008124 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008125 case OMPD_parallel:
8126 case OMPD_for:
8127 case OMPD_parallel_for:
8128 case OMPD_parallel_sections:
8129 case OMPD_for_simd:
8130 case OMPD_parallel_for_simd:
8131 case OMPD_cancel:
8132 case OMPD_cancellation_point:
8133 case OMPD_ordered:
8134 case OMPD_threadprivate:
8135 case OMPD_task:
8136 case OMPD_simd:
8137 case OMPD_sections:
8138 case OMPD_section:
8139 case OMPD_single:
8140 case OMPD_master:
8141 case OMPD_critical:
8142 case OMPD_taskyield:
8143 case OMPD_barrier:
8144 case OMPD_taskwait:
8145 case OMPD_taskgroup:
8146 case OMPD_atomic:
8147 case OMPD_flush:
8148 case OMPD_teams:
8149 case OMPD_target_data:
8150 case OMPD_distribute:
8151 case OMPD_distribute_simd:
8152 case OMPD_distribute_parallel_for:
8153 case OMPD_distribute_parallel_for_simd:
8154 case OMPD_teams_distribute:
8155 case OMPD_teams_distribute_simd:
8156 case OMPD_teams_distribute_parallel_for:
8157 case OMPD_teams_distribute_parallel_for_simd:
8158 case OMPD_declare_simd:
8159 case OMPD_declare_target:
8160 case OMPD_end_declare_target:
8161 case OMPD_declare_reduction:
8162 case OMPD_taskloop:
8163 case OMPD_taskloop_simd:
8164 case OMPD_target:
8165 case OMPD_target_simd:
8166 case OMPD_target_teams_distribute:
8167 case OMPD_target_teams_distribute_simd:
8168 case OMPD_target_teams_distribute_parallel_for:
8169 case OMPD_target_teams_distribute_parallel_for_simd:
8170 case OMPD_target_teams:
8171 case OMPD_target_parallel:
8172 case OMPD_target_parallel_for:
8173 case OMPD_target_parallel_for_simd:
8174 case OMPD_unknown:
8175 llvm_unreachable("Unexpected standalone target data directive.");
8176 break;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008177 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008178 CGF.EmitRuntimeCall(createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008179 };
8180
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008181 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray](
8182 CodeGenFunction &CGF, PrePostActionTy &) {
8183 // Fill up the arrays with all the mapped variables.
8184 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
8185 MappableExprsHandler::MapValuesArrayTy Pointers;
8186 MappableExprsHandler::MapValuesArrayTy Sizes;
8187 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008188
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008189 // Get map clause information.
8190 MappableExprsHandler MEHandler(D, CGF);
8191 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
8192
8193 TargetDataInfo Info;
8194 // Fill up the arrays and create the arguments.
8195 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
8196 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
8197 Info.PointersArray, Info.SizesArray,
8198 Info.MapTypesArray, Info);
8199 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
8200 InputInfo.BasePointersArray =
8201 Address(Info.BasePointersArray, CGM.getPointerAlign());
8202 InputInfo.PointersArray =
8203 Address(Info.PointersArray, CGM.getPointerAlign());
8204 InputInfo.SizesArray =
8205 Address(Info.SizesArray, CGM.getPointerAlign());
8206 MapTypesArray = Info.MapTypesArray;
8207 if (D.hasClausesOfKind<OMPDependClause>())
8208 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
8209 else
Alexey Bataev768f1f22018-01-09 19:59:25 +00008210 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008211 };
8212
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008213 if (IfCond) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008214 emitOMPIfClause(CGF, IfCond, TargetThenGen,
8215 [](CodeGenFunction &CGF, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008216 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008217 RegionCodeGenTy ThenRCG(TargetThenGen);
8218 ThenRCG(CGF);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008219 }
8220}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008221
8222namespace {
8223 /// Kind of parameter in a function with 'declare simd' directive.
8224 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
8225 /// Attribute set of the parameter.
8226 struct ParamAttrTy {
8227 ParamKindTy Kind = Vector;
8228 llvm::APSInt StrideOrArg;
8229 llvm::APSInt Alignment;
8230 };
8231} // namespace
8232
8233static unsigned evaluateCDTSize(const FunctionDecl *FD,
8234 ArrayRef<ParamAttrTy> ParamAttrs) {
8235 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
8236 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
8237 // of that clause. The VLEN value must be power of 2.
8238 // In other case the notion of the function`s "characteristic data type" (CDT)
8239 // is used to compute the vector length.
8240 // CDT is defined in the following order:
8241 // a) For non-void function, the CDT is the return type.
8242 // b) If the function has any non-uniform, non-linear parameters, then the
8243 // CDT is the type of the first such parameter.
8244 // c) If the CDT determined by a) or b) above is struct, union, or class
8245 // type which is pass-by-value (except for the type that maps to the
8246 // built-in complex data type), the characteristic data type is int.
8247 // d) If none of the above three cases is applicable, the CDT is int.
8248 // The VLEN is then determined based on the CDT and the size of vector
8249 // register of that ISA for which current vector version is generated. The
8250 // VLEN is computed using the formula below:
8251 // VLEN = sizeof(vector_register) / sizeof(CDT),
8252 // where vector register size specified in section 3.2.1 Registers and the
8253 // Stack Frame of original AMD64 ABI document.
8254 QualType RetType = FD->getReturnType();
8255 if (RetType.isNull())
8256 return 0;
8257 ASTContext &C = FD->getASTContext();
8258 QualType CDT;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008259 if (!RetType.isNull() && !RetType->isVoidType()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008260 CDT = RetType;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008261 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008262 unsigned Offset = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008263 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008264 if (ParamAttrs[Offset].Kind == Vector)
8265 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
8266 ++Offset;
8267 }
8268 if (CDT.isNull()) {
8269 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
8270 if (ParamAttrs[I + Offset].Kind == Vector) {
8271 CDT = FD->getParamDecl(I)->getType();
8272 break;
8273 }
8274 }
8275 }
8276 }
8277 if (CDT.isNull())
8278 CDT = C.IntTy;
8279 CDT = CDT->getCanonicalTypeUnqualified();
8280 if (CDT->isRecordType() || CDT->isUnionType())
8281 CDT = C.IntTy;
8282 return C.getTypeSize(CDT);
8283}
8284
8285static void
8286emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00008287 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008288 ArrayRef<ParamAttrTy> ParamAttrs,
8289 OMPDeclareSimdDeclAttr::BranchStateTy State) {
8290 struct ISADataTy {
8291 char ISA;
8292 unsigned VecRegSize;
8293 };
8294 ISADataTy ISAData[] = {
8295 {
8296 'b', 128
8297 }, // SSE
8298 {
8299 'c', 256
8300 }, // AVX
8301 {
8302 'd', 256
8303 }, // AVX2
8304 {
8305 'e', 512
8306 }, // AVX512
8307 };
8308 llvm::SmallVector<char, 2> Masked;
8309 switch (State) {
8310 case OMPDeclareSimdDeclAttr::BS_Undefined:
8311 Masked.push_back('N');
8312 Masked.push_back('M');
8313 break;
8314 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
8315 Masked.push_back('N');
8316 break;
8317 case OMPDeclareSimdDeclAttr::BS_Inbranch:
8318 Masked.push_back('M');
8319 break;
8320 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008321 for (char Mask : Masked) {
8322 for (const ISADataTy &Data : ISAData) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008323 SmallString<256> Buffer;
8324 llvm::raw_svector_ostream Out(Buffer);
8325 Out << "_ZGV" << Data.ISA << Mask;
8326 if (!VLENVal) {
8327 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
8328 evaluateCDTSize(FD, ParamAttrs));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008329 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008330 Out << VLENVal;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008331 }
8332 for (const ParamAttrTy &ParamAttr : ParamAttrs) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008333 switch (ParamAttr.Kind){
8334 case LinearWithVarStride:
8335 Out << 's' << ParamAttr.StrideOrArg;
8336 break;
8337 case Linear:
8338 Out << 'l';
8339 if (!!ParamAttr.StrideOrArg)
8340 Out << ParamAttr.StrideOrArg;
8341 break;
8342 case Uniform:
8343 Out << 'u';
8344 break;
8345 case Vector:
8346 Out << 'v';
8347 break;
8348 }
8349 if (!!ParamAttr.Alignment)
8350 Out << 'a' << ParamAttr.Alignment;
8351 }
8352 Out << '_' << Fn->getName();
8353 Fn->addFnAttr(Out.str());
8354 }
8355 }
8356}
8357
8358void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
8359 llvm::Function *Fn) {
8360 ASTContext &C = CGM.getContext();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008361 FD = FD->getMostRecentDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008362 // Map params to their positions in function decl.
8363 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
8364 if (isa<CXXMethodDecl>(FD))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008365 ParamPositions.try_emplace(FD, 0);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008366 unsigned ParamPos = ParamPositions.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008367 for (const ParmVarDecl *P : FD->parameters()) {
8368 ParamPositions.try_emplace(P->getCanonicalDecl(), ParamPos);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008369 ++ParamPos;
8370 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008371 while (FD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008372 for (const auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008373 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
8374 // Mark uniform parameters.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008375 for (const Expr *E : Attr->uniforms()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008376 E = E->IgnoreParenImpCasts();
8377 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008378 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008379 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008380 } else {
8381 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
8382 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008383 Pos = ParamPositions[PVD];
8384 }
8385 ParamAttrs[Pos].Kind = Uniform;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008386 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008387 // Get alignment info.
8388 auto NI = Attr->alignments_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008389 for (const Expr *E : Attr->aligneds()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008390 E = E->IgnoreParenImpCasts();
8391 unsigned Pos;
8392 QualType ParmTy;
8393 if (isa<CXXThisExpr>(E)) {
8394 Pos = ParamPositions[FD];
8395 ParmTy = E->getType();
8396 } else {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008397 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
8398 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008399 Pos = ParamPositions[PVD];
8400 ParmTy = PVD->getType();
8401 }
8402 ParamAttrs[Pos].Alignment =
8403 (*NI)
8404 ? (*NI)->EvaluateKnownConstInt(C)
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008405 : llvm::APSInt::getUnsigned(
8406 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
8407 .getQuantity());
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008408 ++NI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008409 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008410 // Mark linear parameters.
8411 auto SI = Attr->steps_begin();
8412 auto MI = Attr->modifiers_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008413 for (const Expr *E : Attr->linears()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008414 E = E->IgnoreParenImpCasts();
8415 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008416 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008417 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008418 } else {
8419 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
8420 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008421 Pos = ParamPositions[PVD];
8422 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008423 ParamAttrTy &ParamAttr = ParamAttrs[Pos];
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008424 ParamAttr.Kind = Linear;
8425 if (*SI) {
8426 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
8427 Expr::SE_AllowSideEffects)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008428 if (const auto *DRE =
8429 cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
8430 if (const auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008431 ParamAttr.Kind = LinearWithVarStride;
8432 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
8433 ParamPositions[StridePVD->getCanonicalDecl()]);
8434 }
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008435 }
8436 }
8437 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008438 ++SI;
8439 ++MI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008440 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008441 llvm::APSInt VLENVal;
8442 if (const Expr *VLEN = Attr->getSimdlen())
8443 VLENVal = VLEN->EvaluateKnownConstInt(C);
8444 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
8445 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
8446 CGM.getTriple().getArch() == llvm::Triple::x86_64)
8447 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008448 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008449 FD = FD->getPreviousDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008450 }
8451}
Alexey Bataev8b427062016-05-25 12:36:08 +00008452
8453namespace {
8454/// Cleanup action for doacross support.
8455class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
8456public:
8457 static const int DoacrossFinArgs = 2;
8458
8459private:
8460 llvm::Value *RTLFn;
8461 llvm::Value *Args[DoacrossFinArgs];
8462
8463public:
8464 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
8465 : RTLFn(RTLFn) {
8466 assert(CallArgs.size() == DoacrossFinArgs);
8467 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
8468 }
8469 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
8470 if (!CGF.HaveInsertPoint())
8471 return;
8472 CGF.EmitRuntimeCall(RTLFn, Args);
8473 }
8474};
8475} // namespace
8476
8477void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
8478 const OMPLoopDirective &D) {
8479 if (!CGF.HaveInsertPoint())
8480 return;
8481
8482 ASTContext &C = CGM.getContext();
8483 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
8484 RecordDecl *RD;
8485 if (KmpDimTy.isNull()) {
8486 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
8487 // kmp_int64 lo; // lower
8488 // kmp_int64 up; // upper
8489 // kmp_int64 st; // stride
8490 // };
8491 RD = C.buildImplicitRecord("kmp_dim");
8492 RD->startDefinition();
8493 addFieldToRecordDecl(C, RD, Int64Ty);
8494 addFieldToRecordDecl(C, RD, Int64Ty);
8495 addFieldToRecordDecl(C, RD, Int64Ty);
8496 RD->completeDefinition();
8497 KmpDimTy = C.getRecordType(RD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008498 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00008499 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008500 }
Alexey Bataev8b427062016-05-25 12:36:08 +00008501
8502 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
8503 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
8504 enum { LowerFD = 0, UpperFD, StrideFD };
8505 // Fill dims with data.
8506 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
8507 // dims.upper = num_iterations;
8508 LValue UpperLVal =
8509 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
8510 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
8511 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
8512 Int64Ty, D.getNumIterations()->getExprLoc());
8513 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
8514 // dims.stride = 1;
8515 LValue StrideLVal =
8516 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
8517 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
8518 StrideLVal);
8519
8520 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
8521 // kmp_int32 num_dims, struct kmp_dim * dims);
8522 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
8523 getThreadID(CGF, D.getLocStart()),
8524 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
8525 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
8526 DimsAddr.getPointer(), CGM.VoidPtrTy)};
8527
8528 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
8529 CGF.EmitRuntimeCall(RTLFn, Args);
8530 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
8531 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
8532 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
8533 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
8534 llvm::makeArrayRef(FiniArgs));
8535}
8536
8537void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
8538 const OMPDependClause *C) {
8539 QualType Int64Ty =
8540 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
8541 const Expr *CounterVal = C->getCounterValue();
8542 assert(CounterVal);
8543 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
8544 CounterVal->getType(), Int64Ty,
8545 CounterVal->getExprLoc());
8546 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
8547 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
8548 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
8549 getThreadID(CGF, C->getLocStart()),
8550 CntAddr.getPointer()};
8551 llvm::Value *RTLFn;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008552 if (C->getDependencyKind() == OMPC_DEPEND_source) {
Alexey Bataev8b427062016-05-25 12:36:08 +00008553 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008554 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00008555 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
8556 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
8557 }
8558 CGF.EmitRuntimeCall(RTLFn, Args);
8559}
8560
Alexey Bataev7ef47a62018-02-22 18:33:31 +00008561void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, SourceLocation Loc,
8562 llvm::Value *Callee,
8563 ArrayRef<llvm::Value *> Args) const {
8564 assert(Loc.isValid() && "Outlined function call location must be valid.");
Alexey Bataev3c595a62017-08-14 15:01:03 +00008565 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
8566
8567 if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008568 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00008569 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008570 return;
8571 }
8572 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00008573 CGF.EmitRuntimeCall(Callee, Args);
8574}
8575
8576void CGOpenMPRuntime::emitOutlinedFunctionCall(
8577 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
8578 ArrayRef<llvm::Value *> Args) const {
Alexey Bataev7ef47a62018-02-22 18:33:31 +00008579 emitCall(CGF, Loc, OutlinedFn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008580}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00008581
8582Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
8583 const VarDecl *NativeParam,
8584 const VarDecl *TargetParam) const {
8585 return CGF.GetAddrOfLocalVar(NativeParam);
8586}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00008587
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00008588Address CGOpenMPRuntime::getAddressOfLocalVariable(CodeGenFunction &CGF,
8589 const VarDecl *VD) {
8590 return Address::invalid();
8591}
8592
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00008593llvm::Value *CGOpenMPSIMDRuntime::emitParallelOutlinedFunction(
8594 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8595 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
8596 llvm_unreachable("Not supported in SIMD-only mode");
8597}
8598
8599llvm::Value *CGOpenMPSIMDRuntime::emitTeamsOutlinedFunction(
8600 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8601 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
8602 llvm_unreachable("Not supported in SIMD-only mode");
8603}
8604
8605llvm::Value *CGOpenMPSIMDRuntime::emitTaskOutlinedFunction(
8606 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8607 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
8608 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
8609 bool Tied, unsigned &NumberOfParts) {
8610 llvm_unreachable("Not supported in SIMD-only mode");
8611}
8612
8613void CGOpenMPSIMDRuntime::emitParallelCall(CodeGenFunction &CGF,
8614 SourceLocation Loc,
8615 llvm::Value *OutlinedFn,
8616 ArrayRef<llvm::Value *> CapturedVars,
8617 const Expr *IfCond) {
8618 llvm_unreachable("Not supported in SIMD-only mode");
8619}
8620
8621void CGOpenMPSIMDRuntime::emitCriticalRegion(
8622 CodeGenFunction &CGF, StringRef CriticalName,
8623 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
8624 const Expr *Hint) {
8625 llvm_unreachable("Not supported in SIMD-only mode");
8626}
8627
8628void CGOpenMPSIMDRuntime::emitMasterRegion(CodeGenFunction &CGF,
8629 const RegionCodeGenTy &MasterOpGen,
8630 SourceLocation Loc) {
8631 llvm_unreachable("Not supported in SIMD-only mode");
8632}
8633
8634void CGOpenMPSIMDRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
8635 SourceLocation Loc) {
8636 llvm_unreachable("Not supported in SIMD-only mode");
8637}
8638
8639void CGOpenMPSIMDRuntime::emitTaskgroupRegion(
8640 CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen,
8641 SourceLocation Loc) {
8642 llvm_unreachable("Not supported in SIMD-only mode");
8643}
8644
8645void CGOpenMPSIMDRuntime::emitSingleRegion(
8646 CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen,
8647 SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars,
8648 ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs,
8649 ArrayRef<const Expr *> AssignmentOps) {
8650 llvm_unreachable("Not supported in SIMD-only mode");
8651}
8652
8653void CGOpenMPSIMDRuntime::emitOrderedRegion(CodeGenFunction &CGF,
8654 const RegionCodeGenTy &OrderedOpGen,
8655 SourceLocation Loc,
8656 bool IsThreads) {
8657 llvm_unreachable("Not supported in SIMD-only mode");
8658}
8659
8660void CGOpenMPSIMDRuntime::emitBarrierCall(CodeGenFunction &CGF,
8661 SourceLocation Loc,
8662 OpenMPDirectiveKind Kind,
8663 bool EmitChecks,
8664 bool ForceSimpleCall) {
8665 llvm_unreachable("Not supported in SIMD-only mode");
8666}
8667
8668void CGOpenMPSIMDRuntime::emitForDispatchInit(
8669 CodeGenFunction &CGF, SourceLocation Loc,
8670 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
8671 bool Ordered, const DispatchRTInput &DispatchValues) {
8672 llvm_unreachable("Not supported in SIMD-only mode");
8673}
8674
8675void CGOpenMPSIMDRuntime::emitForStaticInit(
8676 CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind,
8677 const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values) {
8678 llvm_unreachable("Not supported in SIMD-only mode");
8679}
8680
8681void CGOpenMPSIMDRuntime::emitDistributeStaticInit(
8682 CodeGenFunction &CGF, SourceLocation Loc,
8683 OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values) {
8684 llvm_unreachable("Not supported in SIMD-only mode");
8685}
8686
8687void CGOpenMPSIMDRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
8688 SourceLocation Loc,
8689 unsigned IVSize,
8690 bool IVSigned) {
8691 llvm_unreachable("Not supported in SIMD-only mode");
8692}
8693
8694void CGOpenMPSIMDRuntime::emitForStaticFinish(CodeGenFunction &CGF,
8695 SourceLocation Loc,
8696 OpenMPDirectiveKind DKind) {
8697 llvm_unreachable("Not supported in SIMD-only mode");
8698}
8699
8700llvm::Value *CGOpenMPSIMDRuntime::emitForNext(CodeGenFunction &CGF,
8701 SourceLocation Loc,
8702 unsigned IVSize, bool IVSigned,
8703 Address IL, Address LB,
8704 Address UB, Address ST) {
8705 llvm_unreachable("Not supported in SIMD-only mode");
8706}
8707
8708void CGOpenMPSIMDRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
8709 llvm::Value *NumThreads,
8710 SourceLocation Loc) {
8711 llvm_unreachable("Not supported in SIMD-only mode");
8712}
8713
8714void CGOpenMPSIMDRuntime::emitProcBindClause(CodeGenFunction &CGF,
8715 OpenMPProcBindClauseKind ProcBind,
8716 SourceLocation Loc) {
8717 llvm_unreachable("Not supported in SIMD-only mode");
8718}
8719
8720Address CGOpenMPSIMDRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
8721 const VarDecl *VD,
8722 Address VDAddr,
8723 SourceLocation Loc) {
8724 llvm_unreachable("Not supported in SIMD-only mode");
8725}
8726
8727llvm::Function *CGOpenMPSIMDRuntime::emitThreadPrivateVarDefinition(
8728 const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit,
8729 CodeGenFunction *CGF) {
8730 llvm_unreachable("Not supported in SIMD-only mode");
8731}
8732
8733Address CGOpenMPSIMDRuntime::getAddrOfArtificialThreadPrivate(
8734 CodeGenFunction &CGF, QualType VarType, StringRef Name) {
8735 llvm_unreachable("Not supported in SIMD-only mode");
8736}
8737
8738void CGOpenMPSIMDRuntime::emitFlush(CodeGenFunction &CGF,
8739 ArrayRef<const Expr *> Vars,
8740 SourceLocation Loc) {
8741 llvm_unreachable("Not supported in SIMD-only mode");
8742}
8743
8744void CGOpenMPSIMDRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
8745 const OMPExecutableDirective &D,
8746 llvm::Value *TaskFunction,
8747 QualType SharedsTy, Address Shareds,
8748 const Expr *IfCond,
8749 const OMPTaskDataTy &Data) {
8750 llvm_unreachable("Not supported in SIMD-only mode");
8751}
8752
8753void CGOpenMPSIMDRuntime::emitTaskLoopCall(
8754 CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D,
8755 llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
8756 const Expr *IfCond, const OMPTaskDataTy &Data) {
8757 llvm_unreachable("Not supported in SIMD-only mode");
8758}
8759
8760void CGOpenMPSIMDRuntime::emitReduction(
8761 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
8762 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
8763 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
8764 assert(Options.SimpleReduction && "Only simple reduction is expected.");
8765 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
8766 ReductionOps, Options);
8767}
8768
8769llvm::Value *CGOpenMPSIMDRuntime::emitTaskReductionInit(
8770 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
8771 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
8772 llvm_unreachable("Not supported in SIMD-only mode");
8773}
8774
8775void CGOpenMPSIMDRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
8776 SourceLocation Loc,
8777 ReductionCodeGen &RCG,
8778 unsigned N) {
8779 llvm_unreachable("Not supported in SIMD-only mode");
8780}
8781
8782Address CGOpenMPSIMDRuntime::getTaskReductionItem(CodeGenFunction &CGF,
8783 SourceLocation Loc,
8784 llvm::Value *ReductionsPtr,
8785 LValue SharedLVal) {
8786 llvm_unreachable("Not supported in SIMD-only mode");
8787}
8788
8789void CGOpenMPSIMDRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
8790 SourceLocation Loc) {
8791 llvm_unreachable("Not supported in SIMD-only mode");
8792}
8793
8794void CGOpenMPSIMDRuntime::emitCancellationPointCall(
8795 CodeGenFunction &CGF, SourceLocation Loc,
8796 OpenMPDirectiveKind CancelRegion) {
8797 llvm_unreachable("Not supported in SIMD-only mode");
8798}
8799
8800void CGOpenMPSIMDRuntime::emitCancelCall(CodeGenFunction &CGF,
8801 SourceLocation Loc, const Expr *IfCond,
8802 OpenMPDirectiveKind CancelRegion) {
8803 llvm_unreachable("Not supported in SIMD-only mode");
8804}
8805
8806void CGOpenMPSIMDRuntime::emitTargetOutlinedFunction(
8807 const OMPExecutableDirective &D, StringRef ParentName,
8808 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
8809 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
8810 llvm_unreachable("Not supported in SIMD-only mode");
8811}
8812
8813void CGOpenMPSIMDRuntime::emitTargetCall(CodeGenFunction &CGF,
8814 const OMPExecutableDirective &D,
8815 llvm::Value *OutlinedFn,
8816 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00008817 const Expr *IfCond, const Expr *Device) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00008818 llvm_unreachable("Not supported in SIMD-only mode");
8819}
8820
8821bool CGOpenMPSIMDRuntime::emitTargetFunctions(GlobalDecl GD) {
8822 llvm_unreachable("Not supported in SIMD-only mode");
8823}
8824
8825bool CGOpenMPSIMDRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
8826 llvm_unreachable("Not supported in SIMD-only mode");
8827}
8828
8829bool CGOpenMPSIMDRuntime::emitTargetGlobal(GlobalDecl GD) {
8830 return false;
8831}
8832
8833llvm::Function *CGOpenMPSIMDRuntime::emitRegistrationFunction() {
8834 return nullptr;
8835}
8836
8837void CGOpenMPSIMDRuntime::emitTeamsCall(CodeGenFunction &CGF,
8838 const OMPExecutableDirective &D,
8839 SourceLocation Loc,
8840 llvm::Value *OutlinedFn,
8841 ArrayRef<llvm::Value *> CapturedVars) {
8842 llvm_unreachable("Not supported in SIMD-only mode");
8843}
8844
8845void CGOpenMPSIMDRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
8846 const Expr *NumTeams,
8847 const Expr *ThreadLimit,
8848 SourceLocation Loc) {
8849 llvm_unreachable("Not supported in SIMD-only mode");
8850}
8851
8852void CGOpenMPSIMDRuntime::emitTargetDataCalls(
8853 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8854 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
8855 llvm_unreachable("Not supported in SIMD-only mode");
8856}
8857
8858void CGOpenMPSIMDRuntime::emitTargetDataStandAloneCall(
8859 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8860 const Expr *Device) {
8861 llvm_unreachable("Not supported in SIMD-only mode");
8862}
8863
8864void CGOpenMPSIMDRuntime::emitDoacrossInit(CodeGenFunction &CGF,
8865 const OMPLoopDirective &D) {
8866 llvm_unreachable("Not supported in SIMD-only mode");
8867}
8868
8869void CGOpenMPSIMDRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
8870 const OMPDependClause *C) {
8871 llvm_unreachable("Not supported in SIMD-only mode");
8872}
8873
8874const VarDecl *
8875CGOpenMPSIMDRuntime::translateParameter(const FieldDecl *FD,
8876 const VarDecl *NativeParam) const {
8877 llvm_unreachable("Not supported in SIMD-only mode");
8878}
8879
8880Address
8881CGOpenMPSIMDRuntime::getParameterAddress(CodeGenFunction &CGF,
8882 const VarDecl *NativeParam,
8883 const VarDecl *TargetParam) const {
8884 llvm_unreachable("Not supported in SIMD-only mode");
8885}
8886