blob: 18b51ea0bcc174843f23a47813afa5fe1dbbe140 [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);
Alexey Bataev18fa2322018-05-02 14:20:50 +0000786 std::string Name = CGF.CGM.getOpenMPRuntime().getName({"init"});
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000787 auto *GV = new llvm::GlobalVariable(
788 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
Alexey Bataev18fa2322018-05-02 14:20:50 +0000789 llvm::GlobalValue::PrivateLinkage, Init, Name);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000790 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
791 RValue InitRVal;
792 switch (CGF.getEvaluationKind(Ty)) {
793 case TEK_Scalar:
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000794 InitRVal = CGF.EmitLoadOfLValue(LV, DRD->getLocation());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000795 break;
796 case TEK_Complex:
797 InitRVal =
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000798 RValue::getComplex(CGF.EmitLoadOfComplex(LV, DRD->getLocation()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000799 break;
800 case TEK_Aggregate:
801 InitRVal = RValue::getAggregate(LV.getAddress());
802 break;
803 }
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000804 OpaqueValueExpr OVE(DRD->getLocation(), Ty, VK_RValue);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000805 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
806 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
807 /*IsInitializer=*/false);
808 }
809}
810
811/// \brief Emit initialization of arrays of complex types.
812/// \param DestAddr Address of the array.
813/// \param Type Type of array.
814/// \param Init Initial expression of array.
815/// \param SrcAddr Address of the original array.
816static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
Alexey Bataeva7b19152017-10-12 20:03:39 +0000817 QualType Type, bool EmitDeclareReductionInit,
818 const Expr *Init,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000819 const OMPDeclareReductionDecl *DRD,
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000820 Address SrcAddr = Address::invalid()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000821 // Perform element-by-element initialization.
822 QualType ElementTy;
823
824 // Drill down to the base element type on both arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000825 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
826 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000827 DestAddr =
828 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
829 if (DRD)
830 SrcAddr =
831 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
832
833 llvm::Value *SrcBegin = nullptr;
834 if (DRD)
835 SrcBegin = SrcAddr.getPointer();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000836 llvm::Value *DestBegin = DestAddr.getPointer();
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000837 // Cast from pointer to array type to pointer to single element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000838 llvm::Value *DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000839 // The basic structure here is a while-do loop.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000840 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
841 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
842 llvm::Value *IsEmpty =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000843 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
844 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
845
846 // Enter the loop body, making that address the current address.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000847 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000848 CGF.EmitBlock(BodyBB);
849
850 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
851
852 llvm::PHINode *SrcElementPHI = nullptr;
853 Address SrcElementCurrent = Address::invalid();
854 if (DRD) {
855 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
856 "omp.arraycpy.srcElementPast");
857 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
858 SrcElementCurrent =
859 Address(SrcElementPHI,
860 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
861 }
862 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
863 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
864 DestElementPHI->addIncoming(DestBegin, EntryBB);
865 Address DestElementCurrent =
866 Address(DestElementPHI,
867 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
868
869 // Emit copy.
870 {
871 CodeGenFunction::RunCleanupsScope InitScope(CGF);
Alexey Bataeva7b19152017-10-12 20:03:39 +0000872 if (EmitDeclareReductionInit) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000873 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
874 SrcElementCurrent, ElementTy);
875 } else
876 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
877 /*IsInitializer=*/false);
878 }
879
880 if (DRD) {
881 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000882 llvm::Value *SrcElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000883 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
884 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
885 }
886
887 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000888 llvm::Value *DestElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000889 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
890 // Check whether we've reached the end.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000891 llvm::Value *Done =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000892 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
893 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
894 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
895
896 // Done.
897 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
898}
899
Alexey Bataev92327c52018-03-26 16:40:55 +0000900static llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy>
901isDeclareTargetDeclaration(const ValueDecl *VD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000902 for (const Decl *D : VD->redecls()) {
Alexey Bataev92327c52018-03-26 16:40:55 +0000903 if (!D->hasAttrs())
904 continue;
905 if (const auto *Attr = D->getAttr<OMPDeclareTargetDeclAttr>())
906 return Attr->getMapType();
907 }
Alexey Bataevfb388282018-05-01 14:09:46 +0000908 if (const auto *V = dyn_cast<VarDecl>(VD)) {
909 if (const VarDecl *TD = V->getTemplateInstantiationPattern())
910 return isDeclareTargetDeclaration(TD);
911 } else if (const auto *FD = dyn_cast<FunctionDecl>(VD)) {
912 if (const auto *TD = FD->getTemplateInstantiationPattern())
913 return isDeclareTargetDeclaration(TD);
914 }
915
Alexey Bataev92327c52018-03-26 16:40:55 +0000916 return llvm::None;
917}
918
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000919LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000920 return CGF.EmitOMPSharedLValue(E);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000921}
922
923LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
924 const Expr *E) {
925 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
926 return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
927 return LValue();
928}
929
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000930void ReductionCodeGen::emitAggregateInitialization(
931 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
932 const OMPDeclareReductionDecl *DRD) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000933 // Emit VarDecl with copy init for arrays.
934 // Get the address of the original variable captured in current
935 // captured region.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000936 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000937 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva7b19152017-10-12 20:03:39 +0000938 bool EmitDeclareReductionInit =
939 DRD && (DRD->getInitializer() || !PrivateVD->hasInit());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000940 EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
Alexey Bataeva7b19152017-10-12 20:03:39 +0000941 EmitDeclareReductionInit,
942 EmitDeclareReductionInit ? ClausesData[N].ReductionOp
943 : PrivateVD->getInit(),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000944 DRD, SharedLVal.getAddress());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000945}
946
947ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
948 ArrayRef<const Expr *> Privates,
949 ArrayRef<const Expr *> ReductionOps) {
950 ClausesData.reserve(Shareds.size());
951 SharedAddresses.reserve(Shareds.size());
952 Sizes.reserve(Shareds.size());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000953 BaseDecls.reserve(Shareds.size());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000954 auto IPriv = Privates.begin();
955 auto IRed = ReductionOps.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000956 for (const Expr *Ref : Shareds) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000957 ClausesData.emplace_back(Ref, *IPriv, *IRed);
958 std::advance(IPriv, 1);
959 std::advance(IRed, 1);
960 }
961}
962
963void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
964 assert(SharedAddresses.size() == N &&
965 "Number of generated lvalues must be exactly N.");
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000966 LValue First = emitSharedLValue(CGF, ClausesData[N].Ref);
967 LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Ref);
968 SharedAddresses.emplace_back(First, Second);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000969}
970
971void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000972 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000973 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
974 QualType PrivateType = PrivateVD->getType();
975 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000976 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000977 Sizes.emplace_back(
978 CGF.getTypeSize(
979 SharedAddresses[N].first.getType().getNonReferenceType()),
980 nullptr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000981 return;
982 }
983 llvm::Value *Size;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000984 llvm::Value *SizeInChars;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000985 auto *ElemType =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000986 cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
987 ->getElementType();
988 auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000989 if (AsArraySection) {
990 Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
991 SharedAddresses[N].first.getPointer());
992 Size = CGF.Builder.CreateNUWAdd(
993 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000994 SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000995 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000996 SizeInChars = CGF.getTypeSize(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000997 SharedAddresses[N].first.getType().getNonReferenceType());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000998 Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000999 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001000 Sizes.emplace_back(SizeInChars, Size);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001001 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1002 CGF,
1003 cast<OpaqueValueExpr>(
1004 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
1005 RValue::get(Size));
1006 CGF.EmitVariablyModifiedType(PrivateType);
1007}
1008
1009void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
1010 llvm::Value *Size) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001011 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001012 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1013 QualType PrivateType = PrivateVD->getType();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001014 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001015 assert(!Size && !Sizes[N].second &&
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001016 "Size should be nullptr for non-variably modified reduction "
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001017 "items.");
1018 return;
1019 }
1020 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1021 CGF,
1022 cast<OpaqueValueExpr>(
1023 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
1024 RValue::get(Size));
1025 CGF.EmitVariablyModifiedType(PrivateType);
1026}
1027
1028void ReductionCodeGen::emitInitialization(
1029 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
1030 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
1031 assert(SharedAddresses.size() > N && "No variable was generated");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001032 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001033 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001034 const OMPDeclareReductionDecl *DRD =
1035 getReductionInit(ClausesData[N].ReductionOp);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001036 QualType PrivateType = PrivateVD->getType();
1037 PrivateAddr = CGF.Builder.CreateElementBitCast(
1038 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1039 QualType SharedType = SharedAddresses[N].first.getType();
1040 SharedLVal = CGF.MakeAddrLValue(
1041 CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
1042 CGF.ConvertTypeForMem(SharedType)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001043 SharedType, SharedAddresses[N].first.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001044 CGF.CGM.getTBAAInfoForSubobject(SharedAddresses[N].first, SharedType));
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001045 if (CGF.getContext().getAsArrayType(PrivateVD->getType())) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001046 emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001047 } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
1048 emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
1049 PrivateAddr, SharedLVal.getAddress(),
1050 SharedLVal.getType());
1051 } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
1052 !CGF.isTrivialInitializer(PrivateVD->getInit())) {
1053 CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
1054 PrivateVD->getType().getQualifiers(),
1055 /*IsInitializer=*/false);
1056 }
1057}
1058
1059bool ReductionCodeGen::needCleanups(unsigned N) {
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 return DTorKind != QualType::DK_none;
1065}
1066
1067void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
1068 Address PrivateAddr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001069 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001070 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1071 QualType PrivateType = PrivateVD->getType();
1072 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1073 if (needCleanups(N)) {
1074 PrivateAddr = CGF.Builder.CreateElementBitCast(
1075 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1076 CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
1077 }
1078}
1079
1080static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1081 LValue BaseLV) {
1082 BaseTy = BaseTy.getNonReferenceType();
1083 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1084 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001085 if (const auto *PtrTy = BaseTy->getAs<PointerType>()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001086 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001087 } else {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00001088 LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(), BaseTy);
1089 BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001090 }
1091 BaseTy = BaseTy->getPointeeType();
1092 }
1093 return CGF.MakeAddrLValue(
1094 CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
1095 CGF.ConvertTypeForMem(ElTy)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001096 BaseLV.getType(), BaseLV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001097 CGF.CGM.getTBAAInfoForSubobject(BaseLV, BaseLV.getType()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001098}
1099
1100static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1101 llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
1102 llvm::Value *Addr) {
1103 Address Tmp = Address::invalid();
1104 Address TopTmp = Address::invalid();
1105 Address MostTopTmp = Address::invalid();
1106 BaseTy = BaseTy.getNonReferenceType();
1107 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1108 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1109 Tmp = CGF.CreateMemTemp(BaseTy);
1110 if (TopTmp.isValid())
1111 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
1112 else
1113 MostTopTmp = Tmp;
1114 TopTmp = Tmp;
1115 BaseTy = BaseTy->getPointeeType();
1116 }
1117 llvm::Type *Ty = BaseLVType;
1118 if (Tmp.isValid())
1119 Ty = Tmp.getElementType();
1120 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
1121 if (Tmp.isValid()) {
1122 CGF.Builder.CreateStore(Addr, Tmp);
1123 return MostTopTmp;
1124 }
1125 return Address(Addr, BaseLVAlignment);
1126}
1127
Alexey Bataev1c44e152018-03-06 18:59:43 +00001128static const VarDecl *getBaseDecl(const Expr *Ref, const DeclRefExpr *&DE) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001129 const VarDecl *OrigVD = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001130 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(Ref)) {
1131 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
1132 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001133 Base = TempOASE->getBase()->IgnoreParenImpCasts();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001134 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001135 Base = TempASE->getBase()->IgnoreParenImpCasts();
1136 DE = cast<DeclRefExpr>(Base);
1137 OrigVD = cast<VarDecl>(DE->getDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001138 } else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Ref)) {
1139 const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
1140 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001141 Base = TempASE->getBase()->IgnoreParenImpCasts();
1142 DE = cast<DeclRefExpr>(Base);
1143 OrigVD = cast<VarDecl>(DE->getDecl());
1144 }
Alexey Bataev1c44e152018-03-06 18:59:43 +00001145 return OrigVD;
1146}
1147
1148Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
1149 Address PrivateAddr) {
1150 const DeclRefExpr *DE;
1151 if (const VarDecl *OrigVD = ::getBaseDecl(ClausesData[N].Ref, DE)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001152 BaseDecls.emplace_back(OrigVD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001153 LValue OriginalBaseLValue = CGF.EmitLValue(DE);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001154 LValue BaseLValue =
1155 loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1156 OriginalBaseLValue);
1157 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1158 BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001159 llvm::Value *PrivatePointer =
1160 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1161 PrivateAddr.getPointer(),
1162 SharedAddresses[N].first.getAddress().getType());
1163 llvm::Value *Ptr = CGF.Builder.CreateGEP(PrivatePointer, Adjustment);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001164 return castToBase(CGF, OrigVD->getType(),
1165 SharedAddresses[N].first.getType(),
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001166 OriginalBaseLValue.getAddress().getType(),
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001167 OriginalBaseLValue.getAlignment(), Ptr);
1168 }
1169 BaseDecls.emplace_back(
1170 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1171 return PrivateAddr;
1172}
1173
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001174bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001175 const OMPDeclareReductionDecl *DRD =
1176 getReductionInit(ClausesData[N].ReductionOp);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001177 return DRD && DRD->getInitializer();
1178}
1179
Alexey Bataev18095712014-10-10 12:19:54 +00001180LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00001181 return CGF.EmitLoadOfPointerLValue(
1182 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1183 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +00001184}
1185
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001186void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001187 if (!CGF.HaveInsertPoint())
1188 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001189 // 1.2.2 OpenMP Language Terminology
1190 // Structured block - An executable statement with a single entry at the
1191 // top and a single exit at the bottom.
1192 // The point of exit cannot be a branch out of the structured block.
1193 // longjmp() and throw() must not violate the entry/exit criteria.
1194 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001195 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001196 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001197}
1198
Alexey Bataev62b63b12015-03-10 07:28:44 +00001199LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1200 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001201 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1202 getThreadIDVariable()->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00001203 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001204}
1205
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001206static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
1207 QualType FieldTy) {
1208 auto *Field = FieldDecl::Create(
1209 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
1210 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
1211 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
1212 Field->setAccess(AS_public);
1213 DC->addDecl(Field);
1214 return Field;
1215}
1216
Alexey Bataev18fa2322018-05-02 14:20:50 +00001217CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM, StringRef FirstSeparator,
1218 StringRef Separator)
1219 : CGM(CGM), FirstSeparator(FirstSeparator), Separator(Separator),
1220 OffloadEntriesInfoManager(CGM) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001221 ASTContext &C = CGM.getContext();
1222 RecordDecl *RD = C.buildImplicitRecord("ident_t");
1223 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1224 RD->startDefinition();
1225 // reserved_1
1226 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1227 // flags
1228 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1229 // reserved_2
1230 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1231 // reserved_3
1232 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1233 // psource
1234 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
1235 RD->completeDefinition();
1236 IdentQTy = C.getRecordType(RD);
1237 IdentTy = CGM.getTypes().ConvertRecordDeclType(RD);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001238 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +00001239
1240 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +00001241}
1242
Alexey Bataev91797552015-03-18 04:13:55 +00001243void CGOpenMPRuntime::clear() {
1244 InternalVars.clear();
1245}
1246
Alexey Bataev18fa2322018-05-02 14:20:50 +00001247std::string CGOpenMPRuntime::getName(ArrayRef<StringRef> Parts) const {
1248 SmallString<128> Buffer;
1249 llvm::raw_svector_ostream OS(Buffer);
1250 StringRef Sep = FirstSeparator;
1251 for (StringRef Part : Parts) {
1252 OS << Sep << Part;
1253 Sep = Separator;
1254 }
1255 return OS.str();
1256}
1257
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001258static llvm::Function *
1259emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1260 const Expr *CombinerInitializer, const VarDecl *In,
1261 const VarDecl *Out, bool IsCombiner) {
1262 // void .omp_combiner.(Ty *in, Ty *out);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001263 ASTContext &C = CGM.getContext();
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001264 QualType PtrTy = C.getPointerType(Ty).withRestrict();
1265 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001266 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001267 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001268 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001269 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001270 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001271 Args.push_back(&OmpInParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001272 const CGFunctionInfo &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001273 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001274 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00001275 std::string Name = CGM.getOpenMPRuntime().getName(
1276 {IsCombiner ? "omp_combiner" : "omp_initializer", ""});
1277 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
1278 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001279 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001280 Fn->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001281 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001282 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001283 CodeGenFunction CGF(CGM);
1284 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1285 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001286 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, In->getLocation(),
1287 Out->getLocation());
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001288 CodeGenFunction::OMPPrivateScope Scope(CGF);
1289 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001290 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001291 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1292 .getAddress();
1293 });
1294 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001295 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001296 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1297 .getAddress();
1298 });
1299 (void)Scope.Privatize();
Alexey Bataev070f43a2017-09-06 14:49:58 +00001300 if (!IsCombiner && Out->hasInit() &&
1301 !CGF.isTrivialInitializer(Out->getInit())) {
1302 CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
1303 Out->getType().getQualifiers(),
1304 /*IsInitializer=*/true);
1305 }
1306 if (CombinerInitializer)
1307 CGF.EmitIgnoredExpr(CombinerInitializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001308 Scope.ForceCleanup();
1309 CGF.FinishFunction();
1310 return Fn;
1311}
1312
1313void CGOpenMPRuntime::emitUserDefinedReduction(
1314 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1315 if (UDRMap.count(D) > 0)
1316 return;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001317 ASTContext &C = CGM.getContext();
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001318 if (!In || !Out) {
1319 In = &C.Idents.get("omp_in");
1320 Out = &C.Idents.get("omp_out");
1321 }
1322 llvm::Function *Combiner = emitCombinerOrInitializer(
1323 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
1324 cast<VarDecl>(D->lookup(Out).front()),
1325 /*IsCombiner=*/true);
1326 llvm::Function *Initializer = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001327 if (const Expr *Init = D->getInitializer()) {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001328 if (!Priv || !Orig) {
1329 Priv = &C.Idents.get("omp_priv");
1330 Orig = &C.Idents.get("omp_orig");
1331 }
1332 Initializer = emitCombinerOrInitializer(
Alexey Bataev070f43a2017-09-06 14:49:58 +00001333 CGM, D->getType(),
1334 D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init
1335 : nullptr,
1336 cast<VarDecl>(D->lookup(Orig).front()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001337 cast<VarDecl>(D->lookup(Priv).front()),
1338 /*IsCombiner=*/false);
1339 }
Alexey Bataev43a919f2018-04-13 17:48:43 +00001340 UDRMap.try_emplace(D, Combiner, Initializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001341 if (CGF) {
1342 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1343 Decls.second.push_back(D);
1344 }
1345}
1346
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001347std::pair<llvm::Function *, llvm::Function *>
1348CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1349 auto I = UDRMap.find(D);
1350 if (I != UDRMap.end())
1351 return I->second;
1352 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1353 return UDRMap.lookup(D);
1354}
1355
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001356static llvm::Value *emitParallelOrTeamsOutlinedFunction(
1357 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1358 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1359 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001360 assert(ThreadIDVar->getType()->isPointerType() &&
1361 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +00001362 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00001363 bool HasCancel = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001364 if (const auto *OPD = dyn_cast<OMPParallelDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001365 HasCancel = OPD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001366 else if (const auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001367 HasCancel = OPSD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001368 else if (const auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001369 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001370 else if (const auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D))
Alexey Bataev2139ed62017-11-16 18:20:21 +00001371 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001372 else if (const auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&D))
Alexey Bataev10a54312017-11-27 16:54:08 +00001373 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001374 else if (const auto *OPFD =
1375 dyn_cast<OMPTeamsDistributeParallelForDirective>(&D))
Alexey Bataev10a54312017-11-27 16:54:08 +00001376 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001377 else if (const auto *OPFD =
Alexey Bataev10a54312017-11-27 16:54:08 +00001378 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D))
1379 HasCancel = OPFD->hasCancel();
Alexey Bataev25e5b442015-09-15 12:52:43 +00001380 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001381 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +00001382 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001383 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +00001384}
1385
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001386llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
1387 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1388 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1389 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1390 return emitParallelOrTeamsOutlinedFunction(
1391 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1392}
1393
1394llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1395 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1396 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1397 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1398 return emitParallelOrTeamsOutlinedFunction(
1399 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1400}
1401
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001402llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
1403 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +00001404 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1405 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1406 bool Tied, unsigned &NumberOfParts) {
1407 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1408 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001409 llvm::Value *ThreadID = getThreadID(CGF, D.getLocStart());
1410 llvm::Value *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
Alexey Bataev48591dd2016-04-20 04:01:36 +00001411 llvm::Value *TaskArgs[] = {
1412 UpLoc, ThreadID,
1413 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1414 TaskTVar->getType()->castAs<PointerType>())
1415 .getPointer()};
1416 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1417 };
1418 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1419 UntiedCodeGen);
1420 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001421 assert(!ThreadIDVar->getType()->isPointerType() &&
1422 "thread id variable must be of type kmp_int32 for tasks");
Alexey Bataev475a7442018-01-12 19:39:11 +00001423 const OpenMPDirectiveKind Region =
1424 isOpenMPTaskLoopDirective(D.getDirectiveKind()) ? OMPD_taskloop
1425 : OMPD_task;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001426 const CapturedStmt *CS = D.getCapturedStmt(Region);
1427 const auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001428 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +00001429 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1430 InnermostKind,
1431 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +00001432 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001433 llvm::Value *Res = CGF.GenerateCapturedStmtFunction(*CS);
Alexey Bataev48591dd2016-04-20 04:01:36 +00001434 if (!Tied)
1435 NumberOfParts = Action.getNumberOfParts();
1436 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001437}
1438
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001439static void buildStructValue(ConstantStructBuilder &Fields, CodeGenModule &CGM,
1440 const RecordDecl *RD, const CGRecordLayout &RL,
1441 ArrayRef<llvm::Constant *> Data) {
1442 llvm::StructType *StructTy = RL.getLLVMType();
1443 unsigned PrevIdx = 0;
1444 ConstantInitBuilder CIBuilder(CGM);
1445 auto DI = Data.begin();
1446 for (const FieldDecl *FD : RD->fields()) {
1447 unsigned Idx = RL.getLLVMFieldNo(FD);
1448 // Fill the alignment.
1449 for (unsigned I = PrevIdx; I < Idx; ++I)
1450 Fields.add(llvm::Constant::getNullValue(StructTy->getElementType(I)));
1451 PrevIdx = Idx + 1;
1452 Fields.add(*DI);
1453 ++DI;
1454 }
1455}
1456
1457template <class... As>
1458static llvm::GlobalVariable *
1459createConstantGlobalStruct(CodeGenModule &CGM, QualType Ty,
1460 ArrayRef<llvm::Constant *> Data, const Twine &Name,
1461 As &&... Args) {
1462 const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1463 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1464 ConstantInitBuilder CIBuilder(CGM);
1465 ConstantStructBuilder Fields = CIBuilder.beginStruct(RL.getLLVMType());
1466 buildStructValue(Fields, CGM, RD, RL, Data);
1467 return Fields.finishAndCreateGlobal(
1468 Name, CGM.getContext().getAlignOfGlobalVarInChars(Ty),
1469 /*isConstant=*/true, std::forward<As>(Args)...);
1470}
1471
1472template <typename T>
1473void createConstantGlobalStructAndAddToParent(CodeGenModule &CGM, QualType Ty,
1474 ArrayRef<llvm::Constant *> Data,
1475 T &Parent) {
1476 const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1477 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1478 ConstantStructBuilder Fields = Parent.beginStruct(RL.getLLVMType());
1479 buildStructValue(Fields, CGM, RD, RL, Data);
1480 Fields.finishAndAddTo(Parent);
1481}
1482
Alexey Bataev50b3c952016-02-19 10:38:26 +00001483Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001484 CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
Alexey Bataev15007ba2014-05-07 06:18:01 +00001485 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +00001486 if (!Entry) {
1487 if (!DefaultOpenMPPSource) {
1488 // Initialize default location for psource field of ident_t structure of
1489 // all ident_t objects. Format is ";file;function;line;column;;".
1490 // Taken from
1491 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1492 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +00001493 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001494 DefaultOpenMPPSource =
1495 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1496 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001497
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001498 llvm::Constant *Data[] = {llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1499 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
1500 llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1501 llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1502 DefaultOpenMPPSource};
1503 llvm::GlobalValue *DefaultOpenMPLocation = createConstantGlobalStruct(
1504 CGM, IdentQTy, Data, "", llvm::GlobalValue::PrivateLinkage);
1505 DefaultOpenMPLocation->setUnnamedAddr(
1506 llvm::GlobalValue::UnnamedAddr::Global);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001507
John McCall7f416cc2015-09-08 08:05:57 +00001508 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +00001509 }
John McCall7f416cc2015-09-08 08:05:57 +00001510 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +00001511}
1512
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001513llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1514 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001515 unsigned Flags) {
1516 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +00001517 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001518 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +00001519 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +00001520 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001521
1522 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1523
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001524 CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
John McCall7f416cc2015-09-08 08:05:57 +00001525 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001526 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1527 if (I != OpenMPLocThreadIDMap.end())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001528 LocValue = Address(I->second.DebugLoc, Align);
John McCall7f416cc2015-09-08 08:05:57 +00001529
Alexander Musmanc6388682014-12-15 07:07:06 +00001530 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1531 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +00001532 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +00001533 // Generate "ident_t .kmpc_loc.addr;"
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001534 Address AI = CGF.CreateMemTemp(IdentQTy, ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +00001535 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +00001536 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001537 LocValue = AI;
1538
1539 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1540 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001541 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001542 CGF.getTypeSize(IdentQTy));
Alexey Bataev9959db52014-05-06 10:08:46 +00001543 }
1544
1545 // char **psource = &.kmpc_loc_<flags>.addr.psource;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001546 LValue Base = CGF.MakeAddrLValue(LocValue, IdentQTy);
1547 auto Fields = cast<RecordDecl>(IdentQTy->getAsTagDecl())->field_begin();
1548 LValue PSource =
1549 CGF.EmitLValueForField(Base, *std::next(Fields, IdentField_PSource));
Alexey Bataev9959db52014-05-06 10:08:46 +00001550
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001551 llvm::Value *OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
Alexey Bataevf002aca2014-05-30 05:48:40 +00001552 if (OMPDebugLoc == nullptr) {
1553 SmallString<128> Buffer2;
1554 llvm::raw_svector_ostream OS2(Buffer2);
1555 // Build debug location
1556 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1557 OS2 << ";" << PLoc.getFilename() << ";";
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001558 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl))
Alexey Bataevf002aca2014-05-30 05:48:40 +00001559 OS2 << FD->getQualifiedNameAsString();
Alexey Bataevf002aca2014-05-30 05:48:40 +00001560 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1561 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1562 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +00001563 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001564 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001565 CGF.EmitStoreOfScalar(OMPDebugLoc, PSource);
Alexey Bataevf002aca2014-05-30 05:48:40 +00001566
John McCall7f416cc2015-09-08 08:05:57 +00001567 // Our callers always pass this to a runtime function, so for
1568 // convenience, go ahead and return a naked pointer.
1569 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001570}
1571
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001572llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1573 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001574 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1575
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001576 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001577 // Check whether we've already cached a load of the thread id in this
1578 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001579 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001580 if (I != OpenMPLocThreadIDMap.end()) {
1581 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001582 if (ThreadID != nullptr)
1583 return ThreadID;
1584 }
Alexey Bataevaee18552017-08-16 14:01:00 +00001585 // If exceptions are enabled, do not use parameter to avoid possible crash.
Alexey Bataev5d2c9a42017-11-02 18:55:05 +00001586 if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions ||
1587 !CGF.getLangOpts().CXXExceptions ||
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001588 CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
Alexey Bataevaee18552017-08-16 14:01:00 +00001589 if (auto *OMPRegionInfo =
1590 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1591 if (OMPRegionInfo->getThreadIDVariable()) {
1592 // Check if this an outlined function with thread id passed as argument.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001593 LValue LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev1e491372018-01-23 18:44:14 +00001594 ThreadID = CGF.EmitLoadOfScalar(LVal, Loc);
Alexey Bataevaee18552017-08-16 14:01:00 +00001595 // If value loaded in entry block, cache it and use it everywhere in
1596 // function.
1597 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1598 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1599 Elem.second.ThreadID = ThreadID;
1600 }
1601 return ThreadID;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001602 }
Alexey Bataevd6c57552014-07-25 07:55:17 +00001603 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001604 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001605
1606 // This is not an outlined function region - need to call __kmpc_int32
1607 // kmpc_global_thread_num(ident_t *loc).
1608 // Generate thread id value and cache this value for use across the
1609 // function.
1610 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1611 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001612 llvm::CallInst *Call = CGF.Builder.CreateCall(
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001613 createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1614 emitUpdateLocation(CGF, Loc));
1615 Call->setCallingConv(CGF.getRuntimeCC());
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001616 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001617 Elem.second.ThreadID = Call;
1618 return Call;
Alexey Bataev9959db52014-05-06 10:08:46 +00001619}
1620
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001621void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001622 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001623 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1624 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001625 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001626 for(auto *D : FunctionUDRMap[CGF.CurFn])
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001627 UDRMap.erase(D);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001628 FunctionUDRMap.erase(CGF.CurFn);
1629 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001630}
1631
1632llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001633 return IdentTy->getPointerTo();
Alexey Bataev9959db52014-05-06 10:08:46 +00001634}
1635
1636llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001637 if (!Kmpc_MicroTy) {
1638 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1639 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1640 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1641 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1642 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001643 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1644}
1645
1646llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001647CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001648 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001649 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001650 case OMPRTL__kmpc_fork_call: {
1651 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1652 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001653 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1654 getKmpc_MicroPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001655 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001656 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001657 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1658 break;
1659 }
1660 case OMPRTL__kmpc_global_thread_num: {
1661 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001662 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001663 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001664 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001665 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1666 break;
1667 }
Alexey Bataev97720002014-11-11 04:05:39 +00001668 case OMPRTL__kmpc_threadprivate_cached: {
1669 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1670 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1671 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1672 CGM.VoidPtrTy, CGM.SizeTy,
1673 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001674 auto *FnTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001675 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1676 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1677 break;
1678 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001679 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001680 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1681 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001682 llvm::Type *TypeParams[] = {
1683 getIdentTyPointerTy(), CGM.Int32Ty,
1684 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001685 auto *FnTy =
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001686 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1687 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1688 break;
1689 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001690 case OMPRTL__kmpc_critical_with_hint: {
1691 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1692 // kmp_critical_name *crit, uintptr_t hint);
1693 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1694 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1695 CGM.IntPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001696 auto *FnTy =
Alexey Bataevfc57d162015-12-15 10:55:09 +00001697 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1698 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1699 break;
1700 }
Alexey Bataev97720002014-11-11 04:05:39 +00001701 case OMPRTL__kmpc_threadprivate_register: {
1702 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1703 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1704 // typedef void *(*kmpc_ctor)(void *);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001705 auto *KmpcCtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001706 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1707 /*isVarArg*/ false)->getPointerTo();
1708 // typedef void *(*kmpc_cctor)(void *, void *);
1709 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001710 auto *KmpcCopyCtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001711 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001712 /*isVarArg*/ false)
1713 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00001714 // typedef void (*kmpc_dtor)(void *);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001715 auto *KmpcDtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001716 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1717 ->getPointerTo();
1718 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1719 KmpcCopyCtorTy, KmpcDtorTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001720 auto *FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
Alexey Bataev97720002014-11-11 04:05:39 +00001721 /*isVarArg*/ false);
1722 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1723 break;
1724 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001725 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001726 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1727 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001728 llvm::Type *TypeParams[] = {
1729 getIdentTyPointerTy(), CGM.Int32Ty,
1730 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001731 auto *FnTy =
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001732 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1733 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1734 break;
1735 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001736 case OMPRTL__kmpc_cancel_barrier: {
1737 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1738 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001739 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001740 auto *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001741 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1742 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001743 break;
1744 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001745 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001746 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001747 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001748 auto *FnTy =
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001749 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1750 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1751 break;
1752 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001753 case OMPRTL__kmpc_for_static_fini: {
1754 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1755 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001756 auto *FnTy =
Alexander Musmanc6388682014-12-15 07:07:06 +00001757 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1758 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1759 break;
1760 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001761 case OMPRTL__kmpc_push_num_threads: {
1762 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1763 // kmp_int32 num_threads)
1764 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1765 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001766 auto *FnTy =
Alexey Bataevb2059782014-10-13 08:23:51 +00001767 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1768 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1769 break;
1770 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001771 case OMPRTL__kmpc_serialized_parallel: {
1772 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1773 // global_tid);
1774 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001775 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001776 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1777 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1778 break;
1779 }
1780 case OMPRTL__kmpc_end_serialized_parallel: {
1781 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1782 // global_tid);
1783 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001784 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001785 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1786 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1787 break;
1788 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001789 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001790 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001791 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001792 auto *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001793 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001794 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1795 break;
1796 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001797 case OMPRTL__kmpc_master: {
1798 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1799 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001800 auto *FnTy =
Alexey Bataev8d690652014-12-04 07:23:53 +00001801 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1802 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1803 break;
1804 }
1805 case OMPRTL__kmpc_end_master: {
1806 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1807 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001808 auto *FnTy =
Alexey Bataev8d690652014-12-04 07:23:53 +00001809 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1810 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1811 break;
1812 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001813 case OMPRTL__kmpc_omp_taskyield: {
1814 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1815 // int end_part);
1816 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001817 auto *FnTy =
Alexey Bataev9f797f32015-02-05 05:57:51 +00001818 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1819 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1820 break;
1821 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001822 case OMPRTL__kmpc_single: {
1823 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1824 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001825 auto *FnTy =
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001826 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1827 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1828 break;
1829 }
1830 case OMPRTL__kmpc_end_single: {
1831 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1832 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001833 auto *FnTy =
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001834 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1835 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1836 break;
1837 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001838 case OMPRTL__kmpc_omp_task_alloc: {
1839 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1840 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1841 // kmp_routine_entry_t *task_entry);
1842 assert(KmpRoutineEntryPtrTy != nullptr &&
1843 "Type kmp_routine_entry_t must be created.");
1844 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1845 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1846 // Return void * and then cast to particular kmp_task_t type.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001847 auto *FnTy =
Alexey Bataev62b63b12015-03-10 07:28:44 +00001848 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1849 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1850 break;
1851 }
1852 case OMPRTL__kmpc_omp_task: {
1853 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1854 // *new_task);
1855 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1856 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001857 auto *FnTy =
Alexey Bataev62b63b12015-03-10 07:28:44 +00001858 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1859 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1860 break;
1861 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001862 case OMPRTL__kmpc_copyprivate: {
1863 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001864 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001865 // kmp_int32 didit);
1866 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1867 auto *CpyFnTy =
1868 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001869 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001870 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1871 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001872 auto *FnTy =
Alexey Bataeva63048e2015-03-23 06:18:07 +00001873 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1874 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1875 break;
1876 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001877 case OMPRTL__kmpc_reduce: {
1878 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1879 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1880 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1881 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1882 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1883 /*isVarArg=*/false);
1884 llvm::Type *TypeParams[] = {
1885 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1886 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1887 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001888 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001889 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1890 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1891 break;
1892 }
1893 case OMPRTL__kmpc_reduce_nowait: {
1894 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1895 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1896 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1897 // *lck);
1898 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1899 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1900 /*isVarArg=*/false);
1901 llvm::Type *TypeParams[] = {
1902 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1903 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1904 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001905 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001906 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1907 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1908 break;
1909 }
1910 case OMPRTL__kmpc_end_reduce: {
1911 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1912 // kmp_critical_name *lck);
1913 llvm::Type *TypeParams[] = {
1914 getIdentTyPointerTy(), CGM.Int32Ty,
1915 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001916 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001917 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1918 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1919 break;
1920 }
1921 case OMPRTL__kmpc_end_reduce_nowait: {
1922 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1923 // kmp_critical_name *lck);
1924 llvm::Type *TypeParams[] = {
1925 getIdentTyPointerTy(), CGM.Int32Ty,
1926 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001927 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001928 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1929 RTLFn =
1930 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1931 break;
1932 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001933 case OMPRTL__kmpc_omp_task_begin_if0: {
1934 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1935 // *new_task);
1936 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1937 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001938 auto *FnTy =
Alexey Bataev1d677132015-04-22 13:57:31 +00001939 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1940 RTLFn =
1941 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1942 break;
1943 }
1944 case OMPRTL__kmpc_omp_task_complete_if0: {
1945 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1946 // *new_task);
1947 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1948 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001949 auto *FnTy =
Alexey Bataev1d677132015-04-22 13:57:31 +00001950 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1951 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1952 /*Name=*/"__kmpc_omp_task_complete_if0");
1953 break;
1954 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001955 case OMPRTL__kmpc_ordered: {
1956 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1957 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001958 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001959 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1960 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1961 break;
1962 }
1963 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001964 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001965 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001966 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001967 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1968 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1969 break;
1970 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001971 case OMPRTL__kmpc_omp_taskwait: {
1972 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1973 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001974 auto *FnTy =
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001975 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1976 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1977 break;
1978 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001979 case OMPRTL__kmpc_taskgroup: {
1980 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1981 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001982 auto *FnTy =
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001983 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1984 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1985 break;
1986 }
1987 case OMPRTL__kmpc_end_taskgroup: {
1988 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1989 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001990 auto *FnTy =
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001991 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1992 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1993 break;
1994 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001995 case OMPRTL__kmpc_push_proc_bind: {
1996 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1997 // int proc_bind)
1998 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001999 auto *FnTy =
Alexey Bataev7f210c62015-06-18 13:40:03 +00002000 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2001 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
2002 break;
2003 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002004 case OMPRTL__kmpc_omp_task_with_deps: {
2005 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
2006 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
2007 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
2008 llvm::Type *TypeParams[] = {
2009 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
2010 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002011 auto *FnTy =
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002012 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
2013 RTLFn =
2014 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
2015 break;
2016 }
2017 case OMPRTL__kmpc_omp_wait_deps: {
2018 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
2019 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
2020 // kmp_depend_info_t *noalias_dep_list);
2021 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2022 CGM.Int32Ty, CGM.VoidPtrTy,
2023 CGM.Int32Ty, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002024 auto *FnTy =
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002025 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2026 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
2027 break;
2028 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00002029 case OMPRTL__kmpc_cancellationpoint: {
2030 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
2031 // global_tid, kmp_int32 cncl_kind)
2032 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002033 auto *FnTy =
Alexey Bataev0f34da12015-07-02 04:17:07 +00002034 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2035 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
2036 break;
2037 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002038 case OMPRTL__kmpc_cancel: {
2039 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
2040 // kmp_int32 cncl_kind)
2041 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002042 auto *FnTy =
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002043 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2044 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
2045 break;
2046 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002047 case OMPRTL__kmpc_push_num_teams: {
2048 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
2049 // kmp_int32 num_teams, kmp_int32 num_threads)
2050 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
2051 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002052 auto *FnTy =
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002053 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2054 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
2055 break;
2056 }
2057 case OMPRTL__kmpc_fork_teams: {
2058 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
2059 // microtask, ...);
2060 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2061 getKmpc_MicroPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002062 auto *FnTy =
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002063 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
2064 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
2065 break;
2066 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002067 case OMPRTL__kmpc_taskloop: {
2068 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
2069 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
2070 // sched, kmp_uint64 grainsize, void *task_dup);
2071 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2072 CGM.IntTy,
2073 CGM.VoidPtrTy,
2074 CGM.IntTy,
2075 CGM.Int64Ty->getPointerTo(),
2076 CGM.Int64Ty->getPointerTo(),
2077 CGM.Int64Ty,
2078 CGM.IntTy,
2079 CGM.IntTy,
2080 CGM.Int64Ty,
2081 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002082 auto *FnTy =
Alexey Bataev7292c292016-04-25 12:22:29 +00002083 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2084 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
2085 break;
2086 }
Alexey Bataev8b427062016-05-25 12:36:08 +00002087 case OMPRTL__kmpc_doacross_init: {
2088 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
2089 // num_dims, struct kmp_dim *dims);
2090 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2091 CGM.Int32Ty,
2092 CGM.Int32Ty,
2093 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002094 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002095 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2096 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
2097 break;
2098 }
2099 case OMPRTL__kmpc_doacross_fini: {
2100 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
2101 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002102 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002103 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2104 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
2105 break;
2106 }
2107 case OMPRTL__kmpc_doacross_post: {
2108 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
2109 // *vec);
2110 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2111 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002112 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002113 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2114 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
2115 break;
2116 }
2117 case OMPRTL__kmpc_doacross_wait: {
2118 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
2119 // *vec);
2120 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2121 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002122 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002123 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2124 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
2125 break;
2126 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002127 case OMPRTL__kmpc_task_reduction_init: {
2128 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
2129 // *data);
2130 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002131 auto *FnTy =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002132 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2133 RTLFn =
2134 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
2135 break;
2136 }
2137 case OMPRTL__kmpc_task_reduction_get_th_data: {
2138 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
2139 // *d);
2140 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002141 auto *FnTy =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002142 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2143 RTLFn = CGM.CreateRuntimeFunction(
2144 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2145 break;
2146 }
Samuel Antaobed3c462015-10-02 16:14:20 +00002147 case OMPRTL__tgt_target: {
George Rokos63bc9d62017-11-21 18:25:12 +00002148 // Build int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
2149 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Samuel Antaobed3c462015-10-02 16:14:20 +00002150 // *arg_types);
George Rokos63bc9d62017-11-21 18:25:12 +00002151 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaobed3c462015-10-02 16:14:20 +00002152 CGM.VoidPtrTy,
2153 CGM.Int32Ty,
2154 CGM.VoidPtrPtrTy,
2155 CGM.VoidPtrPtrTy,
2156 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002157 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002158 auto *FnTy =
Samuel Antaobed3c462015-10-02 16:14:20 +00002159 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2160 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2161 break;
2162 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002163 case OMPRTL__tgt_target_nowait: {
2164 // Build int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
2165 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2166 // int64_t *arg_types);
2167 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2168 CGM.VoidPtrTy,
2169 CGM.Int32Ty,
2170 CGM.VoidPtrPtrTy,
2171 CGM.VoidPtrPtrTy,
2172 CGM.SizeTy->getPointerTo(),
2173 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002174 auto *FnTy =
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002175 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2176 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_nowait");
2177 break;
2178 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00002179 case OMPRTL__tgt_target_teams: {
George Rokos63bc9d62017-11-21 18:25:12 +00002180 // Build int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002181 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
George Rokos63bc9d62017-11-21 18:25:12 +00002182 // int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2183 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002184 CGM.VoidPtrTy,
2185 CGM.Int32Ty,
2186 CGM.VoidPtrPtrTy,
2187 CGM.VoidPtrPtrTy,
2188 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002189 CGM.Int64Ty->getPointerTo(),
Samuel Antaob68e2db2016-03-03 16:20:23 +00002190 CGM.Int32Ty,
2191 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002192 auto *FnTy =
Samuel Antaob68e2db2016-03-03 16:20:23 +00002193 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2194 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2195 break;
2196 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002197 case OMPRTL__tgt_target_teams_nowait: {
2198 // Build int32_t __tgt_target_teams_nowait(int64_t device_id, void
2199 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
2200 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2201 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2202 CGM.VoidPtrTy,
2203 CGM.Int32Ty,
2204 CGM.VoidPtrPtrTy,
2205 CGM.VoidPtrPtrTy,
2206 CGM.SizeTy->getPointerTo(),
2207 CGM.Int64Ty->getPointerTo(),
2208 CGM.Int32Ty,
2209 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002210 auto *FnTy =
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002211 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2212 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams_nowait");
2213 break;
2214 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002215 case OMPRTL__tgt_register_lib: {
2216 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2217 QualType ParamTy =
2218 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2219 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002220 auto *FnTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002221 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2222 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2223 break;
2224 }
2225 case OMPRTL__tgt_unregister_lib: {
2226 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2227 QualType ParamTy =
2228 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2229 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002230 auto *FnTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002231 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2232 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2233 break;
2234 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002235 case OMPRTL__tgt_target_data_begin: {
George Rokos63bc9d62017-11-21 18:25:12 +00002236 // Build void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
2237 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2238 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002239 CGM.Int32Ty,
2240 CGM.VoidPtrPtrTy,
2241 CGM.VoidPtrPtrTy,
2242 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002243 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002244 auto *FnTy =
Samuel Antaodf158d52016-04-27 22:58:19 +00002245 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2246 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2247 break;
2248 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002249 case OMPRTL__tgt_target_data_begin_nowait: {
2250 // Build void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
2251 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2252 // *arg_types);
2253 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2254 CGM.Int32Ty,
2255 CGM.VoidPtrPtrTy,
2256 CGM.VoidPtrPtrTy,
2257 CGM.SizeTy->getPointerTo(),
2258 CGM.Int64Ty->getPointerTo()};
2259 auto *FnTy =
2260 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2261 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin_nowait");
2262 break;
2263 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002264 case OMPRTL__tgt_target_data_end: {
George Rokos63bc9d62017-11-21 18:25:12 +00002265 // Build void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
2266 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2267 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002268 CGM.Int32Ty,
2269 CGM.VoidPtrPtrTy,
2270 CGM.VoidPtrPtrTy,
2271 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002272 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002273 auto *FnTy =
Samuel Antaodf158d52016-04-27 22:58:19 +00002274 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2275 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2276 break;
2277 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002278 case OMPRTL__tgt_target_data_end_nowait: {
2279 // Build void __tgt_target_data_end_nowait(int64_t device_id, int32_t
2280 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2281 // *arg_types);
2282 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2283 CGM.Int32Ty,
2284 CGM.VoidPtrPtrTy,
2285 CGM.VoidPtrPtrTy,
2286 CGM.SizeTy->getPointerTo(),
2287 CGM.Int64Ty->getPointerTo()};
2288 auto *FnTy =
2289 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2290 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end_nowait");
2291 break;
2292 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002293 case OMPRTL__tgt_target_data_update: {
George Rokos63bc9d62017-11-21 18:25:12 +00002294 // Build void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
2295 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2296 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antao8d2d7302016-05-26 18:30:22 +00002297 CGM.Int32Ty,
2298 CGM.VoidPtrPtrTy,
2299 CGM.VoidPtrPtrTy,
2300 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002301 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002302 auto *FnTy =
Samuel Antao8d2d7302016-05-26 18:30:22 +00002303 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2304 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2305 break;
2306 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002307 case OMPRTL__tgt_target_data_update_nowait: {
2308 // Build void __tgt_target_data_update_nowait(int64_t device_id, int32_t
2309 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2310 // *arg_types);
2311 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2312 CGM.Int32Ty,
2313 CGM.VoidPtrPtrTy,
2314 CGM.VoidPtrPtrTy,
2315 CGM.SizeTy->getPointerTo(),
2316 CGM.Int64Ty->getPointerTo()};
2317 auto *FnTy =
2318 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2319 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update_nowait");
2320 break;
2321 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002322 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002323 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002324 return RTLFn;
2325}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002326
Alexander Musman21212e42015-03-13 10:38:23 +00002327llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2328 bool IVSigned) {
2329 assert((IVSize == 32 || IVSize == 64) &&
2330 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002331 StringRef Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2332 : "__kmpc_for_static_init_4u")
2333 : (IVSigned ? "__kmpc_for_static_init_8"
2334 : "__kmpc_for_static_init_8u");
2335 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2336 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
Alexander Musman21212e42015-03-13 10:38:23 +00002337 llvm::Type *TypeParams[] = {
2338 getIdentTyPointerTy(), // loc
2339 CGM.Int32Ty, // tid
2340 CGM.Int32Ty, // schedtype
2341 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2342 PtrTy, // p_lower
2343 PtrTy, // p_upper
2344 PtrTy, // p_stride
2345 ITy, // incr
2346 ITy // chunk
2347 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002348 auto *FnTy =
Alexander Musman21212e42015-03-13 10:38:23 +00002349 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2350 return CGM.CreateRuntimeFunction(FnTy, Name);
2351}
2352
Alexander Musman92bdaab2015-03-12 13:37:50 +00002353llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2354 bool IVSigned) {
2355 assert((IVSize == 32 || IVSize == 64) &&
2356 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002357 StringRef Name =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002358 IVSize == 32
2359 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2360 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002361 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
Alexander Musman92bdaab2015-03-12 13:37:50 +00002362 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2363 CGM.Int32Ty, // tid
2364 CGM.Int32Ty, // schedtype
2365 ITy, // lower
2366 ITy, // upper
2367 ITy, // stride
2368 ITy // chunk
2369 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002370 auto *FnTy =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002371 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2372 return CGM.CreateRuntimeFunction(FnTy, Name);
2373}
2374
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002375llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2376 bool IVSigned) {
2377 assert((IVSize == 32 || IVSize == 64) &&
2378 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002379 StringRef Name =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002380 IVSize == 32
2381 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2382 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2383 llvm::Type *TypeParams[] = {
2384 getIdentTyPointerTy(), // loc
2385 CGM.Int32Ty, // tid
2386 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002387 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002388 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2389 return CGM.CreateRuntimeFunction(FnTy, Name);
2390}
2391
Alexander Musman92bdaab2015-03-12 13:37:50 +00002392llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2393 bool IVSigned) {
2394 assert((IVSize == 32 || IVSize == 64) &&
2395 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002396 StringRef Name =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002397 IVSize == 32
2398 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2399 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002400 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2401 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002402 llvm::Type *TypeParams[] = {
2403 getIdentTyPointerTy(), // loc
2404 CGM.Int32Ty, // tid
2405 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2406 PtrTy, // p_lower
2407 PtrTy, // p_upper
2408 PtrTy // p_stride
2409 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002410 auto *FnTy =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002411 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2412 return CGM.CreateRuntimeFunction(FnTy, Name);
2413}
2414
Alexey Bataev03f270c2018-03-30 18:31:07 +00002415Address CGOpenMPRuntime::getAddrOfDeclareTargetLink(const VarDecl *VD) {
2416 if (CGM.getLangOpts().OpenMPSimd)
2417 return Address::invalid();
Alexey Bataev92327c52018-03-26 16:40:55 +00002418 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2419 isDeclareTargetDeclaration(VD);
2420 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2421 SmallString<64> PtrName;
2422 {
2423 llvm::raw_svector_ostream OS(PtrName);
2424 OS << CGM.getMangledName(GlobalDecl(VD)) << "_decl_tgt_link_ptr";
2425 }
2426 llvm::Value *Ptr = CGM.getModule().getNamedValue(PtrName);
2427 if (!Ptr) {
2428 QualType PtrTy = CGM.getContext().getPointerType(VD->getType());
2429 Ptr = getOrCreateInternalVariable(CGM.getTypes().ConvertTypeForMem(PtrTy),
2430 PtrName);
Alexey Bataev03f270c2018-03-30 18:31:07 +00002431 if (!CGM.getLangOpts().OpenMPIsDevice) {
2432 auto *GV = cast<llvm::GlobalVariable>(Ptr);
2433 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2434 GV->setInitializer(CGM.GetAddrOfGlobal(VD));
2435 }
2436 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ptr));
2437 registerTargetGlobalVariable(VD, cast<llvm::Constant>(Ptr));
Alexey Bataev92327c52018-03-26 16:40:55 +00002438 }
2439 return Address(Ptr, CGM.getContext().getDeclAlign(VD));
2440 }
2441 return Address::invalid();
2442}
2443
Alexey Bataev97720002014-11-11 04:05:39 +00002444llvm::Constant *
2445CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002446 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2447 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002448 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev18fa2322018-05-02 14:20:50 +00002449 std::string Suffix = getName({"cache", ""});
2450 return getOrCreateInternalVariable(
2451 CGM.Int8PtrPtrTy, Twine(CGM.getMangledName(VD)).concat(Suffix));
Alexey Bataev97720002014-11-11 04:05:39 +00002452}
2453
John McCall7f416cc2015-09-08 08:05:57 +00002454Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2455 const VarDecl *VD,
2456 Address VDAddr,
2457 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002458 if (CGM.getLangOpts().OpenMPUseTLS &&
2459 CGM.getContext().getTargetInfo().isTLSSupported())
2460 return VDAddr;
2461
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002462 llvm::Type *VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002463 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002464 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2465 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002466 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2467 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002468 return Address(CGF.EmitRuntimeCall(
2469 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2470 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002471}
2472
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002473void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002474 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002475 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2476 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2477 // library.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002478 llvm::Value *OMPLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002479 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002480 OMPLoc);
2481 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2482 // to register constructor/destructor for variable.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002483 llvm::Value *Args[] = {
2484 OMPLoc, CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.VoidPtrTy),
2485 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002486 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002487 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002488}
2489
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002490llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002491 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002492 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002493 if (CGM.getLangOpts().OpenMPUseTLS &&
2494 CGM.getContext().getTargetInfo().isTLSSupported())
2495 return nullptr;
2496
Alexey Bataev97720002014-11-11 04:05:39 +00002497 VD = VD->getDefinition(CGM.getContext());
2498 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
2499 ThreadPrivateWithDefinition.insert(VD);
2500 QualType ASTTy = VD->getType();
2501
2502 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002503 const Expr *Init = VD->getAnyInitializer();
Alexey Bataev97720002014-11-11 04:05:39 +00002504 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2505 // Generate function that re-emits the declaration's initializer into the
2506 // threadprivate copy of the variable VD
2507 CodeGenFunction CtorCGF(CGM);
2508 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002509 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2510 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002511 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002512 Args.push_back(&Dst);
2513
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002514 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
John McCallc56a8b32016-03-11 04:30:31 +00002515 CGM.getContext().VoidPtrTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002516 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002517 std::string Name = getName({"__kmpc_global_ctor_", ""});
2518 llvm::Function *Fn =
2519 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002520 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002521 Args, Loc, Loc);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002522 llvm::Value *ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002523 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002524 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002525 Address Arg = Address(ArgVal, VDAddr.getAlignment());
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002526 Arg = CtorCGF.Builder.CreateElementBitCast(
2527 Arg, CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002528 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2529 /*IsInitializer=*/true);
2530 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002531 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002532 CGM.getContext().VoidPtrTy, Dst.getLocation());
2533 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2534 CtorCGF.FinishFunction();
2535 Ctor = Fn;
2536 }
2537 if (VD->getType().isDestructedType() != QualType::DK_none) {
2538 // Generate function that emits destructor call for the threadprivate copy
2539 // of the variable VD
2540 CodeGenFunction DtorCGF(CGM);
2541 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002542 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2543 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002544 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002545 Args.push_back(&Dst);
2546
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002547 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
John McCallc56a8b32016-03-11 04:30:31 +00002548 CGM.getContext().VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002549 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002550 std::string Name = getName({"__kmpc_global_dtor_", ""});
2551 llvm::Function *Fn =
2552 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002553 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002554 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002555 Loc, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002556 // Create a scope with an artificial location for the body of this function.
2557 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002558 llvm::Value *ArgVal = DtorCGF.EmitLoadOfScalar(
Alexey Bataev97720002014-11-11 04:05:39 +00002559 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002560 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2561 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002562 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2563 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2564 DtorCGF.FinishFunction();
2565 Dtor = Fn;
2566 }
2567 // Do not emit init function if it is not required.
2568 if (!Ctor && !Dtor)
2569 return nullptr;
2570
2571 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002572 auto *CopyCtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2573 /*isVarArg=*/false)
2574 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002575 // Copying constructor for the threadprivate variable.
2576 // Must be NULL - reserved by runtime, but currently it requires that this
2577 // parameter is always NULL. Otherwise it fires assertion.
2578 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2579 if (Ctor == nullptr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002580 auto *CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2581 /*isVarArg=*/false)
2582 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002583 Ctor = llvm::Constant::getNullValue(CtorTy);
2584 }
2585 if (Dtor == nullptr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002586 auto *DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2587 /*isVarArg=*/false)
2588 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002589 Dtor = llvm::Constant::getNullValue(DtorTy);
2590 }
2591 if (!CGF) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002592 auto *InitFunctionTy =
Alexey Bataev97720002014-11-11 04:05:39 +00002593 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002594 std::string Name = getName({"__omp_threadprivate_init_", ""});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002595 llvm::Function *InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Alexey Bataev18fa2322018-05-02 14:20:50 +00002596 InitFunctionTy, Name, CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002597 CodeGenFunction InitCGF(CGM);
2598 FunctionArgList ArgList;
2599 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2600 CGM.getTypes().arrangeNullaryFunction(), ArgList,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002601 Loc, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002602 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002603 InitCGF.FinishFunction();
2604 return InitFunction;
2605 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002606 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002607 }
2608 return nullptr;
2609}
2610
Alexey Bataev34f8a702018-03-28 14:28:54 +00002611/// \brief Obtain information that uniquely identifies a target entry. This
2612/// consists of the file and device IDs as well as line number associated with
2613/// the relevant entry source location.
2614static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
2615 unsigned &DeviceID, unsigned &FileID,
2616 unsigned &LineNum) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002617 SourceManager &SM = C.getSourceManager();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002618
2619 // The loc should be always valid and have a file ID (the user cannot use
2620 // #pragma directives in macros)
2621
2622 assert(Loc.isValid() && "Source location is expected to be always valid.");
Alexey Bataev34f8a702018-03-28 14:28:54 +00002623
2624 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
2625 assert(PLoc.isValid() && "Source location is expected to be always valid.");
2626
2627 llvm::sys::fs::UniqueID ID;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00002628 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
2629 SM.getDiagnostics().Report(diag::err_cannot_open_file)
2630 << PLoc.getFilename() << EC.message();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002631
2632 DeviceID = ID.getDevice();
2633 FileID = ID.getFile();
2634 LineNum = PLoc.getLine();
2635}
2636
2637bool CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD,
2638 llvm::GlobalVariable *Addr,
2639 bool PerformInit) {
2640 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2641 isDeclareTargetDeclaration(VD);
2642 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link)
2643 return false;
2644 VD = VD->getDefinition(CGM.getContext());
2645 if (VD && !DeclareTargetWithDefinition.insert(VD).second)
2646 return CGM.getLangOpts().OpenMPIsDevice;
2647
2648 QualType ASTTy = VD->getType();
2649
2650 SourceLocation Loc = VD->getCanonicalDecl()->getLocStart();
2651 // Produce the unique prefix to identify the new target regions. We use
2652 // the source location of the variable declaration which we know to not
2653 // conflict with any target region.
2654 unsigned DeviceID;
2655 unsigned FileID;
2656 unsigned Line;
2657 getTargetEntryUniqueInfo(CGM.getContext(), Loc, DeviceID, FileID, Line);
2658 SmallString<128> Buffer, Out;
2659 {
2660 llvm::raw_svector_ostream OS(Buffer);
2661 OS << "__omp_offloading_" << llvm::format("_%x", DeviceID)
2662 << llvm::format("_%x_", FileID) << VD->getName() << "_l" << Line;
2663 }
2664
2665 const Expr *Init = VD->getAnyInitializer();
2666 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2667 llvm::Constant *Ctor;
2668 llvm::Constant *ID;
2669 if (CGM.getLangOpts().OpenMPIsDevice) {
2670 // Generate function that re-emits the declaration's initializer into
2671 // the threadprivate copy of the variable VD
2672 CodeGenFunction CtorCGF(CGM);
2673
2674 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2675 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2676 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2677 FTy, Twine(Buffer, "_ctor"), FI, Loc);
2678 auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF);
2679 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2680 FunctionArgList(), Loc, Loc);
2681 auto AL = ApplyDebugLocation::CreateArtificial(CtorCGF);
2682 CtorCGF.EmitAnyExprToMem(Init,
2683 Address(Addr, CGM.getContext().getDeclAlign(VD)),
2684 Init->getType().getQualifiers(),
2685 /*IsInitializer=*/true);
2686 CtorCGF.FinishFunction();
2687 Ctor = Fn;
2688 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
2689 } else {
2690 Ctor = new llvm::GlobalVariable(
2691 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2692 llvm::GlobalValue::PrivateLinkage,
2693 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_ctor"));
2694 ID = Ctor;
2695 }
2696
2697 // Register the information for the entry associated with the constructor.
2698 Out.clear();
2699 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2700 DeviceID, FileID, Twine(Buffer, "_ctor").toStringRef(Out), Line, Ctor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002701 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryCtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002702 }
2703 if (VD->getType().isDestructedType() != QualType::DK_none) {
2704 llvm::Constant *Dtor;
2705 llvm::Constant *ID;
2706 if (CGM.getLangOpts().OpenMPIsDevice) {
2707 // Generate function that emits destructor call for the threadprivate
2708 // copy of the variable VD
2709 CodeGenFunction DtorCGF(CGM);
2710
2711 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2712 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2713 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2714 FTy, Twine(Buffer, "_dtor"), FI, Loc);
2715 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
2716 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2717 FunctionArgList(), Loc, Loc);
2718 // Create a scope with an artificial location for the body of this
2719 // function.
2720 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
2721 DtorCGF.emitDestroy(Address(Addr, CGM.getContext().getDeclAlign(VD)),
2722 ASTTy, DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2723 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2724 DtorCGF.FinishFunction();
2725 Dtor = Fn;
2726 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
2727 } else {
2728 Dtor = new llvm::GlobalVariable(
2729 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2730 llvm::GlobalValue::PrivateLinkage,
2731 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_dtor"));
2732 ID = Dtor;
2733 }
2734 // Register the information for the entry associated with the destructor.
2735 Out.clear();
2736 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2737 DeviceID, FileID, Twine(Buffer, "_dtor").toStringRef(Out), Line, Dtor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002738 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryDtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002739 }
2740 return CGM.getLangOpts().OpenMPIsDevice;
2741}
2742
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002743Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2744 QualType VarType,
2745 StringRef Name) {
Alexey Bataev18fa2322018-05-02 14:20:50 +00002746 std::string Suffix = getName({"artificial", ""});
2747 std::string CacheSuffix = getName({"cache", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002748 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002749 llvm::Value *GAddr =
2750 getOrCreateInternalVariable(VarLVType, Twine(Name).concat(Suffix));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002751 llvm::Value *Args[] = {
2752 emitUpdateLocation(CGF, SourceLocation()),
2753 getThreadID(CGF, SourceLocation()),
2754 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2755 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2756 /*IsSigned=*/false),
Alexey Bataev18fa2322018-05-02 14:20:50 +00002757 getOrCreateInternalVariable(
2758 CGM.VoidPtrPtrTy, Twine(Name).concat(Suffix).concat(CacheSuffix))};
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002759 return Address(
2760 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2761 CGF.EmitRuntimeCall(
2762 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2763 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2764 CGM.getPointerAlign());
2765}
2766
Alexey Bataev1d677132015-04-22 13:57:31 +00002767/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
2768/// function. Here is the logic:
2769/// if (Cond) {
2770/// ThenGen();
2771/// } else {
2772/// ElseGen();
2773/// }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002774void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2775 const RegionCodeGenTy &ThenGen,
2776 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002777 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2778
2779 // If the condition constant folds and can be elided, try to avoid emitting
2780 // the condition and the dead arm of the if/else.
2781 bool CondConstant;
2782 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002783 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002784 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002785 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002786 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002787 return;
2788 }
2789
2790 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2791 // emit the conditional branch.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002792 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("omp_if.then");
2793 llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else");
2794 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("omp_if.end");
Alexey Bataev1d677132015-04-22 13:57:31 +00002795 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2796
2797 // Emit the 'then' code.
2798 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002799 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002800 CGF.EmitBranch(ContBlock);
2801 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002802 // There is no need to emit line number for unconditional branch.
2803 (void)ApplyDebugLocation::CreateEmpty(CGF);
2804 CGF.EmitBlock(ElseBlock);
2805 ElseGen(CGF);
2806 // There is no need to emit line number for unconditional branch.
2807 (void)ApplyDebugLocation::CreateEmpty(CGF);
2808 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002809 // Emit the continuation block for code after the if.
2810 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002811}
2812
Alexey Bataev1d677132015-04-22 13:57:31 +00002813void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2814 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002815 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002816 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002817 if (!CGF.HaveInsertPoint())
2818 return;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002819 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002820 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2821 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002822 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002823 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002824 llvm::Value *Args[] = {
2825 RTLoc,
2826 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002827 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002828 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2829 RealArgs.append(std::begin(Args), std::end(Args));
2830 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2831
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002832 llvm::Value *RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002833 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2834 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002835 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2836 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002837 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
2838 llvm::Value *ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00002839 // Build calls:
2840 // __kmpc_serialized_parallel(&Loc, GTid);
2841 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002842 CGF.EmitRuntimeCall(
2843 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002844
Alexey Bataev1d677132015-04-22 13:57:31 +00002845 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002846 Address ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002847 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2848 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00002849 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00002850 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2851 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2852 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2853 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002854 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002855
Alexey Bataev1d677132015-04-22 13:57:31 +00002856 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002857 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00002858 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002859 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2860 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002861 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002862 if (IfCond) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002863 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002864 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002865 RegionCodeGenTy ThenRCG(ThenGen);
2866 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002867 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002868}
2869
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002870// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002871// thread-ID variable (it is passed in a first argument of the outlined function
2872// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2873// regular serial code region, get thread ID by calling kmp_int32
2874// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2875// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002876Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2877 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002878 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002879 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002880 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002881 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002882
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002883 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2884 QualType Int32Ty =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002885 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002886 Address ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
Alexey Bataevd74d0602014-10-13 06:02:40 +00002887 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002888 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002889
2890 return ThreadIDTemp;
2891}
2892
Alexey Bataev97720002014-11-11 04:05:39 +00002893llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002894CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002895 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002896 SmallString<256> Buffer;
2897 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002898 Out << Name;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002899 StringRef RuntimeName = Out.str();
Alexey Bataev43a919f2018-04-13 17:48:43 +00002900 auto &Elem = *InternalVars.try_emplace(RuntimeName, nullptr).first;
David Blaikie13156b62014-11-19 03:06:06 +00002901 if (Elem.second) {
2902 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002903 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002904 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002905 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002906
David Blaikie13156b62014-11-19 03:06:06 +00002907 return Elem.second = new llvm::GlobalVariable(
2908 CGM.getModule(), Ty, /*IsConstant*/ false,
2909 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2910 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002911}
2912
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002913llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev18fa2322018-05-02 14:20:50 +00002914 std::string Prefix = Twine("gomp_critical_user_", CriticalName).str();
2915 std::string Name = getName({Prefix, "var"});
2916 return getOrCreateInternalVariable(KmpCriticalNameTy, Name);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002917}
2918
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002919namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002920/// Common pre(post)-action for different OpenMP constructs.
2921class CommonActionTy final : public PrePostActionTy {
2922 llvm::Value *EnterCallee;
2923 ArrayRef<llvm::Value *> EnterArgs;
2924 llvm::Value *ExitCallee;
2925 ArrayRef<llvm::Value *> ExitArgs;
2926 bool Conditional;
2927 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002928
2929public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002930 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2931 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2932 bool Conditional = false)
2933 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2934 ExitArgs(ExitArgs), Conditional(Conditional) {}
2935 void Enter(CodeGenFunction &CGF) override {
2936 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2937 if (Conditional) {
2938 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2939 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2940 ContBlock = CGF.createBasicBlock("omp_if.end");
2941 // Generate the branch (If-stmt)
2942 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2943 CGF.EmitBlock(ThenBlock);
2944 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002945 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002946 void Done(CodeGenFunction &CGF) {
2947 // Emit the rest of blocks/branches
2948 CGF.EmitBranch(ContBlock);
2949 CGF.EmitBlock(ContBlock, true);
2950 }
2951 void Exit(CodeGenFunction &CGF) override {
2952 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002953 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002954};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002955} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002956
2957void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2958 StringRef CriticalName,
2959 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002960 SourceLocation Loc, const Expr *Hint) {
2961 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002962 // CriticalOpGen();
2963 // __kmpc_end_critical(ident_t *, gtid, Lock);
2964 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002965 if (!CGF.HaveInsertPoint())
2966 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002967 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2968 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002969 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2970 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002971 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002972 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2973 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2974 }
2975 CommonActionTy Action(
2976 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2977 : OMPRTL__kmpc_critical),
2978 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2979 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002980 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002981}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002982
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002983void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002984 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002985 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002986 if (!CGF.HaveInsertPoint())
2987 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002988 // if(__kmpc_master(ident_t *, gtid)) {
2989 // MasterOpGen();
2990 // __kmpc_end_master(ident_t *, gtid);
2991 // }
2992 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002993 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002994 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2995 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2996 /*Conditional=*/true);
2997 MasterOpGen.setAction(Action);
2998 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2999 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00003000}
3001
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003002void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
3003 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003004 if (!CGF.HaveInsertPoint())
3005 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00003006 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
3007 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003008 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00003009 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003010 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003011 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
3012 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00003013}
3014
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003015void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
3016 const RegionCodeGenTy &TaskgroupOpGen,
3017 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003018 if (!CGF.HaveInsertPoint())
3019 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003020 // __kmpc_taskgroup(ident_t *, gtid);
3021 // TaskgroupOpGen();
3022 // __kmpc_end_taskgroup(ident_t *, gtid);
3023 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003024 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3025 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
3026 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
3027 Args);
3028 TaskgroupOpGen.setAction(Action);
3029 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003030}
3031
John McCall7f416cc2015-09-08 08:05:57 +00003032/// Given an array of pointers to variables, project the address of a
3033/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003034static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
3035 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00003036 // Pull out the pointer to the variable.
3037 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003038 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00003039 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
3040
3041 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003042 Addr = CGF.Builder.CreateElementBitCast(
3043 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00003044 return Addr;
3045}
3046
Alexey Bataeva63048e2015-03-23 06:18:07 +00003047static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00003048 CodeGenModule &CGM, llvm::Type *ArgsType,
3049 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003050 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps,
3051 SourceLocation Loc) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003052 ASTContext &C = CGM.getContext();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003053 // void copy_func(void *LHSArg, void *RHSArg);
3054 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003055 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3056 ImplicitParamDecl::Other);
3057 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3058 ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003059 Args.push_back(&LHSArg);
3060 Args.push_back(&RHSArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003061 const auto &CGFI =
3062 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003063 std::string Name =
3064 CGM.getOpenMPRuntime().getName({"omp", "copyprivate", "copy_func"});
3065 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
3066 llvm::GlobalValue::InternalLinkage, Name,
3067 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003068 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003069 Fn->setDoesNotRecurse();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003070 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003071 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00003072 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003073 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00003074 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3075 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
3076 ArgsType), CGF.getPointerAlign());
3077 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3078 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
3079 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00003080 // *(Type0*)Dst[0] = *(Type0*)Src[0];
3081 // *(Type1*)Dst[1] = *(Type1*)Src[1];
3082 // ...
3083 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00003084 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003085 const auto *DestVar =
3086 cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003087 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
3088
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003089 const auto *SrcVar =
3090 cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003091 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
3092
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003093 const auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003094 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00003095 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003096 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00003097 CGF.FinishFunction();
3098 return Fn;
3099}
3100
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003101void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003102 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00003103 SourceLocation Loc,
3104 ArrayRef<const Expr *> CopyprivateVars,
3105 ArrayRef<const Expr *> SrcExprs,
3106 ArrayRef<const Expr *> DstExprs,
3107 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003108 if (!CGF.HaveInsertPoint())
3109 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00003110 assert(CopyprivateVars.size() == SrcExprs.size() &&
3111 CopyprivateVars.size() == DstExprs.size() &&
3112 CopyprivateVars.size() == AssignmentOps.size());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003113 ASTContext &C = CGM.getContext();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003114 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003115 // if(__kmpc_single(ident_t *, gtid)) {
3116 // SingleOpGen();
3117 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003118 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003119 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00003120 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3121 // <copy_func>, did_it);
3122
John McCall7f416cc2015-09-08 08:05:57 +00003123 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003124 if (!CopyprivateVars.empty()) {
3125 // int32 did_it = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003126 QualType KmpInt32Ty =
3127 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003128 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00003129 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003130 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003131 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00003132 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003133 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
3134 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
3135 /*Conditional=*/true);
3136 SingleOpGen.setAction(Action);
3137 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
3138 if (DidIt.isValid()) {
3139 // did_it = 1;
3140 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
3141 }
3142 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003143 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3144 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00003145 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00003146 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003147 QualType CopyprivateArrayTy =
Alexey Bataeva63048e2015-03-23 06:18:07 +00003148 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3149 /*IndexTypeQuals=*/0);
3150 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00003151 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00003152 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
3153 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00003154 Address Elem = CGF.Builder.CreateConstArrayGEP(
3155 CopyprivateList, I, CGF.getPointerSize());
3156 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00003157 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003158 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
3159 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003160 }
3161 // Build function that copies private values from single region to all other
3162 // threads in the corresponding parallel region.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003163 llvm::Value *CpyFn = emitCopyprivateCopyFunction(
Alexey Bataeva63048e2015-03-23 06:18:07 +00003164 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003165 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps, Loc);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003166 llvm::Value *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00003167 Address CL =
3168 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
3169 CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003170 llvm::Value *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003171 llvm::Value *Args[] = {
3172 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
3173 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00003174 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00003175 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00003176 CpyFn, // void (*) (void *, void *) <copy_func>
3177 DidItVal // i32 did_it
3178 };
3179 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
3180 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003181}
3182
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003183void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
3184 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00003185 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003186 if (!CGF.HaveInsertPoint())
3187 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003188 // __kmpc_ordered(ident_t *, gtid);
3189 // OrderedOpGen();
3190 // __kmpc_end_ordered(ident_t *, gtid);
3191 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00003192 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003193 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003194 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
3195 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
3196 Args);
3197 OrderedOpGen.setAction(Action);
3198 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
3199 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003200 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003201 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003202}
3203
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003204void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00003205 OpenMPDirectiveKind Kind, bool EmitChecks,
3206 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003207 if (!CGF.HaveInsertPoint())
3208 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00003209 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003210 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003211 unsigned Flags;
3212 if (Kind == OMPD_for)
3213 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
3214 else if (Kind == OMPD_sections)
3215 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
3216 else if (Kind == OMPD_single)
3217 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
3218 else if (Kind == OMPD_barrier)
3219 Flags = OMP_IDENT_BARRIER_EXPL;
3220 else
3221 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003222 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
3223 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003224 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
3225 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003226 if (auto *OMPRegionInfo =
3227 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00003228 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003229 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003230 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00003231 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003232 // if (__kmpc_cancel_barrier()) {
3233 // exit from construct;
3234 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003235 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
3236 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
3237 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003238 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
3239 CGF.EmitBlock(ExitBB);
3240 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003241 CodeGenFunction::JumpDest CancelDestination =
Alexey Bataev25e5b442015-09-15 12:52:43 +00003242 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003243 CGF.EmitBranchThroughCleanup(CancelDestination);
3244 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
3245 }
3246 return;
3247 }
3248 }
3249 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00003250}
3251
Alexander Musmanc6388682014-12-15 07:07:06 +00003252/// \brief Map the OpenMP loop schedule to the runtime enumeration.
3253static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003254 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003255 switch (ScheduleKind) {
3256 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003257 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
3258 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00003259 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003260 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003261 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003262 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003263 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003264 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
3265 case OMPC_SCHEDULE_auto:
3266 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00003267 case OMPC_SCHEDULE_unknown:
3268 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003269 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00003270 }
3271 llvm_unreachable("Unexpected runtime schedule");
3272}
3273
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003274/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
3275static OpenMPSchedType
3276getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
3277 // only static is allowed for dist_schedule
3278 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
3279}
3280
Alexander Musmanc6388682014-12-15 07:07:06 +00003281bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
3282 bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003283 OpenMPSchedType Schedule =
3284 getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00003285 return Schedule == OMP_sch_static;
3286}
3287
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003288bool CGOpenMPRuntime::isStaticNonchunked(
3289 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003290 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003291 return Schedule == OMP_dist_sch_static;
3292}
3293
3294
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003295bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003296 OpenMPSchedType Schedule =
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003297 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003298 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
3299 return Schedule != OMP_sch_static;
3300}
3301
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003302static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
3303 OpenMPScheduleClauseModifier M1,
3304 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00003305 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003306 switch (M1) {
3307 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003308 Modifier = OMP_sch_modifier_monotonic;
3309 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003310 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003311 Modifier = OMP_sch_modifier_nonmonotonic;
3312 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003313 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003314 if (Schedule == OMP_sch_static_chunked)
3315 Schedule = OMP_sch_static_balanced_chunked;
3316 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003317 case OMPC_SCHEDULE_MODIFIER_last:
3318 case OMPC_SCHEDULE_MODIFIER_unknown:
3319 break;
3320 }
3321 switch (M2) {
3322 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003323 Modifier = OMP_sch_modifier_monotonic;
3324 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003325 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003326 Modifier = OMP_sch_modifier_nonmonotonic;
3327 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003328 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003329 if (Schedule == OMP_sch_static_chunked)
3330 Schedule = OMP_sch_static_balanced_chunked;
3331 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003332 case OMPC_SCHEDULE_MODIFIER_last:
3333 case OMPC_SCHEDULE_MODIFIER_unknown:
3334 break;
3335 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00003336 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003337}
3338
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003339void CGOpenMPRuntime::emitForDispatchInit(
3340 CodeGenFunction &CGF, SourceLocation Loc,
3341 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
3342 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003343 if (!CGF.HaveInsertPoint())
3344 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003345 OpenMPSchedType Schedule = getRuntimeSchedule(
3346 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00003347 assert(Ordered ||
3348 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00003349 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
3350 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00003351 // Call __kmpc_dispatch_init(
3352 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
3353 // kmp_int[32|64] lower, kmp_int[32|64] upper,
3354 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00003355
John McCall7f416cc2015-09-08 08:05:57 +00003356 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003357 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
3358 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00003359 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003360 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3361 CGF.Builder.getInt32(addMonoNonMonoModifier(
3362 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003363 DispatchValues.LB, // Lower
3364 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003365 CGF.Builder.getIntN(IVSize, 1), // Stride
3366 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00003367 };
3368 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
3369}
3370
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003371static void emitForStaticInitCall(
3372 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
3373 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
3374 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003375 const CGOpenMPRuntime::StaticRTInput &Values) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003376 if (!CGF.HaveInsertPoint())
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003377 return;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003378
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003379 assert(!Values.Ordered);
3380 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
3381 Schedule == OMP_sch_static_balanced_chunked ||
3382 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
3383 Schedule == OMP_dist_sch_static ||
3384 Schedule == OMP_dist_sch_static_chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003385
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003386 // Call __kmpc_for_static_init(
3387 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
3388 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
3389 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
3390 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
3391 llvm::Value *Chunk = Values.Chunk;
3392 if (Chunk == nullptr) {
3393 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
3394 Schedule == OMP_dist_sch_static) &&
3395 "expected static non-chunked schedule");
3396 // If the Chunk was not specified in the clause - use default value 1.
3397 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3398 } else {
3399 assert((Schedule == OMP_sch_static_chunked ||
3400 Schedule == OMP_sch_static_balanced_chunked ||
3401 Schedule == OMP_ord_static_chunked ||
3402 Schedule == OMP_dist_sch_static_chunked) &&
3403 "expected static chunked schedule");
3404 }
3405 llvm::Value *Args[] = {
3406 UpdateLocation,
3407 ThreadId,
3408 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3409 M2)), // Schedule type
3410 Values.IL.getPointer(), // &isLastIter
3411 Values.LB.getPointer(), // &LB
3412 Values.UB.getPointer(), // &UB
3413 Values.ST.getPointer(), // &Stride
3414 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3415 Chunk // Chunk
3416 };
3417 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003418}
3419
John McCall7f416cc2015-09-08 08:05:57 +00003420void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3421 SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003422 OpenMPDirectiveKind DKind,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003423 const OpenMPScheduleTy &ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003424 const StaticRTInput &Values) {
3425 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3426 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3427 assert(isOpenMPWorksharingDirective(DKind) &&
3428 "Expected loop-based or sections-based directive.");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003429 llvm::Value *UpdatedLocation = emitUpdateLocation(CGF, Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003430 isOpenMPLoopDirective(DKind)
3431 ? OMP_IDENT_WORK_LOOP
3432 : OMP_IDENT_WORK_SECTIONS);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003433 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3434 llvm::Constant *StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003435 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003436 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003437 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003438}
John McCall7f416cc2015-09-08 08:05:57 +00003439
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003440void CGOpenMPRuntime::emitDistributeStaticInit(
3441 CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003442 OpenMPDistScheduleClauseKind SchedKind,
3443 const CGOpenMPRuntime::StaticRTInput &Values) {
3444 OpenMPSchedType ScheduleNum =
3445 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003446 llvm::Value *UpdatedLocation =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003447 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003448 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3449 llvm::Constant *StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003450 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003451 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3452 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003453 OMPC_SCHEDULE_MODIFIER_unknown, Values);
Alexander Musmanc6388682014-12-15 07:07:06 +00003454}
3455
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003456void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
Alexey Bataevf43f7142017-09-06 16:17:35 +00003457 SourceLocation Loc,
3458 OpenMPDirectiveKind DKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003459 if (!CGF.HaveInsertPoint())
3460 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003461 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataevf43f7142017-09-06 16:17:35 +00003462 llvm::Value *Args[] = {
3463 emitUpdateLocation(CGF, Loc,
3464 isOpenMPDistributeDirective(DKind)
3465 ? OMP_IDENT_WORK_DISTRIBUTE
3466 : isOpenMPLoopDirective(DKind)
3467 ? OMP_IDENT_WORK_LOOP
3468 : OMP_IDENT_WORK_SECTIONS),
3469 getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003470 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3471 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003472}
3473
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003474void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3475 SourceLocation Loc,
3476 unsigned IVSize,
3477 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003478 if (!CGF.HaveInsertPoint())
3479 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003480 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003481 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003482 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3483}
3484
Alexander Musman92bdaab2015-03-12 13:37:50 +00003485llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3486 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003487 bool IVSigned, Address IL,
3488 Address LB, Address UB,
3489 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003490 // Call __kmpc_dispatch_next(
3491 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3492 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3493 // kmp_int[32|64] *p_stride);
3494 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003495 emitUpdateLocation(CGF, Loc),
3496 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003497 IL.getPointer(), // &isLastIter
3498 LB.getPointer(), // &Lower
3499 UB.getPointer(), // &Upper
3500 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003501 };
3502 llvm::Value *Call =
3503 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3504 return CGF.EmitScalarConversion(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003505 Call, CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/1),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003506 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003507}
3508
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003509void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3510 llvm::Value *NumThreads,
3511 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003512 if (!CGF.HaveInsertPoint())
3513 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003514 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3515 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003516 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003517 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003518 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3519 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003520}
3521
Alexey Bataev7f210c62015-06-18 13:40:03 +00003522void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3523 OpenMPProcBindClauseKind ProcBind,
3524 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003525 if (!CGF.HaveInsertPoint())
3526 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003527 // Constants for proc bind value accepted by the runtime.
3528 enum ProcBindTy {
3529 ProcBindFalse = 0,
3530 ProcBindTrue,
3531 ProcBindMaster,
3532 ProcBindClose,
3533 ProcBindSpread,
3534 ProcBindIntel,
3535 ProcBindDefault
3536 } RuntimeProcBind;
3537 switch (ProcBind) {
3538 case OMPC_PROC_BIND_master:
3539 RuntimeProcBind = ProcBindMaster;
3540 break;
3541 case OMPC_PROC_BIND_close:
3542 RuntimeProcBind = ProcBindClose;
3543 break;
3544 case OMPC_PROC_BIND_spread:
3545 RuntimeProcBind = ProcBindSpread;
3546 break;
3547 case OMPC_PROC_BIND_unknown:
3548 llvm_unreachable("Unsupported proc_bind value.");
3549 }
3550 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3551 llvm::Value *Args[] = {
3552 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3553 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3554 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3555}
3556
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003557void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3558 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003559 if (!CGF.HaveInsertPoint())
3560 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003561 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003562 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3563 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003564}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003565
Alexey Bataev62b63b12015-03-10 07:28:44 +00003566namespace {
3567/// \brief Indexes of fields for type kmp_task_t.
3568enum KmpTaskTFields {
3569 /// \brief List of shared variables.
3570 KmpTaskTShareds,
3571 /// \brief Task routine.
3572 KmpTaskTRoutine,
3573 /// \brief Partition id for the untied tasks.
3574 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003575 /// Function with call of destructors for private variables.
3576 Data1,
3577 /// Task priority.
3578 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003579 /// (Taskloops only) Lower bound.
3580 KmpTaskTLowerBound,
3581 /// (Taskloops only) Upper bound.
3582 KmpTaskTUpperBound,
3583 /// (Taskloops only) Stride.
3584 KmpTaskTStride,
3585 /// (Taskloops only) Is last iteration flag.
3586 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003587 /// (Taskloops only) Reduction data.
3588 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003589};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003590} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003591
Samuel Antaoee8fb302016-01-06 13:42:12 +00003592bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003593 return OffloadEntriesTargetRegion.empty() &&
3594 OffloadEntriesDeviceGlobalVar.empty();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003595}
3596
3597/// \brief Initialize target region entry.
3598void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3599 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3600 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003601 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003602 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3603 "only required for the device "
3604 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003605 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003606 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003607 OMPTargetRegionEntryTargetRegion);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003608 ++OffloadingEntriesNum;
3609}
3610
3611void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3612 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3613 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003614 llvm::Constant *Addr, llvm::Constant *ID,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003615 OMPTargetRegionEntryKind Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003616 // If we are emitting code for a target, the entry is already initialized,
3617 // only has to be registered.
3618 if (CGM.getLangOpts().OpenMPIsDevice) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00003619 if (!hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum)) {
3620 unsigned DiagID = CGM.getDiags().getCustomDiagID(
3621 DiagnosticsEngine::Error,
3622 "Unable to find target region on line '%0' in the device code.");
3623 CGM.getDiags().Report(DiagID) << LineNum;
3624 return;
3625 }
Samuel Antao2de62b02016-02-13 23:35:10 +00003626 auto &Entry =
3627 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003628 assert(Entry.isValid() && "Entry not initialized!");
3629 Entry.setAddress(Addr);
3630 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003631 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003632 } else {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003633 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003634 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00003635 ++OffloadingEntriesNum;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003636 }
3637}
3638
3639bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003640 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3641 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003642 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3643 if (PerDevice == OffloadEntriesTargetRegion.end())
3644 return false;
3645 auto PerFile = PerDevice->second.find(FileID);
3646 if (PerFile == PerDevice->second.end())
3647 return false;
3648 auto PerParentName = PerFile->second.find(ParentName);
3649 if (PerParentName == PerFile->second.end())
3650 return false;
3651 auto PerLine = PerParentName->second.find(LineNum);
3652 if (PerLine == PerParentName->second.end())
3653 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003654 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003655 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003656 return false;
3657 return true;
3658}
3659
3660void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3661 const OffloadTargetRegionEntryInfoActTy &Action) {
3662 // Scan all target region entries and perform the provided action.
Alexey Bataev03f270c2018-03-30 18:31:07 +00003663 for (const auto &D : OffloadEntriesTargetRegion)
3664 for (const auto &F : D.second)
3665 for (const auto &P : F.second)
3666 for (const auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003667 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003668}
3669
Alexey Bataev03f270c2018-03-30 18:31:07 +00003670void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3671 initializeDeviceGlobalVarEntryInfo(StringRef Name,
3672 OMPTargetGlobalVarEntryKind Flags,
3673 unsigned Order) {
3674 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3675 "only required for the device "
3676 "code generation.");
3677 OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags);
3678 ++OffloadingEntriesNum;
3679}
Samuel Antaoee8fb302016-01-06 13:42:12 +00003680
Alexey Bataev03f270c2018-03-30 18:31:07 +00003681void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3682 registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr,
3683 CharUnits VarSize,
3684 OMPTargetGlobalVarEntryKind Flags,
3685 llvm::GlobalValue::LinkageTypes Linkage) {
3686 if (CGM.getLangOpts().OpenMPIsDevice) {
3687 auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
3688 assert(Entry.isValid() && Entry.getFlags() == Flags &&
3689 "Entry not initialized!");
3690 assert((!Entry.getAddress() || Entry.getAddress() == Addr) &&
3691 "Resetting with the new address.");
3692 if (Entry.getAddress() && hasDeviceGlobalVarEntryInfo(VarName))
3693 return;
3694 Entry.setAddress(Addr);
3695 Entry.setVarSize(VarSize);
3696 Entry.setLinkage(Linkage);
3697 } else {
3698 if (hasDeviceGlobalVarEntryInfo(VarName))
3699 return;
3700 OffloadEntriesDeviceGlobalVar.try_emplace(
3701 VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage);
3702 ++OffloadingEntriesNum;
3703 }
3704}
3705
3706void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3707 actOnDeviceGlobalVarEntriesInfo(
3708 const OffloadDeviceGlobalVarEntryInfoActTy &Action) {
3709 // Scan all target region entries and perform the provided action.
3710 for (const auto &E : OffloadEntriesDeviceGlobalVar)
3711 Action(E.getKey(), E.getValue());
Samuel Antaoee8fb302016-01-06 13:42:12 +00003712}
3713
3714llvm::Function *
3715CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003716 // If we don't have entries or if we are emitting code for the device, we
3717 // don't need to do anything.
3718 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3719 return nullptr;
3720
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003721 llvm::Module &M = CGM.getModule();
3722 ASTContext &C = CGM.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003723
3724 // Get list of devices we care about
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003725 const std::vector<llvm::Triple> &Devices = CGM.getLangOpts().OMPTargetTriples;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003726
3727 // We should be creating an offloading descriptor only if there are devices
3728 // specified.
3729 assert(!Devices.empty() && "No OpenMP offloading devices??");
3730
3731 // Create the external variables that will point to the begin and end of the
3732 // host entries section. These will be defined by the linker.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003733 llvm::Type *OffloadEntryTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00003734 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
Alexey Bataev18fa2322018-05-02 14:20:50 +00003735 std::string EntriesBeginName = getName({"omp_offloading", "entries_begin"});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003736 auto *HostEntriesBegin = new llvm::GlobalVariable(
Samuel Antaoee8fb302016-01-06 13:42:12 +00003737 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003738 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003739 EntriesBeginName);
3740 std::string EntriesEndName = getName({"omp_offloading", "entries_end"});
3741 auto *HostEntriesEnd =
3742 new llvm::GlobalVariable(M, OffloadEntryTy, /*isConstant=*/true,
3743 llvm::GlobalValue::ExternalLinkage,
3744 /*Initializer=*/nullptr, EntriesEndName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003745
3746 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003747 auto *DeviceImageTy = cast<llvm::StructType>(
3748 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003749 ConstantInitBuilder DeviceImagesBuilder(CGM);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003750 ConstantArrayBuilder DeviceImagesEntries =
3751 DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003752
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003753 for (const llvm::Triple &Device : Devices) {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003754 StringRef T = Device.getTriple();
Alexey Bataev18fa2322018-05-02 14:20:50 +00003755 std::string BeginName = getName({"omp_offloading", "img_start", ""});
Samuel Antaoee8fb302016-01-06 13:42:12 +00003756 auto *ImgBegin = new llvm::GlobalVariable(
3757 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003758 /*Initializer=*/nullptr, Twine(BeginName).concat(T));
3759 std::string EndName = getName({"omp_offloading", "img_end", ""});
Samuel Antaoee8fb302016-01-06 13:42:12 +00003760 auto *ImgEnd = new llvm::GlobalVariable(
3761 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003762 /*Initializer=*/nullptr, Twine(EndName).concat(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003763
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003764 llvm::Constant *Data[] = {ImgBegin, ImgEnd, HostEntriesBegin,
3765 HostEntriesEnd};
3766 createConstantGlobalStructAndAddToParent(CGM, getTgtDeviceImageQTy(), Data,
3767 DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003768 }
3769
3770 // Create device images global array.
Alexey Bataev18fa2322018-05-02 14:20:50 +00003771 std::string ImagesName = getName({"omp_offloading", "device_images"});
John McCall6c9f1fdb2016-11-19 08:17:24 +00003772 llvm::GlobalVariable *DeviceImages =
Alexey Bataev18fa2322018-05-02 14:20:50 +00003773 DeviceImagesEntries.finishAndCreateGlobal(ImagesName,
3774 CGM.getPointerAlign(),
3775 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003776 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003777
3778 // This is a Zero array to be used in the creation of the constant expressions
3779 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3780 llvm::Constant::getNullValue(CGM.Int32Ty)};
3781
3782 // Create the target region descriptor.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003783 llvm::Constant *Data[] = {
3784 llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
3785 llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3786 DeviceImages, Index),
3787 HostEntriesBegin, HostEntriesEnd};
Alexey Bataev18fa2322018-05-02 14:20:50 +00003788 std::string Descriptor = getName({"omp_offloading", "descriptor"});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003789 llvm::GlobalVariable *Desc = createConstantGlobalStruct(
Alexey Bataev18fa2322018-05-02 14:20:50 +00003790 CGM, getTgtBinaryDescriptorQTy(), Data, Descriptor);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003791
3792 // Emit code to register or unregister the descriptor at execution
3793 // startup or closing, respectively.
3794
Alexey Bataev03f270c2018-03-30 18:31:07 +00003795 llvm::Function *UnRegFn;
3796 {
3797 FunctionArgList Args;
3798 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
3799 Args.push_back(&DummyPtr);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003800
Alexey Bataev03f270c2018-03-30 18:31:07 +00003801 CodeGenFunction CGF(CGM);
3802 // Disable debug info for global (de-)initializer because they are not part
3803 // of some particular construct.
3804 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003805 const auto &FI =
3806 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3807 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003808 std::string UnregName = getName({"omp_offloading", "descriptor_unreg"});
3809 UnRegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, UnregName, FI);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003810 CGF.StartFunction(GlobalDecl(), C.VoidTy, UnRegFn, FI, Args);
3811 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3812 Desc);
3813 CGF.FinishFunction();
3814 }
3815 llvm::Function *RegFn;
3816 {
3817 CodeGenFunction CGF(CGM);
3818 // Disable debug info for global (de-)initializer because they are not part
3819 // of some particular construct.
3820 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003821 const auto &FI = CGM.getTypes().arrangeNullaryFunction();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003822 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003823 std::string Descriptor = getName({"omp_offloading", "descriptor_reg"});
3824 RegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, Descriptor, FI);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003825 CGF.StartFunction(GlobalDecl(), C.VoidTy, RegFn, FI, FunctionArgList());
3826 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib), Desc);
3827 // Create a variable to drive the registration and unregistration of the
3828 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3829 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(),
3830 SourceLocation(), nullptr, C.CharTy,
3831 ImplicitParamDecl::Other);
3832 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3833 CGF.FinishFunction();
3834 }
George Rokos29d0f002017-05-27 03:03:13 +00003835 if (CGM.supportsCOMDAT()) {
3836 // It is sufficient to call registration function only once, so create a
3837 // COMDAT group for registration/unregistration functions and associated
3838 // data. That would reduce startup time and code size. Registration
3839 // function serves as a COMDAT group key.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003840 llvm::Comdat *ComdatKey = M.getOrInsertComdat(RegFn->getName());
George Rokos29d0f002017-05-27 03:03:13 +00003841 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3842 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3843 RegFn->setComdat(ComdatKey);
3844 UnRegFn->setComdat(ComdatKey);
3845 DeviceImages->setComdat(ComdatKey);
3846 Desc->setComdat(ComdatKey);
3847 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003848 return RegFn;
3849}
3850
Alexey Bataev03f270c2018-03-30 18:31:07 +00003851void CGOpenMPRuntime::createOffloadEntry(
3852 llvm::Constant *ID, llvm::Constant *Addr, uint64_t Size, int32_t Flags,
3853 llvm::GlobalValue::LinkageTypes Linkage) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003854 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003855 llvm::Module &M = CGM.getModule();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003856 llvm::LLVMContext &C = M.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003857
3858 // Create constant string with the name.
3859 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3860
Alexey Bataev18fa2322018-05-02 14:20:50 +00003861 std::string StringName = getName({"omp_offloading", "entry_name"});
3862 auto *Str = new llvm::GlobalVariable(
3863 M, StrPtrInit->getType(), /*isConstant=*/true,
3864 llvm::GlobalValue::InternalLinkage, StrPtrInit, StringName);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003865 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003866
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003867 llvm::Constant *Data[] = {llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy),
3868 llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy),
3869 llvm::ConstantInt::get(CGM.SizeTy, Size),
3870 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
3871 llvm::ConstantInt::get(CGM.Int32Ty, 0)};
Alexey Bataev18fa2322018-05-02 14:20:50 +00003872 std::string EntryName = getName({"omp_offloading", "entry", ""});
3873 llvm::GlobalVariable *Entry =
3874 createConstantGlobalStruct(CGM, getTgtOffloadEntryQTy(), Data,
3875 Twine(EntryName).concat(Name), Linkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003876
3877 // The entry has to be created in the section the linker expects it to be.
Alexey Bataev18fa2322018-05-02 14:20:50 +00003878 std::string Section = getName({"omp_offloading", "entries"});
3879 Entry->setSection(Section);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003880}
3881
3882void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3883 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003884 // can easily figure out what to emit. The produced metadata looks like
3885 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003886 //
3887 // !omp_offload.info = !{!1, ...}
3888 //
3889 // Right now we only generate metadata for function that contain target
3890 // regions.
3891
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003892 // If we do not have entries, we don't need to do anything.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003893 if (OffloadEntriesInfoManager.empty())
3894 return;
3895
3896 llvm::Module &M = CGM.getModule();
3897 llvm::LLVMContext &C = M.getContext();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003898 SmallVector<const OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
Samuel Antaoee8fb302016-01-06 13:42:12 +00003899 OrderedEntries(OffloadEntriesInfoManager.size());
3900
Simon Pilgrim2c518802017-03-30 14:13:19 +00003901 // Auxiliary methods to create metadata values and strings.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003902 auto &&GetMDInt = [this](unsigned V) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003903 return llvm::ConstantAsMetadata::get(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003904 llvm::ConstantInt::get(CGM.Int32Ty, V));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003905 };
3906
Alexey Bataev03f270c2018-03-30 18:31:07 +00003907 auto &&GetMDString = [&C](StringRef V) { return llvm::MDString::get(C, V); };
3908
3909 // Create the offloading info metadata node.
3910 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003911
3912 // Create function that emits metadata for each target region entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00003913 auto &&TargetRegionMetadataEmitter =
3914 [&C, MD, &OrderedEntries, &GetMDInt, &GetMDString](
3915 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3916 unsigned Line,
3917 const OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3918 // Generate metadata for target regions. Each entry of this metadata
3919 // contains:
3920 // - Entry 0 -> Kind of this type of metadata (0).
3921 // - Entry 1 -> Device ID of the file where the entry was identified.
3922 // - Entry 2 -> File ID of the file where the entry was identified.
3923 // - Entry 3 -> Mangled name of the function where the entry was
3924 // identified.
3925 // - Entry 4 -> Line in the file where the entry was identified.
3926 // - Entry 5 -> Order the entry was created.
3927 // The first element of the metadata node is the kind.
3928 llvm::Metadata *Ops[] = {GetMDInt(E.getKind()), GetMDInt(DeviceID),
3929 GetMDInt(FileID), GetMDString(ParentName),
3930 GetMDInt(Line), GetMDInt(E.getOrder())};
Samuel Antaoee8fb302016-01-06 13:42:12 +00003931
Alexey Bataev03f270c2018-03-30 18:31:07 +00003932 // Save this entry in the right position of the ordered entries array.
3933 OrderedEntries[E.getOrder()] = &E;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003934
Alexey Bataev03f270c2018-03-30 18:31:07 +00003935 // Add metadata to the named metadata node.
3936 MD->addOperand(llvm::MDNode::get(C, Ops));
3937 };
Samuel Antaoee8fb302016-01-06 13:42:12 +00003938
3939 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3940 TargetRegionMetadataEmitter);
3941
Alexey Bataev03f270c2018-03-30 18:31:07 +00003942 // Create function that emits metadata for each device global variable entry;
3943 auto &&DeviceGlobalVarMetadataEmitter =
3944 [&C, &OrderedEntries, &GetMDInt, &GetMDString,
3945 MD](StringRef MangledName,
3946 const OffloadEntriesInfoManagerTy::OffloadEntryInfoDeviceGlobalVar
3947 &E) {
3948 // Generate metadata for global variables. Each entry of this metadata
3949 // contains:
3950 // - Entry 0 -> Kind of this type of metadata (1).
3951 // - Entry 1 -> Mangled name of the variable.
3952 // - Entry 2 -> Declare target kind.
3953 // - Entry 3 -> Order the entry was created.
3954 // The first element of the metadata node is the kind.
3955 llvm::Metadata *Ops[] = {
3956 GetMDInt(E.getKind()), GetMDString(MangledName),
3957 GetMDInt(E.getFlags()), GetMDInt(E.getOrder())};
3958
3959 // Save this entry in the right position of the ordered entries array.
3960 OrderedEntries[E.getOrder()] = &E;
3961
3962 // Add metadata to the named metadata node.
3963 MD->addOperand(llvm::MDNode::get(C, Ops));
3964 };
3965
3966 OffloadEntriesInfoManager.actOnDeviceGlobalVarEntriesInfo(
3967 DeviceGlobalVarMetadataEmitter);
3968
3969 for (const auto *E : OrderedEntries) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003970 assert(E && "All ordered entries must exist!");
Alexey Bataev03f270c2018-03-30 18:31:07 +00003971 if (const auto *CE =
Samuel Antaoee8fb302016-01-06 13:42:12 +00003972 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3973 E)) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00003974 if (!CE->getID() || !CE->getAddress()) {
3975 unsigned DiagID = CGM.getDiags().getCustomDiagID(
3976 DiagnosticsEngine::Error,
3977 "Offloading entry for target region is incorect: either the "
3978 "address or the ID is invalid.");
3979 CGM.getDiags().Report(DiagID);
3980 continue;
3981 }
Alexey Bataev34f8a702018-03-28 14:28:54 +00003982 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0,
Alexey Bataev03f270c2018-03-30 18:31:07 +00003983 CE->getFlags(), llvm::GlobalValue::WeakAnyLinkage);
3984 } else if (const auto *CE =
3985 dyn_cast<OffloadEntriesInfoManagerTy::
3986 OffloadEntryInfoDeviceGlobalVar>(E)) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00003987 if (!CE->getAddress()) {
3988 unsigned DiagID = CGM.getDiags().getCustomDiagID(
3989 DiagnosticsEngine::Error,
3990 "Offloading entry for declare target varible is inccorect: the "
3991 "address is invalid.");
3992 CGM.getDiags().Report(DiagID);
3993 continue;
3994 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00003995 createOffloadEntry(CE->getAddress(), CE->getAddress(),
3996 CE->getVarSize().getQuantity(), CE->getFlags(),
3997 CE->getLinkage());
3998 } else {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003999 llvm_unreachable("Unsupported entry kind.");
Alexey Bataev03f270c2018-03-30 18:31:07 +00004000 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004001 }
4002}
4003
4004/// \brief Loads all the offload entries information from the host IR
4005/// metadata.
4006void CGOpenMPRuntime::loadOffloadInfoMetadata() {
4007 // If we are in target mode, load the metadata from the host IR. This code has
4008 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
4009
4010 if (!CGM.getLangOpts().OpenMPIsDevice)
4011 return;
4012
4013 if (CGM.getLangOpts().OMPHostIRFile.empty())
4014 return;
4015
4016 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004017 if (auto EC = Buf.getError()) {
4018 CGM.getDiags().Report(diag::err_cannot_open_file)
4019 << CGM.getLangOpts().OMPHostIRFile << EC.message();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004020 return;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004021 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004022
4023 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00004024 auto ME = expectedToErrorOrAndEmitErrors(
4025 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004026
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004027 if (auto EC = ME.getError()) {
4028 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4029 DiagnosticsEngine::Error, "Unable to parse host IR file '%0':'%1'");
4030 CGM.getDiags().Report(DiagID)
4031 << CGM.getLangOpts().OMPHostIRFile << EC.message();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004032 return;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004033 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004034
4035 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
4036 if (!MD)
4037 return;
4038
George Burgess IV00f70bd2018-03-01 05:43:23 +00004039 for (llvm::MDNode *MN : MD->operands()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004040 auto &&GetMDInt = [MN](unsigned Idx) {
4041 auto *V = cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004042 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
4043 };
4044
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004045 auto &&GetMDString = [MN](unsigned Idx) {
4046 auto *V = cast<llvm::MDString>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004047 return V->getString();
4048 };
4049
Alexey Bataev03f270c2018-03-30 18:31:07 +00004050 switch (GetMDInt(0)) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004051 default:
4052 llvm_unreachable("Unexpected metadata!");
4053 break;
4054 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
Alexey Bataev34f8a702018-03-28 14:28:54 +00004055 OffloadingEntryInfoTargetRegion:
Samuel Antaoee8fb302016-01-06 13:42:12 +00004056 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
Alexey Bataev03f270c2018-03-30 18:31:07 +00004057 /*DeviceID=*/GetMDInt(1), /*FileID=*/GetMDInt(2),
4058 /*ParentName=*/GetMDString(3), /*Line=*/GetMDInt(4),
4059 /*Order=*/GetMDInt(5));
4060 break;
4061 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
4062 OffloadingEntryInfoDeviceGlobalVar:
4063 OffloadEntriesInfoManager.initializeDeviceGlobalVarEntryInfo(
4064 /*MangledName=*/GetMDString(1),
4065 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
4066 /*Flags=*/GetMDInt(2)),
4067 /*Order=*/GetMDInt(3));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004068 break;
4069 }
4070 }
4071}
4072
Alexey Bataev62b63b12015-03-10 07:28:44 +00004073void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
4074 if (!KmpRoutineEntryPtrTy) {
4075 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004076 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004077 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
4078 FunctionProtoType::ExtProtoInfo EPI;
4079 KmpRoutineEntryPtrQTy = C.getPointerType(
4080 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
4081 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
4082 }
4083}
4084
Samuel Antaoee8fb302016-01-06 13:42:12 +00004085QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004086 // Make sure the type of the entry is already created. This is the type we
4087 // have to create:
4088 // struct __tgt_offload_entry{
4089 // void *addr; // Pointer to the offload entry info.
4090 // // (function or global)
4091 // char *name; // Name of the function or global.
4092 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00004093 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
4094 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004095 // };
4096 if (TgtOffloadEntryQTy.isNull()) {
4097 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004098 RecordDecl *RD = C.buildImplicitRecord("__tgt_offload_entry");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004099 RD->startDefinition();
4100 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4101 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
4102 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00004103 addFieldToRecordDecl(
4104 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4105 addFieldToRecordDecl(
4106 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004107 RD->completeDefinition();
Jonas Hahnfeld5e4df282018-01-18 15:38:03 +00004108 RD->addAttr(PackedAttr::CreateImplicit(C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004109 TgtOffloadEntryQTy = C.getRecordType(RD);
4110 }
4111 return TgtOffloadEntryQTy;
4112}
4113
4114QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
4115 // These are the types we need to build:
4116 // struct __tgt_device_image{
4117 // void *ImageStart; // Pointer to the target code start.
4118 // void *ImageEnd; // Pointer to the target code end.
4119 // // We also add the host entries to the device image, as it may be useful
4120 // // for the target runtime to have access to that information.
4121 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
4122 // // the entries.
4123 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4124 // // entries (non inclusive).
4125 // };
4126 if (TgtDeviceImageQTy.isNull()) {
4127 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004128 RecordDecl *RD = C.buildImplicitRecord("__tgt_device_image");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004129 RD->startDefinition();
4130 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4131 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4132 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4133 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4134 RD->completeDefinition();
4135 TgtDeviceImageQTy = C.getRecordType(RD);
4136 }
4137 return TgtDeviceImageQTy;
4138}
4139
4140QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
4141 // struct __tgt_bin_desc{
4142 // int32_t NumDevices; // Number of devices supported.
4143 // __tgt_device_image *DeviceImages; // Arrays of device images
4144 // // (one per device).
4145 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
4146 // // entries.
4147 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4148 // // entries (non inclusive).
4149 // };
4150 if (TgtBinaryDescriptorQTy.isNull()) {
4151 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004152 RecordDecl *RD = C.buildImplicitRecord("__tgt_bin_desc");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004153 RD->startDefinition();
4154 addFieldToRecordDecl(
4155 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4156 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
4157 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4158 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4159 RD->completeDefinition();
4160 TgtBinaryDescriptorQTy = C.getRecordType(RD);
4161 }
4162 return TgtBinaryDescriptorQTy;
4163}
4164
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004165namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00004166struct PrivateHelpersTy {
4167 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
4168 const VarDecl *PrivateElemInit)
4169 : Original(Original), PrivateCopy(PrivateCopy),
4170 PrivateElemInit(PrivateElemInit) {}
4171 const VarDecl *Original;
4172 const VarDecl *PrivateCopy;
4173 const VarDecl *PrivateElemInit;
4174};
4175typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00004176} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004177
Alexey Bataev9e034042015-05-05 04:05:12 +00004178static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00004179createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004180 if (!Privates.empty()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004181 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004182 // Build struct .kmp_privates_t. {
4183 // /* private vars */
4184 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004185 RecordDecl *RD = C.buildImplicitRecord(".kmp_privates.t");
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004186 RD->startDefinition();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004187 for (const auto &Pair : Privates) {
4188 const VarDecl *VD = Pair.second.Original;
4189 QualType Type = VD->getType().getNonReferenceType();
4190 FieldDecl *FD = addFieldToRecordDecl(C, RD, Type);
Alexey Bataevc71a4092015-09-11 10:29:41 +00004191 if (VD->hasAttrs()) {
4192 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
4193 E(VD->getAttrs().end());
4194 I != E; ++I)
4195 FD->addAttr(*I);
4196 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004197 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004198 RD->completeDefinition();
4199 return RD;
4200 }
4201 return nullptr;
4202}
4203
Alexey Bataev9e034042015-05-05 04:05:12 +00004204static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00004205createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
4206 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004207 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004208 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004209 // Build struct kmp_task_t {
4210 // void * shareds;
4211 // kmp_routine_entry_t routine;
4212 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00004213 // kmp_cmplrdata_t data1;
4214 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00004215 // For taskloops additional fields:
4216 // kmp_uint64 lb;
4217 // kmp_uint64 ub;
4218 // kmp_int64 st;
4219 // kmp_int32 liter;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004220 // void * reductions;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004221 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004222 RecordDecl *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004223 UD->startDefinition();
4224 addFieldToRecordDecl(C, UD, KmpInt32Ty);
4225 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
4226 UD->completeDefinition();
4227 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004228 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t");
Alexey Bataev62b63b12015-03-10 07:28:44 +00004229 RD->startDefinition();
4230 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4231 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
4232 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004233 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
4234 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004235 if (isOpenMPTaskLoopDirective(Kind)) {
4236 QualType KmpUInt64Ty =
4237 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4238 QualType KmpInt64Ty =
4239 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4240 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4241 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4242 addFieldToRecordDecl(C, RD, KmpInt64Ty);
4243 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004244 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004245 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004246 RD->completeDefinition();
4247 return RD;
4248}
4249
4250static RecordDecl *
4251createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004252 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004253 ASTContext &C = CGM.getContext();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004254 // Build struct kmp_task_t_with_privates {
4255 // kmp_task_t task_data;
4256 // .kmp_privates_t. privates;
4257 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004258 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004259 RD->startDefinition();
4260 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004261 if (const RecordDecl *PrivateRD = createPrivatesRecordDecl(CGM, Privates))
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004262 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004263 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004264 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004265}
4266
4267/// \brief Emit a proxy function which accepts kmp_task_t as the second
4268/// argument.
4269/// \code
4270/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004271/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00004272/// For taskloops:
4273/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004274/// tt->reductions, tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004275/// return 0;
4276/// }
4277/// \endcode
4278static llvm::Value *
4279emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00004280 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
4281 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004282 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004283 QualType SharedsPtrTy, llvm::Value *TaskFunction,
4284 llvm::Value *TaskPrivatesMap) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004285 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004286 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004287 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4288 ImplicitParamDecl::Other);
4289 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4290 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4291 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004292 Args.push_back(&GtidArg);
4293 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004294 const auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004295 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004296 llvm::FunctionType *TaskEntryTy =
4297 CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004298 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_entry", ""});
4299 auto *TaskEntry = llvm::Function::Create(
4300 TaskEntryTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004301 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskEntry, TaskEntryFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004302 TaskEntry->setDoesNotRecurse();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004303 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004304 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args,
4305 Loc, Loc);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004306
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004307 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00004308 // tt,
4309 // For taskloops:
4310 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
4311 // tt->task_data.shareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004312 llvm::Value *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00004313 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00004314 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4315 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4316 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004317 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004318 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004319 LValue Base =
4320 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004321 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004322 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004323 LValue PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
4324 llvm::Value *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004325
4326 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004327 LValue SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
4328 llvm::Value *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev1e491372018-01-23 18:44:14 +00004329 CGF.EmitLoadOfScalar(SharedsLVal, Loc),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004330 CGF.ConvertTypeForMem(SharedsPtrTy));
4331
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004332 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4333 llvm::Value *PrivatesParam;
4334 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004335 LValue PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004336 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004337 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004338 } else {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004339 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004340 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004341
Alexey Bataev7292c292016-04-25 12:22:29 +00004342 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
4343 TaskPrivatesMap,
4344 CGF.Builder
4345 .CreatePointerBitCastOrAddrSpaceCast(
4346 TDBase.getAddress(), CGF.VoidPtrTy)
4347 .getPointer()};
4348 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
4349 std::end(CommonArgs));
4350 if (isOpenMPTaskLoopDirective(Kind)) {
4351 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004352 LValue LBLVal = CGF.EmitLValueForField(Base, *LBFI);
4353 llvm::Value *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004354 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004355 LValue UBLVal = CGF.EmitLValueForField(Base, *UBFI);
4356 llvm::Value *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004357 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004358 LValue StLVal = CGF.EmitLValueForField(Base, *StFI);
4359 llvm::Value *StParam = CGF.EmitLoadOfScalar(StLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004360 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004361 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4362 llvm::Value *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004363 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004364 LValue RLVal = CGF.EmitLValueForField(Base, *RFI);
4365 llvm::Value *RParam = CGF.EmitLoadOfScalar(RLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004366 CallArgs.push_back(LBParam);
4367 CallArgs.push_back(UBParam);
4368 CallArgs.push_back(StParam);
4369 CallArgs.push_back(LIParam);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004370 CallArgs.push_back(RParam);
Alexey Bataev7292c292016-04-25 12:22:29 +00004371 }
4372 CallArgs.push_back(SharedsParam);
4373
Alexey Bataev3c595a62017-08-14 15:01:03 +00004374 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
4375 CallArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004376 CGF.EmitStoreThroughLValue(RValue::get(CGF.Builder.getInt32(/*C=*/0)),
4377 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004378 CGF.FinishFunction();
4379 return TaskEntry;
4380}
4381
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004382static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
4383 SourceLocation Loc,
4384 QualType KmpInt32Ty,
4385 QualType KmpTaskTWithPrivatesPtrQTy,
4386 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004387 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004388 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004389 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4390 ImplicitParamDecl::Other);
4391 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4392 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4393 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004394 Args.push_back(&GtidArg);
4395 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004396 const auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004397 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004398 llvm::FunctionType *DestructorFnTy =
4399 CGM.getTypes().GetFunctionType(DestructorFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004400 std::string Name =
4401 CGM.getOpenMPRuntime().getName({"omp_task_destructor", ""});
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004402 auto *DestructorFn =
4403 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00004404 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004405 CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004406 DestructorFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004407 DestructorFn->setDoesNotRecurse();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004408 CodeGenFunction CGF(CGM);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004409 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004410 Args, Loc, Loc);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004411
Alexey Bataev31300ed2016-02-04 11:27:03 +00004412 LValue Base = CGF.EmitLoadOfPointerLValue(
4413 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4414 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004415 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004416 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
4417 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004418 Base = CGF.EmitLValueForField(Base, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004419 for (const auto *Field :
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004420 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004421 if (QualType::DestructionKind DtorKind =
4422 Field->getType().isDestructedType()) {
4423 LValue FieldLValue = CGF.EmitLValueForField(Base, Field);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004424 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
4425 }
4426 }
4427 CGF.FinishFunction();
4428 return DestructorFn;
4429}
4430
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004431/// \brief Emit a privates mapping function for correct handling of private and
4432/// firstprivate variables.
4433/// \code
4434/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
4435/// **noalias priv1,..., <tyn> **noalias privn) {
4436/// *priv1 = &.privates.priv1;
4437/// ...;
4438/// *privn = &.privates.privn;
4439/// }
4440/// \endcode
4441static llvm::Value *
4442emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00004443 ArrayRef<const Expr *> PrivateVars,
4444 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004445 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004446 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004447 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004448 ASTContext &C = CGM.getContext();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004449 FunctionArgList Args;
4450 ImplicitParamDecl TaskPrivatesArg(
4451 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00004452 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
4453 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004454 Args.push_back(&TaskPrivatesArg);
4455 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
4456 unsigned Counter = 1;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004457 for (const Expr *E : PrivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004458 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004459 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4460 C.getPointerType(C.getPointerType(E->getType()))
4461 .withConst()
4462 .withRestrict(),
4463 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004464 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004465 PrivateVarsPos[VD] = Counter;
4466 ++Counter;
4467 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004468 for (const Expr *E : FirstprivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004469 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004470 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4471 C.getPointerType(C.getPointerType(E->getType()))
4472 .withConst()
4473 .withRestrict(),
4474 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004475 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004476 PrivateVarsPos[VD] = Counter;
4477 ++Counter;
4478 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004479 for (const Expr *E : LastprivateVars) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004480 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004481 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4482 C.getPointerType(C.getPointerType(E->getType()))
4483 .withConst()
4484 .withRestrict(),
4485 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004486 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004487 PrivateVarsPos[VD] = Counter;
4488 ++Counter;
4489 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004490 const auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004491 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004492 llvm::FunctionType *TaskPrivatesMapTy =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004493 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004494 std::string Name =
4495 CGM.getOpenMPRuntime().getName({"omp_task_privates_map", ""});
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004496 auto *TaskPrivatesMap = llvm::Function::Create(
Alexey Bataev18fa2322018-05-02 14:20:50 +00004497 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage, Name,
4498 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004499 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004500 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00004501 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00004502 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00004503 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004504 CodeGenFunction CGF(CGM);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004505 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004506 TaskPrivatesMapFnInfo, Args, Loc, Loc);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004507
4508 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00004509 LValue Base = CGF.EmitLoadOfPointerLValue(
4510 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4511 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004512 const auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004513 Counter = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004514 for (const FieldDecl *Field : PrivatesQTyRD->fields()) {
4515 LValue FieldLVal = CGF.EmitLValueForField(Base, Field);
4516 const VarDecl *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
4517 LValue RefLVal =
4518 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
4519 LValue RefLoadLVal = CGF.EmitLoadOfPointerLValue(
Alexey Bataev31300ed2016-02-04 11:27:03 +00004520 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00004521 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004522 ++Counter;
4523 }
4524 CGF.FinishFunction();
4525 return TaskPrivatesMap;
4526}
4527
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004528static bool stable_sort_comparator(const PrivateDataTy P1,
4529 const PrivateDataTy P2) {
4530 return P1.first > P2.first;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004531}
4532
Alexey Bataevf93095a2016-05-05 08:46:22 +00004533/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00004534static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004535 const OMPExecutableDirective &D,
4536 Address KmpTaskSharedsPtr, LValue TDBase,
4537 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4538 QualType SharedsTy, QualType SharedsPtrTy,
4539 const OMPTaskDataTy &Data,
4540 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004541 ASTContext &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004542 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4543 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004544 OpenMPDirectiveKind Kind = isOpenMPTaskLoopDirective(D.getDirectiveKind())
4545 ? OMPD_taskloop
4546 : OMPD_task;
4547 const CapturedStmt &CS = *D.getCapturedStmt(Kind);
4548 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004549 LValue SrcBase;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004550 bool IsTargetTask =
4551 isOpenMPTargetDataManagementDirective(D.getDirectiveKind()) ||
4552 isOpenMPTargetExecutionDirective(D.getDirectiveKind());
4553 // For target-based directives skip 3 firstprivate arrays BasePointersArray,
4554 // PointersArray and SizesArray. The original variables for these arrays are
4555 // not captured and we get their addresses explicitly.
4556 if ((!IsTargetTask && !Data.FirstprivateVars.empty()) ||
Alexey Bataev8451efa2018-01-15 19:06:12 +00004557 (IsTargetTask && KmpTaskSharedsPtr.isValid())) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004558 SrcBase = CGF.MakeAddrLValue(
4559 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4560 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4561 SharedsTy);
4562 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004563 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004564 for (const PrivateDataTy &Pair : Privates) {
4565 const VarDecl *VD = Pair.second.PrivateCopy;
4566 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004567 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4568 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004569 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004570 if (const VarDecl *Elem = Pair.second.PrivateElemInit) {
4571 const VarDecl *OriginalVD = Pair.second.Original;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004572 // Check if the variable is the target-based BasePointersArray,
4573 // PointersArray or SizesArray.
4574 LValue SharedRefLValue;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004575 QualType Type = OriginalVD->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004576 const FieldDecl *SharedField = CapturesInfo.lookup(OriginalVD);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004577 if (IsTargetTask && !SharedField) {
4578 assert(isa<ImplicitParamDecl>(OriginalVD) &&
4579 isa<CapturedDecl>(OriginalVD->getDeclContext()) &&
4580 cast<CapturedDecl>(OriginalVD->getDeclContext())
4581 ->getNumParams() == 0 &&
4582 isa<TranslationUnitDecl>(
4583 cast<CapturedDecl>(OriginalVD->getDeclContext())
4584 ->getDeclContext()) &&
4585 "Expected artificial target data variable.");
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004586 SharedRefLValue =
4587 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type);
4588 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004589 SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4590 SharedRefLValue = CGF.MakeAddrLValue(
4591 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
4592 SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl),
4593 SharedRefLValue.getTBAAInfo());
4594 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004595 if (Type->isArrayType()) {
4596 // Initialize firstprivate array.
4597 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4598 // Perform simple memcpy.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004599 CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004600 } else {
4601 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00004602 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00004603 CGF.EmitOMPAggregateAssign(
4604 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4605 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4606 Address SrcElement) {
4607 // Clean up any temporaries needed by the initialization.
4608 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4609 InitScope.addPrivate(
4610 Elem, [SrcElement]() -> Address { return SrcElement; });
4611 (void)InitScope.Privatize();
4612 // Emit initialization for single element.
4613 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4614 CGF, &CapturesInfo);
4615 CGF.EmitAnyExprToMem(Init, DestElement,
4616 Init->getType().getQualifiers(),
4617 /*IsInitializer=*/false);
4618 });
4619 }
4620 } else {
4621 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4622 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4623 return SharedRefLValue.getAddress();
4624 });
4625 (void)InitScope.Privatize();
4626 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4627 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4628 /*capturedByInit=*/false);
4629 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004630 } else {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004631 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004632 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004633 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004634 ++FI;
4635 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004636}
4637
4638/// Check if duplication function is required for taskloops.
4639static bool checkInitIsRequired(CodeGenFunction &CGF,
4640 ArrayRef<PrivateDataTy> Privates) {
4641 bool InitRequired = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004642 for (const PrivateDataTy &Pair : Privates) {
4643 const VarDecl *VD = Pair.second.PrivateCopy;
4644 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004645 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4646 !CGF.isTrivialInitializer(Init));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004647 if (InitRequired)
4648 break;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004649 }
4650 return InitRequired;
4651}
4652
4653
4654/// Emit task_dup function (for initialization of
4655/// private/firstprivate/lastprivate vars and last_iter flag)
4656/// \code
4657/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4658/// lastpriv) {
4659/// // setup lastprivate flag
4660/// task_dst->last = lastpriv;
4661/// // could be constructor calls here...
4662/// }
4663/// \endcode
4664static llvm::Value *
4665emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4666 const OMPExecutableDirective &D,
4667 QualType KmpTaskTWithPrivatesPtrQTy,
4668 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4669 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4670 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4671 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004672 ASTContext &C = CGM.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004673 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004674 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4675 KmpTaskTWithPrivatesPtrQTy,
4676 ImplicitParamDecl::Other);
4677 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4678 KmpTaskTWithPrivatesPtrQTy,
4679 ImplicitParamDecl::Other);
4680 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4681 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004682 Args.push_back(&DstArg);
4683 Args.push_back(&SrcArg);
4684 Args.push_back(&LastprivArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004685 const auto &TaskDupFnInfo =
Alexey Bataevf93095a2016-05-05 08:46:22 +00004686 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004687 llvm::FunctionType *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004688 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_dup", ""});
4689 auto *TaskDup = llvm::Function::Create(
4690 TaskDupTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004691 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskDup, TaskDupFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004692 TaskDup->setDoesNotRecurse();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004693 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004694 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args, Loc,
4695 Loc);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004696
4697 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4698 CGF.GetAddrOfLocalVar(&DstArg),
4699 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4700 // task_dst->liter = lastpriv;
4701 if (WithLastIter) {
4702 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4703 LValue Base = CGF.EmitLValueForField(
4704 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4705 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4706 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4707 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4708 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4709 }
4710
4711 // Emit initial values for private copies (if any).
4712 assert(!Privates.empty());
4713 Address KmpTaskSharedsPtr = Address::invalid();
4714 if (!Data.FirstprivateVars.empty()) {
4715 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4716 CGF.GetAddrOfLocalVar(&SrcArg),
4717 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4718 LValue Base = CGF.EmitLValueForField(
4719 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4720 KmpTaskSharedsPtr = Address(
4721 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4722 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4723 KmpTaskTShareds)),
4724 Loc),
4725 CGF.getNaturalTypeAlignment(SharedsTy));
4726 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004727 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4728 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004729 CGF.FinishFunction();
4730 return TaskDup;
4731}
4732
Alexey Bataev8a831592016-05-10 10:36:51 +00004733/// Checks if destructor function is required to be generated.
4734/// \return true if cleanups are required, false otherwise.
4735static bool
4736checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4737 bool NeedsCleanup = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004738 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4739 const auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4740 for (const FieldDecl *FD : PrivateRD->fields()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004741 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4742 if (NeedsCleanup)
4743 break;
4744 }
4745 return NeedsCleanup;
4746}
4747
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004748CGOpenMPRuntime::TaskResultTy
4749CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4750 const OMPExecutableDirective &D,
4751 llvm::Value *TaskFunction, QualType SharedsTy,
4752 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004753 ASTContext &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004754 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004755 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004756 auto I = Data.PrivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004757 for (const Expr *E : Data.PrivateVars) {
4758 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004759 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004760 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004761 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004762 /*PrivateElemInit=*/nullptr));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004763 ++I;
4764 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004765 I = Data.FirstprivateCopies.begin();
4766 auto IElemInitRef = Data.FirstprivateInits.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004767 for (const Expr *E : Data.FirstprivateVars) {
4768 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004769 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004770 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004771 PrivateHelpersTy(
4772 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004773 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl())));
Richard Trieucc3949d2016-02-18 22:34:54 +00004774 ++I;
4775 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004776 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004777 I = Data.LastprivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004778 for (const Expr *E : Data.LastprivateVars) {
4779 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004780 Privates.emplace_back(
Alexey Bataevf93095a2016-05-05 08:46:22 +00004781 C.getDeclAlign(VD),
4782 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004783 /*PrivateElemInit=*/nullptr));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004784 ++I;
4785 }
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004786 std::stable_sort(Privates.begin(), Privates.end(), stable_sort_comparator);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004787 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004788 // Build type kmp_routine_entry_t (if not built yet).
4789 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004790 // Build type kmp_task_t (if not built yet).
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004791 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
4792 if (SavedKmpTaskloopTQTy.isNull()) {
4793 SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4794 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4795 }
4796 KmpTaskTQTy = SavedKmpTaskloopTQTy;
Alexey Bataev3a03a7f2017-10-11 15:56:38 +00004797 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004798 assert((D.getDirectiveKind() == OMPD_task ||
4799 isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||
4800 isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) &&
4801 "Expected taskloop, task or target directive");
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004802 if (SavedKmpTaskTQTy.isNull()) {
4803 SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4804 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4805 }
4806 KmpTaskTQTy = SavedKmpTaskTQTy;
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004807 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004808 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004809 // Build particular struct kmp_task_t for the given task.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004810 const RecordDecl *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004811 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004812 QualType KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004813 QualType KmpTaskTWithPrivatesPtrQTy =
4814 C.getPointerType(KmpTaskTWithPrivatesQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004815 llvm::Type *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4816 llvm::Type *KmpTaskTWithPrivatesPtrTy =
4817 KmpTaskTWithPrivatesTy->getPointerTo();
4818 llvm::Value *KmpTaskTWithPrivatesTySize =
4819 CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004820 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4821
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004822 // Emit initial values for private copies (if any).
4823 llvm::Value *TaskPrivatesMap = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004824 llvm::Type *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00004825 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004826 if (!Privates.empty()) {
4827 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004828 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4829 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4830 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004831 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4832 TaskPrivatesMap, TaskPrivatesMapTy);
4833 } else {
4834 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4835 cast<llvm::PointerType>(TaskPrivatesMapTy));
4836 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004837 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4838 // kmp_task_t *tt);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004839 llvm::Value *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004840 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4841 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4842 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004843
4844 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4845 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4846 // kmp_routine_entry_t *task_entry);
4847 // Task flags. Format is taken from
4848 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4849 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004850 enum {
4851 TiedFlag = 0x1,
4852 FinalFlag = 0x2,
4853 DestructorsFlag = 0x8,
4854 PriorityFlag = 0x20
4855 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004856 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004857 bool NeedsCleanup = false;
4858 if (!Privates.empty()) {
4859 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4860 if (NeedsCleanup)
4861 Flags = Flags | DestructorsFlag;
4862 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004863 if (Data.Priority.getInt())
4864 Flags = Flags | PriorityFlag;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004865 llvm::Value *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004866 Data.Final.getPointer()
4867 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00004868 CGF.Builder.getInt32(FinalFlag),
4869 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004870 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004871 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004872 llvm::Value *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004873 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4874 getThreadID(CGF, Loc), TaskFlags,
4875 KmpTaskTWithPrivatesTySize, SharedsSize,
4876 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4877 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004878 llvm::Value *NewTask = CGF.EmitRuntimeCall(
Alexey Bataev62b63b12015-03-10 07:28:44 +00004879 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004880 llvm::Value *NewTaskNewTaskTTy =
4881 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4882 NewTask, KmpTaskTWithPrivatesPtrTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004883 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4884 KmpTaskTWithPrivatesQTy);
4885 LValue TDBase =
4886 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004887 // Fill the data in the resulting kmp_task_t record.
4888 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00004889 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004890 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00004891 KmpTaskSharedsPtr =
4892 Address(CGF.EmitLoadOfScalar(
4893 CGF.EmitLValueForField(
4894 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4895 KmpTaskTShareds)),
4896 Loc),
4897 CGF.getNaturalTypeAlignment(SharedsTy));
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004898 LValue Dest = CGF.MakeAddrLValue(KmpTaskSharedsPtr, SharedsTy);
4899 LValue Src = CGF.MakeAddrLValue(Shareds, SharedsTy);
Richard Smithe78fac52018-04-05 20:52:58 +00004900 CGF.EmitAggregateCopy(Dest, Src, SharedsTy, AggValueSlot::DoesNotOverlap);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004901 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004902 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00004903 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004904 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004905 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4906 SharedsTy, SharedsPtrTy, Data, Privates,
4907 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004908 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4909 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4910 Result.TaskDupFn = emitTaskDupFunction(
4911 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4912 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4913 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004914 }
4915 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00004916 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4917 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00004918 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00004919 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004920 const RecordDecl *KmpCmplrdataUD =
4921 (*FI)->getType()->getAsUnionType()->getDecl();
Alexey Bataevad537bb2016-05-30 09:06:50 +00004922 if (NeedsCleanup) {
4923 llvm::Value *DestructorFn = emitDestructorsFunction(
4924 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4925 KmpTaskTWithPrivatesQTy);
4926 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4927 LValue DestructorsLV = CGF.EmitLValueForField(
4928 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4929 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4930 DestructorFn, KmpRoutineEntryPtrTy),
4931 DestructorsLV);
4932 }
4933 // Set priority.
4934 if (Data.Priority.getInt()) {
4935 LValue Data2LV = CGF.EmitLValueForField(
4936 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
4937 LValue PriorityLV = CGF.EmitLValueForField(
4938 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
4939 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
4940 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004941 Result.NewTask = NewTask;
4942 Result.TaskEntry = TaskEntry;
4943 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
4944 Result.TDBase = TDBase;
4945 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
4946 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00004947}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004948
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004949void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
4950 const OMPExecutableDirective &D,
4951 llvm::Value *TaskFunction,
4952 QualType SharedsTy, Address Shareds,
4953 const Expr *IfCond,
4954 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004955 if (!CGF.HaveInsertPoint())
4956 return;
4957
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004958 TaskResultTy Result =
4959 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4960 llvm::Value *NewTask = Result.NewTask;
4961 llvm::Value *TaskEntry = Result.TaskEntry;
4962 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
4963 LValue TDBase = Result.TDBase;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004964 const RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
4965 ASTContext &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004966 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00004967 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004968 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00004969 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004970 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00004971 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004972 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
4973 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004974 QualType FlagsTy =
4975 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004976 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
4977 if (KmpDependInfoTy.isNull()) {
4978 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
4979 KmpDependInfoRD->startDefinition();
4980 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
4981 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
4982 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
4983 KmpDependInfoRD->completeDefinition();
4984 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004985 } else {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004986 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004987 }
John McCall7f416cc2015-09-08 08:05:57 +00004988 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004989 // Define type kmp_depend_info[<Dependences.size()>];
4990 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00004991 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004992 ArrayType::Normal, /*IndexTypeQuals=*/0);
4993 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00004994 DependenciesArray =
4995 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004996 for (unsigned I = 0; I < NumDependencies; ++I) {
4997 const Expr *E = Data.Dependences[I].second;
4998 LValue Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004999 llvm::Value *Size;
5000 QualType Ty = E->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005001 if (const auto *ASE =
5002 dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005003 LValue UpAddrLVal =
5004 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
5005 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00005006 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005007 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00005008 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005009 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
5010 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005011 } else {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005012 Size = CGF.getTypeSize(Ty);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005013 }
5014 LValue Base = CGF.MakeAddrLValue(
5015 CGF.Builder.CreateConstArrayGEP(DependenciesArray, I, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005016 KmpDependInfoTy);
5017 // deps[i].base_addr = &<Dependences[i].second>;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005018 LValue BaseAddrLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005019 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00005020 CGF.EmitStoreOfScalar(
5021 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
5022 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005023 // deps[i].len = sizeof(<Dependences[i].second>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005024 LValue LenLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005025 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
5026 CGF.EmitStoreOfScalar(Size, LenLVal);
5027 // deps[i].flags = <Dependences[i].first>;
5028 RTLDependenceKindTy DepKind;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005029 switch (Data.Dependences[I].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005030 case OMPC_DEPEND_in:
5031 DepKind = DepIn;
5032 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00005033 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005034 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005035 case OMPC_DEPEND_inout:
5036 DepKind = DepInOut;
5037 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00005038 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005039 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005040 case OMPC_DEPEND_unknown:
5041 llvm_unreachable("Unknown task dependence type");
5042 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005043 LValue FlagsLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005044 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
5045 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
5046 FlagsLVal);
5047 }
John McCall7f416cc2015-09-08 08:05:57 +00005048 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5049 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005050 CGF.VoidPtrTy);
5051 }
5052
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005053 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev62b63b12015-03-10 07:28:44 +00005054 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005055 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
5056 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
5057 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
5058 // list is not empty
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005059 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5060 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00005061 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
5062 llvm::Value *DepTaskArgs[7];
5063 if (NumDependencies) {
5064 DepTaskArgs[0] = UpLoc;
5065 DepTaskArgs[1] = ThreadID;
5066 DepTaskArgs[2] = NewTask;
5067 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
5068 DepTaskArgs[4] = DependenciesArray.getPointer();
5069 DepTaskArgs[5] = CGF.Builder.getInt32(0);
5070 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5071 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005072 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
5073 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005074 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005075 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005076 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005077 LValue PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005078 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
5079 }
John McCall7f416cc2015-09-08 08:05:57 +00005080 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005081 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00005082 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00005083 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005084 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00005085 TaskArgs);
5086 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00005087 // Check if parent region is untied and build return for untied task;
5088 if (auto *Region =
5089 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5090 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00005091 };
John McCall7f416cc2015-09-08 08:05:57 +00005092
5093 llvm::Value *DepWaitTaskArgs[6];
5094 if (NumDependencies) {
5095 DepWaitTaskArgs[0] = UpLoc;
5096 DepWaitTaskArgs[1] = ThreadID;
5097 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
5098 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
5099 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
5100 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5101 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005102 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00005103 NumDependencies, &DepWaitTaskArgs,
5104 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005105 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005106 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
5107 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
5108 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
5109 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
5110 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00005111 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005112 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005113 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005114 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00005115 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
5116 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005117 Action.Enter(CGF);
5118 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00005119 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00005120 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005121 };
5122
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005123 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
5124 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005125 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
5126 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005127 RegionCodeGenTy RCG(CodeGen);
5128 CommonActionTy Action(
5129 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
5130 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
5131 RCG.setAction(Action);
5132 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005133 };
John McCall7f416cc2015-09-08 08:05:57 +00005134
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005135 if (IfCond) {
Alexey Bataev1d677132015-04-22 13:57:31 +00005136 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005137 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005138 RegionCodeGenTy ThenRCG(ThenCodeGen);
5139 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00005140 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00005141}
5142
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005143void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
5144 const OMPLoopDirective &D,
5145 llvm::Value *TaskFunction,
5146 QualType SharedsTy, Address Shareds,
5147 const Expr *IfCond,
5148 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005149 if (!CGF.HaveInsertPoint())
5150 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005151 TaskResultTy Result =
5152 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005153 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev7292c292016-04-25 12:22:29 +00005154 // libcall.
5155 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
5156 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
5157 // sched, kmp_uint64 grainsize, void *task_dup);
5158 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5159 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
5160 llvm::Value *IfVal;
5161 if (IfCond) {
5162 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
5163 /*isSigned=*/true);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005164 } else {
Alexey Bataev7292c292016-04-25 12:22:29 +00005165 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005166 }
Alexey Bataev7292c292016-04-25 12:22:29 +00005167
5168 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005169 Result.TDBase,
5170 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005171 const auto *LBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005172 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
5173 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
5174 /*IsInitializer=*/true);
5175 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005176 Result.TDBase,
5177 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005178 const auto *UBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005179 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
5180 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
5181 /*IsInitializer=*/true);
5182 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005183 Result.TDBase,
5184 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005185 const auto *StVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005186 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
5187 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
5188 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005189 // Store reductions address.
5190 LValue RedLVal = CGF.EmitLValueForField(
5191 Result.TDBase,
5192 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005193 if (Data.Reductions) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005194 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005195 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005196 CGF.EmitNullInitialization(RedLVal.getAddress(),
5197 CGF.getContext().VoidPtrTy);
5198 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005199 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00005200 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00005201 UpLoc,
5202 ThreadID,
5203 Result.NewTask,
5204 IfVal,
5205 LBLVal.getPointer(),
5206 UBLVal.getPointer(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005207 CGF.EmitLoadOfScalar(StLVal, Loc),
Alexey Bataev33446032017-07-12 18:09:32 +00005208 llvm::ConstantInt::getNullValue(
5209 CGF.IntTy), // Always 0 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005210 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005211 CGF.IntTy, Data.Schedule.getPointer()
5212 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005213 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005214 Data.Schedule.getPointer()
5215 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005216 /*isSigned=*/false)
5217 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00005218 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5219 Result.TaskDupFn, CGF.VoidPtrTy)
5220 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00005221 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
5222}
5223
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005224/// \brief Emit reduction operation for each element of array (required for
5225/// array sections) LHS op = RHS.
5226/// \param Type Type of array.
5227/// \param LHSVar Variable on the left side of the reduction operation
5228/// (references element of array in original variable).
5229/// \param RHSVar Variable on the right side of the reduction operation
5230/// (references element of array in original variable).
5231/// \param RedOpGen Generator of reduction operation with use of LHSVar and
5232/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00005233static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005234 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
5235 const VarDecl *RHSVar,
5236 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
5237 const Expr *, const Expr *)> &RedOpGen,
5238 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
5239 const Expr *UpExpr = nullptr) {
5240 // Perform element-by-element initialization.
5241 QualType ElementTy;
5242 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
5243 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
5244
5245 // Drill down to the base element type on both arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005246 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
5247 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005248
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005249 llvm::Value *RHSBegin = RHSAddr.getPointer();
5250 llvm::Value *LHSBegin = LHSAddr.getPointer();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005251 // Cast from pointer to array type to pointer to single element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005252 llvm::Value *LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005253 // The basic structure here is a while-do loop.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005254 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
5255 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
5256 llvm::Value *IsEmpty =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005257 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
5258 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
5259
5260 // Enter the loop body, making that address the current address.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005261 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005262 CGF.EmitBlock(BodyBB);
5263
5264 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
5265
5266 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
5267 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
5268 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
5269 Address RHSElementCurrent =
5270 Address(RHSElementPHI,
5271 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5272
5273 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
5274 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
5275 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
5276 Address LHSElementCurrent =
5277 Address(LHSElementPHI,
5278 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5279
5280 // Emit copy.
5281 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005282 Scope.addPrivate(LHSVar, [=]() { return LHSElementCurrent; });
5283 Scope.addPrivate(RHSVar, [=]() { return RHSElementCurrent; });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005284 Scope.Privatize();
5285 RedOpGen(CGF, XExpr, EExpr, UpExpr);
5286 Scope.ForceCleanup();
5287
5288 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005289 llvm::Value *LHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005290 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005291 llvm::Value *RHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005292 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
5293 // Check whether we've reached the end.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005294 llvm::Value *Done =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005295 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
5296 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
5297 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
5298 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
5299
5300 // Done.
5301 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
5302}
5303
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005304/// Emit reduction combiner. If the combiner is a simple expression emit it as
5305/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
5306/// UDR combiner function.
5307static void emitReductionCombiner(CodeGenFunction &CGF,
5308 const Expr *ReductionOp) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005309 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
5310 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
5311 if (const auto *DRE =
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005312 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005313 if (const auto *DRD =
5314 dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005315 std::pair<llvm::Function *, llvm::Function *> Reduction =
5316 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
5317 RValue Func = RValue::get(Reduction.first);
5318 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
5319 CGF.EmitIgnoredExpr(ReductionOp);
5320 return;
5321 }
5322 CGF.EmitIgnoredExpr(ReductionOp);
5323}
5324
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005325llvm::Value *CGOpenMPRuntime::emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005326 CodeGenModule &CGM, SourceLocation Loc, llvm::Type *ArgsType,
5327 ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs,
5328 ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005329 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005330
5331 // void reduction_func(void *LHSArg, void *RHSArg);
5332 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005333 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5334 ImplicitParamDecl::Other);
5335 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5336 ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005337 Args.push_back(&LHSArg);
5338 Args.push_back(&RHSArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005339 const auto &CGFI =
5340 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005341 std::string Name = getName({"omp", "reduction", "reduction_func"});
5342 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
5343 llvm::GlobalValue::InternalLinkage, Name,
5344 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005345 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005346 Fn->setDoesNotRecurse();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005347 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005348 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005349
5350 // Dst = (void*[n])(LHSArg);
5351 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00005352 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5353 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
5354 ArgsType), CGF.getPointerAlign());
5355 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5356 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
5357 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005358
5359 // ...
5360 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
5361 // ...
5362 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005363 auto IPriv = Privates.begin();
5364 unsigned Idx = 0;
5365 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005366 const auto *RHSVar =
5367 cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
5368 Scope.addPrivate(RHSVar, [&CGF, RHS, Idx, RHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005369 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005370 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005371 const auto *LHSVar =
5372 cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
5373 Scope.addPrivate(LHSVar, [&CGF, LHS, Idx, LHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005374 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005375 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005376 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00005377 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005378 // Get array size and emit VLA type.
5379 ++Idx;
5380 Address Elem =
5381 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
5382 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005383 const VariableArrayType *VLA =
5384 CGF.getContext().getAsVariableArrayType(PrivTy);
5385 const auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005386 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00005387 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005388 CGF.EmitVariablyModifiedType(PrivTy);
5389 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005390 }
5391 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005392 IPriv = Privates.begin();
5393 auto ILHS = LHSExprs.begin();
5394 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005395 for (const Expr *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005396 if ((*IPriv)->getType()->isArrayType()) {
5397 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005398 const auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5399 const auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005400 EmitOMPAggregateReduction(
5401 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5402 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5403 emitReductionCombiner(CGF, E);
5404 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005405 } else {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005406 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005407 emitReductionCombiner(CGF, E);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005408 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005409 ++IPriv;
5410 ++ILHS;
5411 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005412 }
5413 Scope.ForceCleanup();
5414 CGF.FinishFunction();
5415 return Fn;
5416}
5417
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005418void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
5419 const Expr *ReductionOp,
5420 const Expr *PrivateRef,
5421 const DeclRefExpr *LHS,
5422 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005423 if (PrivateRef->getType()->isArrayType()) {
5424 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005425 const auto *LHSVar = cast<VarDecl>(LHS->getDecl());
5426 const auto *RHSVar = cast<VarDecl>(RHS->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005427 EmitOMPAggregateReduction(
5428 CGF, PrivateRef->getType(), LHSVar, RHSVar,
5429 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5430 emitReductionCombiner(CGF, ReductionOp);
5431 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005432 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005433 // Emit reduction for array subscript or single variable.
5434 emitReductionCombiner(CGF, ReductionOp);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005435 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005436}
5437
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005438void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005439 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005440 ArrayRef<const Expr *> LHSExprs,
5441 ArrayRef<const Expr *> RHSExprs,
5442 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005443 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005444 if (!CGF.HaveInsertPoint())
5445 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005446
5447 bool WithNowait = Options.WithNowait;
5448 bool SimpleReduction = Options.SimpleReduction;
5449
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005450 // Next code should be emitted for reduction:
5451 //
5452 // static kmp_critical_name lock = { 0 };
5453 //
5454 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
5455 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
5456 // ...
5457 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
5458 // *(Type<n>-1*)rhs[<n>-1]);
5459 // }
5460 //
5461 // ...
5462 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
5463 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5464 // RedList, reduce_func, &<lock>)) {
5465 // case 1:
5466 // ...
5467 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5468 // ...
5469 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5470 // break;
5471 // case 2:
5472 // ...
5473 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5474 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00005475 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005476 // break;
5477 // default:;
5478 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005479 //
5480 // if SimpleReduction is true, only the next code is generated:
5481 // ...
5482 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5483 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005484
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005485 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005486
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005487 if (SimpleReduction) {
5488 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005489 auto IPriv = Privates.begin();
5490 auto ILHS = LHSExprs.begin();
5491 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005492 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005493 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5494 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005495 ++IPriv;
5496 ++ILHS;
5497 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005498 }
5499 return;
5500 }
5501
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005502 // 1. Build a list of reduction variables.
5503 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005504 auto Size = RHSExprs.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005505 for (const Expr *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005506 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005507 // Reserve place for array size.
5508 ++Size;
5509 }
5510 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005511 QualType ReductionArrayTy =
5512 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
5513 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00005514 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005515 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005516 auto IPriv = Privates.begin();
5517 unsigned Idx = 0;
5518 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00005519 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005520 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00005521 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005522 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00005523 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
5524 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005525 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005526 // Store array size.
5527 ++Idx;
5528 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
5529 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00005530 llvm::Value *Size = CGF.Builder.CreateIntCast(
5531 CGF.getVLASize(
5532 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
Sander de Smalen891af03a2018-02-03 13:55:59 +00005533 .NumElts,
Alexey Bataev1189bd02016-01-26 12:20:39 +00005534 CGF.SizeTy, /*isSigned=*/false);
5535 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
5536 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005537 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005538 }
5539
5540 // 2. Emit reduce_func().
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005541 llvm::Value *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005542 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
5543 Privates, LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005544
5545 // 3. Create static kmp_critical_name lock = { 0 };
Alexey Bataev18fa2322018-05-02 14:20:50 +00005546 std::string Name = getName({"reduction"});
5547 llvm::Value *Lock = getCriticalRegionLock(Name);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005548
5549 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5550 // RedList, reduce_func, &<lock>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005551 llvm::Value *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
5552 llvm::Value *ThreadId = getThreadID(CGF, Loc);
5553 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
5554 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Samuel Antao4c8035b2016-12-12 18:00:20 +00005555 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005556 llvm::Value *Args[] = {
5557 IdentTLoc, // ident_t *<loc>
5558 ThreadId, // i32 <gtid>
5559 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5560 ReductionArrayTySize, // size_type sizeof(RedList)
5561 RL, // void *RedList
5562 ReductionFn, // void (*) (void *, void *) <reduce_func>
5563 Lock // kmp_critical_name *&<lock>
5564 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005565 llvm::Value *Res = CGF.EmitRuntimeCall(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005566 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5567 : OMPRTL__kmpc_reduce),
5568 Args);
5569
5570 // 5. Build switch(res)
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005571 llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5572 llvm::SwitchInst *SwInst =
5573 CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005574
5575 // 6. Build case 1:
5576 // ...
5577 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5578 // ...
5579 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5580 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005581 llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005582 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5583 CGF.EmitBlock(Case1BB);
5584
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005585 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5586 llvm::Value *EndArgs[] = {
5587 IdentTLoc, // ident_t *<loc>
5588 ThreadId, // i32 <gtid>
5589 Lock // kmp_critical_name *&<lock>
5590 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005591 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps](
5592 CodeGenFunction &CGF, PrePostActionTy &Action) {
5593 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005594 auto IPriv = Privates.begin();
5595 auto ILHS = LHSExprs.begin();
5596 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005597 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005598 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5599 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005600 ++IPriv;
5601 ++ILHS;
5602 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005603 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005604 };
5605 RegionCodeGenTy RCG(CodeGen);
5606 CommonActionTy Action(
5607 nullptr, llvm::None,
5608 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5609 : OMPRTL__kmpc_end_reduce),
5610 EndArgs);
5611 RCG.setAction(Action);
5612 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005613
5614 CGF.EmitBranch(DefaultBB);
5615
5616 // 7. Build case 2:
5617 // ...
5618 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5619 // ...
5620 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005621 llvm::BasicBlock *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005622 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5623 CGF.EmitBlock(Case2BB);
5624
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005625 auto &&AtomicCodeGen = [Loc, Privates, LHSExprs, RHSExprs, ReductionOps](
5626 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005627 auto ILHS = LHSExprs.begin();
5628 auto IRHS = RHSExprs.begin();
5629 auto IPriv = Privates.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005630 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005631 const Expr *XExpr = nullptr;
5632 const Expr *EExpr = nullptr;
5633 const Expr *UpExpr = nullptr;
5634 BinaryOperatorKind BO = BO_Comma;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005635 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005636 if (BO->getOpcode() == BO_Assign) {
5637 XExpr = BO->getLHS();
5638 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005639 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005640 }
5641 // Try to emit update expression as a simple atomic.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005642 const Expr *RHSExpr = UpExpr;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005643 if (RHSExpr) {
5644 // Analyze RHS part of the whole expression.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005645 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005646 RHSExpr->IgnoreParenImpCasts())) {
5647 // If this is a conditional operator, analyze its condition for
5648 // min/max reduction operator.
5649 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005650 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005651 if (const auto *BORHS =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005652 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5653 EExpr = BORHS->getRHS();
5654 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005655 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005656 }
5657 if (XExpr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005658 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005659 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005660 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5661 const Expr *EExpr, const Expr *UpExpr) {
5662 LValue X = CGF.EmitLValue(XExpr);
5663 RValue E;
5664 if (EExpr)
5665 E = CGF.EmitAnyExpr(EExpr);
5666 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005667 X, E, BO, /*IsXLHSInRHSPart=*/true,
5668 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005669 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005670 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5671 PrivateScope.addPrivate(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005672 VD, [&CGF, VD, XRValue, Loc]() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005673 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5674 CGF.emitOMPSimpleStore(
5675 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5676 VD->getType().getNonReferenceType(), Loc);
5677 return LHSTemp;
5678 });
5679 (void)PrivateScope.Privatize();
5680 return CGF.EmitAnyExpr(UpExpr);
5681 });
5682 };
5683 if ((*IPriv)->getType()->isArrayType()) {
5684 // Emit atomic reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005685 const auto *RHSVar =
5686 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005687 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5688 AtomicRedGen, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005689 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005690 // Emit atomic reduction for array subscript or single variable.
5691 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005692 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005693 } else {
5694 // Emit as a critical region.
5695 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005696 const Expr *, const Expr *) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005697 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005698 std::string Name = RT.getName({"atomic_reduction"});
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005699 RT.emitCriticalRegion(
Alexey Bataev18fa2322018-05-02 14:20:50 +00005700 CGF, Name,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005701 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5702 Action.Enter(CGF);
5703 emitReductionCombiner(CGF, E);
5704 },
5705 Loc);
5706 };
5707 if ((*IPriv)->getType()->isArrayType()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005708 const auto *LHSVar =
5709 cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5710 const auto *RHSVar =
5711 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005712 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5713 CritRedGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005714 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005715 CritRedGen(CGF, nullptr, nullptr, nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005716 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005717 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005718 ++ILHS;
5719 ++IRHS;
5720 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005721 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005722 };
5723 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5724 if (!WithNowait) {
5725 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5726 llvm::Value *EndArgs[] = {
5727 IdentTLoc, // ident_t *<loc>
5728 ThreadId, // i32 <gtid>
5729 Lock // kmp_critical_name *&<lock>
5730 };
5731 CommonActionTy Action(nullptr, llvm::None,
5732 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5733 EndArgs);
5734 AtomicRCG.setAction(Action);
5735 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005736 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005737 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005738 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005739
5740 CGF.EmitBranch(DefaultBB);
5741 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5742}
5743
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005744/// Generates unique name for artificial threadprivate variables.
Alexey Bataev1c44e152018-03-06 18:59:43 +00005745/// Format is: <Prefix> "." <Decl_mangled_name> "_" "<Decl_start_loc_raw_enc>"
5746static std::string generateUniqueName(CodeGenModule &CGM, StringRef Prefix,
5747 const Expr *Ref) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005748 SmallString<256> Buffer;
5749 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev1c44e152018-03-06 18:59:43 +00005750 const clang::DeclRefExpr *DE;
5751 const VarDecl *D = ::getBaseDecl(Ref, DE);
5752 if (!D)
5753 D = cast<VarDecl>(cast<DeclRefExpr>(Ref)->getDecl());
5754 D = D->getCanonicalDecl();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005755 std::string Name = CGM.getOpenMPRuntime().getName(
5756 {D->isLocalVarDeclOrParm() ? D->getName() : CGM.getMangledName(D)});
5757 Out << Prefix << Name << "_"
5758 << D->getCanonicalDecl()->getLocStart().getRawEncoding();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005759 return Out.str();
5760}
5761
5762/// Emits reduction initializer function:
5763/// \code
5764/// void @.red_init(void* %arg) {
5765/// %0 = bitcast void* %arg to <type>*
5766/// store <type> <init>, <type>* %0
5767/// ret void
5768/// }
5769/// \endcode
5770static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5771 SourceLocation Loc,
5772 ReductionCodeGen &RCG, unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005773 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005774 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005775 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5776 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005777 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005778 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005779 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005780 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005781 std::string Name = CGM.getOpenMPRuntime().getName({"red_init", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005782 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005783 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005784 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005785 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005786 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005787 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005788 Address PrivateAddr = CGF.EmitLoadOfPointer(
5789 CGF.GetAddrOfLocalVar(&Param),
5790 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5791 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 LValue SharedLVal;
5803 // If initializer uses initializer from declare reduction construct, emit a
5804 // pointer to the address of the original reduction item (reuired by reduction
5805 // initializer)
5806 if (RCG.usesReductionInitializer(N)) {
5807 Address SharedAddr =
5808 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5809 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00005810 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataev21dab122018-03-09 15:20:30 +00005811 SharedAddr = CGF.EmitLoadOfPointer(
5812 SharedAddr,
5813 CGM.getContext().VoidPtrTy.castAs<PointerType>()->getTypePtr());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005814 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5815 } else {
5816 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5817 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5818 CGM.getContext().VoidPtrTy);
5819 }
5820 // Emit the initializer:
5821 // %0 = bitcast void* %arg to <type>*
5822 // store <type> <init>, <type>* %0
5823 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5824 [](CodeGenFunction &) { return false; });
5825 CGF.FinishFunction();
5826 return Fn;
5827}
5828
5829/// Emits reduction combiner function:
5830/// \code
5831/// void @.red_comb(void* %arg0, void* %arg1) {
5832/// %lhs = bitcast void* %arg0 to <type>*
5833/// %rhs = bitcast void* %arg1 to <type>*
5834/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5835/// store <type> %2, <type>* %lhs
5836/// ret void
5837/// }
5838/// \endcode
5839static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5840 SourceLocation Loc,
5841 ReductionCodeGen &RCG, unsigned N,
5842 const Expr *ReductionOp,
5843 const Expr *LHS, const Expr *RHS,
5844 const Expr *PrivateRef) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005845 ASTContext &C = CGM.getContext();
5846 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5847 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005848 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005849 ImplicitParamDecl ParamInOut(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
5850 C.VoidPtrTy, ImplicitParamDecl::Other);
5851 ImplicitParamDecl ParamIn(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5852 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005853 Args.emplace_back(&ParamInOut);
5854 Args.emplace_back(&ParamIn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005855 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005856 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005857 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005858 std::string Name = CGM.getOpenMPRuntime().getName({"red_comb", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005859 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005860 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005861 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005862 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005863 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005864 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005865 llvm::Value *Size = nullptr;
5866 // If the size of the reduction item is non-constant, load it from global
5867 // threadprivate variable.
5868 if (RCG.getSizes(N).second) {
5869 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5870 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005871 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005872 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5873 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005874 }
5875 RCG.emitAggregateType(CGF, N, Size);
5876 // Remap lhs and rhs variables to the addresses of the function arguments.
5877 // %lhs = bitcast void* %arg0 to <type>*
5878 // %rhs = bitcast void* %arg1 to <type>*
5879 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005880 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005881 // Pull out the pointer to the variable.
5882 Address PtrAddr = CGF.EmitLoadOfPointer(
5883 CGF.GetAddrOfLocalVar(&ParamInOut),
5884 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5885 return CGF.Builder.CreateElementBitCast(
5886 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
5887 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005888 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005889 // Pull out the pointer to the variable.
5890 Address PtrAddr = CGF.EmitLoadOfPointer(
5891 CGF.GetAddrOfLocalVar(&ParamIn),
5892 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5893 return CGF.Builder.CreateElementBitCast(
5894 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
5895 });
5896 PrivateScope.Privatize();
5897 // Emit the combiner body:
5898 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
5899 // store <type> %2, <type>* %lhs
5900 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
5901 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
5902 cast<DeclRefExpr>(RHS));
5903 CGF.FinishFunction();
5904 return Fn;
5905}
5906
5907/// Emits reduction finalizer function:
5908/// \code
5909/// void @.red_fini(void* %arg) {
5910/// %0 = bitcast void* %arg to <type>*
5911/// <destroy>(<type>* %0)
5912/// ret void
5913/// }
5914/// \endcode
5915static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
5916 SourceLocation Loc,
5917 ReductionCodeGen &RCG, unsigned N) {
5918 if (!RCG.needCleanups(N))
5919 return nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005920 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005921 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005922 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5923 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005924 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005925 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005926 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005927 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005928 std::string Name = CGM.getOpenMPRuntime().getName({"red_fini", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005929 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005930 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005931 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005932 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005933 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005934 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005935 Address PrivateAddr = CGF.EmitLoadOfPointer(
5936 CGF.GetAddrOfLocalVar(&Param),
5937 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5938 llvm::Value *Size = nullptr;
5939 // If the size of the reduction item is non-constant, load it from global
5940 // threadprivate variable.
5941 if (RCG.getSizes(N).second) {
5942 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5943 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005944 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005945 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5946 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005947 }
5948 RCG.emitAggregateType(CGF, N, Size);
5949 // Emit the finalizer body:
5950 // <destroy>(<type>* %0)
5951 RCG.emitCleanups(CGF, N, PrivateAddr);
5952 CGF.FinishFunction();
5953 return Fn;
5954}
5955
5956llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
5957 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
5958 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
5959 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
5960 return nullptr;
5961
5962 // Build typedef struct:
5963 // kmp_task_red_input {
5964 // void *reduce_shar; // shared reduction item
5965 // size_t reduce_size; // size of data item
5966 // void *reduce_init; // data initialization routine
5967 // void *reduce_fini; // data finalization routine
5968 // void *reduce_comb; // data combiner routine
5969 // kmp_task_red_flags_t flags; // flags for additional info from compiler
5970 // } kmp_task_red_input_t;
5971 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005972 RecordDecl *RD = C.buildImplicitRecord("kmp_task_red_input_t");
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005973 RD->startDefinition();
5974 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5975 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
5976 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5977 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5978 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5979 const FieldDecl *FlagsFD = addFieldToRecordDecl(
5980 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
5981 RD->completeDefinition();
5982 QualType RDType = C.getRecordType(RD);
5983 unsigned Size = Data.ReductionVars.size();
5984 llvm::APInt ArraySize(/*numBits=*/64, Size);
5985 QualType ArrayRDType = C.getConstantArrayType(
5986 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5987 // kmp_task_red_input_t .rd_input.[Size];
5988 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
5989 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
5990 Data.ReductionOps);
5991 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
5992 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
5993 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
5994 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
5995 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
5996 TaskRedInput.getPointer(), Idxs,
5997 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
5998 ".rd_input.gep.");
5999 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
6000 // ElemLVal.reduce_shar = &Shareds[Cnt];
6001 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
6002 RCG.emitSharedLValue(CGF, Cnt);
6003 llvm::Value *CastedShared =
6004 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
6005 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
6006 RCG.emitAggregateType(CGF, Cnt);
6007 llvm::Value *SizeValInChars;
6008 llvm::Value *SizeVal;
6009 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
6010 // We use delayed creation/initialization for VLAs, array sections and
6011 // custom reduction initializations. It is required because runtime does not
6012 // provide the way to pass the sizes of VLAs/array sections to
6013 // initializer/combiner/finalizer functions and does not pass the pointer to
6014 // original reduction item to the initializer. Instead threadprivate global
6015 // variables are used to store these values and use them in the functions.
6016 bool DelayedCreation = !!SizeVal;
6017 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
6018 /*isSigned=*/false);
6019 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
6020 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
6021 // ElemLVal.reduce_init = init;
6022 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
6023 llvm::Value *InitAddr =
6024 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
6025 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
6026 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
6027 // ElemLVal.reduce_fini = fini;
6028 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
6029 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
6030 llvm::Value *FiniAddr = Fini
6031 ? CGF.EmitCastToVoidPtr(Fini)
6032 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
6033 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
6034 // ElemLVal.reduce_comb = comb;
6035 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
6036 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
6037 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
6038 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
6039 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
6040 // ElemLVal.flags = 0;
6041 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
6042 if (DelayedCreation) {
6043 CGF.EmitStoreOfScalar(
6044 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
6045 FlagsLVal);
6046 } else
6047 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
6048 }
6049 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
6050 // *data);
6051 llvm::Value *Args[] = {
6052 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6053 /*isSigned=*/true),
6054 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
6055 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
6056 CGM.VoidPtrTy)};
6057 return CGF.EmitRuntimeCall(
6058 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
6059}
6060
6061void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
6062 SourceLocation Loc,
6063 ReductionCodeGen &RCG,
6064 unsigned N) {
6065 auto Sizes = RCG.getSizes(N);
6066 // Emit threadprivate global variable if the type is non-constant
6067 // (Sizes.second = nullptr).
6068 if (Sizes.second) {
6069 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
6070 /*isSigned=*/false);
6071 Address SizeAddr = getAddrOfArtificialThreadPrivate(
6072 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00006073 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006074 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
6075 }
6076 // Store address of the original reduction item if custom initializer is used.
6077 if (RCG.usesReductionInitializer(N)) {
6078 Address SharedAddr = getAddrOfArtificialThreadPrivate(
6079 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00006080 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006081 CGF.Builder.CreateStore(
6082 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6083 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
6084 SharedAddr, /*IsVolatile=*/false);
6085 }
6086}
6087
6088Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
6089 SourceLocation Loc,
6090 llvm::Value *ReductionsPtr,
6091 LValue SharedLVal) {
6092 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
6093 // *d);
6094 llvm::Value *Args[] = {
6095 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6096 /*isSigned=*/true),
6097 ReductionsPtr,
6098 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
6099 CGM.VoidPtrTy)};
6100 return Address(
6101 CGF.EmitRuntimeCall(
6102 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
6103 SharedLVal.getAlignment());
6104}
6105
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006106void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
6107 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006108 if (!CGF.HaveInsertPoint())
6109 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006110 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
6111 // global_tid);
6112 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
6113 // Ignore return result until untied tasks are supported.
6114 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00006115 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
6116 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006117}
6118
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006119void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006120 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006121 const RegionCodeGenTy &CodeGen,
6122 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006123 if (!CGF.HaveInsertPoint())
6124 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00006125 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006126 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00006127}
6128
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006129namespace {
6130enum RTCancelKind {
6131 CancelNoreq = 0,
6132 CancelParallel = 1,
6133 CancelLoop = 2,
6134 CancelSections = 3,
6135 CancelTaskgroup = 4
6136};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00006137} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006138
6139static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
6140 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00006141 if (CancelRegion == OMPD_parallel)
6142 CancelKind = CancelParallel;
6143 else if (CancelRegion == OMPD_for)
6144 CancelKind = CancelLoop;
6145 else if (CancelRegion == OMPD_sections)
6146 CancelKind = CancelSections;
6147 else {
6148 assert(CancelRegion == OMPD_taskgroup);
6149 CancelKind = CancelTaskgroup;
6150 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006151 return CancelKind;
6152}
6153
6154void CGOpenMPRuntime::emitCancellationPointCall(
6155 CodeGenFunction &CGF, SourceLocation Loc,
6156 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006157 if (!CGF.HaveInsertPoint())
6158 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006159 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
6160 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006161 if (auto *OMPRegionInfo =
6162 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00006163 // For 'cancellation point taskgroup', the task region info may not have a
6164 // cancel. This may instead happen in another adjacent task.
6165 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006166 llvm::Value *Args[] = {
6167 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
6168 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006169 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006170 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006171 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
6172 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006173 // exit from construct;
6174 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006175 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6176 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6177 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006178 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6179 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006180 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006181 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev25e5b442015-09-15 12:52:43 +00006182 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006183 CGF.EmitBranchThroughCleanup(CancelDest);
6184 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6185 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006186 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006187}
6188
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006189void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00006190 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006191 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006192 if (!CGF.HaveInsertPoint())
6193 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006194 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
6195 // kmp_int32 cncl_kind);
6196 if (auto *OMPRegionInfo =
6197 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006198 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
6199 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006200 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00006201 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006202 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00006203 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
6204 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006205 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006206 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00006207 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00006208 // exit from construct;
6209 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006210 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6211 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6212 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev87933c72015-09-18 08:07:34 +00006213 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6214 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00006215 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006216 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev87933c72015-09-18 08:07:34 +00006217 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
6218 CGF.EmitBranchThroughCleanup(CancelDest);
6219 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6220 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006221 if (IfCond) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006222 emitOMPIfClause(CGF, IfCond, ThenGen,
6223 [](CodeGenFunction &, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006224 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006225 RegionCodeGenTy ThenRCG(ThenGen);
6226 ThenRCG(CGF);
6227 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006228 }
6229}
Samuel Antaobed3c462015-10-02 16:14:20 +00006230
Samuel Antaoee8fb302016-01-06 13:42:12 +00006231void CGOpenMPRuntime::emitTargetOutlinedFunction(
6232 const OMPExecutableDirective &D, StringRef ParentName,
6233 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006234 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00006235 assert(!ParentName.empty() && "Invalid target region parent name!");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006236 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
6237 IsOffloadEntry, CodeGen);
6238}
6239
6240void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
6241 const OMPExecutableDirective &D, StringRef ParentName,
6242 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
6243 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00006244 // Create a unique name for the entry function using the source location
6245 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00006246 //
Samuel Antao2de62b02016-02-13 23:35:10 +00006247 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00006248 //
6249 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00006250 // mangled name of the function that encloses the target region and BB is the
6251 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00006252
6253 unsigned DeviceID;
6254 unsigned FileID;
6255 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00006256 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00006257 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006258 SmallString<64> EntryFnName;
6259 {
6260 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00006261 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
6262 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00006263 }
6264
Alexey Bataev475a7442018-01-12 19:39:11 +00006265 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006266
Samuel Antaobed3c462015-10-02 16:14:20 +00006267 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006268 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00006269 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006270
Samuel Antao6d004262016-06-16 18:39:34 +00006271 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006272
6273 // If this target outline function is not an offload entry, we don't need to
6274 // register it.
6275 if (!IsOffloadEntry)
6276 return;
6277
6278 // The target region ID is used by the runtime library to identify the current
6279 // target region, so it only has to be unique and not necessarily point to
6280 // anything. It could be the pointer to the outlined function that implements
6281 // the target region, but we aren't using that so that the compiler doesn't
6282 // need to keep that, and could therefore inline the host function if proven
6283 // worthwhile during optimization. In the other hand, if emitting code for the
6284 // device, the ID has to be the function address so that it can retrieved from
6285 // the offloading entry and launched by the runtime library. We also mark the
6286 // outlined function to have external linkage in case we are emitting code for
6287 // the device, because these functions will be entry points to the device.
6288
6289 if (CGM.getLangOpts().OpenMPIsDevice) {
6290 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
6291 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
Rafael Espindolacbca4872018-01-11 22:15:12 +00006292 OutlinedFn->setDSOLocal(false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006293 } else {
Alexey Bataev18fa2322018-05-02 14:20:50 +00006294 std::string Name = getName({"omp_offload", "region_id"});
Samuel Antaoee8fb302016-01-06 13:42:12 +00006295 OutlinedFnID = new llvm::GlobalVariable(
6296 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
6297 llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00006298 llvm::Constant::getNullValue(CGM.Int8Ty), Name);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006299 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00006300
6301 // Register the information for the entry associated with this target region.
6302 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00006303 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
Alexey Bataev03f270c2018-03-30 18:31:07 +00006304 OffloadEntriesInfoManagerTy::OMPTargetRegionEntryTargetRegion);
Samuel Antaobed3c462015-10-02 16:14:20 +00006305}
6306
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006307/// discard all CompoundStmts intervening between two constructs
6308static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006309 while (const auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006310 Body = CS->body_front();
6311
6312 return Body;
6313}
6314
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006315/// Emit the number of teams for a target directive. Inspect the num_teams
6316/// clause associated with a teams construct combined or closely nested
6317/// with the target directive.
6318///
6319/// Emit a team of size one for directives such as 'target parallel' that
6320/// have no associated teams construct.
6321///
6322/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006323static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006324emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6325 CodeGenFunction &CGF,
6326 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006327 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6328 "teams directive expected to be "
6329 "emitted only for the host!");
6330
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006331 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006332
6333 // If the target directive is combined with a teams directive:
6334 // Return the value in the num_teams clause, if any.
6335 // Otherwise, return 0 to denote the runtime default.
6336 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
6337 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
6338 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006339 llvm::Value *NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
6340 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006341 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6342 /*IsSigned=*/true);
6343 }
6344
6345 // The default value is 0.
6346 return Bld.getInt32(0);
6347 }
6348
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006349 // If the target directive is combined with a parallel directive but not a
6350 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006351 if (isOpenMPParallelDirective(D.getDirectiveKind()))
6352 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006353
6354 // If the current target region has a teams region enclosed, we need to get
6355 // the number of teams to pass to the runtime function call. This is done
6356 // by generating the expression in a inlined region. This is required because
6357 // the expression is captured in the enclosing target environment when the
6358 // teams directive is not combined with target.
6359
Alexey Bataev475a7442018-01-12 19:39:11 +00006360 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006361
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006362 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006363 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006364 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006365 if (const auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006366 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6367 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6368 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
6369 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6370 /*IsSigned=*/true);
6371 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006372
Alexey Bataev50a1c782017-12-01 21:31:08 +00006373 // If we have an enclosed teams directive but no num_teams clause we use
6374 // the default value 0.
6375 return Bld.getInt32(0);
6376 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006377 }
6378
6379 // No teams associated with the directive.
6380 return nullptr;
6381}
6382
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006383/// Emit the number of threads for a target directive. Inspect the
6384/// thread_limit clause associated with a teams construct combined or closely
6385/// nested with the target directive.
6386///
6387/// Emit the num_threads clause for directives such as 'target parallel' that
6388/// have no associated teams construct.
6389///
6390/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006391static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006392emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6393 CodeGenFunction &CGF,
6394 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006395 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6396 "teams directive expected to be "
6397 "emitted only for the host!");
6398
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006399 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006400
6401 //
6402 // If the target directive is combined with a teams directive:
6403 // Return the value in the thread_limit clause, if any.
6404 //
6405 // If the target directive is combined with a parallel directive:
6406 // Return the value in the num_threads clause, if any.
6407 //
6408 // If both clauses are set, select the minimum of the two.
6409 //
6410 // If neither teams or parallel combined directives set the number of threads
6411 // in a team, return 0 to denote the runtime default.
6412 //
6413 // If this is not a teams directive return nullptr.
6414
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006415 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
6416 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006417 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
6418 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006419 llvm::Value *ThreadLimitVal = nullptr;
6420
6421 if (const auto *ThreadLimitClause =
6422 D.getSingleClause<OMPThreadLimitClause>()) {
6423 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006424 llvm::Value *ThreadLimit =
6425 CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
6426 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006427 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6428 /*IsSigned=*/true);
6429 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006430
6431 if (const auto *NumThreadsClause =
6432 D.getSingleClause<OMPNumThreadsClause>()) {
6433 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
6434 llvm::Value *NumThreads =
6435 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
6436 /*IgnoreResultAssign*/ true);
6437 NumThreadsVal =
6438 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
6439 }
6440
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006441 // Select the lesser of thread_limit and num_threads.
6442 if (NumThreadsVal)
6443 ThreadLimitVal = ThreadLimitVal
6444 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
6445 ThreadLimitVal),
6446 NumThreadsVal, ThreadLimitVal)
6447 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00006448
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006449 // Set default value passed to the runtime if either teams or a target
6450 // parallel type directive is found but no clause is specified.
6451 if (!ThreadLimitVal)
6452 ThreadLimitVal = DefaultThreadLimitVal;
6453
6454 return ThreadLimitVal;
6455 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00006456
Samuel Antaob68e2db2016-03-03 16:20:23 +00006457 // If the current target region has a teams region enclosed, we need to get
6458 // the thread limit to pass to the runtime function call. This is done
6459 // by generating the expression in a inlined region. This is required because
6460 // the expression is captured in the enclosing target environment when the
6461 // teams directive is not combined with target.
6462
Alexey Bataev475a7442018-01-12 19:39:11 +00006463 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006464
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006465 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006466 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006467 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006468 if (const auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006469 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6470 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6471 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
6472 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6473 /*IsSigned=*/true);
6474 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006475
Alexey Bataev50a1c782017-12-01 21:31:08 +00006476 // If we have an enclosed teams directive but no thread_limit clause we
6477 // use the default value 0.
6478 return CGF.Builder.getInt32(0);
6479 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006480 }
6481
6482 // No teams associated with the directive.
6483 return nullptr;
6484}
6485
Samuel Antao86ace552016-04-27 22:40:57 +00006486namespace {
6487// \brief Utility to handle information from clauses associated with a given
6488// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
6489// It provides a convenient interface to obtain the information and generate
6490// code for that information.
6491class MappableExprsHandler {
6492public:
6493 /// \brief Values for bit flags used to specify the mapping type for
6494 /// offloading.
6495 enum OpenMPOffloadMappingFlags {
Samuel Antao86ace552016-04-27 22:40:57 +00006496 /// \brief Allocate memory on the device and move data from host to device.
6497 OMP_MAP_TO = 0x01,
6498 /// \brief Allocate memory on the device and move data from device to host.
6499 OMP_MAP_FROM = 0x02,
6500 /// \brief Always perform the requested mapping action on the element, even
6501 /// if it was already mapped before.
6502 OMP_MAP_ALWAYS = 0x04,
Samuel Antao86ace552016-04-27 22:40:57 +00006503 /// \brief Delete the element from the device environment, ignoring the
6504 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00006505 OMP_MAP_DELETE = 0x08,
George Rokos065755d2017-11-07 18:27:04 +00006506 /// \brief The element being mapped is a pointer-pointee pair; both the
6507 /// pointer and the pointee should be mapped.
6508 OMP_MAP_PTR_AND_OBJ = 0x10,
6509 /// \brief This flags signals that the base address of an entry should be
6510 /// passed to the target kernel as an argument.
6511 OMP_MAP_TARGET_PARAM = 0x20,
Samuel Antaocc10b852016-07-28 14:23:26 +00006512 /// \brief Signal that the runtime library has to return the device pointer
George Rokos065755d2017-11-07 18:27:04 +00006513 /// in the current position for the data being mapped. Used when we have the
6514 /// use_device_ptr clause.
6515 OMP_MAP_RETURN_PARAM = 0x40,
Samuel Antaod486f842016-05-26 16:53:38 +00006516 /// \brief This flag signals that the reference being passed is a pointer to
6517 /// private data.
George Rokos065755d2017-11-07 18:27:04 +00006518 OMP_MAP_PRIVATE = 0x80,
Samuel Antao86ace552016-04-27 22:40:57 +00006519 /// \brief Pass the element to the device by value.
George Rokos065755d2017-11-07 18:27:04 +00006520 OMP_MAP_LITERAL = 0x100,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006521 /// Implicit map
6522 OMP_MAP_IMPLICIT = 0x200,
Samuel Antao86ace552016-04-27 22:40:57 +00006523 };
6524
Samuel Antaocc10b852016-07-28 14:23:26 +00006525 /// Class that associates information with a base pointer to be passed to the
6526 /// runtime library.
6527 class BasePointerInfo {
6528 /// The base pointer.
6529 llvm::Value *Ptr = nullptr;
6530 /// The base declaration that refers to this device pointer, or null if
6531 /// there is none.
6532 const ValueDecl *DevPtrDecl = nullptr;
6533
6534 public:
6535 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
6536 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
6537 llvm::Value *operator*() const { return Ptr; }
6538 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
6539 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
6540 };
6541
6542 typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00006543 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
George Rokos63bc9d62017-11-21 18:25:12 +00006544 typedef SmallVector<uint64_t, 16> MapFlagsArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00006545
6546private:
6547 /// \brief Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00006548 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00006549
6550 /// \brief Function the directive is being generated for.
6551 CodeGenFunction &CGF;
6552
Samuel Antaod486f842016-05-26 16:53:38 +00006553 /// \brief Set of all first private variables in the current directive.
6554 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
Alexey Bataev3f96fe62017-12-13 17:31:39 +00006555 /// Set of all reduction variables in the current directive.
6556 llvm::SmallPtrSet<const VarDecl *, 8> ReductionDecls;
Samuel Antaod486f842016-05-26 16:53:38 +00006557
Samuel Antao6890b092016-07-28 14:25:09 +00006558 /// Map between device pointer declarations and their expression components.
6559 /// The key value for declarations in 'this' is null.
6560 llvm::DenseMap<
6561 const ValueDecl *,
6562 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6563 DevPointersMap;
6564
Samuel Antao86ace552016-04-27 22:40:57 +00006565 llvm::Value *getExprTypeSize(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006566 QualType ExprTy = E->getType().getCanonicalType();
Samuel Antao86ace552016-04-27 22:40:57 +00006567
6568 // Reference types are ignored for mapping purposes.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006569 if (const auto *RefTy = ExprTy->getAs<ReferenceType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006570 ExprTy = RefTy->getPointeeType().getCanonicalType();
6571
6572 // Given that an array section is considered a built-in type, we need to
6573 // do the calculation based on the length of the section instead of relying
6574 // on CGF.getTypeSize(E->getType()).
6575 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6576 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6577 OAE->getBase()->IgnoreParenImpCasts())
6578 .getCanonicalType();
6579
6580 // If there is no length associated with the expression, that means we
6581 // are using the whole length of the base.
6582 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6583 return CGF.getTypeSize(BaseTy);
6584
6585 llvm::Value *ElemSize;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006586 if (const auto *PTy = BaseTy->getAs<PointerType>()) {
Samuel Antao86ace552016-04-27 22:40:57 +00006587 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006588 } else {
6589 const auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
Samuel Antao86ace552016-04-27 22:40:57 +00006590 assert(ATy && "Expecting array type if not a pointer type.");
6591 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6592 }
6593
6594 // If we don't have a length at this point, that is because we have an
6595 // array section with a single element.
6596 if (!OAE->getLength())
6597 return ElemSize;
6598
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006599 llvm::Value *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
Samuel Antao86ace552016-04-27 22:40:57 +00006600 LengthVal =
6601 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6602 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6603 }
6604 return CGF.getTypeSize(ExprTy);
6605 }
6606
6607 /// \brief Return the corresponding bits for a given map clause modifier. Add
6608 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006609 /// map as the first one of a series of maps that relate to the same map
6610 /// expression.
George Rokos63bc9d62017-11-21 18:25:12 +00006611 uint64_t getMapTypeBits(OpenMPMapClauseKind MapType,
Samuel Antao86ace552016-04-27 22:40:57 +00006612 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
George Rokos065755d2017-11-07 18:27:04 +00006613 bool AddIsTargetParamFlag) const {
George Rokos63bc9d62017-11-21 18:25:12 +00006614 uint64_t Bits = 0u;
Samuel Antao86ace552016-04-27 22:40:57 +00006615 switch (MapType) {
6616 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006617 case OMPC_MAP_release:
6618 // alloc and release is the default behavior in the runtime library, i.e.
6619 // if we don't pass any bits alloc/release that is what the runtime is
6620 // going to do. Therefore, we don't need to signal anything for these two
6621 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006622 break;
6623 case OMPC_MAP_to:
6624 Bits = OMP_MAP_TO;
6625 break;
6626 case OMPC_MAP_from:
6627 Bits = OMP_MAP_FROM;
6628 break;
6629 case OMPC_MAP_tofrom:
6630 Bits = OMP_MAP_TO | OMP_MAP_FROM;
6631 break;
6632 case OMPC_MAP_delete:
6633 Bits = OMP_MAP_DELETE;
6634 break;
Samuel Antao86ace552016-04-27 22:40:57 +00006635 default:
6636 llvm_unreachable("Unexpected map type!");
6637 break;
6638 }
6639 if (AddPtrFlag)
George Rokos065755d2017-11-07 18:27:04 +00006640 Bits |= OMP_MAP_PTR_AND_OBJ;
6641 if (AddIsTargetParamFlag)
6642 Bits |= OMP_MAP_TARGET_PARAM;
Samuel Antao86ace552016-04-27 22:40:57 +00006643 if (MapTypeModifier == OMPC_MAP_always)
6644 Bits |= OMP_MAP_ALWAYS;
6645 return Bits;
6646 }
6647
6648 /// \brief Return true if the provided expression is a final array section. A
6649 /// final array section, is one whose length can't be proved to be one.
6650 bool isFinalArraySectionExpression(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006651 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antao86ace552016-04-27 22:40:57 +00006652
6653 // It is not an array section and therefore not a unity-size one.
6654 if (!OASE)
6655 return false;
6656
6657 // An array section with no colon always refer to a single element.
6658 if (OASE->getColonLoc().isInvalid())
6659 return false;
6660
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006661 const Expr *Length = OASE->getLength();
Samuel Antao86ace552016-04-27 22:40:57 +00006662
6663 // If we don't have a length we have to check if the array has size 1
6664 // for this dimension. Also, we should always expect a length if the
6665 // base type is pointer.
6666 if (!Length) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006667 QualType BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6668 OASE->getBase()->IgnoreParenImpCasts())
6669 .getCanonicalType();
6670 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antao86ace552016-04-27 22:40:57 +00006671 return ATy->getSize().getSExtValue() != 1;
6672 // If we don't have a constant dimension length, we have to consider
6673 // the current section as having any size, so it is not necessarily
6674 // unitary. If it happen to be unity size, that's user fault.
6675 return true;
6676 }
6677
6678 // Check if the length evaluates to 1.
6679 llvm::APSInt ConstLength;
6680 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
6681 return true; // Can have more that size 1.
6682
6683 return ConstLength.getSExtValue() != 1;
6684 }
6685
Alexey Bataev92327c52018-03-26 16:40:55 +00006686 /// \brief Return the adjusted map modifiers if the declaration a capture
6687 /// refers to appears in a first-private clause. This is expected to be used
6688 /// only with directives that start with 'target'.
6689 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
6690 unsigned CurrentModifiers) {
6691 assert(Cap.capturesVariable() && "Expected capture by reference only!");
6692
6693 // A first private variable captured by reference will use only the
6694 // 'private ptr' and 'map to' flag. Return the right flags if the captured
6695 // declaration is known as first-private in this handler.
6696 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
6697 return MappableExprsHandler::OMP_MAP_PRIVATE |
6698 MappableExprsHandler::OMP_MAP_TO;
6699 // Reduction variable will use only the 'private ptr' and 'map to_from'
6700 // flag.
6701 if (ReductionDecls.count(Cap.getCapturedVar())) {
6702 return MappableExprsHandler::OMP_MAP_TO |
6703 MappableExprsHandler::OMP_MAP_FROM;
6704 }
6705
6706 // We didn't modify anything.
6707 return CurrentModifiers;
6708 }
6709
6710public:
6711 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
6712 : CurDir(Dir), CGF(CGF) {
6713 // Extract firstprivate clause information.
6714 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006715 for (const Expr *D : C->varlists())
Alexey Bataev92327c52018-03-26 16:40:55 +00006716 FirstPrivateDecls.insert(
6717 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
6718 for (const auto *C : Dir.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006719 for (const Expr *D : C->varlists()) {
Alexey Bataev92327c52018-03-26 16:40:55 +00006720 ReductionDecls.insert(
6721 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
6722 }
6723 }
6724 // Extract device pointer clause information.
6725 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006726 for (const auto &L : C->component_lists())
Alexey Bataev92327c52018-03-26 16:40:55 +00006727 DevPointersMap[L.first].push_back(L.second);
6728 }
6729
Samuel Antao86ace552016-04-27 22:40:57 +00006730 /// \brief Generate the base pointers, section pointers, sizes and map type
6731 /// bits for the provided map type, map modifier, and expression components.
6732 /// \a IsFirstComponent should be set to true if the provided set of
6733 /// components is the first associated with a capture.
6734 void generateInfoForComponentList(
6735 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6736 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006737 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006738 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006739 bool IsFirstComponentList, bool IsImplicit) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006740
6741 // The following summarizes what has to be generated for each map and the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006742 // types below. The generated information is expressed in this order:
Samuel Antao86ace552016-04-27 22:40:57 +00006743 // base pointer, section pointer, size, flags
6744 // (to add to the ones that come from the map type and modifier).
6745 //
6746 // double d;
6747 // int i[100];
6748 // float *p;
6749 //
6750 // struct S1 {
6751 // int i;
6752 // float f[50];
6753 // }
6754 // struct S2 {
6755 // int i;
6756 // float f[50];
6757 // S1 s;
6758 // double *p;
6759 // struct S2 *ps;
6760 // }
6761 // S2 s;
6762 // S2 *ps;
6763 //
6764 // map(d)
6765 // &d, &d, sizeof(double), noflags
6766 //
6767 // map(i)
6768 // &i, &i, 100*sizeof(int), noflags
6769 //
6770 // map(i[1:23])
6771 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
6772 //
6773 // map(p)
6774 // &p, &p, sizeof(float*), noflags
6775 //
6776 // map(p[1:24])
6777 // p, &p[1], 24*sizeof(float), noflags
6778 //
6779 // map(s)
6780 // &s, &s, sizeof(S2), noflags
6781 //
6782 // map(s.i)
6783 // &s, &(s.i), sizeof(int), noflags
6784 //
6785 // map(s.s.f)
6786 // &s, &(s.i.f), 50*sizeof(int), noflags
6787 //
6788 // map(s.p)
6789 // &s, &(s.p), sizeof(double*), noflags
6790 //
6791 // map(s.p[:22], s.a s.b)
6792 // &s, &(s.p), sizeof(double*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006793 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006794 //
6795 // map(s.ps)
6796 // &s, &(s.ps), sizeof(S2*), noflags
6797 //
6798 // map(s.ps->s.i)
6799 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006800 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006801 //
6802 // map(s.ps->ps)
6803 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006804 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006805 //
6806 // map(s.ps->ps->ps)
6807 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006808 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
6809 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006810 //
6811 // map(s.ps->ps->s.f[:22])
6812 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006813 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
6814 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006815 //
6816 // map(ps)
6817 // &ps, &ps, sizeof(S2*), noflags
6818 //
6819 // map(ps->i)
6820 // ps, &(ps->i), sizeof(int), noflags
6821 //
6822 // map(ps->s.f)
6823 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
6824 //
6825 // map(ps->p)
6826 // ps, &(ps->p), sizeof(double*), noflags
6827 //
6828 // map(ps->p[:22])
6829 // ps, &(ps->p), sizeof(double*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006830 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006831 //
6832 // map(ps->ps)
6833 // ps, &(ps->ps), sizeof(S2*), noflags
6834 //
6835 // map(ps->ps->s.i)
6836 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006837 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006838 //
6839 // map(ps->ps->ps)
6840 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006841 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006842 //
6843 // map(ps->ps->ps->ps)
6844 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006845 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
6846 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006847 //
6848 // map(ps->ps->ps->s.f[:22])
6849 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006850 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
6851 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006852
6853 // Track if the map information being generated is the first for a capture.
6854 bool IsCaptureFirstInfo = IsFirstComponentList;
Alexey Bataev92327c52018-03-26 16:40:55 +00006855 bool IsLink = false; // Is this variable a "declare target link"?
Samuel Antao86ace552016-04-27 22:40:57 +00006856
6857 // Scan the components from the base to the complete expression.
6858 auto CI = Components.rbegin();
6859 auto CE = Components.rend();
6860 auto I = CI;
6861
6862 // Track if the map information being generated is the first for a list of
6863 // components.
6864 bool IsExpressionFirstInfo = true;
6865 llvm::Value *BP = nullptr;
6866
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006867 if (const auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
Samuel Antao86ace552016-04-27 22:40:57 +00006868 // The base is the 'this' pointer. The content of the pointer is going
6869 // to be the base of the field being mapped.
6870 BP = CGF.EmitScalarExpr(ME->getBase());
6871 } else {
6872 // The base is the reference to the variable.
6873 // BP = &Var.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006874 BP = CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Alexey Bataev92327c52018-03-26 16:40:55 +00006875 if (const auto *VD =
6876 dyn_cast_or_null<VarDecl>(I->getAssociatedDeclaration())) {
6877 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev2c1dffe2018-04-16 20:34:41 +00006878 isDeclareTargetDeclaration(VD))
6879 if (*Res == OMPDeclareTargetDeclAttr::MT_Link) {
6880 IsLink = true;
6881 BP = CGF.CGM.getOpenMPRuntime()
6882 .getAddrOfDeclareTargetLink(VD)
6883 .getPointer();
6884 }
Alexey Bataev92327c52018-03-26 16:40:55 +00006885 }
Samuel Antao86ace552016-04-27 22:40:57 +00006886
6887 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00006888 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00006889 // reference. References are ignored for mapping purposes.
6890 QualType Ty =
6891 I->getAssociatedDeclaration()->getType().getNonReferenceType();
6892 if (Ty->isAnyPointerType() && std::next(I) != CE) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006893 LValue PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
Samuel Antao86ace552016-04-27 22:40:57 +00006894 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
Samuel Antao403ffd42016-07-27 22:49:49 +00006895 Ty->castAs<PointerType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006896 .getPointer();
6897
6898 // We do not need to generate individual map information for the
6899 // pointer, it can be associated with the combined storage.
6900 ++I;
6901 }
6902 }
6903
George Rokos63bc9d62017-11-21 18:25:12 +00006904 uint64_t DefaultFlags = IsImplicit ? OMP_MAP_IMPLICIT : 0;
Samuel Antao86ace552016-04-27 22:40:57 +00006905 for (; I != CE; ++I) {
6906 auto Next = std::next(I);
6907
6908 // We need to generate the addresses and sizes if this is the last
6909 // component, if the component is a pointer or if it is an array section
6910 // whose length can't be proved to be one. If this is a pointer, it
6911 // becomes the base address for the following components.
6912
6913 // A final array section, is one whose length can't be proved to be one.
6914 bool IsFinalArraySection =
6915 isFinalArraySectionExpression(I->getAssociatedExpression());
6916
6917 // Get information on whether the element is a pointer. Have to do a
6918 // special treatment for array sections given that they are built-in
6919 // types.
6920 const auto *OASE =
6921 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
6922 bool IsPointer =
6923 (OASE &&
6924 OMPArraySectionExpr::getBaseOriginalType(OASE)
6925 .getCanonicalType()
6926 ->isAnyPointerType()) ||
6927 I->getAssociatedExpression()->getType()->isAnyPointerType();
6928
6929 if (Next == CE || IsPointer || IsFinalArraySection) {
Samuel Antao86ace552016-04-27 22:40:57 +00006930 // If this is not the last component, we expect the pointer to be
6931 // associated with an array expression or member expression.
6932 assert((Next == CE ||
6933 isa<MemberExpr>(Next->getAssociatedExpression()) ||
6934 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
6935 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
6936 "Unexpected expression");
6937
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006938 llvm::Value *LB =
6939 CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006940 llvm::Value *Size = getExprTypeSize(I->getAssociatedExpression());
Samuel Antao86ace552016-04-27 22:40:57 +00006941
Samuel Antao03a3cec2016-07-27 22:52:16 +00006942 // If we have a member expression and the current component is a
6943 // reference, we have to map the reference too. Whenever we have a
6944 // reference, the section that reference refers to is going to be a
6945 // load instruction from the storage assigned to the reference.
6946 if (isa<MemberExpr>(I->getAssociatedExpression()) &&
6947 I->getAssociatedDeclaration()->getType()->isReferenceType()) {
6948 auto *LI = cast<llvm::LoadInst>(LB);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006949 llvm::Value *RefAddr = LI->getPointerOperand();
Samuel Antao03a3cec2016-07-27 22:52:16 +00006950
6951 BasePointers.push_back(BP);
6952 Pointers.push_back(RefAddr);
6953 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006954 Types.push_back(DefaultFlags |
6955 getMapTypeBits(
6956 /*MapType*/ OMPC_MAP_alloc,
6957 /*MapTypeModifier=*/OMPC_MAP_unknown,
6958 !IsExpressionFirstInfo, IsCaptureFirstInfo));
Samuel Antao03a3cec2016-07-27 22:52:16 +00006959 IsExpressionFirstInfo = false;
6960 IsCaptureFirstInfo = false;
6961 // The reference will be the next base address.
6962 BP = RefAddr;
6963 }
6964
6965 BasePointers.push_back(BP);
Samuel Antao86ace552016-04-27 22:40:57 +00006966 Pointers.push_back(LB);
6967 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00006968
Samuel Antao6782e942016-05-26 16:48:10 +00006969 // We need to add a pointer flag for each map that comes from the
6970 // same expression except for the first one. We also need to signal
6971 // this map is the first one that relates with the current capture
6972 // (there is a set of entries for each capture).
Alexey Bataev92327c52018-03-26 16:40:55 +00006973 Types.push_back(DefaultFlags |
6974 getMapTypeBits(MapType, MapTypeModifier,
6975 !IsExpressionFirstInfo || IsLink,
6976 IsCaptureFirstInfo && !IsLink));
Samuel Antao86ace552016-04-27 22:40:57 +00006977
6978 // If we have a final array section, we are done with this expression.
6979 if (IsFinalArraySection)
6980 break;
6981
6982 // The pointer becomes the base for the next element.
6983 if (Next != CE)
6984 BP = LB;
6985
6986 IsExpressionFirstInfo = false;
6987 IsCaptureFirstInfo = false;
Samuel Antao86ace552016-04-27 22:40:57 +00006988 }
6989 }
6990 }
6991
Samuel Antao86ace552016-04-27 22:40:57 +00006992 /// \brief Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00006993 /// types for the extracted mappable expressions. Also, for each item that
6994 /// relates with a device pointer, a pair of the relevant declaration and
6995 /// index where it occurs is appended to the device pointers info array.
6996 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006997 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
6998 MapFlagsArrayTy &Types) const {
6999 BasePointers.clear();
7000 Pointers.clear();
7001 Sizes.clear();
7002 Types.clear();
7003
7004 struct MapInfo {
Samuel Antaocc10b852016-07-28 14:23:26 +00007005 /// Kind that defines how a device pointer has to be returned.
7006 enum ReturnPointerKind {
7007 // Don't have to return any pointer.
7008 RPK_None,
7009 // Pointer is the base of the declaration.
7010 RPK_Base,
7011 // Pointer is a member of the base declaration - 'this'
7012 RPK_Member,
7013 // Pointer is a reference and a member of the base declaration - 'this'
7014 RPK_MemberReference,
7015 };
Samuel Antao86ace552016-04-27 22:40:57 +00007016 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007017 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
7018 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
7019 ReturnPointerKind ReturnDevicePointer = RPK_None;
7020 bool IsImplicit = false;
Hans Wennborgbc1b58d2016-07-30 00:41:37 +00007021
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007022 MapInfo() = default;
Samuel Antaocc10b852016-07-28 14:23:26 +00007023 MapInfo(
7024 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
7025 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007026 ReturnPointerKind ReturnDevicePointer, bool IsImplicit)
Samuel Antaocc10b852016-07-28 14:23:26 +00007027 : Components(Components), MapType(MapType),
7028 MapTypeModifier(MapTypeModifier),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007029 ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
Samuel Antao86ace552016-04-27 22:40:57 +00007030 };
7031
7032 // We have to process the component lists that relate with the same
7033 // declaration in a single chunk so that we can generate the map flags
7034 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00007035 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00007036
7037 // Helper function to fill the information map for the different supported
7038 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00007039 auto &&InfoGen = [&Info](
7040 const ValueDecl *D,
7041 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
7042 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007043 MapInfo::ReturnPointerKind ReturnDevicePointer, bool IsImplicit) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007044 const ValueDecl *VD =
7045 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007046 Info[VD].emplace_back(L, MapType, MapModifier, ReturnDevicePointer,
7047 IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007048 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00007049
Paul Robinson78fb1322016-08-01 22:12:46 +00007050 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007051 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
7052 for (const auto &L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00007053 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007054 MapInfo::RPK_None, C->isImplicit());
7055 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007056 for (const auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
7057 for (const auto &L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00007058 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007059 MapInfo::RPK_None, C->isImplicit());
7060 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007061 for (const auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
7062 for (const auto &L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00007063 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007064 MapInfo::RPK_None, C->isImplicit());
7065 }
Samuel Antao86ace552016-04-27 22:40:57 +00007066
Samuel Antaocc10b852016-07-28 14:23:26 +00007067 // Look at the use_device_ptr clause information and mark the existing map
7068 // entries as such. If there is no map information for an entry in the
7069 // use_device_ptr list, we create one with map type 'alloc' and zero size
7070 // section. It is the user fault if that was not mapped before.
Paul Robinson78fb1322016-08-01 22:12:46 +00007071 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007072 for (const auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
7073 for (const auto &L : C->component_lists()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007074 assert(!L.second.empty() && "Not expecting empty list of components!");
7075 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
7076 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007077 const Expr *IE = L.second.back().getAssociatedExpression();
Samuel Antaocc10b852016-07-28 14:23:26 +00007078 // If the first component is a member expression, we have to look into
7079 // 'this', which maps to null in the map of map information. Otherwise
7080 // look directly for the information.
7081 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
7082
7083 // We potentially have map information for this declaration already.
7084 // Look for the first set of components that refer to it.
7085 if (It != Info.end()) {
7086 auto CI = std::find_if(
7087 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
7088 return MI.Components.back().getAssociatedDeclaration() == VD;
7089 });
7090 // If we found a map entry, signal that the pointer has to be returned
7091 // and move on to the next declaration.
7092 if (CI != It->second.end()) {
7093 CI->ReturnDevicePointer = isa<MemberExpr>(IE)
7094 ? (VD->getType()->isReferenceType()
7095 ? MapInfo::RPK_MemberReference
7096 : MapInfo::RPK_Member)
7097 : MapInfo::RPK_Base;
7098 continue;
7099 }
7100 }
7101
7102 // We didn't find any match in our map information - generate a zero
7103 // size array section.
Paul Robinson78fb1322016-08-01 22:12:46 +00007104 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Alexey Bataev1e491372018-01-23 18:44:14 +00007105 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(this->CGF.EmitLValue(IE),
7106 IE->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +00007107 BasePointers.push_back({Ptr, VD});
7108 Pointers.push_back(Ptr);
Paul Robinson15c84002016-07-29 20:46:16 +00007109 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
George Rokos065755d2017-11-07 18:27:04 +00007110 Types.push_back(OMP_MAP_RETURN_PARAM | OMP_MAP_TARGET_PARAM);
Samuel Antaocc10b852016-07-28 14:23:26 +00007111 }
7112
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007113 for (const auto &M : Info) {
Samuel Antao86ace552016-04-27 22:40:57 +00007114 // We need to know when we generate information for the first component
7115 // associated with a capture, because the mapping flags depend on it.
7116 bool IsFirstComponentList = true;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007117 for (const MapInfo &L : M.second) {
Samuel Antao86ace552016-04-27 22:40:57 +00007118 assert(!L.Components.empty() &&
7119 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00007120
7121 // Remember the current base pointer index.
7122 unsigned CurrentBasePointersIdx = BasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00007123 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007124 this->generateInfoForComponentList(
7125 L.MapType, L.MapTypeModifier, L.Components, BasePointers, Pointers,
7126 Sizes, Types, IsFirstComponentList, L.IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007127
7128 // If this entry relates with a device pointer, set the relevant
7129 // declaration and add the 'return pointer' flag.
7130 if (IsFirstComponentList &&
7131 L.ReturnDevicePointer != MapInfo::RPK_None) {
7132 // If the pointer is not the base of the map, we need to skip the
7133 // base. If it is a reference in a member field, we also need to skip
7134 // the map of the reference.
7135 if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
7136 ++CurrentBasePointersIdx;
7137 if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
7138 ++CurrentBasePointersIdx;
7139 }
7140 assert(BasePointers.size() > CurrentBasePointersIdx &&
7141 "Unexpected number of mapped base pointers.");
7142
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007143 const ValueDecl *RelevantVD =
7144 L.Components.back().getAssociatedDeclaration();
Samuel Antaocc10b852016-07-28 14:23:26 +00007145 assert(RelevantVD &&
7146 "No relevant declaration related with device pointer??");
7147
7148 BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
George Rokos065755d2017-11-07 18:27:04 +00007149 Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PARAM;
Samuel Antaocc10b852016-07-28 14:23:26 +00007150 }
Samuel Antao86ace552016-04-27 22:40:57 +00007151 IsFirstComponentList = false;
7152 }
7153 }
7154 }
7155
7156 /// \brief Generate the base pointers, section pointers, sizes and map types
7157 /// associated to a given capture.
7158 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00007159 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007160 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007161 MapValuesArrayTy &Pointers,
7162 MapValuesArrayTy &Sizes,
7163 MapFlagsArrayTy &Types) const {
7164 assert(!Cap->capturesVariableArrayType() &&
7165 "Not expecting to generate map info for a variable array type!");
7166
7167 BasePointers.clear();
7168 Pointers.clear();
7169 Sizes.clear();
7170 Types.clear();
7171
Samuel Antao6890b092016-07-28 14:25:09 +00007172 // We need to know when we generating information for the first component
7173 // associated with a capture, because the mapping flags depend on it.
7174 bool IsFirstComponentList = true;
7175
Samuel Antao86ace552016-04-27 22:40:57 +00007176 const ValueDecl *VD =
7177 Cap->capturesThis()
7178 ? nullptr
George Burgess IV00f70bd2018-03-01 05:43:23 +00007179 : Cap->getCapturedVar()->getCanonicalDecl();
Samuel Antao86ace552016-04-27 22:40:57 +00007180
Samuel Antao6890b092016-07-28 14:25:09 +00007181 // If this declaration appears in a is_device_ptr clause we just have to
7182 // pass the pointer by value. If it is a reference to a declaration, we just
7183 // pass its value, otherwise, if it is a member expression, we need to map
7184 // 'to' the field.
7185 if (!VD) {
7186 auto It = DevPointersMap.find(VD);
7187 if (It != DevPointersMap.end()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007188 for (ArrayRef<OMPClauseMappableExprCommon::MappableComponent> L :
7189 It->second) {
Samuel Antao6890b092016-07-28 14:25:09 +00007190 generateInfoForComponentList(
7191 /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007192 BasePointers, Pointers, Sizes, Types, IsFirstComponentList,
7193 /*IsImplicit=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +00007194 IsFirstComponentList = false;
7195 }
7196 return;
7197 }
7198 } else if (DevPointersMap.count(VD)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007199 BasePointers.emplace_back(Arg, VD);
Samuel Antao6890b092016-07-28 14:25:09 +00007200 Pointers.push_back(Arg);
7201 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
George Rokos065755d2017-11-07 18:27:04 +00007202 Types.push_back(OMP_MAP_LITERAL | OMP_MAP_TARGET_PARAM);
Samuel Antao6890b092016-07-28 14:25:09 +00007203 return;
7204 }
7205
Paul Robinson78fb1322016-08-01 22:12:46 +00007206 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007207 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
7208 for (const auto &L : C->decl_component_lists(VD)) {
Samuel Antao86ace552016-04-27 22:40:57 +00007209 assert(L.first == VD &&
7210 "We got information for the wrong declaration??");
7211 assert(!L.second.empty() &&
7212 "Not expecting declaration with no component lists.");
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007213 generateInfoForComponentList(
7214 C->getMapType(), C->getMapTypeModifier(), L.second, BasePointers,
7215 Pointers, Sizes, Types, IsFirstComponentList, C->isImplicit());
Samuel Antao86ace552016-04-27 22:40:57 +00007216 IsFirstComponentList = false;
7217 }
7218
7219 return;
7220 }
Samuel Antaod486f842016-05-26 16:53:38 +00007221
7222 /// \brief Generate the default map information for a given capture \a CI,
7223 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00007224 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
7225 const FieldDecl &RI, llvm::Value *CV,
7226 MapBaseValuesArrayTy &CurBasePointers,
7227 MapValuesArrayTy &CurPointers,
7228 MapValuesArrayTy &CurSizes,
7229 MapFlagsArrayTy &CurMapTypes) {
Samuel Antaod486f842016-05-26 16:53:38 +00007230
7231 // Do the default mapping.
7232 if (CI.capturesThis()) {
7233 CurBasePointers.push_back(CV);
7234 CurPointers.push_back(CV);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007235 const auto *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007236 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
7237 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00007238 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00007239 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007240 CurBasePointers.push_back(CV);
7241 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00007242 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007243 // We have to signal to the runtime captures passed by value that are
7244 // not pointers.
George Rokos065755d2017-11-07 18:27:04 +00007245 CurMapTypes.push_back(OMP_MAP_LITERAL);
Samuel Antaod486f842016-05-26 16:53:38 +00007246 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
7247 } else {
7248 // Pointers are implicitly mapped with a zero size and no flags
7249 // (other than first map that is added for all implicit maps).
7250 CurMapTypes.push_back(0u);
Samuel Antaod486f842016-05-26 16:53:38 +00007251 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
7252 }
7253 } else {
7254 assert(CI.capturesVariable() && "Expected captured reference.");
7255 CurBasePointers.push_back(CV);
7256 CurPointers.push_back(CV);
7257
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007258 const auto *PtrTy = cast<ReferenceType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007259 QualType ElementType = PtrTy->getPointeeType();
7260 CurSizes.push_back(CGF.getTypeSize(ElementType));
7261 // The default map type for a scalar/complex type is 'to' because by
7262 // default the value doesn't have to be retrieved. For an aggregate
7263 // type, the default is 'tofrom'.
Alexey Bataev3f96fe62017-12-13 17:31:39 +00007264 CurMapTypes.emplace_back(adjustMapModifiersForPrivateClauses(
7265 CI, ElementType->isAggregateType() ? (OMP_MAP_TO | OMP_MAP_FROM)
7266 : OMP_MAP_TO));
Samuel Antaod486f842016-05-26 16:53:38 +00007267 }
George Rokos065755d2017-11-07 18:27:04 +00007268 // Every default map produces a single argument which is a target parameter.
7269 CurMapTypes.back() |= OMP_MAP_TARGET_PARAM;
Samuel Antaod486f842016-05-26 16:53:38 +00007270 }
Samuel Antao86ace552016-04-27 22:40:57 +00007271};
Samuel Antaodf158d52016-04-27 22:58:19 +00007272
7273enum OpenMPOffloadingReservedDeviceIDs {
7274 /// \brief Device ID if the device was not defined, runtime should get it
7275 /// from environment variables in the spec.
7276 OMP_DEVICEID_UNDEF = -1,
7277};
7278} // anonymous namespace
7279
7280/// \brief Emit the arrays used to pass the captures and map information to the
7281/// offloading runtime library. If there is no map or capture information,
7282/// return nullptr by reference.
7283static void
Samuel Antaocc10b852016-07-28 14:23:26 +00007284emitOffloadingArrays(CodeGenFunction &CGF,
7285 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00007286 MappableExprsHandler::MapValuesArrayTy &Pointers,
7287 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00007288 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
7289 CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007290 CodeGenModule &CGM = CGF.CGM;
7291 ASTContext &Ctx = CGF.getContext();
Samuel Antaodf158d52016-04-27 22:58:19 +00007292
Samuel Antaocc10b852016-07-28 14:23:26 +00007293 // Reset the array information.
7294 Info.clearArrayInfo();
7295 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00007296
Samuel Antaocc10b852016-07-28 14:23:26 +00007297 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007298 // Detect if we have any capture size requiring runtime evaluation of the
7299 // size so that a constant array could be eventually used.
7300 bool hasRuntimeEvaluationCaptureSize = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007301 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00007302 if (!isa<llvm::Constant>(S)) {
7303 hasRuntimeEvaluationCaptureSize = true;
7304 break;
7305 }
7306
Samuel Antaocc10b852016-07-28 14:23:26 +00007307 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00007308 QualType PointerArrayType =
7309 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
7310 /*IndexTypeQuals=*/0);
7311
Samuel Antaocc10b852016-07-28 14:23:26 +00007312 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007313 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00007314 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007315 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
7316
7317 // If we don't have any VLA types or other types that require runtime
7318 // evaluation, we can use a constant array for the map sizes, otherwise we
7319 // need to fill up the arrays as we do for the pointers.
7320 if (hasRuntimeEvaluationCaptureSize) {
7321 QualType SizeArrayType = Ctx.getConstantArrayType(
7322 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
7323 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00007324 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007325 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
7326 } else {
7327 // We expect all the sizes to be constant, so we collect them to create
7328 // a constant array.
7329 SmallVector<llvm::Constant *, 16> ConstSizes;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007330 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00007331 ConstSizes.push_back(cast<llvm::Constant>(S));
7332
7333 auto *SizesArrayInit = llvm::ConstantArray::get(
7334 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
Alexey Bataev18fa2322018-05-02 14:20:50 +00007335 std::string Name = CGM.getOpenMPRuntime().getName({"offload_sizes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00007336 auto *SizesArrayGbl = new llvm::GlobalVariable(
7337 CGM.getModule(), SizesArrayInit->getType(),
7338 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00007339 SizesArrayInit, Name);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00007340 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00007341 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00007342 }
7343
7344 // The map types are always constant so we don't need to generate code to
7345 // fill arrays. Instead, we create an array constant.
7346 llvm::Constant *MapTypesArrayInit =
7347 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
Alexey Bataev18fa2322018-05-02 14:20:50 +00007348 std::string MaptypesName =
7349 CGM.getOpenMPRuntime().getName({"offload_maptypes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00007350 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
7351 CGM.getModule(), MapTypesArrayInit->getType(),
7352 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00007353 MapTypesArrayInit, MaptypesName);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00007354 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00007355 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00007356
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007357 for (unsigned I = 0; I < Info.NumberOfPtrs; ++I) {
7358 llvm::Value *BPVal = *BasePointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00007359 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007360 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007361 Info.BasePointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00007362 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7363 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00007364 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
7365 CGF.Builder.CreateStore(BPVal, BPAddr);
7366
Samuel Antaocc10b852016-07-28 14:23:26 +00007367 if (Info.requiresDevicePointerInfo())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007368 if (const ValueDecl *DevVD = BasePointers[I].getDevicePtrDecl())
Alexey Bataev43a919f2018-04-13 17:48:43 +00007369 Info.CaptureDeviceAddrMap.try_emplace(DevVD, BPAddr);
Samuel Antaocc10b852016-07-28 14:23:26 +00007370
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007371 llvm::Value *PVal = Pointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00007372 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007373 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007374 Info.PointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00007375 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7376 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00007377 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
7378 CGF.Builder.CreateStore(PVal, PAddr);
7379
7380 if (hasRuntimeEvaluationCaptureSize) {
7381 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007382 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
7383 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007384 /*Idx0=*/0,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007385 /*Idx1=*/I);
Samuel Antaodf158d52016-04-27 22:58:19 +00007386 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
7387 CGF.Builder.CreateStore(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007388 CGF.Builder.CreateIntCast(Sizes[I], CGM.SizeTy, /*isSigned=*/true),
Samuel Antaodf158d52016-04-27 22:58:19 +00007389 SAddr);
7390 }
7391 }
7392 }
7393}
7394/// \brief Emit the arguments to be passed to the runtime library based on the
7395/// arrays of pointers, sizes and map types.
7396static void emitOffloadingArraysArgument(
7397 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
7398 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007399 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007400 CodeGenModule &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00007401 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007402 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007403 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
7404 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007405 /*Idx0=*/0, /*Idx1=*/0);
7406 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007407 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
7408 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007409 /*Idx0=*/0,
7410 /*Idx1=*/0);
7411 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007412 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007413 /*Idx0=*/0, /*Idx1=*/0);
7414 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
George Rokos63bc9d62017-11-21 18:25:12 +00007415 llvm::ArrayType::get(CGM.Int64Ty, Info.NumberOfPtrs),
Samuel Antaocc10b852016-07-28 14:23:26 +00007416 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007417 /*Idx0=*/0,
7418 /*Idx1=*/0);
7419 } else {
7420 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
7421 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
7422 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
7423 MapTypesArrayArg =
George Rokos63bc9d62017-11-21 18:25:12 +00007424 llvm::ConstantPointerNull::get(CGM.Int64Ty->getPointerTo());
Samuel Antaodf158d52016-04-27 22:58:19 +00007425 }
Samuel Antao86ace552016-04-27 22:40:57 +00007426}
7427
Samuel Antaobed3c462015-10-02 16:14:20 +00007428void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
7429 const OMPExecutableDirective &D,
7430 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00007431 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00007432 const Expr *IfCond, const Expr *Device) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00007433 if (!CGF.HaveInsertPoint())
7434 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00007435
Samuel Antaoee8fb302016-01-06 13:42:12 +00007436 assert(OutlinedFn && "Invalid outlined function!");
7437
Alexey Bataev8451efa2018-01-15 19:06:12 +00007438 const bool RequiresOuterTask = D.hasClausesOfKind<OMPDependClause>();
7439 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Alexey Bataev475a7442018-01-12 19:39:11 +00007440 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Alexey Bataev8451efa2018-01-15 19:06:12 +00007441 auto &&ArgsCodegen = [&CS, &CapturedVars](CodeGenFunction &CGF,
7442 PrePostActionTy &) {
7443 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7444 };
7445 emitInlinedDirective(CGF, OMPD_unknown, ArgsCodegen);
Samuel Antao86ace552016-04-27 22:40:57 +00007446
Alexey Bataev8451efa2018-01-15 19:06:12 +00007447 CodeGenFunction::OMPTargetDataInfo InputInfo;
7448 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00007449 // Fill up the pointer arrays and transfer execution to the device.
Alexey Bataev8451efa2018-01-15 19:06:12 +00007450 auto &&ThenGen = [this, Device, OutlinedFn, OutlinedFnID, &D, &InputInfo,
7451 &MapTypesArray, &CS, RequiresOuterTask,
7452 &CapturedVars](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobed3c462015-10-02 16:14:20 +00007453 // On top of the arrays that were filled up, the target offloading call
7454 // takes as arguments the device id as well as the host pointer. The host
7455 // pointer is used by the runtime library to identify the current target
7456 // region, so it only has to be unique and not necessarily point to
7457 // anything. It could be the pointer to the outlined function that
7458 // implements the target region, but we aren't using that so that the
7459 // compiler doesn't need to keep that, and could therefore inline the host
7460 // function if proven worthwhile during optimization.
7461
Samuel Antaoee8fb302016-01-06 13:42:12 +00007462 // From this point on, we need to have an ID of the target region defined.
7463 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00007464
7465 // Emit device ID if any.
7466 llvm::Value *DeviceID;
George Rokos63bc9d62017-11-21 18:25:12 +00007467 if (Device) {
Samuel Antaobed3c462015-10-02 16:14:20 +00007468 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007469 CGF.Int64Ty, /*isSigned=*/true);
7470 } else {
7471 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7472 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007473
Samuel Antaodf158d52016-04-27 22:58:19 +00007474 // Emit the number of elements in the offloading arrays.
Alexey Bataev8451efa2018-01-15 19:06:12 +00007475 llvm::Value *PointerNum =
7476 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaodf158d52016-04-27 22:58:19 +00007477
Samuel Antaob68e2db2016-03-03 16:20:23 +00007478 // Return value of the runtime offloading call.
7479 llvm::Value *Return;
7480
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007481 llvm::Value *NumTeams = emitNumTeamsForTargetDirective(*this, CGF, D);
7482 llvm::Value *NumThreads = emitNumThreadsForTargetDirective(*this, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007483
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007484 bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007485 // The target region is an outlined function launched by the runtime
7486 // via calls __tgt_target() or __tgt_target_teams().
7487 //
7488 // __tgt_target() launches a target region with one team and one thread,
7489 // executing a serial region. This master thread may in turn launch
7490 // more threads within its team upon encountering a parallel region,
7491 // however, no additional teams can be launched on the device.
7492 //
7493 // __tgt_target_teams() launches a target region with one or more teams,
7494 // each with one or more threads. This call is required for target
7495 // constructs such as:
7496 // 'target teams'
7497 // 'target' / 'teams'
7498 // 'target teams distribute parallel for'
7499 // 'target parallel'
7500 // and so on.
7501 //
7502 // Note that on the host and CPU targets, the runtime implementation of
7503 // these calls simply call the outlined function without forking threads.
7504 // The outlined functions themselves have runtime calls to
7505 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
7506 // the compiler in emitTeamsCall() and emitParallelCall().
7507 //
7508 // In contrast, on the NVPTX target, the implementation of
7509 // __tgt_target_teams() launches a GPU kernel with the requested number
7510 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00007511 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007512 // If we have NumTeams defined this means that we have an enclosed teams
7513 // region. Therefore we also expect to have NumThreads defined. These two
7514 // values should be defined in the presence of a teams directive,
7515 // regardless of having any clauses associated. If the user is using teams
7516 // but no clauses, these two values will be the default that should be
7517 // passed to the runtime library - a 32-bit integer with the value zero.
7518 assert(NumThreads && "Thread limit expression should be available along "
7519 "with number of teams.");
Alexey Bataev8451efa2018-01-15 19:06:12 +00007520 llvm::Value *OffloadingArgs[] = {DeviceID,
7521 OutlinedFnID,
7522 PointerNum,
7523 InputInfo.BasePointersArray.getPointer(),
7524 InputInfo.PointersArray.getPointer(),
7525 InputInfo.SizesArray.getPointer(),
7526 MapTypesArray,
7527 NumTeams,
7528 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00007529 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00007530 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_teams_nowait
7531 : OMPRTL__tgt_target_teams),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007532 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007533 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00007534 llvm::Value *OffloadingArgs[] = {DeviceID,
7535 OutlinedFnID,
7536 PointerNum,
7537 InputInfo.BasePointersArray.getPointer(),
7538 InputInfo.PointersArray.getPointer(),
7539 InputInfo.SizesArray.getPointer(),
7540 MapTypesArray};
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007541 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00007542 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_nowait
7543 : OMPRTL__tgt_target),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007544 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007545 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007546
Alexey Bataev2a007e02017-10-02 14:20:58 +00007547 // Check the error code and execute the host version if required.
7548 llvm::BasicBlock *OffloadFailedBlock =
7549 CGF.createBasicBlock("omp_offload.failed");
7550 llvm::BasicBlock *OffloadContBlock =
7551 CGF.createBasicBlock("omp_offload.cont");
7552 llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
7553 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
7554
7555 CGF.EmitBlock(OffloadFailedBlock);
Alexey Bataev8451efa2018-01-15 19:06:12 +00007556 if (RequiresOuterTask) {
7557 CapturedVars.clear();
7558 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7559 }
7560 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, CapturedVars);
Alexey Bataev2a007e02017-10-02 14:20:58 +00007561 CGF.EmitBranch(OffloadContBlock);
7562
7563 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00007564 };
7565
Samuel Antaoee8fb302016-01-06 13:42:12 +00007566 // Notify that the host version must be executed.
Alexey Bataev8451efa2018-01-15 19:06:12 +00007567 auto &&ElseGen = [this, &D, OutlinedFn, &CS, &CapturedVars,
7568 RequiresOuterTask](CodeGenFunction &CGF,
7569 PrePostActionTy &) {
7570 if (RequiresOuterTask) {
7571 CapturedVars.clear();
7572 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7573 }
7574 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, CapturedVars);
7575 };
7576
7577 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray,
7578 &CapturedVars, RequiresOuterTask,
7579 &CS](CodeGenFunction &CGF, PrePostActionTy &) {
7580 // Fill up the arrays with all the captured variables.
7581 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
7582 MappableExprsHandler::MapValuesArrayTy Pointers;
7583 MappableExprsHandler::MapValuesArrayTy Sizes;
7584 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7585
7586 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
7587 MappableExprsHandler::MapValuesArrayTy CurPointers;
7588 MappableExprsHandler::MapValuesArrayTy CurSizes;
7589 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
7590
7591 // Get mappable expression information.
7592 MappableExprsHandler MEHandler(D, CGF);
7593
7594 auto RI = CS.getCapturedRecordDecl()->field_begin();
7595 auto CV = CapturedVars.begin();
7596 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
7597 CE = CS.capture_end();
7598 CI != CE; ++CI, ++RI, ++CV) {
7599 CurBasePointers.clear();
7600 CurPointers.clear();
7601 CurSizes.clear();
7602 CurMapTypes.clear();
7603
7604 // VLA sizes are passed to the outlined region by copy and do not have map
7605 // information associated.
7606 if (CI->capturesVariableArrayType()) {
7607 CurBasePointers.push_back(*CV);
7608 CurPointers.push_back(*CV);
7609 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
7610 // Copy to the device as an argument. No need to retrieve it.
7611 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_LITERAL |
7612 MappableExprsHandler::OMP_MAP_TARGET_PARAM);
7613 } else {
7614 // If we have any information in the map clause, we use it, otherwise we
7615 // just do a default mapping.
7616 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
7617 CurSizes, CurMapTypes);
7618 if (CurBasePointers.empty())
7619 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
7620 CurPointers, CurSizes, CurMapTypes);
7621 }
7622 // We expect to have at least an element of information for this capture.
7623 assert(!CurBasePointers.empty() &&
7624 "Non-existing map pointer for capture!");
7625 assert(CurBasePointers.size() == CurPointers.size() &&
7626 CurBasePointers.size() == CurSizes.size() &&
7627 CurBasePointers.size() == CurMapTypes.size() &&
7628 "Inconsistent map information sizes!");
7629
7630 // We need to append the results of this capture to what we already have.
7631 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
7632 Pointers.append(CurPointers.begin(), CurPointers.end());
7633 Sizes.append(CurSizes.begin(), CurSizes.end());
7634 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
7635 }
Alexey Bataev92327c52018-03-26 16:40:55 +00007636 // Map other list items in the map clause which are not captured variables
7637 // but "declare target link" global variables.
7638 for (const auto *C : D.getClausesOfKind<OMPMapClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007639 for (const auto &L : C->component_lists()) {
Alexey Bataev92327c52018-03-26 16:40:55 +00007640 if (!L.first)
7641 continue;
7642 const auto *VD = dyn_cast<VarDecl>(L.first);
7643 if (!VD)
7644 continue;
7645 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
7646 isDeclareTargetDeclaration(VD);
7647 if (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link)
7648 continue;
7649 MEHandler.generateInfoForComponentList(
7650 C->getMapType(), C->getMapTypeModifier(), L.second, BasePointers,
7651 Pointers, Sizes, MapTypes, /*IsFirstComponentList=*/true,
7652 C->isImplicit());
7653 }
7654 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00007655
7656 TargetDataInfo Info;
7657 // Fill up the arrays and create the arguments.
7658 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
7659 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
7660 Info.PointersArray, Info.SizesArray,
7661 Info.MapTypesArray, Info);
7662 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
7663 InputInfo.BasePointersArray =
7664 Address(Info.BasePointersArray, CGM.getPointerAlign());
7665 InputInfo.PointersArray =
7666 Address(Info.PointersArray, CGM.getPointerAlign());
7667 InputInfo.SizesArray = Address(Info.SizesArray, CGM.getPointerAlign());
7668 MapTypesArray = Info.MapTypesArray;
7669 if (RequiresOuterTask)
7670 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
7671 else
7672 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
7673 };
7674
7675 auto &&TargetElseGen = [this, &ElseGen, &D, RequiresOuterTask](
7676 CodeGenFunction &CGF, PrePostActionTy &) {
7677 if (RequiresOuterTask) {
7678 CodeGenFunction::OMPTargetDataInfo InputInfo;
7679 CGF.EmitOMPTargetTaskBasedDirective(D, ElseGen, InputInfo);
7680 } else {
7681 emitInlinedDirective(CGF, D.getDirectiveKind(), ElseGen);
7682 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00007683 };
7684
7685 // If we have a target function ID it means that we need to support
7686 // offloading, otherwise, just execute on the host. We need to execute on host
7687 // regardless of the conditional in the if clause if, e.g., the user do not
7688 // specify target triples.
7689 if (OutlinedFnID) {
Alexey Bataev8451efa2018-01-15 19:06:12 +00007690 if (IfCond) {
7691 emitOMPIfClause(CGF, IfCond, TargetThenGen, TargetElseGen);
7692 } else {
7693 RegionCodeGenTy ThenRCG(TargetThenGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007694 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007695 }
7696 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00007697 RegionCodeGenTy ElseRCG(TargetElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007698 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007699 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007700}
Samuel Antaoee8fb302016-01-06 13:42:12 +00007701
7702void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
7703 StringRef ParentName) {
7704 if (!S)
7705 return;
7706
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007707 // Codegen OMP target directives that offload compute to the device.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007708 bool RequiresDeviceCodegen =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007709 isa<OMPExecutableDirective>(S) &&
7710 isOpenMPTargetExecutionDirective(
7711 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00007712
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007713 if (RequiresDeviceCodegen) {
7714 const auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007715 unsigned DeviceID;
7716 unsigned FileID;
7717 unsigned Line;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007718 getTargetEntryUniqueInfo(CGM.getContext(), E.getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00007719 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007720
7721 // Is this a target region that should not be emitted as an entry point? If
7722 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00007723 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
7724 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007725 return;
7726
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007727 switch (E.getDirectiveKind()) {
7728 case OMPD_target:
7729 CodeGenFunction::EmitOMPTargetDeviceFunction(CGM, ParentName,
7730 cast<OMPTargetDirective>(E));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007731 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007732 case OMPD_target_parallel:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00007733 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007734 CGM, ParentName, cast<OMPTargetParallelDirective>(E));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00007735 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007736 case OMPD_target_teams:
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00007737 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007738 CGM, ParentName, cast<OMPTargetTeamsDirective>(E));
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00007739 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007740 case OMPD_target_teams_distribute:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007741 CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007742 CGM, ParentName, cast<OMPTargetTeamsDistributeDirective>(E));
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007743 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007744 case OMPD_target_teams_distribute_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007745 CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007746 CGM, ParentName, cast<OMPTargetTeamsDistributeSimdDirective>(E));
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007747 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007748 case OMPD_target_parallel_for:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007749 CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007750 CGM, ParentName, cast<OMPTargetParallelForDirective>(E));
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007751 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007752 case OMPD_target_parallel_for_simd:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007753 CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007754 CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(E));
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007755 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007756 case OMPD_target_simd:
Alexey Bataevf8365372017-11-17 17:57:25 +00007757 CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007758 CGM, ParentName, cast<OMPTargetSimdDirective>(E));
Alexey Bataevf8365372017-11-17 17:57:25 +00007759 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007760 case OMPD_target_teams_distribute_parallel_for:
Carlo Bertolli52978c32018-01-03 21:12:44 +00007761 CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
7762 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007763 cast<OMPTargetTeamsDistributeParallelForDirective>(E));
Carlo Bertolli52978c32018-01-03 21:12:44 +00007764 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007765 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00007766 CodeGenFunction::
7767 EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
7768 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007769 cast<OMPTargetTeamsDistributeParallelForSimdDirective>(E));
Alexey Bataev647dd842018-01-15 20:59:40 +00007770 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007771 case OMPD_parallel:
7772 case OMPD_for:
7773 case OMPD_parallel_for:
7774 case OMPD_parallel_sections:
7775 case OMPD_for_simd:
7776 case OMPD_parallel_for_simd:
7777 case OMPD_cancel:
7778 case OMPD_cancellation_point:
7779 case OMPD_ordered:
7780 case OMPD_threadprivate:
7781 case OMPD_task:
7782 case OMPD_simd:
7783 case OMPD_sections:
7784 case OMPD_section:
7785 case OMPD_single:
7786 case OMPD_master:
7787 case OMPD_critical:
7788 case OMPD_taskyield:
7789 case OMPD_barrier:
7790 case OMPD_taskwait:
7791 case OMPD_taskgroup:
7792 case OMPD_atomic:
7793 case OMPD_flush:
7794 case OMPD_teams:
7795 case OMPD_target_data:
7796 case OMPD_target_exit_data:
7797 case OMPD_target_enter_data:
7798 case OMPD_distribute:
7799 case OMPD_distribute_simd:
7800 case OMPD_distribute_parallel_for:
7801 case OMPD_distribute_parallel_for_simd:
7802 case OMPD_teams_distribute:
7803 case OMPD_teams_distribute_simd:
7804 case OMPD_teams_distribute_parallel_for:
7805 case OMPD_teams_distribute_parallel_for_simd:
7806 case OMPD_target_update:
7807 case OMPD_declare_simd:
7808 case OMPD_declare_target:
7809 case OMPD_end_declare_target:
7810 case OMPD_declare_reduction:
7811 case OMPD_taskloop:
7812 case OMPD_taskloop_simd:
7813 case OMPD_unknown:
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007814 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
7815 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00007816 return;
7817 }
7818
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007819 if (const auto *E = dyn_cast<OMPExecutableDirective>(S)) {
Alexey Bataev475a7442018-01-12 19:39:11 +00007820 if (!E->hasAssociatedStmt() || !E->getAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00007821 return;
7822
7823 scanForTargetRegionsFunctions(
Alexey Bataev475a7442018-01-12 19:39:11 +00007824 E->getInnermostCapturedStmt()->getCapturedStmt(), ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007825 return;
7826 }
7827
7828 // If this is a lambda function, look into its body.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007829 if (const auto *L = dyn_cast<LambdaExpr>(S))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007830 S = L->getBody();
7831
7832 // Keep looking for target regions recursively.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007833 for (const Stmt *II : S->children())
Samuel Antaoee8fb302016-01-06 13:42:12 +00007834 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007835}
7836
7837bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007838 const auto *FD = cast<FunctionDecl>(GD.getDecl());
Samuel Antaoee8fb302016-01-06 13:42:12 +00007839
7840 // If emitting code for the host, we do not process FD here. Instead we do
7841 // the normal code generation.
7842 if (!CGM.getLangOpts().OpenMPIsDevice)
7843 return false;
7844
7845 // Try to detect target regions in the function.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007846 scanForTargetRegionsFunctions(FD->getBody(), CGM.getMangledName(GD));
Samuel Antaoee8fb302016-01-06 13:42:12 +00007847
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007848 // Do not to emit function if it is not marked as declare target.
Alexey Bataevfb388282018-05-01 14:09:46 +00007849 return !isDeclareTargetDeclaration(FD) &&
7850 AlreadyEmittedTargetFunctions.count(FD->getCanonicalDecl()) == 0;
Samuel Antaoee8fb302016-01-06 13:42:12 +00007851}
7852
7853bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
7854 if (!CGM.getLangOpts().OpenMPIsDevice)
7855 return false;
7856
7857 // Check if there are Ctors/Dtors in this declaration and look for target
7858 // regions in it. We use the complete variant to produce the kernel name
7859 // mangling.
7860 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007861 if (const auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
7862 for (const CXXConstructorDecl *Ctor : RD->ctors()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00007863 StringRef ParentName =
7864 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
7865 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
7866 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007867 if (const CXXDestructorDecl *Dtor = RD->getDestructor()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00007868 StringRef ParentName =
7869 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
7870 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
7871 }
7872 }
7873
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007874 // Do not to emit variable if it is not marked as declare target.
Alexey Bataev92327c52018-03-26 16:40:55 +00007875 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev03f270c2018-03-30 18:31:07 +00007876 isDeclareTargetDeclaration(cast<VarDecl>(GD.getDecl()));
Alexey Bataev92327c52018-03-26 16:40:55 +00007877 return !Res || *Res == OMPDeclareTargetDeclAttr::MT_Link;
Samuel Antaoee8fb302016-01-06 13:42:12 +00007878}
7879
Alexey Bataev03f270c2018-03-30 18:31:07 +00007880void CGOpenMPRuntime::registerTargetGlobalVariable(const VarDecl *VD,
7881 llvm::Constant *Addr) {
7882 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
7883 isDeclareTargetDeclaration(VD)) {
7884 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags;
7885 StringRef VarName;
7886 CharUnits VarSize;
7887 llvm::GlobalValue::LinkageTypes Linkage;
7888 switch (*Res) {
7889 case OMPDeclareTargetDeclAttr::MT_To:
7890 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo;
7891 VarName = CGM.getMangledName(VD);
7892 VarSize = CGM.getContext().getTypeSizeInChars(VD->getType());
7893 Linkage = CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false);
7894 break;
7895 case OMPDeclareTargetDeclAttr::MT_Link:
7896 // Map type 'to' because we do not map the original variable but the
7897 // reference.
7898 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo;
7899 if (!CGM.getLangOpts().OpenMPIsDevice) {
7900 Addr =
7901 cast<llvm::Constant>(getAddrOfDeclareTargetLink(VD).getPointer());
7902 }
7903 VarName = Addr->getName();
7904 VarSize = CGM.getPointerSize();
7905 Linkage = llvm::GlobalValue::WeakAnyLinkage;
7906 break;
7907 }
7908 OffloadEntriesInfoManager.registerDeviceGlobalVarEntryInfo(
7909 VarName, Addr, VarSize, Flags, Linkage);
7910 }
7911}
7912
Samuel Antaoee8fb302016-01-06 13:42:12 +00007913bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007914 if (isa<FunctionDecl>(GD.getDecl()))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007915 return emitTargetFunctions(GD);
7916
7917 return emitTargetGlobalVariable(GD);
7918}
7919
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007920CGOpenMPRuntime::DisableAutoDeclareTargetRAII::DisableAutoDeclareTargetRAII(
7921 CodeGenModule &CGM)
7922 : CGM(CGM) {
7923 if (CGM.getLangOpts().OpenMPIsDevice) {
7924 SavedShouldMarkAsGlobal = CGM.getOpenMPRuntime().ShouldMarkAsGlobal;
7925 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = false;
7926 }
7927}
7928
7929CGOpenMPRuntime::DisableAutoDeclareTargetRAII::~DisableAutoDeclareTargetRAII() {
7930 if (CGM.getLangOpts().OpenMPIsDevice)
7931 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = SavedShouldMarkAsGlobal;
7932}
7933
Alexey Bataev6d944102018-05-02 15:45:28 +00007934bool CGOpenMPRuntime::markAsGlobalTarget(GlobalDecl GD) {
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007935 if (!CGM.getLangOpts().OpenMPIsDevice || !ShouldMarkAsGlobal)
7936 return true;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007937
Alexey Bataev6d944102018-05-02 15:45:28 +00007938 const auto *D = cast<FunctionDecl>(GD.getDecl());
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007939 const FunctionDecl *FD = D->getCanonicalDecl();
Alexey Bataev34f8a702018-03-28 14:28:54 +00007940 // Do not to emit function if it is marked as declare target as it was already
7941 // emitted.
7942 if (isDeclareTargetDeclaration(D)) {
7943 if (D->hasBody() && AlreadyEmittedTargetFunctions.count(FD) == 0) {
7944 if (auto *F = dyn_cast_or_null<llvm::Function>(
Alexey Bataev6d944102018-05-02 15:45:28 +00007945 CGM.GetGlobalValue(CGM.getMangledName(GD))))
Alexey Bataev34f8a702018-03-28 14:28:54 +00007946 return !F->isDeclaration();
7947 return false;
7948 }
7949 return true;
7950 }
7951
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007952 return !AlreadyEmittedTargetFunctions.insert(FD).second;
7953}
7954
Samuel Antaoee8fb302016-01-06 13:42:12 +00007955llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
7956 // If we have offloading in the current module, we need to emit the entries
7957 // now and register the offloading descriptor.
7958 createOffloadEntriesAndInfoMetadata();
7959
7960 // Create and register the offloading binary descriptors. This is the main
7961 // entity that captures all the information about offloading in the current
7962 // compilation unit.
7963 return createOffloadingBinaryDescriptorRegistration();
7964}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007965
7966void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
7967 const OMPExecutableDirective &D,
7968 SourceLocation Loc,
7969 llvm::Value *OutlinedFn,
7970 ArrayRef<llvm::Value *> CapturedVars) {
7971 if (!CGF.HaveInsertPoint())
7972 return;
7973
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007974 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007975 CodeGenFunction::RunCleanupsScope Scope(CGF);
7976
7977 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
7978 llvm::Value *Args[] = {
7979 RTLoc,
7980 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
7981 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
7982 llvm::SmallVector<llvm::Value *, 16> RealArgs;
7983 RealArgs.append(std::begin(Args), std::end(Args));
7984 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
7985
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007986 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007987 CGF.EmitRuntimeCall(RTLFn, RealArgs);
7988}
7989
7990void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00007991 const Expr *NumTeams,
7992 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007993 SourceLocation Loc) {
7994 if (!CGF.HaveInsertPoint())
7995 return;
7996
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007997 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007998
Carlo Bertollic6872252016-04-04 15:55:02 +00007999 llvm::Value *NumTeamsVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008000 NumTeams
Carlo Bertollic6872252016-04-04 15:55:02 +00008001 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
8002 CGF.CGM.Int32Ty, /* isSigned = */ true)
8003 : CGF.Builder.getInt32(0);
8004
8005 llvm::Value *ThreadLimitVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008006 ThreadLimit
Carlo Bertollic6872252016-04-04 15:55:02 +00008007 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
8008 CGF.CGM.Int32Ty, /* isSigned = */ true)
8009 : CGF.Builder.getInt32(0);
8010
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008011 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00008012 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
8013 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008014 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
8015 PushNumTeamsArgs);
8016}
Samuel Antaodf158d52016-04-27 22:58:19 +00008017
Samuel Antaocc10b852016-07-28 14:23:26 +00008018void CGOpenMPRuntime::emitTargetDataCalls(
8019 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8020 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008021 if (!CGF.HaveInsertPoint())
8022 return;
8023
Samuel Antaocc10b852016-07-28 14:23:26 +00008024 // Action used to replace the default codegen action and turn privatization
8025 // off.
8026 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00008027
8028 // Generate the code for the opening of the data environment. Capture all the
8029 // arguments of the runtime call by reference because they are used in the
8030 // closing of the region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008031 auto &&BeginThenGen = [this, &D, Device, &Info,
8032 &CodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008033 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00008034 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00008035 MappableExprsHandler::MapValuesArrayTy Pointers;
8036 MappableExprsHandler::MapValuesArrayTy Sizes;
8037 MappableExprsHandler::MapFlagsArrayTy MapTypes;
8038
8039 // Get map clause information.
8040 MappableExprsHandler MCHandler(D, CGF);
8041 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00008042
8043 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00008044 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008045
8046 llvm::Value *BasePointersArrayArg = nullptr;
8047 llvm::Value *PointersArrayArg = nullptr;
8048 llvm::Value *SizesArrayArg = nullptr;
8049 llvm::Value *MapTypesArrayArg = nullptr;
8050 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008051 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008052
8053 // Emit device ID if any.
8054 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008055 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008056 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008057 CGF.Int64Ty, /*isSigned=*/true);
8058 } else {
8059 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8060 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008061
8062 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008063 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00008064
8065 llvm::Value *OffloadingArgs[] = {
8066 DeviceID, PointerNum, BasePointersArrayArg,
8067 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008068 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_begin),
Samuel Antaodf158d52016-04-27 22:58:19 +00008069 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00008070
8071 // If device pointer privatization is required, emit the body of the region
8072 // here. It will have to be duplicated: with and without privatization.
8073 if (!Info.CaptureDeviceAddrMap.empty())
8074 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008075 };
8076
8077 // Generate code for the closing of the data region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008078 auto &&EndThenGen = [this, Device, &Info](CodeGenFunction &CGF,
8079 PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008080 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00008081
8082 llvm::Value *BasePointersArrayArg = nullptr;
8083 llvm::Value *PointersArrayArg = nullptr;
8084 llvm::Value *SizesArrayArg = nullptr;
8085 llvm::Value *MapTypesArrayArg = nullptr;
8086 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008087 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008088
8089 // Emit device ID if any.
8090 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008091 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008092 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008093 CGF.Int64Ty, /*isSigned=*/true);
8094 } else {
8095 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8096 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008097
8098 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008099 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00008100
8101 llvm::Value *OffloadingArgs[] = {
8102 DeviceID, PointerNum, BasePointersArrayArg,
8103 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008104 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_end),
Samuel Antaodf158d52016-04-27 22:58:19 +00008105 OffloadingArgs);
8106 };
8107
Samuel Antaocc10b852016-07-28 14:23:26 +00008108 // If we need device pointer privatization, we need to emit the body of the
8109 // region with no privatization in the 'else' branch of the conditional.
8110 // Otherwise, we don't have to do anything.
8111 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
8112 PrePostActionTy &) {
8113 if (!Info.CaptureDeviceAddrMap.empty()) {
8114 CodeGen.setAction(NoPrivAction);
8115 CodeGen(CGF);
8116 }
8117 };
8118
8119 // We don't have to do anything to close the region if the if clause evaluates
8120 // to false.
8121 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00008122
8123 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008124 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00008125 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00008126 RegionCodeGenTy RCG(BeginThenGen);
8127 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008128 }
8129
Samuel Antaocc10b852016-07-28 14:23:26 +00008130 // If we don't require privatization of device pointers, we emit the body in
8131 // between the runtime calls. This avoids duplicating the body code.
8132 if (Info.CaptureDeviceAddrMap.empty()) {
8133 CodeGen.setAction(NoPrivAction);
8134 CodeGen(CGF);
8135 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008136
8137 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008138 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00008139 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00008140 RegionCodeGenTy RCG(EndThenGen);
8141 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008142 }
8143}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008144
Samuel Antao8d2d7302016-05-26 18:30:22 +00008145void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00008146 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8147 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008148 if (!CGF.HaveInsertPoint())
8149 return;
8150
Samuel Antao8dd66282016-04-27 23:14:30 +00008151 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00008152 isa<OMPTargetExitDataDirective>(D) ||
8153 isa<OMPTargetUpdateDirective>(D)) &&
8154 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00008155
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008156 CodeGenFunction::OMPTargetDataInfo InputInfo;
8157 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008158 // Generate the code for the opening of the data environment.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008159 auto &&ThenGen = [this, &D, Device, &InputInfo,
8160 &MapTypesArray](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008161 // Emit device ID if any.
8162 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008163 if (Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008164 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008165 CGF.Int64Ty, /*isSigned=*/true);
8166 } else {
8167 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8168 }
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008169
8170 // Emit the number of elements in the offloading arrays.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008171 llvm::Constant *PointerNum =
8172 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008173
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008174 llvm::Value *OffloadingArgs[] = {DeviceID,
8175 PointerNum,
8176 InputInfo.BasePointersArray.getPointer(),
8177 InputInfo.PointersArray.getPointer(),
8178 InputInfo.SizesArray.getPointer(),
8179 MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00008180
Samuel Antao8d2d7302016-05-26 18:30:22 +00008181 // Select the right runtime function call for each expected standalone
8182 // directive.
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008183 const bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Samuel Antao8d2d7302016-05-26 18:30:22 +00008184 OpenMPRTLFunction RTLFn;
8185 switch (D.getDirectiveKind()) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00008186 case OMPD_target_enter_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008187 RTLFn = HasNowait ? OMPRTL__tgt_target_data_begin_nowait
8188 : OMPRTL__tgt_target_data_begin;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008189 break;
8190 case OMPD_target_exit_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008191 RTLFn = HasNowait ? OMPRTL__tgt_target_data_end_nowait
8192 : OMPRTL__tgt_target_data_end;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008193 break;
8194 case OMPD_target_update:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008195 RTLFn = HasNowait ? OMPRTL__tgt_target_data_update_nowait
8196 : OMPRTL__tgt_target_data_update;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008197 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008198 case OMPD_parallel:
8199 case OMPD_for:
8200 case OMPD_parallel_for:
8201 case OMPD_parallel_sections:
8202 case OMPD_for_simd:
8203 case OMPD_parallel_for_simd:
8204 case OMPD_cancel:
8205 case OMPD_cancellation_point:
8206 case OMPD_ordered:
8207 case OMPD_threadprivate:
8208 case OMPD_task:
8209 case OMPD_simd:
8210 case OMPD_sections:
8211 case OMPD_section:
8212 case OMPD_single:
8213 case OMPD_master:
8214 case OMPD_critical:
8215 case OMPD_taskyield:
8216 case OMPD_barrier:
8217 case OMPD_taskwait:
8218 case OMPD_taskgroup:
8219 case OMPD_atomic:
8220 case OMPD_flush:
8221 case OMPD_teams:
8222 case OMPD_target_data:
8223 case OMPD_distribute:
8224 case OMPD_distribute_simd:
8225 case OMPD_distribute_parallel_for:
8226 case OMPD_distribute_parallel_for_simd:
8227 case OMPD_teams_distribute:
8228 case OMPD_teams_distribute_simd:
8229 case OMPD_teams_distribute_parallel_for:
8230 case OMPD_teams_distribute_parallel_for_simd:
8231 case OMPD_declare_simd:
8232 case OMPD_declare_target:
8233 case OMPD_end_declare_target:
8234 case OMPD_declare_reduction:
8235 case OMPD_taskloop:
8236 case OMPD_taskloop_simd:
8237 case OMPD_target:
8238 case OMPD_target_simd:
8239 case OMPD_target_teams_distribute:
8240 case OMPD_target_teams_distribute_simd:
8241 case OMPD_target_teams_distribute_parallel_for:
8242 case OMPD_target_teams_distribute_parallel_for_simd:
8243 case OMPD_target_teams:
8244 case OMPD_target_parallel:
8245 case OMPD_target_parallel_for:
8246 case OMPD_target_parallel_for_simd:
8247 case OMPD_unknown:
8248 llvm_unreachable("Unexpected standalone target data directive.");
8249 break;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008250 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008251 CGF.EmitRuntimeCall(createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008252 };
8253
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008254 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray](
8255 CodeGenFunction &CGF, PrePostActionTy &) {
8256 // Fill up the arrays with all the mapped variables.
8257 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
8258 MappableExprsHandler::MapValuesArrayTy Pointers;
8259 MappableExprsHandler::MapValuesArrayTy Sizes;
8260 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008261
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008262 // Get map clause information.
8263 MappableExprsHandler MEHandler(D, CGF);
8264 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
8265
8266 TargetDataInfo Info;
8267 // Fill up the arrays and create the arguments.
8268 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
8269 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
8270 Info.PointersArray, Info.SizesArray,
8271 Info.MapTypesArray, Info);
8272 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
8273 InputInfo.BasePointersArray =
8274 Address(Info.BasePointersArray, CGM.getPointerAlign());
8275 InputInfo.PointersArray =
8276 Address(Info.PointersArray, CGM.getPointerAlign());
8277 InputInfo.SizesArray =
8278 Address(Info.SizesArray, CGM.getPointerAlign());
8279 MapTypesArray = Info.MapTypesArray;
8280 if (D.hasClausesOfKind<OMPDependClause>())
8281 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
8282 else
Alexey Bataev768f1f22018-01-09 19:59:25 +00008283 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008284 };
8285
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008286 if (IfCond) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008287 emitOMPIfClause(CGF, IfCond, TargetThenGen,
8288 [](CodeGenFunction &CGF, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008289 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008290 RegionCodeGenTy ThenRCG(TargetThenGen);
8291 ThenRCG(CGF);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008292 }
8293}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008294
8295namespace {
8296 /// Kind of parameter in a function with 'declare simd' directive.
8297 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
8298 /// Attribute set of the parameter.
8299 struct ParamAttrTy {
8300 ParamKindTy Kind = Vector;
8301 llvm::APSInt StrideOrArg;
8302 llvm::APSInt Alignment;
8303 };
8304} // namespace
8305
8306static unsigned evaluateCDTSize(const FunctionDecl *FD,
8307 ArrayRef<ParamAttrTy> ParamAttrs) {
8308 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
8309 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
8310 // of that clause. The VLEN value must be power of 2.
8311 // In other case the notion of the function`s "characteristic data type" (CDT)
8312 // is used to compute the vector length.
8313 // CDT is defined in the following order:
8314 // a) For non-void function, the CDT is the return type.
8315 // b) If the function has any non-uniform, non-linear parameters, then the
8316 // CDT is the type of the first such parameter.
8317 // c) If the CDT determined by a) or b) above is struct, union, or class
8318 // type which is pass-by-value (except for the type that maps to the
8319 // built-in complex data type), the characteristic data type is int.
8320 // d) If none of the above three cases is applicable, the CDT is int.
8321 // The VLEN is then determined based on the CDT and the size of vector
8322 // register of that ISA for which current vector version is generated. The
8323 // VLEN is computed using the formula below:
8324 // VLEN = sizeof(vector_register) / sizeof(CDT),
8325 // where vector register size specified in section 3.2.1 Registers and the
8326 // Stack Frame of original AMD64 ABI document.
8327 QualType RetType = FD->getReturnType();
8328 if (RetType.isNull())
8329 return 0;
8330 ASTContext &C = FD->getASTContext();
8331 QualType CDT;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008332 if (!RetType.isNull() && !RetType->isVoidType()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008333 CDT = RetType;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008334 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008335 unsigned Offset = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008336 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008337 if (ParamAttrs[Offset].Kind == Vector)
8338 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
8339 ++Offset;
8340 }
8341 if (CDT.isNull()) {
8342 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
8343 if (ParamAttrs[I + Offset].Kind == Vector) {
8344 CDT = FD->getParamDecl(I)->getType();
8345 break;
8346 }
8347 }
8348 }
8349 }
8350 if (CDT.isNull())
8351 CDT = C.IntTy;
8352 CDT = CDT->getCanonicalTypeUnqualified();
8353 if (CDT->isRecordType() || CDT->isUnionType())
8354 CDT = C.IntTy;
8355 return C.getTypeSize(CDT);
8356}
8357
8358static void
8359emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00008360 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008361 ArrayRef<ParamAttrTy> ParamAttrs,
8362 OMPDeclareSimdDeclAttr::BranchStateTy State) {
8363 struct ISADataTy {
8364 char ISA;
8365 unsigned VecRegSize;
8366 };
8367 ISADataTy ISAData[] = {
8368 {
8369 'b', 128
8370 }, // SSE
8371 {
8372 'c', 256
8373 }, // AVX
8374 {
8375 'd', 256
8376 }, // AVX2
8377 {
8378 'e', 512
8379 }, // AVX512
8380 };
8381 llvm::SmallVector<char, 2> Masked;
8382 switch (State) {
8383 case OMPDeclareSimdDeclAttr::BS_Undefined:
8384 Masked.push_back('N');
8385 Masked.push_back('M');
8386 break;
8387 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
8388 Masked.push_back('N');
8389 break;
8390 case OMPDeclareSimdDeclAttr::BS_Inbranch:
8391 Masked.push_back('M');
8392 break;
8393 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008394 for (char Mask : Masked) {
8395 for (const ISADataTy &Data : ISAData) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008396 SmallString<256> Buffer;
8397 llvm::raw_svector_ostream Out(Buffer);
8398 Out << "_ZGV" << Data.ISA << Mask;
8399 if (!VLENVal) {
8400 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
8401 evaluateCDTSize(FD, ParamAttrs));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008402 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008403 Out << VLENVal;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008404 }
8405 for (const ParamAttrTy &ParamAttr : ParamAttrs) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008406 switch (ParamAttr.Kind){
8407 case LinearWithVarStride:
8408 Out << 's' << ParamAttr.StrideOrArg;
8409 break;
8410 case Linear:
8411 Out << 'l';
8412 if (!!ParamAttr.StrideOrArg)
8413 Out << ParamAttr.StrideOrArg;
8414 break;
8415 case Uniform:
8416 Out << 'u';
8417 break;
8418 case Vector:
8419 Out << 'v';
8420 break;
8421 }
8422 if (!!ParamAttr.Alignment)
8423 Out << 'a' << ParamAttr.Alignment;
8424 }
8425 Out << '_' << Fn->getName();
8426 Fn->addFnAttr(Out.str());
8427 }
8428 }
8429}
8430
8431void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
8432 llvm::Function *Fn) {
8433 ASTContext &C = CGM.getContext();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008434 FD = FD->getMostRecentDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008435 // Map params to their positions in function decl.
8436 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
8437 if (isa<CXXMethodDecl>(FD))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008438 ParamPositions.try_emplace(FD, 0);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008439 unsigned ParamPos = ParamPositions.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008440 for (const ParmVarDecl *P : FD->parameters()) {
8441 ParamPositions.try_emplace(P->getCanonicalDecl(), ParamPos);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008442 ++ParamPos;
8443 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008444 while (FD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008445 for (const auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008446 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
8447 // Mark uniform parameters.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008448 for (const Expr *E : Attr->uniforms()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008449 E = E->IgnoreParenImpCasts();
8450 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008451 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008452 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008453 } else {
8454 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
8455 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008456 Pos = ParamPositions[PVD];
8457 }
8458 ParamAttrs[Pos].Kind = Uniform;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008459 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008460 // Get alignment info.
8461 auto NI = Attr->alignments_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008462 for (const Expr *E : Attr->aligneds()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008463 E = E->IgnoreParenImpCasts();
8464 unsigned Pos;
8465 QualType ParmTy;
8466 if (isa<CXXThisExpr>(E)) {
8467 Pos = ParamPositions[FD];
8468 ParmTy = E->getType();
8469 } else {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008470 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
8471 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008472 Pos = ParamPositions[PVD];
8473 ParmTy = PVD->getType();
8474 }
8475 ParamAttrs[Pos].Alignment =
8476 (*NI)
8477 ? (*NI)->EvaluateKnownConstInt(C)
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008478 : llvm::APSInt::getUnsigned(
8479 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
8480 .getQuantity());
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008481 ++NI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008482 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008483 // Mark linear parameters.
8484 auto SI = Attr->steps_begin();
8485 auto MI = Attr->modifiers_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008486 for (const Expr *E : Attr->linears()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008487 E = E->IgnoreParenImpCasts();
8488 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008489 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008490 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008491 } else {
8492 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
8493 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008494 Pos = ParamPositions[PVD];
8495 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008496 ParamAttrTy &ParamAttr = ParamAttrs[Pos];
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008497 ParamAttr.Kind = Linear;
8498 if (*SI) {
8499 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
8500 Expr::SE_AllowSideEffects)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008501 if (const auto *DRE =
8502 cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
8503 if (const auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008504 ParamAttr.Kind = LinearWithVarStride;
8505 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
8506 ParamPositions[StridePVD->getCanonicalDecl()]);
8507 }
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008508 }
8509 }
8510 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008511 ++SI;
8512 ++MI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008513 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008514 llvm::APSInt VLENVal;
8515 if (const Expr *VLEN = Attr->getSimdlen())
8516 VLENVal = VLEN->EvaluateKnownConstInt(C);
8517 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
8518 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
8519 CGM.getTriple().getArch() == llvm::Triple::x86_64)
8520 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008521 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008522 FD = FD->getPreviousDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008523 }
8524}
Alexey Bataev8b427062016-05-25 12:36:08 +00008525
8526namespace {
8527/// Cleanup action for doacross support.
8528class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
8529public:
8530 static const int DoacrossFinArgs = 2;
8531
8532private:
8533 llvm::Value *RTLFn;
8534 llvm::Value *Args[DoacrossFinArgs];
8535
8536public:
8537 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
8538 : RTLFn(RTLFn) {
8539 assert(CallArgs.size() == DoacrossFinArgs);
8540 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
8541 }
8542 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
8543 if (!CGF.HaveInsertPoint())
8544 return;
8545 CGF.EmitRuntimeCall(RTLFn, Args);
8546 }
8547};
8548} // namespace
8549
8550void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
8551 const OMPLoopDirective &D) {
8552 if (!CGF.HaveInsertPoint())
8553 return;
8554
8555 ASTContext &C = CGM.getContext();
8556 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
8557 RecordDecl *RD;
8558 if (KmpDimTy.isNull()) {
8559 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
8560 // kmp_int64 lo; // lower
8561 // kmp_int64 up; // upper
8562 // kmp_int64 st; // stride
8563 // };
8564 RD = C.buildImplicitRecord("kmp_dim");
8565 RD->startDefinition();
8566 addFieldToRecordDecl(C, RD, Int64Ty);
8567 addFieldToRecordDecl(C, RD, Int64Ty);
8568 addFieldToRecordDecl(C, RD, Int64Ty);
8569 RD->completeDefinition();
8570 KmpDimTy = C.getRecordType(RD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008571 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00008572 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008573 }
Alexey Bataev8b427062016-05-25 12:36:08 +00008574
8575 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
8576 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
8577 enum { LowerFD = 0, UpperFD, StrideFD };
8578 // Fill dims with data.
8579 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
8580 // dims.upper = num_iterations;
8581 LValue UpperLVal =
8582 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
8583 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
8584 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
8585 Int64Ty, D.getNumIterations()->getExprLoc());
8586 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
8587 // dims.stride = 1;
8588 LValue StrideLVal =
8589 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
8590 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
8591 StrideLVal);
8592
8593 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
8594 // kmp_int32 num_dims, struct kmp_dim * dims);
8595 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
8596 getThreadID(CGF, D.getLocStart()),
8597 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
8598 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
8599 DimsAddr.getPointer(), CGM.VoidPtrTy)};
8600
8601 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
8602 CGF.EmitRuntimeCall(RTLFn, Args);
8603 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
8604 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
8605 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
8606 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
8607 llvm::makeArrayRef(FiniArgs));
8608}
8609
8610void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
8611 const OMPDependClause *C) {
8612 QualType Int64Ty =
8613 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
8614 const Expr *CounterVal = C->getCounterValue();
8615 assert(CounterVal);
8616 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
8617 CounterVal->getType(), Int64Ty,
8618 CounterVal->getExprLoc());
8619 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
8620 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
8621 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
8622 getThreadID(CGF, C->getLocStart()),
8623 CntAddr.getPointer()};
8624 llvm::Value *RTLFn;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008625 if (C->getDependencyKind() == OMPC_DEPEND_source) {
Alexey Bataev8b427062016-05-25 12:36:08 +00008626 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008627 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00008628 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
8629 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
8630 }
8631 CGF.EmitRuntimeCall(RTLFn, Args);
8632}
8633
Alexey Bataev7ef47a62018-02-22 18:33:31 +00008634void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, SourceLocation Loc,
8635 llvm::Value *Callee,
8636 ArrayRef<llvm::Value *> Args) const {
8637 assert(Loc.isValid() && "Outlined function call location must be valid.");
Alexey Bataev3c595a62017-08-14 15:01:03 +00008638 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
8639
8640 if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008641 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00008642 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008643 return;
8644 }
8645 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00008646 CGF.EmitRuntimeCall(Callee, Args);
8647}
8648
8649void CGOpenMPRuntime::emitOutlinedFunctionCall(
8650 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
8651 ArrayRef<llvm::Value *> Args) const {
Alexey Bataev7ef47a62018-02-22 18:33:31 +00008652 emitCall(CGF, Loc, OutlinedFn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008653}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00008654
8655Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
8656 const VarDecl *NativeParam,
8657 const VarDecl *TargetParam) const {
8658 return CGF.GetAddrOfLocalVar(NativeParam);
8659}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00008660
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00008661Address CGOpenMPRuntime::getAddressOfLocalVariable(CodeGenFunction &CGF,
8662 const VarDecl *VD) {
8663 return Address::invalid();
8664}
8665
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00008666llvm::Value *CGOpenMPSIMDRuntime::emitParallelOutlinedFunction(
8667 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8668 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
8669 llvm_unreachable("Not supported in SIMD-only mode");
8670}
8671
8672llvm::Value *CGOpenMPSIMDRuntime::emitTeamsOutlinedFunction(
8673 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8674 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
8675 llvm_unreachable("Not supported in SIMD-only mode");
8676}
8677
8678llvm::Value *CGOpenMPSIMDRuntime::emitTaskOutlinedFunction(
8679 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8680 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
8681 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
8682 bool Tied, unsigned &NumberOfParts) {
8683 llvm_unreachable("Not supported in SIMD-only mode");
8684}
8685
8686void CGOpenMPSIMDRuntime::emitParallelCall(CodeGenFunction &CGF,
8687 SourceLocation Loc,
8688 llvm::Value *OutlinedFn,
8689 ArrayRef<llvm::Value *> CapturedVars,
8690 const Expr *IfCond) {
8691 llvm_unreachable("Not supported in SIMD-only mode");
8692}
8693
8694void CGOpenMPSIMDRuntime::emitCriticalRegion(
8695 CodeGenFunction &CGF, StringRef CriticalName,
8696 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
8697 const Expr *Hint) {
8698 llvm_unreachable("Not supported in SIMD-only mode");
8699}
8700
8701void CGOpenMPSIMDRuntime::emitMasterRegion(CodeGenFunction &CGF,
8702 const RegionCodeGenTy &MasterOpGen,
8703 SourceLocation Loc) {
8704 llvm_unreachable("Not supported in SIMD-only mode");
8705}
8706
8707void CGOpenMPSIMDRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
8708 SourceLocation Loc) {
8709 llvm_unreachable("Not supported in SIMD-only mode");
8710}
8711
8712void CGOpenMPSIMDRuntime::emitTaskgroupRegion(
8713 CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen,
8714 SourceLocation Loc) {
8715 llvm_unreachable("Not supported in SIMD-only mode");
8716}
8717
8718void CGOpenMPSIMDRuntime::emitSingleRegion(
8719 CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen,
8720 SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars,
8721 ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs,
8722 ArrayRef<const Expr *> AssignmentOps) {
8723 llvm_unreachable("Not supported in SIMD-only mode");
8724}
8725
8726void CGOpenMPSIMDRuntime::emitOrderedRegion(CodeGenFunction &CGF,
8727 const RegionCodeGenTy &OrderedOpGen,
8728 SourceLocation Loc,
8729 bool IsThreads) {
8730 llvm_unreachable("Not supported in SIMD-only mode");
8731}
8732
8733void CGOpenMPSIMDRuntime::emitBarrierCall(CodeGenFunction &CGF,
8734 SourceLocation Loc,
8735 OpenMPDirectiveKind Kind,
8736 bool EmitChecks,
8737 bool ForceSimpleCall) {
8738 llvm_unreachable("Not supported in SIMD-only mode");
8739}
8740
8741void CGOpenMPSIMDRuntime::emitForDispatchInit(
8742 CodeGenFunction &CGF, SourceLocation Loc,
8743 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
8744 bool Ordered, const DispatchRTInput &DispatchValues) {
8745 llvm_unreachable("Not supported in SIMD-only mode");
8746}
8747
8748void CGOpenMPSIMDRuntime::emitForStaticInit(
8749 CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind,
8750 const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values) {
8751 llvm_unreachable("Not supported in SIMD-only mode");
8752}
8753
8754void CGOpenMPSIMDRuntime::emitDistributeStaticInit(
8755 CodeGenFunction &CGF, SourceLocation Loc,
8756 OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values) {
8757 llvm_unreachable("Not supported in SIMD-only mode");
8758}
8759
8760void CGOpenMPSIMDRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
8761 SourceLocation Loc,
8762 unsigned IVSize,
8763 bool IVSigned) {
8764 llvm_unreachable("Not supported in SIMD-only mode");
8765}
8766
8767void CGOpenMPSIMDRuntime::emitForStaticFinish(CodeGenFunction &CGF,
8768 SourceLocation Loc,
8769 OpenMPDirectiveKind DKind) {
8770 llvm_unreachable("Not supported in SIMD-only mode");
8771}
8772
8773llvm::Value *CGOpenMPSIMDRuntime::emitForNext(CodeGenFunction &CGF,
8774 SourceLocation Loc,
8775 unsigned IVSize, bool IVSigned,
8776 Address IL, Address LB,
8777 Address UB, Address ST) {
8778 llvm_unreachable("Not supported in SIMD-only mode");
8779}
8780
8781void CGOpenMPSIMDRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
8782 llvm::Value *NumThreads,
8783 SourceLocation Loc) {
8784 llvm_unreachable("Not supported in SIMD-only mode");
8785}
8786
8787void CGOpenMPSIMDRuntime::emitProcBindClause(CodeGenFunction &CGF,
8788 OpenMPProcBindClauseKind ProcBind,
8789 SourceLocation Loc) {
8790 llvm_unreachable("Not supported in SIMD-only mode");
8791}
8792
8793Address CGOpenMPSIMDRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
8794 const VarDecl *VD,
8795 Address VDAddr,
8796 SourceLocation Loc) {
8797 llvm_unreachable("Not supported in SIMD-only mode");
8798}
8799
8800llvm::Function *CGOpenMPSIMDRuntime::emitThreadPrivateVarDefinition(
8801 const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit,
8802 CodeGenFunction *CGF) {
8803 llvm_unreachable("Not supported in SIMD-only mode");
8804}
8805
8806Address CGOpenMPSIMDRuntime::getAddrOfArtificialThreadPrivate(
8807 CodeGenFunction &CGF, QualType VarType, StringRef Name) {
8808 llvm_unreachable("Not supported in SIMD-only mode");
8809}
8810
8811void CGOpenMPSIMDRuntime::emitFlush(CodeGenFunction &CGF,
8812 ArrayRef<const Expr *> Vars,
8813 SourceLocation Loc) {
8814 llvm_unreachable("Not supported in SIMD-only mode");
8815}
8816
8817void CGOpenMPSIMDRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
8818 const OMPExecutableDirective &D,
8819 llvm::Value *TaskFunction,
8820 QualType SharedsTy, Address Shareds,
8821 const Expr *IfCond,
8822 const OMPTaskDataTy &Data) {
8823 llvm_unreachable("Not supported in SIMD-only mode");
8824}
8825
8826void CGOpenMPSIMDRuntime::emitTaskLoopCall(
8827 CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D,
8828 llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
8829 const Expr *IfCond, const OMPTaskDataTy &Data) {
8830 llvm_unreachable("Not supported in SIMD-only mode");
8831}
8832
8833void CGOpenMPSIMDRuntime::emitReduction(
8834 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
8835 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
8836 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
8837 assert(Options.SimpleReduction && "Only simple reduction is expected.");
8838 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
8839 ReductionOps, Options);
8840}
8841
8842llvm::Value *CGOpenMPSIMDRuntime::emitTaskReductionInit(
8843 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
8844 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
8845 llvm_unreachable("Not supported in SIMD-only mode");
8846}
8847
8848void CGOpenMPSIMDRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
8849 SourceLocation Loc,
8850 ReductionCodeGen &RCG,
8851 unsigned N) {
8852 llvm_unreachable("Not supported in SIMD-only mode");
8853}
8854
8855Address CGOpenMPSIMDRuntime::getTaskReductionItem(CodeGenFunction &CGF,
8856 SourceLocation Loc,
8857 llvm::Value *ReductionsPtr,
8858 LValue SharedLVal) {
8859 llvm_unreachable("Not supported in SIMD-only mode");
8860}
8861
8862void CGOpenMPSIMDRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
8863 SourceLocation Loc) {
8864 llvm_unreachable("Not supported in SIMD-only mode");
8865}
8866
8867void CGOpenMPSIMDRuntime::emitCancellationPointCall(
8868 CodeGenFunction &CGF, SourceLocation Loc,
8869 OpenMPDirectiveKind CancelRegion) {
8870 llvm_unreachable("Not supported in SIMD-only mode");
8871}
8872
8873void CGOpenMPSIMDRuntime::emitCancelCall(CodeGenFunction &CGF,
8874 SourceLocation Loc, const Expr *IfCond,
8875 OpenMPDirectiveKind CancelRegion) {
8876 llvm_unreachable("Not supported in SIMD-only mode");
8877}
8878
8879void CGOpenMPSIMDRuntime::emitTargetOutlinedFunction(
8880 const OMPExecutableDirective &D, StringRef ParentName,
8881 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
8882 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
8883 llvm_unreachable("Not supported in SIMD-only mode");
8884}
8885
8886void CGOpenMPSIMDRuntime::emitTargetCall(CodeGenFunction &CGF,
8887 const OMPExecutableDirective &D,
8888 llvm::Value *OutlinedFn,
8889 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00008890 const Expr *IfCond, const Expr *Device) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00008891 llvm_unreachable("Not supported in SIMD-only mode");
8892}
8893
8894bool CGOpenMPSIMDRuntime::emitTargetFunctions(GlobalDecl GD) {
8895 llvm_unreachable("Not supported in SIMD-only mode");
8896}
8897
8898bool CGOpenMPSIMDRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
8899 llvm_unreachable("Not supported in SIMD-only mode");
8900}
8901
8902bool CGOpenMPSIMDRuntime::emitTargetGlobal(GlobalDecl GD) {
8903 return false;
8904}
8905
8906llvm::Function *CGOpenMPSIMDRuntime::emitRegistrationFunction() {
8907 return nullptr;
8908}
8909
8910void CGOpenMPSIMDRuntime::emitTeamsCall(CodeGenFunction &CGF,
8911 const OMPExecutableDirective &D,
8912 SourceLocation Loc,
8913 llvm::Value *OutlinedFn,
8914 ArrayRef<llvm::Value *> CapturedVars) {
8915 llvm_unreachable("Not supported in SIMD-only mode");
8916}
8917
8918void CGOpenMPSIMDRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
8919 const Expr *NumTeams,
8920 const Expr *ThreadLimit,
8921 SourceLocation Loc) {
8922 llvm_unreachable("Not supported in SIMD-only mode");
8923}
8924
8925void CGOpenMPSIMDRuntime::emitTargetDataCalls(
8926 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8927 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
8928 llvm_unreachable("Not supported in SIMD-only mode");
8929}
8930
8931void CGOpenMPSIMDRuntime::emitTargetDataStandAloneCall(
8932 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8933 const Expr *Device) {
8934 llvm_unreachable("Not supported in SIMD-only mode");
8935}
8936
8937void CGOpenMPSIMDRuntime::emitDoacrossInit(CodeGenFunction &CGF,
8938 const OMPLoopDirective &D) {
8939 llvm_unreachable("Not supported in SIMD-only mode");
8940}
8941
8942void CGOpenMPSIMDRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
8943 const OMPDependClause *C) {
8944 llvm_unreachable("Not supported in SIMD-only mode");
8945}
8946
8947const VarDecl *
8948CGOpenMPSIMDRuntime::translateParameter(const FieldDecl *FD,
8949 const VarDecl *NativeParam) const {
8950 llvm_unreachable("Not supported in SIMD-only mode");
8951}
8952
8953Address
8954CGOpenMPSIMDRuntime::getParameterAddress(CodeGenFunction &CGF,
8955 const VarDecl *NativeParam,
8956 const VarDecl *TargetParam) const {
8957 llvm_unreachable("Not supported in SIMD-only mode");
8958}
8959