blob: 2c66f6947d37ab6eed898ceabd270fccdca55742 [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 Bataevdadf2d12018-04-30 18:09:40 +0000902 if (const auto *MD = dyn_cast<CXXMethodDecl>(VD))
903 if (!MD->isStatic())
904 return llvm::None;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000905 for (const Decl *D : VD->redecls()) {
Alexey Bataev92327c52018-03-26 16:40:55 +0000906 if (!D->hasAttrs())
907 continue;
908 if (const auto *Attr = D->getAttr<OMPDeclareTargetDeclAttr>())
909 return Attr->getMapType();
910 }
Alexey Bataevfb388282018-05-01 14:09:46 +0000911 if (const auto *V = dyn_cast<VarDecl>(VD)) {
912 if (const VarDecl *TD = V->getTemplateInstantiationPattern())
913 return isDeclareTargetDeclaration(TD);
914 } else if (const auto *FD = dyn_cast<FunctionDecl>(VD)) {
915 if (const auto *TD = FD->getTemplateInstantiationPattern())
916 return isDeclareTargetDeclaration(TD);
917 }
918
Alexey Bataev92327c52018-03-26 16:40:55 +0000919 return llvm::None;
920}
921
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000922LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000923 return CGF.EmitOMPSharedLValue(E);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000924}
925
926LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
927 const Expr *E) {
928 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
929 return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
930 return LValue();
931}
932
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000933void ReductionCodeGen::emitAggregateInitialization(
934 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
935 const OMPDeclareReductionDecl *DRD) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000936 // Emit VarDecl with copy init for arrays.
937 // Get the address of the original variable captured in current
938 // captured region.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000939 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000940 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva7b19152017-10-12 20:03:39 +0000941 bool EmitDeclareReductionInit =
942 DRD && (DRD->getInitializer() || !PrivateVD->hasInit());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000943 EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
Alexey Bataeva7b19152017-10-12 20:03:39 +0000944 EmitDeclareReductionInit,
945 EmitDeclareReductionInit ? ClausesData[N].ReductionOp
946 : PrivateVD->getInit(),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000947 DRD, SharedLVal.getAddress());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000948}
949
950ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
951 ArrayRef<const Expr *> Privates,
952 ArrayRef<const Expr *> ReductionOps) {
953 ClausesData.reserve(Shareds.size());
954 SharedAddresses.reserve(Shareds.size());
955 Sizes.reserve(Shareds.size());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000956 BaseDecls.reserve(Shareds.size());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000957 auto IPriv = Privates.begin();
958 auto IRed = ReductionOps.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000959 for (const Expr *Ref : Shareds) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000960 ClausesData.emplace_back(Ref, *IPriv, *IRed);
961 std::advance(IPriv, 1);
962 std::advance(IRed, 1);
963 }
964}
965
966void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
967 assert(SharedAddresses.size() == N &&
968 "Number of generated lvalues must be exactly N.");
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000969 LValue First = emitSharedLValue(CGF, ClausesData[N].Ref);
970 LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Ref);
971 SharedAddresses.emplace_back(First, Second);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000972}
973
974void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000975 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000976 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
977 QualType PrivateType = PrivateVD->getType();
978 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000979 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000980 Sizes.emplace_back(
981 CGF.getTypeSize(
982 SharedAddresses[N].first.getType().getNonReferenceType()),
983 nullptr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000984 return;
985 }
986 llvm::Value *Size;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000987 llvm::Value *SizeInChars;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000988 auto *ElemType =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000989 cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
990 ->getElementType();
991 auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000992 if (AsArraySection) {
993 Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
994 SharedAddresses[N].first.getPointer());
995 Size = CGF.Builder.CreateNUWAdd(
996 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000997 SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000998 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000999 SizeInChars = CGF.getTypeSize(
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001000 SharedAddresses[N].first.getType().getNonReferenceType());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001001 Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001002 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001003 Sizes.emplace_back(SizeInChars, Size);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001004 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1005 CGF,
1006 cast<OpaqueValueExpr>(
1007 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
1008 RValue::get(Size));
1009 CGF.EmitVariablyModifiedType(PrivateType);
1010}
1011
1012void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
1013 llvm::Value *Size) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001014 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001015 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1016 QualType PrivateType = PrivateVD->getType();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001017 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001018 assert(!Size && !Sizes[N].second &&
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001019 "Size should be nullptr for non-variably modified reduction "
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001020 "items.");
1021 return;
1022 }
1023 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1024 CGF,
1025 cast<OpaqueValueExpr>(
1026 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
1027 RValue::get(Size));
1028 CGF.EmitVariablyModifiedType(PrivateType);
1029}
1030
1031void ReductionCodeGen::emitInitialization(
1032 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
1033 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
1034 assert(SharedAddresses.size() > N && "No variable was generated");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001035 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001036 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001037 const OMPDeclareReductionDecl *DRD =
1038 getReductionInit(ClausesData[N].ReductionOp);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001039 QualType PrivateType = PrivateVD->getType();
1040 PrivateAddr = CGF.Builder.CreateElementBitCast(
1041 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1042 QualType SharedType = SharedAddresses[N].first.getType();
1043 SharedLVal = CGF.MakeAddrLValue(
1044 CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
1045 CGF.ConvertTypeForMem(SharedType)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001046 SharedType, SharedAddresses[N].first.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001047 CGF.CGM.getTBAAInfoForSubobject(SharedAddresses[N].first, SharedType));
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001048 if (CGF.getContext().getAsArrayType(PrivateVD->getType())) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001049 emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001050 } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
1051 emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
1052 PrivateAddr, SharedLVal.getAddress(),
1053 SharedLVal.getType());
1054 } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
1055 !CGF.isTrivialInitializer(PrivateVD->getInit())) {
1056 CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
1057 PrivateVD->getType().getQualifiers(),
1058 /*IsInitializer=*/false);
1059 }
1060}
1061
1062bool ReductionCodeGen::needCleanups(unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001063 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001064 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1065 QualType PrivateType = PrivateVD->getType();
1066 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1067 return DTorKind != QualType::DK_none;
1068}
1069
1070void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
1071 Address PrivateAddr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001072 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001073 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1074 QualType PrivateType = PrivateVD->getType();
1075 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1076 if (needCleanups(N)) {
1077 PrivateAddr = CGF.Builder.CreateElementBitCast(
1078 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1079 CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
1080 }
1081}
1082
1083static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1084 LValue BaseLV) {
1085 BaseTy = BaseTy.getNonReferenceType();
1086 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1087 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001088 if (const auto *PtrTy = BaseTy->getAs<PointerType>()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001089 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001090 } else {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00001091 LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(), BaseTy);
1092 BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001093 }
1094 BaseTy = BaseTy->getPointeeType();
1095 }
1096 return CGF.MakeAddrLValue(
1097 CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
1098 CGF.ConvertTypeForMem(ElTy)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001099 BaseLV.getType(), BaseLV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001100 CGF.CGM.getTBAAInfoForSubobject(BaseLV, BaseLV.getType()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001101}
1102
1103static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1104 llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
1105 llvm::Value *Addr) {
1106 Address Tmp = Address::invalid();
1107 Address TopTmp = Address::invalid();
1108 Address MostTopTmp = Address::invalid();
1109 BaseTy = BaseTy.getNonReferenceType();
1110 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1111 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1112 Tmp = CGF.CreateMemTemp(BaseTy);
1113 if (TopTmp.isValid())
1114 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
1115 else
1116 MostTopTmp = Tmp;
1117 TopTmp = Tmp;
1118 BaseTy = BaseTy->getPointeeType();
1119 }
1120 llvm::Type *Ty = BaseLVType;
1121 if (Tmp.isValid())
1122 Ty = Tmp.getElementType();
1123 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
1124 if (Tmp.isValid()) {
1125 CGF.Builder.CreateStore(Addr, Tmp);
1126 return MostTopTmp;
1127 }
1128 return Address(Addr, BaseLVAlignment);
1129}
1130
Alexey Bataev1c44e152018-03-06 18:59:43 +00001131static const VarDecl *getBaseDecl(const Expr *Ref, const DeclRefExpr *&DE) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001132 const VarDecl *OrigVD = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001133 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(Ref)) {
1134 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
1135 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001136 Base = TempOASE->getBase()->IgnoreParenImpCasts();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001137 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001138 Base = TempASE->getBase()->IgnoreParenImpCasts();
1139 DE = cast<DeclRefExpr>(Base);
1140 OrigVD = cast<VarDecl>(DE->getDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001141 } else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Ref)) {
1142 const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
1143 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001144 Base = TempASE->getBase()->IgnoreParenImpCasts();
1145 DE = cast<DeclRefExpr>(Base);
1146 OrigVD = cast<VarDecl>(DE->getDecl());
1147 }
Alexey Bataev1c44e152018-03-06 18:59:43 +00001148 return OrigVD;
1149}
1150
1151Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
1152 Address PrivateAddr) {
1153 const DeclRefExpr *DE;
1154 if (const VarDecl *OrigVD = ::getBaseDecl(ClausesData[N].Ref, DE)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001155 BaseDecls.emplace_back(OrigVD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001156 LValue OriginalBaseLValue = CGF.EmitLValue(DE);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001157 LValue BaseLValue =
1158 loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1159 OriginalBaseLValue);
1160 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1161 BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001162 llvm::Value *PrivatePointer =
1163 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1164 PrivateAddr.getPointer(),
1165 SharedAddresses[N].first.getAddress().getType());
1166 llvm::Value *Ptr = CGF.Builder.CreateGEP(PrivatePointer, Adjustment);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001167 return castToBase(CGF, OrigVD->getType(),
1168 SharedAddresses[N].first.getType(),
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001169 OriginalBaseLValue.getAddress().getType(),
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001170 OriginalBaseLValue.getAlignment(), Ptr);
1171 }
1172 BaseDecls.emplace_back(
1173 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1174 return PrivateAddr;
1175}
1176
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001177bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001178 const OMPDeclareReductionDecl *DRD =
1179 getReductionInit(ClausesData[N].ReductionOp);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001180 return DRD && DRD->getInitializer();
1181}
1182
Alexey Bataev18095712014-10-10 12:19:54 +00001183LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00001184 return CGF.EmitLoadOfPointerLValue(
1185 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1186 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +00001187}
1188
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001189void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001190 if (!CGF.HaveInsertPoint())
1191 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001192 // 1.2.2 OpenMP Language Terminology
1193 // Structured block - An executable statement with a single entry at the
1194 // top and a single exit at the bottom.
1195 // The point of exit cannot be a branch out of the structured block.
1196 // longjmp() and throw() must not violate the entry/exit criteria.
1197 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001198 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001199 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001200}
1201
Alexey Bataev62b63b12015-03-10 07:28:44 +00001202LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1203 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001204 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1205 getThreadIDVariable()->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00001206 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001207}
1208
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001209static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
1210 QualType FieldTy) {
1211 auto *Field = FieldDecl::Create(
1212 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
1213 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
1214 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
1215 Field->setAccess(AS_public);
1216 DC->addDecl(Field);
1217 return Field;
1218}
1219
Alexey Bataev18fa2322018-05-02 14:20:50 +00001220CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM, StringRef FirstSeparator,
1221 StringRef Separator)
1222 : CGM(CGM), FirstSeparator(FirstSeparator), Separator(Separator),
1223 OffloadEntriesInfoManager(CGM) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001224 ASTContext &C = CGM.getContext();
1225 RecordDecl *RD = C.buildImplicitRecord("ident_t");
1226 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1227 RD->startDefinition();
1228 // reserved_1
1229 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1230 // flags
1231 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1232 // reserved_2
1233 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1234 // reserved_3
1235 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1236 // psource
1237 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
1238 RD->completeDefinition();
1239 IdentQTy = C.getRecordType(RD);
1240 IdentTy = CGM.getTypes().ConvertRecordDeclType(RD);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001241 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +00001242
1243 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +00001244}
1245
Alexey Bataev91797552015-03-18 04:13:55 +00001246void CGOpenMPRuntime::clear() {
1247 InternalVars.clear();
1248}
1249
Alexey Bataev18fa2322018-05-02 14:20:50 +00001250std::string CGOpenMPRuntime::getName(ArrayRef<StringRef> Parts) const {
1251 SmallString<128> Buffer;
1252 llvm::raw_svector_ostream OS(Buffer);
1253 StringRef Sep = FirstSeparator;
1254 for (StringRef Part : Parts) {
1255 OS << Sep << Part;
1256 Sep = Separator;
1257 }
1258 return OS.str();
1259}
1260
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001261static llvm::Function *
1262emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1263 const Expr *CombinerInitializer, const VarDecl *In,
1264 const VarDecl *Out, bool IsCombiner) {
1265 // void .omp_combiner.(Ty *in, Ty *out);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001266 ASTContext &C = CGM.getContext();
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001267 QualType PtrTy = C.getPointerType(Ty).withRestrict();
1268 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001269 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001270 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001271 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001272 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001273 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001274 Args.push_back(&OmpInParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001275 const CGFunctionInfo &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001276 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001277 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00001278 std::string Name = CGM.getOpenMPRuntime().getName(
1279 {IsCombiner ? "omp_combiner" : "omp_initializer", ""});
1280 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
1281 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001282 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001283 Fn->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001284 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001285 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001286 CodeGenFunction CGF(CGM);
1287 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1288 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001289 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, In->getLocation(),
1290 Out->getLocation());
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001291 CodeGenFunction::OMPPrivateScope Scope(CGF);
1292 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001293 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001294 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1295 .getAddress();
1296 });
1297 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001298 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001299 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1300 .getAddress();
1301 });
1302 (void)Scope.Privatize();
Alexey Bataev070f43a2017-09-06 14:49:58 +00001303 if (!IsCombiner && Out->hasInit() &&
1304 !CGF.isTrivialInitializer(Out->getInit())) {
1305 CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
1306 Out->getType().getQualifiers(),
1307 /*IsInitializer=*/true);
1308 }
1309 if (CombinerInitializer)
1310 CGF.EmitIgnoredExpr(CombinerInitializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001311 Scope.ForceCleanup();
1312 CGF.FinishFunction();
1313 return Fn;
1314}
1315
1316void CGOpenMPRuntime::emitUserDefinedReduction(
1317 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1318 if (UDRMap.count(D) > 0)
1319 return;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001320 ASTContext &C = CGM.getContext();
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001321 if (!In || !Out) {
1322 In = &C.Idents.get("omp_in");
1323 Out = &C.Idents.get("omp_out");
1324 }
1325 llvm::Function *Combiner = emitCombinerOrInitializer(
1326 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
1327 cast<VarDecl>(D->lookup(Out).front()),
1328 /*IsCombiner=*/true);
1329 llvm::Function *Initializer = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001330 if (const Expr *Init = D->getInitializer()) {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001331 if (!Priv || !Orig) {
1332 Priv = &C.Idents.get("omp_priv");
1333 Orig = &C.Idents.get("omp_orig");
1334 }
1335 Initializer = emitCombinerOrInitializer(
Alexey Bataev070f43a2017-09-06 14:49:58 +00001336 CGM, D->getType(),
1337 D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init
1338 : nullptr,
1339 cast<VarDecl>(D->lookup(Orig).front()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001340 cast<VarDecl>(D->lookup(Priv).front()),
1341 /*IsCombiner=*/false);
1342 }
Alexey Bataev43a919f2018-04-13 17:48:43 +00001343 UDRMap.try_emplace(D, Combiner, Initializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001344 if (CGF) {
1345 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1346 Decls.second.push_back(D);
1347 }
1348}
1349
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001350std::pair<llvm::Function *, llvm::Function *>
1351CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1352 auto I = UDRMap.find(D);
1353 if (I != UDRMap.end())
1354 return I->second;
1355 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1356 return UDRMap.lookup(D);
1357}
1358
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001359static llvm::Value *emitParallelOrTeamsOutlinedFunction(
1360 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1361 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1362 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001363 assert(ThreadIDVar->getType()->isPointerType() &&
1364 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +00001365 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00001366 bool HasCancel = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001367 if (const auto *OPD = dyn_cast<OMPParallelDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001368 HasCancel = OPD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001369 else if (const auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001370 HasCancel = OPSD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001371 else if (const auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001372 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001373 else if (const auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D))
Alexey Bataev2139ed62017-11-16 18:20:21 +00001374 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001375 else if (const auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&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 =
1378 dyn_cast<OMPTeamsDistributeParallelForDirective>(&D))
Alexey Bataev10a54312017-11-27 16:54:08 +00001379 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001380 else if (const auto *OPFD =
Alexey Bataev10a54312017-11-27 16:54:08 +00001381 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D))
1382 HasCancel = OPFD->hasCancel();
Alexey Bataev25e5b442015-09-15 12:52:43 +00001383 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001384 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +00001385 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001386 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +00001387}
1388
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001389llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
1390 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1391 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1392 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1393 return emitParallelOrTeamsOutlinedFunction(
1394 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1395}
1396
1397llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1398 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1399 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1400 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1401 return emitParallelOrTeamsOutlinedFunction(
1402 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1403}
1404
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001405llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
1406 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +00001407 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1408 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1409 bool Tied, unsigned &NumberOfParts) {
1410 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1411 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001412 llvm::Value *ThreadID = getThreadID(CGF, D.getLocStart());
1413 llvm::Value *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
Alexey Bataev48591dd2016-04-20 04:01:36 +00001414 llvm::Value *TaskArgs[] = {
1415 UpLoc, ThreadID,
1416 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1417 TaskTVar->getType()->castAs<PointerType>())
1418 .getPointer()};
1419 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1420 };
1421 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1422 UntiedCodeGen);
1423 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001424 assert(!ThreadIDVar->getType()->isPointerType() &&
1425 "thread id variable must be of type kmp_int32 for tasks");
Alexey Bataev475a7442018-01-12 19:39:11 +00001426 const OpenMPDirectiveKind Region =
1427 isOpenMPTaskLoopDirective(D.getDirectiveKind()) ? OMPD_taskloop
1428 : OMPD_task;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001429 const CapturedStmt *CS = D.getCapturedStmt(Region);
1430 const auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001431 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +00001432 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1433 InnermostKind,
1434 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +00001435 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001436 llvm::Value *Res = CGF.GenerateCapturedStmtFunction(*CS);
Alexey Bataev48591dd2016-04-20 04:01:36 +00001437 if (!Tied)
1438 NumberOfParts = Action.getNumberOfParts();
1439 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001440}
1441
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001442static void buildStructValue(ConstantStructBuilder &Fields, CodeGenModule &CGM,
1443 const RecordDecl *RD, const CGRecordLayout &RL,
1444 ArrayRef<llvm::Constant *> Data) {
1445 llvm::StructType *StructTy = RL.getLLVMType();
1446 unsigned PrevIdx = 0;
1447 ConstantInitBuilder CIBuilder(CGM);
1448 auto DI = Data.begin();
1449 for (const FieldDecl *FD : RD->fields()) {
1450 unsigned Idx = RL.getLLVMFieldNo(FD);
1451 // Fill the alignment.
1452 for (unsigned I = PrevIdx; I < Idx; ++I)
1453 Fields.add(llvm::Constant::getNullValue(StructTy->getElementType(I)));
1454 PrevIdx = Idx + 1;
1455 Fields.add(*DI);
1456 ++DI;
1457 }
1458}
1459
1460template <class... As>
1461static llvm::GlobalVariable *
1462createConstantGlobalStruct(CodeGenModule &CGM, QualType Ty,
1463 ArrayRef<llvm::Constant *> Data, const Twine &Name,
1464 As &&... Args) {
1465 const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1466 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1467 ConstantInitBuilder CIBuilder(CGM);
1468 ConstantStructBuilder Fields = CIBuilder.beginStruct(RL.getLLVMType());
1469 buildStructValue(Fields, CGM, RD, RL, Data);
1470 return Fields.finishAndCreateGlobal(
1471 Name, CGM.getContext().getAlignOfGlobalVarInChars(Ty),
1472 /*isConstant=*/true, std::forward<As>(Args)...);
1473}
1474
1475template <typename T>
1476void createConstantGlobalStructAndAddToParent(CodeGenModule &CGM, QualType Ty,
1477 ArrayRef<llvm::Constant *> Data,
1478 T &Parent) {
1479 const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1480 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1481 ConstantStructBuilder Fields = Parent.beginStruct(RL.getLLVMType());
1482 buildStructValue(Fields, CGM, RD, RL, Data);
1483 Fields.finishAndAddTo(Parent);
1484}
1485
Alexey Bataev50b3c952016-02-19 10:38:26 +00001486Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001487 CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
Alexey Bataev15007ba2014-05-07 06:18:01 +00001488 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +00001489 if (!Entry) {
1490 if (!DefaultOpenMPPSource) {
1491 // Initialize default location for psource field of ident_t structure of
1492 // all ident_t objects. Format is ";file;function;line;column;;".
1493 // Taken from
1494 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1495 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +00001496 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001497 DefaultOpenMPPSource =
1498 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1499 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001500
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001501 llvm::Constant *Data[] = {llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1502 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
1503 llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1504 llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1505 DefaultOpenMPPSource};
1506 llvm::GlobalValue *DefaultOpenMPLocation = createConstantGlobalStruct(
1507 CGM, IdentQTy, Data, "", llvm::GlobalValue::PrivateLinkage);
1508 DefaultOpenMPLocation->setUnnamedAddr(
1509 llvm::GlobalValue::UnnamedAddr::Global);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001510
John McCall7f416cc2015-09-08 08:05:57 +00001511 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +00001512 }
John McCall7f416cc2015-09-08 08:05:57 +00001513 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +00001514}
1515
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001516llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1517 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001518 unsigned Flags) {
1519 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +00001520 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001521 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +00001522 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +00001523 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001524
1525 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1526
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001527 CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
John McCall7f416cc2015-09-08 08:05:57 +00001528 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001529 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1530 if (I != OpenMPLocThreadIDMap.end())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001531 LocValue = Address(I->second.DebugLoc, Align);
John McCall7f416cc2015-09-08 08:05:57 +00001532
Alexander Musmanc6388682014-12-15 07:07:06 +00001533 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1534 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +00001535 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +00001536 // Generate "ident_t .kmpc_loc.addr;"
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001537 Address AI = CGF.CreateMemTemp(IdentQTy, ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +00001538 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +00001539 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001540 LocValue = AI;
1541
1542 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1543 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001544 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001545 CGF.getTypeSize(IdentQTy));
Alexey Bataev9959db52014-05-06 10:08:46 +00001546 }
1547
1548 // char **psource = &.kmpc_loc_<flags>.addr.psource;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001549 LValue Base = CGF.MakeAddrLValue(LocValue, IdentQTy);
1550 auto Fields = cast<RecordDecl>(IdentQTy->getAsTagDecl())->field_begin();
1551 LValue PSource =
1552 CGF.EmitLValueForField(Base, *std::next(Fields, IdentField_PSource));
Alexey Bataev9959db52014-05-06 10:08:46 +00001553
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001554 llvm::Value *OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
Alexey Bataevf002aca2014-05-30 05:48:40 +00001555 if (OMPDebugLoc == nullptr) {
1556 SmallString<128> Buffer2;
1557 llvm::raw_svector_ostream OS2(Buffer2);
1558 // Build debug location
1559 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1560 OS2 << ";" << PLoc.getFilename() << ";";
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001561 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl))
Alexey Bataevf002aca2014-05-30 05:48:40 +00001562 OS2 << FD->getQualifiedNameAsString();
Alexey Bataevf002aca2014-05-30 05:48:40 +00001563 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1564 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1565 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +00001566 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001567 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001568 CGF.EmitStoreOfScalar(OMPDebugLoc, PSource);
Alexey Bataevf002aca2014-05-30 05:48:40 +00001569
John McCall7f416cc2015-09-08 08:05:57 +00001570 // Our callers always pass this to a runtime function, so for
1571 // convenience, go ahead and return a naked pointer.
1572 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001573}
1574
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001575llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1576 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001577 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1578
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001579 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001580 // Check whether we've already cached a load of the thread id in this
1581 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001582 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001583 if (I != OpenMPLocThreadIDMap.end()) {
1584 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001585 if (ThreadID != nullptr)
1586 return ThreadID;
1587 }
Alexey Bataevaee18552017-08-16 14:01:00 +00001588 // If exceptions are enabled, do not use parameter to avoid possible crash.
Alexey Bataev5d2c9a42017-11-02 18:55:05 +00001589 if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions ||
1590 !CGF.getLangOpts().CXXExceptions ||
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001591 CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
Alexey Bataevaee18552017-08-16 14:01:00 +00001592 if (auto *OMPRegionInfo =
1593 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1594 if (OMPRegionInfo->getThreadIDVariable()) {
1595 // Check if this an outlined function with thread id passed as argument.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001596 LValue LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev1e491372018-01-23 18:44:14 +00001597 ThreadID = CGF.EmitLoadOfScalar(LVal, Loc);
Alexey Bataevaee18552017-08-16 14:01:00 +00001598 // If value loaded in entry block, cache it and use it everywhere in
1599 // function.
1600 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1601 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1602 Elem.second.ThreadID = ThreadID;
1603 }
1604 return ThreadID;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001605 }
Alexey Bataevd6c57552014-07-25 07:55:17 +00001606 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001607 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001608
1609 // This is not an outlined function region - need to call __kmpc_int32
1610 // kmpc_global_thread_num(ident_t *loc).
1611 // Generate thread id value and cache this value for use across the
1612 // function.
1613 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1614 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001615 llvm::CallInst *Call = CGF.Builder.CreateCall(
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001616 createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1617 emitUpdateLocation(CGF, Loc));
1618 Call->setCallingConv(CGF.getRuntimeCC());
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001619 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001620 Elem.second.ThreadID = Call;
1621 return Call;
Alexey Bataev9959db52014-05-06 10:08:46 +00001622}
1623
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001624void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001625 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001626 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1627 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001628 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001629 for(auto *D : FunctionUDRMap[CGF.CurFn])
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001630 UDRMap.erase(D);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001631 FunctionUDRMap.erase(CGF.CurFn);
1632 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001633}
1634
1635llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001636 return IdentTy->getPointerTo();
Alexey Bataev9959db52014-05-06 10:08:46 +00001637}
1638
1639llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001640 if (!Kmpc_MicroTy) {
1641 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1642 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1643 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1644 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1645 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001646 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1647}
1648
1649llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001650CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001651 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001652 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001653 case OMPRTL__kmpc_fork_call: {
1654 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1655 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001656 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1657 getKmpc_MicroPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001658 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001659 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001660 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1661 break;
1662 }
1663 case OMPRTL__kmpc_global_thread_num: {
1664 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001665 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001666 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001667 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001668 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1669 break;
1670 }
Alexey Bataev97720002014-11-11 04:05:39 +00001671 case OMPRTL__kmpc_threadprivate_cached: {
1672 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1673 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1674 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1675 CGM.VoidPtrTy, CGM.SizeTy,
1676 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001677 auto *FnTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001678 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1679 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1680 break;
1681 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001682 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001683 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1684 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001685 llvm::Type *TypeParams[] = {
1686 getIdentTyPointerTy(), CGM.Int32Ty,
1687 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001688 auto *FnTy =
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001689 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1690 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1691 break;
1692 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001693 case OMPRTL__kmpc_critical_with_hint: {
1694 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1695 // kmp_critical_name *crit, uintptr_t hint);
1696 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1697 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1698 CGM.IntPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001699 auto *FnTy =
Alexey Bataevfc57d162015-12-15 10:55:09 +00001700 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1701 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1702 break;
1703 }
Alexey Bataev97720002014-11-11 04:05:39 +00001704 case OMPRTL__kmpc_threadprivate_register: {
1705 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1706 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1707 // typedef void *(*kmpc_ctor)(void *);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001708 auto *KmpcCtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001709 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1710 /*isVarArg*/ false)->getPointerTo();
1711 // typedef void *(*kmpc_cctor)(void *, void *);
1712 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001713 auto *KmpcCopyCtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001714 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001715 /*isVarArg*/ false)
1716 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00001717 // typedef void (*kmpc_dtor)(void *);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001718 auto *KmpcDtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001719 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1720 ->getPointerTo();
1721 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1722 KmpcCopyCtorTy, KmpcDtorTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001723 auto *FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
Alexey Bataev97720002014-11-11 04:05:39 +00001724 /*isVarArg*/ false);
1725 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1726 break;
1727 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001728 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001729 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1730 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001731 llvm::Type *TypeParams[] = {
1732 getIdentTyPointerTy(), CGM.Int32Ty,
1733 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001734 auto *FnTy =
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001735 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1736 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1737 break;
1738 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001739 case OMPRTL__kmpc_cancel_barrier: {
1740 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1741 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001742 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001743 auto *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001744 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1745 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001746 break;
1747 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001748 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001749 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001750 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001751 auto *FnTy =
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001752 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1753 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1754 break;
1755 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001756 case OMPRTL__kmpc_for_static_fini: {
1757 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1758 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001759 auto *FnTy =
Alexander Musmanc6388682014-12-15 07:07:06 +00001760 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1761 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1762 break;
1763 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001764 case OMPRTL__kmpc_push_num_threads: {
1765 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1766 // kmp_int32 num_threads)
1767 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1768 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001769 auto *FnTy =
Alexey Bataevb2059782014-10-13 08:23:51 +00001770 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1771 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1772 break;
1773 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001774 case OMPRTL__kmpc_serialized_parallel: {
1775 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1776 // global_tid);
1777 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001778 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001779 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1780 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1781 break;
1782 }
1783 case OMPRTL__kmpc_end_serialized_parallel: {
1784 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1785 // global_tid);
1786 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001787 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001788 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1789 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1790 break;
1791 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001792 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001793 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001794 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001795 auto *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001796 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001797 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1798 break;
1799 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001800 case OMPRTL__kmpc_master: {
1801 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1802 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001803 auto *FnTy =
Alexey Bataev8d690652014-12-04 07:23:53 +00001804 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1805 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1806 break;
1807 }
1808 case OMPRTL__kmpc_end_master: {
1809 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1810 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001811 auto *FnTy =
Alexey Bataev8d690652014-12-04 07:23:53 +00001812 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1813 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1814 break;
1815 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001816 case OMPRTL__kmpc_omp_taskyield: {
1817 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1818 // int end_part);
1819 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001820 auto *FnTy =
Alexey Bataev9f797f32015-02-05 05:57:51 +00001821 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1822 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1823 break;
1824 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001825 case OMPRTL__kmpc_single: {
1826 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1827 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001828 auto *FnTy =
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001829 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1830 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1831 break;
1832 }
1833 case OMPRTL__kmpc_end_single: {
1834 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1835 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001836 auto *FnTy =
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001837 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1838 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1839 break;
1840 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001841 case OMPRTL__kmpc_omp_task_alloc: {
1842 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1843 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1844 // kmp_routine_entry_t *task_entry);
1845 assert(KmpRoutineEntryPtrTy != nullptr &&
1846 "Type kmp_routine_entry_t must be created.");
1847 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1848 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1849 // Return void * and then cast to particular kmp_task_t type.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001850 auto *FnTy =
Alexey Bataev62b63b12015-03-10 07:28:44 +00001851 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1852 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1853 break;
1854 }
1855 case OMPRTL__kmpc_omp_task: {
1856 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1857 // *new_task);
1858 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1859 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001860 auto *FnTy =
Alexey Bataev62b63b12015-03-10 07:28:44 +00001861 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1862 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1863 break;
1864 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001865 case OMPRTL__kmpc_copyprivate: {
1866 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001867 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001868 // kmp_int32 didit);
1869 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1870 auto *CpyFnTy =
1871 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001872 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001873 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1874 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001875 auto *FnTy =
Alexey Bataeva63048e2015-03-23 06:18:07 +00001876 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1877 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1878 break;
1879 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001880 case OMPRTL__kmpc_reduce: {
1881 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1882 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1883 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1884 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1885 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1886 /*isVarArg=*/false);
1887 llvm::Type *TypeParams[] = {
1888 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1889 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1890 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001891 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001892 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1893 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1894 break;
1895 }
1896 case OMPRTL__kmpc_reduce_nowait: {
1897 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1898 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1899 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1900 // *lck);
1901 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1902 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1903 /*isVarArg=*/false);
1904 llvm::Type *TypeParams[] = {
1905 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1906 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1907 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001908 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001909 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1910 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1911 break;
1912 }
1913 case OMPRTL__kmpc_end_reduce: {
1914 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1915 // kmp_critical_name *lck);
1916 llvm::Type *TypeParams[] = {
1917 getIdentTyPointerTy(), CGM.Int32Ty,
1918 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001919 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001920 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1921 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1922 break;
1923 }
1924 case OMPRTL__kmpc_end_reduce_nowait: {
1925 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1926 // kmp_critical_name *lck);
1927 llvm::Type *TypeParams[] = {
1928 getIdentTyPointerTy(), CGM.Int32Ty,
1929 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001930 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001931 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1932 RTLFn =
1933 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1934 break;
1935 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001936 case OMPRTL__kmpc_omp_task_begin_if0: {
1937 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1938 // *new_task);
1939 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1940 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001941 auto *FnTy =
Alexey Bataev1d677132015-04-22 13:57:31 +00001942 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1943 RTLFn =
1944 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1945 break;
1946 }
1947 case OMPRTL__kmpc_omp_task_complete_if0: {
1948 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1949 // *new_task);
1950 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1951 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001952 auto *FnTy =
Alexey Bataev1d677132015-04-22 13:57:31 +00001953 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1954 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1955 /*Name=*/"__kmpc_omp_task_complete_if0");
1956 break;
1957 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001958 case OMPRTL__kmpc_ordered: {
1959 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1960 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001961 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001962 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1963 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1964 break;
1965 }
1966 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001967 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001968 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001969 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001970 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1971 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1972 break;
1973 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001974 case OMPRTL__kmpc_omp_taskwait: {
1975 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1976 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001977 auto *FnTy =
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001978 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1979 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1980 break;
1981 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001982 case OMPRTL__kmpc_taskgroup: {
1983 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1984 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001985 auto *FnTy =
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001986 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1987 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1988 break;
1989 }
1990 case OMPRTL__kmpc_end_taskgroup: {
1991 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1992 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001993 auto *FnTy =
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001994 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1995 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1996 break;
1997 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001998 case OMPRTL__kmpc_push_proc_bind: {
1999 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
2000 // int proc_bind)
2001 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002002 auto *FnTy =
Alexey Bataev7f210c62015-06-18 13:40:03 +00002003 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2004 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
2005 break;
2006 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002007 case OMPRTL__kmpc_omp_task_with_deps: {
2008 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
2009 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
2010 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
2011 llvm::Type *TypeParams[] = {
2012 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
2013 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002014 auto *FnTy =
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002015 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
2016 RTLFn =
2017 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
2018 break;
2019 }
2020 case OMPRTL__kmpc_omp_wait_deps: {
2021 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
2022 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
2023 // kmp_depend_info_t *noalias_dep_list);
2024 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2025 CGM.Int32Ty, CGM.VoidPtrTy,
2026 CGM.Int32Ty, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002027 auto *FnTy =
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002028 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2029 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
2030 break;
2031 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00002032 case OMPRTL__kmpc_cancellationpoint: {
2033 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
2034 // global_tid, kmp_int32 cncl_kind)
2035 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002036 auto *FnTy =
Alexey Bataev0f34da12015-07-02 04:17:07 +00002037 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2038 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
2039 break;
2040 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002041 case OMPRTL__kmpc_cancel: {
2042 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
2043 // kmp_int32 cncl_kind)
2044 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002045 auto *FnTy =
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002046 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2047 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
2048 break;
2049 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002050 case OMPRTL__kmpc_push_num_teams: {
2051 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
2052 // kmp_int32 num_teams, kmp_int32 num_threads)
2053 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
2054 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002055 auto *FnTy =
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002056 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2057 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
2058 break;
2059 }
2060 case OMPRTL__kmpc_fork_teams: {
2061 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
2062 // microtask, ...);
2063 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2064 getKmpc_MicroPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002065 auto *FnTy =
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002066 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
2067 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
2068 break;
2069 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002070 case OMPRTL__kmpc_taskloop: {
2071 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
2072 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
2073 // sched, kmp_uint64 grainsize, void *task_dup);
2074 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2075 CGM.IntTy,
2076 CGM.VoidPtrTy,
2077 CGM.IntTy,
2078 CGM.Int64Ty->getPointerTo(),
2079 CGM.Int64Ty->getPointerTo(),
2080 CGM.Int64Ty,
2081 CGM.IntTy,
2082 CGM.IntTy,
2083 CGM.Int64Ty,
2084 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002085 auto *FnTy =
Alexey Bataev7292c292016-04-25 12:22:29 +00002086 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2087 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
2088 break;
2089 }
Alexey Bataev8b427062016-05-25 12:36:08 +00002090 case OMPRTL__kmpc_doacross_init: {
2091 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
2092 // num_dims, struct kmp_dim *dims);
2093 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2094 CGM.Int32Ty,
2095 CGM.Int32Ty,
2096 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002097 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002098 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2099 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
2100 break;
2101 }
2102 case OMPRTL__kmpc_doacross_fini: {
2103 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
2104 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002105 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002106 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2107 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
2108 break;
2109 }
2110 case OMPRTL__kmpc_doacross_post: {
2111 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
2112 // *vec);
2113 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2114 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002115 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002116 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2117 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
2118 break;
2119 }
2120 case OMPRTL__kmpc_doacross_wait: {
2121 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
2122 // *vec);
2123 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2124 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002125 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002126 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2127 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
2128 break;
2129 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002130 case OMPRTL__kmpc_task_reduction_init: {
2131 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
2132 // *data);
2133 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002134 auto *FnTy =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002135 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2136 RTLFn =
2137 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
2138 break;
2139 }
2140 case OMPRTL__kmpc_task_reduction_get_th_data: {
2141 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
2142 // *d);
2143 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002144 auto *FnTy =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002145 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2146 RTLFn = CGM.CreateRuntimeFunction(
2147 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2148 break;
2149 }
Samuel Antaobed3c462015-10-02 16:14:20 +00002150 case OMPRTL__tgt_target: {
George Rokos63bc9d62017-11-21 18:25:12 +00002151 // Build int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
2152 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Samuel Antaobed3c462015-10-02 16:14:20 +00002153 // *arg_types);
George Rokos63bc9d62017-11-21 18:25:12 +00002154 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaobed3c462015-10-02 16:14:20 +00002155 CGM.VoidPtrTy,
2156 CGM.Int32Ty,
2157 CGM.VoidPtrPtrTy,
2158 CGM.VoidPtrPtrTy,
2159 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002160 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002161 auto *FnTy =
Samuel Antaobed3c462015-10-02 16:14:20 +00002162 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2163 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2164 break;
2165 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002166 case OMPRTL__tgt_target_nowait: {
2167 // Build int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
2168 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2169 // int64_t *arg_types);
2170 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2171 CGM.VoidPtrTy,
2172 CGM.Int32Ty,
2173 CGM.VoidPtrPtrTy,
2174 CGM.VoidPtrPtrTy,
2175 CGM.SizeTy->getPointerTo(),
2176 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002177 auto *FnTy =
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002178 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2179 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_nowait");
2180 break;
2181 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00002182 case OMPRTL__tgt_target_teams: {
George Rokos63bc9d62017-11-21 18:25:12 +00002183 // Build int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002184 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
George Rokos63bc9d62017-11-21 18:25:12 +00002185 // int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2186 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002187 CGM.VoidPtrTy,
2188 CGM.Int32Ty,
2189 CGM.VoidPtrPtrTy,
2190 CGM.VoidPtrPtrTy,
2191 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002192 CGM.Int64Ty->getPointerTo(),
Samuel Antaob68e2db2016-03-03 16:20:23 +00002193 CGM.Int32Ty,
2194 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002195 auto *FnTy =
Samuel Antaob68e2db2016-03-03 16:20:23 +00002196 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2197 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2198 break;
2199 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002200 case OMPRTL__tgt_target_teams_nowait: {
2201 // Build int32_t __tgt_target_teams_nowait(int64_t device_id, void
2202 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
2203 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2204 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2205 CGM.VoidPtrTy,
2206 CGM.Int32Ty,
2207 CGM.VoidPtrPtrTy,
2208 CGM.VoidPtrPtrTy,
2209 CGM.SizeTy->getPointerTo(),
2210 CGM.Int64Ty->getPointerTo(),
2211 CGM.Int32Ty,
2212 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002213 auto *FnTy =
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002214 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2215 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams_nowait");
2216 break;
2217 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002218 case OMPRTL__tgt_register_lib: {
2219 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2220 QualType ParamTy =
2221 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2222 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002223 auto *FnTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002224 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2225 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2226 break;
2227 }
2228 case OMPRTL__tgt_unregister_lib: {
2229 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2230 QualType ParamTy =
2231 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2232 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002233 auto *FnTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002234 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2235 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2236 break;
2237 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002238 case OMPRTL__tgt_target_data_begin: {
George Rokos63bc9d62017-11-21 18:25:12 +00002239 // Build void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
2240 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2241 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002242 CGM.Int32Ty,
2243 CGM.VoidPtrPtrTy,
2244 CGM.VoidPtrPtrTy,
2245 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002246 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002247 auto *FnTy =
Samuel Antaodf158d52016-04-27 22:58:19 +00002248 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2249 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2250 break;
2251 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002252 case OMPRTL__tgt_target_data_begin_nowait: {
2253 // Build void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
2254 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2255 // *arg_types);
2256 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2257 CGM.Int32Ty,
2258 CGM.VoidPtrPtrTy,
2259 CGM.VoidPtrPtrTy,
2260 CGM.SizeTy->getPointerTo(),
2261 CGM.Int64Ty->getPointerTo()};
2262 auto *FnTy =
2263 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2264 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin_nowait");
2265 break;
2266 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002267 case OMPRTL__tgt_target_data_end: {
George Rokos63bc9d62017-11-21 18:25:12 +00002268 // Build void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
2269 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2270 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002271 CGM.Int32Ty,
2272 CGM.VoidPtrPtrTy,
2273 CGM.VoidPtrPtrTy,
2274 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002275 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002276 auto *FnTy =
Samuel Antaodf158d52016-04-27 22:58:19 +00002277 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2278 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2279 break;
2280 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002281 case OMPRTL__tgt_target_data_end_nowait: {
2282 // Build void __tgt_target_data_end_nowait(int64_t device_id, int32_t
2283 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2284 // *arg_types);
2285 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2286 CGM.Int32Ty,
2287 CGM.VoidPtrPtrTy,
2288 CGM.VoidPtrPtrTy,
2289 CGM.SizeTy->getPointerTo(),
2290 CGM.Int64Ty->getPointerTo()};
2291 auto *FnTy =
2292 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2293 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end_nowait");
2294 break;
2295 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002296 case OMPRTL__tgt_target_data_update: {
George Rokos63bc9d62017-11-21 18:25:12 +00002297 // Build void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
2298 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2299 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antao8d2d7302016-05-26 18:30:22 +00002300 CGM.Int32Ty,
2301 CGM.VoidPtrPtrTy,
2302 CGM.VoidPtrPtrTy,
2303 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002304 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002305 auto *FnTy =
Samuel Antao8d2d7302016-05-26 18:30:22 +00002306 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2307 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2308 break;
2309 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002310 case OMPRTL__tgt_target_data_update_nowait: {
2311 // Build void __tgt_target_data_update_nowait(int64_t device_id, int32_t
2312 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2313 // *arg_types);
2314 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2315 CGM.Int32Ty,
2316 CGM.VoidPtrPtrTy,
2317 CGM.VoidPtrPtrTy,
2318 CGM.SizeTy->getPointerTo(),
2319 CGM.Int64Ty->getPointerTo()};
2320 auto *FnTy =
2321 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2322 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update_nowait");
2323 break;
2324 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002325 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002326 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002327 return RTLFn;
2328}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002329
Alexander Musman21212e42015-03-13 10:38:23 +00002330llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2331 bool IVSigned) {
2332 assert((IVSize == 32 || IVSize == 64) &&
2333 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002334 StringRef Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2335 : "__kmpc_for_static_init_4u")
2336 : (IVSigned ? "__kmpc_for_static_init_8"
2337 : "__kmpc_for_static_init_8u");
2338 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2339 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
Alexander Musman21212e42015-03-13 10:38:23 +00002340 llvm::Type *TypeParams[] = {
2341 getIdentTyPointerTy(), // loc
2342 CGM.Int32Ty, // tid
2343 CGM.Int32Ty, // schedtype
2344 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2345 PtrTy, // p_lower
2346 PtrTy, // p_upper
2347 PtrTy, // p_stride
2348 ITy, // incr
2349 ITy // chunk
2350 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002351 auto *FnTy =
Alexander Musman21212e42015-03-13 10:38:23 +00002352 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2353 return CGM.CreateRuntimeFunction(FnTy, Name);
2354}
2355
Alexander Musman92bdaab2015-03-12 13:37:50 +00002356llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2357 bool IVSigned) {
2358 assert((IVSize == 32 || IVSize == 64) &&
2359 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002360 StringRef Name =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002361 IVSize == 32
2362 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2363 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002364 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
Alexander Musman92bdaab2015-03-12 13:37:50 +00002365 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2366 CGM.Int32Ty, // tid
2367 CGM.Int32Ty, // schedtype
2368 ITy, // lower
2369 ITy, // upper
2370 ITy, // stride
2371 ITy // chunk
2372 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002373 auto *FnTy =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002374 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2375 return CGM.CreateRuntimeFunction(FnTy, Name);
2376}
2377
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002378llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2379 bool IVSigned) {
2380 assert((IVSize == 32 || IVSize == 64) &&
2381 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002382 StringRef Name =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002383 IVSize == 32
2384 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2385 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2386 llvm::Type *TypeParams[] = {
2387 getIdentTyPointerTy(), // loc
2388 CGM.Int32Ty, // tid
2389 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002390 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002391 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2392 return CGM.CreateRuntimeFunction(FnTy, Name);
2393}
2394
Alexander Musman92bdaab2015-03-12 13:37:50 +00002395llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2396 bool IVSigned) {
2397 assert((IVSize == 32 || IVSize == 64) &&
2398 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002399 StringRef Name =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002400 IVSize == 32
2401 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2402 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002403 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2404 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002405 llvm::Type *TypeParams[] = {
2406 getIdentTyPointerTy(), // loc
2407 CGM.Int32Ty, // tid
2408 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2409 PtrTy, // p_lower
2410 PtrTy, // p_upper
2411 PtrTy // p_stride
2412 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002413 auto *FnTy =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002414 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2415 return CGM.CreateRuntimeFunction(FnTy, Name);
2416}
2417
Alexey Bataev03f270c2018-03-30 18:31:07 +00002418Address CGOpenMPRuntime::getAddrOfDeclareTargetLink(const VarDecl *VD) {
2419 if (CGM.getLangOpts().OpenMPSimd)
2420 return Address::invalid();
Alexey Bataev92327c52018-03-26 16:40:55 +00002421 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2422 isDeclareTargetDeclaration(VD);
2423 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2424 SmallString<64> PtrName;
2425 {
2426 llvm::raw_svector_ostream OS(PtrName);
2427 OS << CGM.getMangledName(GlobalDecl(VD)) << "_decl_tgt_link_ptr";
2428 }
2429 llvm::Value *Ptr = CGM.getModule().getNamedValue(PtrName);
2430 if (!Ptr) {
2431 QualType PtrTy = CGM.getContext().getPointerType(VD->getType());
2432 Ptr = getOrCreateInternalVariable(CGM.getTypes().ConvertTypeForMem(PtrTy),
2433 PtrName);
Alexey Bataev03f270c2018-03-30 18:31:07 +00002434 if (!CGM.getLangOpts().OpenMPIsDevice) {
2435 auto *GV = cast<llvm::GlobalVariable>(Ptr);
2436 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2437 GV->setInitializer(CGM.GetAddrOfGlobal(VD));
2438 }
2439 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ptr));
2440 registerTargetGlobalVariable(VD, cast<llvm::Constant>(Ptr));
Alexey Bataev92327c52018-03-26 16:40:55 +00002441 }
2442 return Address(Ptr, CGM.getContext().getDeclAlign(VD));
2443 }
2444 return Address::invalid();
2445}
2446
Alexey Bataev97720002014-11-11 04:05:39 +00002447llvm::Constant *
2448CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002449 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2450 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002451 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev18fa2322018-05-02 14:20:50 +00002452 std::string Suffix = getName({"cache", ""});
2453 return getOrCreateInternalVariable(
2454 CGM.Int8PtrPtrTy, Twine(CGM.getMangledName(VD)).concat(Suffix));
Alexey Bataev97720002014-11-11 04:05:39 +00002455}
2456
John McCall7f416cc2015-09-08 08:05:57 +00002457Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2458 const VarDecl *VD,
2459 Address VDAddr,
2460 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002461 if (CGM.getLangOpts().OpenMPUseTLS &&
2462 CGM.getContext().getTargetInfo().isTLSSupported())
2463 return VDAddr;
2464
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002465 llvm::Type *VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002466 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002467 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2468 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002469 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2470 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002471 return Address(CGF.EmitRuntimeCall(
2472 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2473 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002474}
2475
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002476void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002477 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002478 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2479 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2480 // library.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002481 llvm::Value *OMPLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002482 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002483 OMPLoc);
2484 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2485 // to register constructor/destructor for variable.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002486 llvm::Value *Args[] = {
2487 OMPLoc, CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.VoidPtrTy),
2488 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002489 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002490 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002491}
2492
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002493llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002494 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002495 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002496 if (CGM.getLangOpts().OpenMPUseTLS &&
2497 CGM.getContext().getTargetInfo().isTLSSupported())
2498 return nullptr;
2499
Alexey Bataev97720002014-11-11 04:05:39 +00002500 VD = VD->getDefinition(CGM.getContext());
2501 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
2502 ThreadPrivateWithDefinition.insert(VD);
2503 QualType ASTTy = VD->getType();
2504
2505 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002506 const Expr *Init = VD->getAnyInitializer();
Alexey Bataev97720002014-11-11 04:05:39 +00002507 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2508 // Generate function that re-emits the declaration's initializer into the
2509 // threadprivate copy of the variable VD
2510 CodeGenFunction CtorCGF(CGM);
2511 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002512 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2513 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002514 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002515 Args.push_back(&Dst);
2516
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002517 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
John McCallc56a8b32016-03-11 04:30:31 +00002518 CGM.getContext().VoidPtrTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002519 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002520 std::string Name = getName({"__kmpc_global_ctor_", ""});
2521 llvm::Function *Fn =
2522 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002523 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002524 Args, Loc, Loc);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002525 llvm::Value *ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002526 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002527 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002528 Address Arg = Address(ArgVal, VDAddr.getAlignment());
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002529 Arg = CtorCGF.Builder.CreateElementBitCast(
2530 Arg, CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002531 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2532 /*IsInitializer=*/true);
2533 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002534 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002535 CGM.getContext().VoidPtrTy, Dst.getLocation());
2536 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2537 CtorCGF.FinishFunction();
2538 Ctor = Fn;
2539 }
2540 if (VD->getType().isDestructedType() != QualType::DK_none) {
2541 // Generate function that emits destructor call for the threadprivate copy
2542 // of the variable VD
2543 CodeGenFunction DtorCGF(CGM);
2544 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002545 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2546 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002547 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002548 Args.push_back(&Dst);
2549
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002550 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
John McCallc56a8b32016-03-11 04:30:31 +00002551 CGM.getContext().VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002552 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002553 std::string Name = getName({"__kmpc_global_dtor_", ""});
2554 llvm::Function *Fn =
2555 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002556 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002557 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002558 Loc, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002559 // Create a scope with an artificial location for the body of this function.
2560 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002561 llvm::Value *ArgVal = DtorCGF.EmitLoadOfScalar(
Alexey Bataev97720002014-11-11 04:05:39 +00002562 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002563 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2564 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002565 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2566 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2567 DtorCGF.FinishFunction();
2568 Dtor = Fn;
2569 }
2570 // Do not emit init function if it is not required.
2571 if (!Ctor && !Dtor)
2572 return nullptr;
2573
2574 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002575 auto *CopyCtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2576 /*isVarArg=*/false)
2577 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002578 // Copying constructor for the threadprivate variable.
2579 // Must be NULL - reserved by runtime, but currently it requires that this
2580 // parameter is always NULL. Otherwise it fires assertion.
2581 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2582 if (Ctor == nullptr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002583 auto *CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2584 /*isVarArg=*/false)
2585 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002586 Ctor = llvm::Constant::getNullValue(CtorTy);
2587 }
2588 if (Dtor == nullptr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002589 auto *DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2590 /*isVarArg=*/false)
2591 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002592 Dtor = llvm::Constant::getNullValue(DtorTy);
2593 }
2594 if (!CGF) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002595 auto *InitFunctionTy =
Alexey Bataev97720002014-11-11 04:05:39 +00002596 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002597 std::string Name = getName({"__omp_threadprivate_init_", ""});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002598 llvm::Function *InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Alexey Bataev18fa2322018-05-02 14:20:50 +00002599 InitFunctionTy, Name, CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002600 CodeGenFunction InitCGF(CGM);
2601 FunctionArgList ArgList;
2602 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2603 CGM.getTypes().arrangeNullaryFunction(), ArgList,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002604 Loc, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002605 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002606 InitCGF.FinishFunction();
2607 return InitFunction;
2608 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002609 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002610 }
2611 return nullptr;
2612}
2613
Alexey Bataev34f8a702018-03-28 14:28:54 +00002614/// \brief Obtain information that uniquely identifies a target entry. This
2615/// consists of the file and device IDs as well as line number associated with
2616/// the relevant entry source location.
2617static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
2618 unsigned &DeviceID, unsigned &FileID,
2619 unsigned &LineNum) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002620 SourceManager &SM = C.getSourceManager();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002621
2622 // The loc should be always valid and have a file ID (the user cannot use
2623 // #pragma directives in macros)
2624
2625 assert(Loc.isValid() && "Source location is expected to be always valid.");
Alexey Bataev34f8a702018-03-28 14:28:54 +00002626
2627 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
2628 assert(PLoc.isValid() && "Source location is expected to be always valid.");
2629
2630 llvm::sys::fs::UniqueID ID;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00002631 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
2632 SM.getDiagnostics().Report(diag::err_cannot_open_file)
2633 << PLoc.getFilename() << EC.message();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002634
2635 DeviceID = ID.getDevice();
2636 FileID = ID.getFile();
2637 LineNum = PLoc.getLine();
2638}
2639
2640bool CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD,
2641 llvm::GlobalVariable *Addr,
2642 bool PerformInit) {
2643 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2644 isDeclareTargetDeclaration(VD);
2645 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link)
2646 return false;
2647 VD = VD->getDefinition(CGM.getContext());
2648 if (VD && !DeclareTargetWithDefinition.insert(VD).second)
2649 return CGM.getLangOpts().OpenMPIsDevice;
2650
2651 QualType ASTTy = VD->getType();
2652
2653 SourceLocation Loc = VD->getCanonicalDecl()->getLocStart();
2654 // Produce the unique prefix to identify the new target regions. We use
2655 // the source location of the variable declaration which we know to not
2656 // conflict with any target region.
2657 unsigned DeviceID;
2658 unsigned FileID;
2659 unsigned Line;
2660 getTargetEntryUniqueInfo(CGM.getContext(), Loc, DeviceID, FileID, Line);
2661 SmallString<128> Buffer, Out;
2662 {
2663 llvm::raw_svector_ostream OS(Buffer);
2664 OS << "__omp_offloading_" << llvm::format("_%x", DeviceID)
2665 << llvm::format("_%x_", FileID) << VD->getName() << "_l" << Line;
2666 }
2667
2668 const Expr *Init = VD->getAnyInitializer();
2669 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2670 llvm::Constant *Ctor;
2671 llvm::Constant *ID;
2672 if (CGM.getLangOpts().OpenMPIsDevice) {
2673 // Generate function that re-emits the declaration's initializer into
2674 // the threadprivate copy of the variable VD
2675 CodeGenFunction CtorCGF(CGM);
2676
2677 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2678 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2679 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2680 FTy, Twine(Buffer, "_ctor"), FI, Loc);
2681 auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF);
2682 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2683 FunctionArgList(), Loc, Loc);
2684 auto AL = ApplyDebugLocation::CreateArtificial(CtorCGF);
2685 CtorCGF.EmitAnyExprToMem(Init,
2686 Address(Addr, CGM.getContext().getDeclAlign(VD)),
2687 Init->getType().getQualifiers(),
2688 /*IsInitializer=*/true);
2689 CtorCGF.FinishFunction();
2690 Ctor = Fn;
2691 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
2692 } else {
2693 Ctor = new llvm::GlobalVariable(
2694 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2695 llvm::GlobalValue::PrivateLinkage,
2696 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_ctor"));
2697 ID = Ctor;
2698 }
2699
2700 // Register the information for the entry associated with the constructor.
2701 Out.clear();
2702 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2703 DeviceID, FileID, Twine(Buffer, "_ctor").toStringRef(Out), Line, Ctor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002704 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryCtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002705 }
2706 if (VD->getType().isDestructedType() != QualType::DK_none) {
2707 llvm::Constant *Dtor;
2708 llvm::Constant *ID;
2709 if (CGM.getLangOpts().OpenMPIsDevice) {
2710 // Generate function that emits destructor call for the threadprivate
2711 // copy of the variable VD
2712 CodeGenFunction DtorCGF(CGM);
2713
2714 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2715 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2716 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2717 FTy, Twine(Buffer, "_dtor"), FI, Loc);
2718 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
2719 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2720 FunctionArgList(), Loc, Loc);
2721 // Create a scope with an artificial location for the body of this
2722 // function.
2723 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
2724 DtorCGF.emitDestroy(Address(Addr, CGM.getContext().getDeclAlign(VD)),
2725 ASTTy, DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2726 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2727 DtorCGF.FinishFunction();
2728 Dtor = Fn;
2729 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
2730 } else {
2731 Dtor = new llvm::GlobalVariable(
2732 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2733 llvm::GlobalValue::PrivateLinkage,
2734 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_dtor"));
2735 ID = Dtor;
2736 }
2737 // Register the information for the entry associated with the destructor.
2738 Out.clear();
2739 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2740 DeviceID, FileID, Twine(Buffer, "_dtor").toStringRef(Out), Line, Dtor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002741 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryDtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002742 }
2743 return CGM.getLangOpts().OpenMPIsDevice;
2744}
2745
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002746Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2747 QualType VarType,
2748 StringRef Name) {
Alexey Bataev18fa2322018-05-02 14:20:50 +00002749 std::string Suffix = getName({"artificial", ""});
2750 std::string CacheSuffix = getName({"cache", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002751 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002752 llvm::Value *GAddr =
2753 getOrCreateInternalVariable(VarLVType, Twine(Name).concat(Suffix));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002754 llvm::Value *Args[] = {
2755 emitUpdateLocation(CGF, SourceLocation()),
2756 getThreadID(CGF, SourceLocation()),
2757 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2758 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2759 /*IsSigned=*/false),
Alexey Bataev18fa2322018-05-02 14:20:50 +00002760 getOrCreateInternalVariable(
2761 CGM.VoidPtrPtrTy, Twine(Name).concat(Suffix).concat(CacheSuffix))};
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002762 return Address(
2763 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2764 CGF.EmitRuntimeCall(
2765 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2766 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2767 CGM.getPointerAlign());
2768}
2769
Alexey Bataev1d677132015-04-22 13:57:31 +00002770/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
2771/// function. Here is the logic:
2772/// if (Cond) {
2773/// ThenGen();
2774/// } else {
2775/// ElseGen();
2776/// }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002777void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2778 const RegionCodeGenTy &ThenGen,
2779 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002780 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2781
2782 // If the condition constant folds and can be elided, try to avoid emitting
2783 // the condition and the dead arm of the if/else.
2784 bool CondConstant;
2785 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002786 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002787 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002788 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002789 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002790 return;
2791 }
2792
2793 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2794 // emit the conditional branch.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002795 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("omp_if.then");
2796 llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else");
2797 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("omp_if.end");
Alexey Bataev1d677132015-04-22 13:57:31 +00002798 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2799
2800 // Emit the 'then' code.
2801 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002802 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002803 CGF.EmitBranch(ContBlock);
2804 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002805 // There is no need to emit line number for unconditional branch.
2806 (void)ApplyDebugLocation::CreateEmpty(CGF);
2807 CGF.EmitBlock(ElseBlock);
2808 ElseGen(CGF);
2809 // There is no need to emit line number for unconditional branch.
2810 (void)ApplyDebugLocation::CreateEmpty(CGF);
2811 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002812 // Emit the continuation block for code after the if.
2813 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002814}
2815
Alexey Bataev1d677132015-04-22 13:57:31 +00002816void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2817 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002818 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002819 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002820 if (!CGF.HaveInsertPoint())
2821 return;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002822 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002823 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2824 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002825 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002826 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002827 llvm::Value *Args[] = {
2828 RTLoc,
2829 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002830 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002831 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2832 RealArgs.append(std::begin(Args), std::end(Args));
2833 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2834
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002835 llvm::Value *RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002836 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2837 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002838 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2839 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002840 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
2841 llvm::Value *ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00002842 // Build calls:
2843 // __kmpc_serialized_parallel(&Loc, GTid);
2844 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002845 CGF.EmitRuntimeCall(
2846 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002847
Alexey Bataev1d677132015-04-22 13:57:31 +00002848 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002849 Address ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002850 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2851 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00002852 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00002853 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2854 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2855 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2856 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002857 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002858
Alexey Bataev1d677132015-04-22 13:57:31 +00002859 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002860 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00002861 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002862 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2863 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002864 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002865 if (IfCond) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002866 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002867 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002868 RegionCodeGenTy ThenRCG(ThenGen);
2869 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002870 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002871}
2872
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002873// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002874// thread-ID variable (it is passed in a first argument of the outlined function
2875// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2876// regular serial code region, get thread ID by calling kmp_int32
2877// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2878// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002879Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2880 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002881 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002882 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002883 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002884 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002885
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002886 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2887 QualType Int32Ty =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002888 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002889 Address ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
Alexey Bataevd74d0602014-10-13 06:02:40 +00002890 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002891 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002892
2893 return ThreadIDTemp;
2894}
2895
Alexey Bataev97720002014-11-11 04:05:39 +00002896llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002897CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002898 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002899 SmallString<256> Buffer;
2900 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002901 Out << Name;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002902 StringRef RuntimeName = Out.str();
Alexey Bataev43a919f2018-04-13 17:48:43 +00002903 auto &Elem = *InternalVars.try_emplace(RuntimeName, nullptr).first;
David Blaikie13156b62014-11-19 03:06:06 +00002904 if (Elem.second) {
2905 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002906 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002907 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002908 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002909
David Blaikie13156b62014-11-19 03:06:06 +00002910 return Elem.second = new llvm::GlobalVariable(
2911 CGM.getModule(), Ty, /*IsConstant*/ false,
2912 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2913 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002914}
2915
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002916llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev18fa2322018-05-02 14:20:50 +00002917 std::string Prefix = Twine("gomp_critical_user_", CriticalName).str();
2918 std::string Name = getName({Prefix, "var"});
2919 return getOrCreateInternalVariable(KmpCriticalNameTy, Name);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002920}
2921
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002922namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002923/// Common pre(post)-action for different OpenMP constructs.
2924class CommonActionTy final : public PrePostActionTy {
2925 llvm::Value *EnterCallee;
2926 ArrayRef<llvm::Value *> EnterArgs;
2927 llvm::Value *ExitCallee;
2928 ArrayRef<llvm::Value *> ExitArgs;
2929 bool Conditional;
2930 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002931
2932public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002933 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2934 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2935 bool Conditional = false)
2936 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2937 ExitArgs(ExitArgs), Conditional(Conditional) {}
2938 void Enter(CodeGenFunction &CGF) override {
2939 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2940 if (Conditional) {
2941 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2942 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2943 ContBlock = CGF.createBasicBlock("omp_if.end");
2944 // Generate the branch (If-stmt)
2945 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2946 CGF.EmitBlock(ThenBlock);
2947 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002948 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002949 void Done(CodeGenFunction &CGF) {
2950 // Emit the rest of blocks/branches
2951 CGF.EmitBranch(ContBlock);
2952 CGF.EmitBlock(ContBlock, true);
2953 }
2954 void Exit(CodeGenFunction &CGF) override {
2955 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002956 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002957};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002958} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002959
2960void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2961 StringRef CriticalName,
2962 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002963 SourceLocation Loc, const Expr *Hint) {
2964 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002965 // CriticalOpGen();
2966 // __kmpc_end_critical(ident_t *, gtid, Lock);
2967 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002968 if (!CGF.HaveInsertPoint())
2969 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002970 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2971 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002972 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2973 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002974 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002975 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2976 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2977 }
2978 CommonActionTy Action(
2979 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2980 : OMPRTL__kmpc_critical),
2981 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2982 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002983 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002984}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002985
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002986void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002987 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002988 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002989 if (!CGF.HaveInsertPoint())
2990 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002991 // if(__kmpc_master(ident_t *, gtid)) {
2992 // MasterOpGen();
2993 // __kmpc_end_master(ident_t *, gtid);
2994 // }
2995 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002996 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002997 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2998 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2999 /*Conditional=*/true);
3000 MasterOpGen.setAction(Action);
3001 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
3002 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00003003}
3004
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003005void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
3006 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003007 if (!CGF.HaveInsertPoint())
3008 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00003009 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
3010 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003011 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00003012 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003013 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003014 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
3015 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00003016}
3017
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003018void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
3019 const RegionCodeGenTy &TaskgroupOpGen,
3020 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003021 if (!CGF.HaveInsertPoint())
3022 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003023 // __kmpc_taskgroup(ident_t *, gtid);
3024 // TaskgroupOpGen();
3025 // __kmpc_end_taskgroup(ident_t *, gtid);
3026 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003027 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3028 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
3029 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
3030 Args);
3031 TaskgroupOpGen.setAction(Action);
3032 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003033}
3034
John McCall7f416cc2015-09-08 08:05:57 +00003035/// Given an array of pointers to variables, project the address of a
3036/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003037static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
3038 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00003039 // Pull out the pointer to the variable.
3040 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003041 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00003042 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
3043
3044 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003045 Addr = CGF.Builder.CreateElementBitCast(
3046 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00003047 return Addr;
3048}
3049
Alexey Bataeva63048e2015-03-23 06:18:07 +00003050static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00003051 CodeGenModule &CGM, llvm::Type *ArgsType,
3052 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003053 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps,
3054 SourceLocation Loc) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003055 ASTContext &C = CGM.getContext();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003056 // void copy_func(void *LHSArg, void *RHSArg);
3057 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003058 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3059 ImplicitParamDecl::Other);
3060 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3061 ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003062 Args.push_back(&LHSArg);
3063 Args.push_back(&RHSArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003064 const auto &CGFI =
3065 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003066 std::string Name =
3067 CGM.getOpenMPRuntime().getName({"omp", "copyprivate", "copy_func"});
3068 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
3069 llvm::GlobalValue::InternalLinkage, Name,
3070 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003071 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003072 Fn->setDoesNotRecurse();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003073 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003074 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00003075 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003076 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00003077 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3078 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
3079 ArgsType), CGF.getPointerAlign());
3080 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3081 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
3082 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00003083 // *(Type0*)Dst[0] = *(Type0*)Src[0];
3084 // *(Type1*)Dst[1] = *(Type1*)Src[1];
3085 // ...
3086 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00003087 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003088 const auto *DestVar =
3089 cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003090 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
3091
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003092 const auto *SrcVar =
3093 cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003094 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
3095
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003096 const auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003097 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00003098 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003099 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00003100 CGF.FinishFunction();
3101 return Fn;
3102}
3103
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003104void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003105 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00003106 SourceLocation Loc,
3107 ArrayRef<const Expr *> CopyprivateVars,
3108 ArrayRef<const Expr *> SrcExprs,
3109 ArrayRef<const Expr *> DstExprs,
3110 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003111 if (!CGF.HaveInsertPoint())
3112 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00003113 assert(CopyprivateVars.size() == SrcExprs.size() &&
3114 CopyprivateVars.size() == DstExprs.size() &&
3115 CopyprivateVars.size() == AssignmentOps.size());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003116 ASTContext &C = CGM.getContext();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003117 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003118 // if(__kmpc_single(ident_t *, gtid)) {
3119 // SingleOpGen();
3120 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003121 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003122 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00003123 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3124 // <copy_func>, did_it);
3125
John McCall7f416cc2015-09-08 08:05:57 +00003126 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003127 if (!CopyprivateVars.empty()) {
3128 // int32 did_it = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003129 QualType KmpInt32Ty =
3130 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003131 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00003132 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003133 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003134 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00003135 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003136 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
3137 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
3138 /*Conditional=*/true);
3139 SingleOpGen.setAction(Action);
3140 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
3141 if (DidIt.isValid()) {
3142 // did_it = 1;
3143 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
3144 }
3145 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003146 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3147 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00003148 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00003149 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003150 QualType CopyprivateArrayTy =
Alexey Bataeva63048e2015-03-23 06:18:07 +00003151 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3152 /*IndexTypeQuals=*/0);
3153 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00003154 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00003155 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
3156 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00003157 Address Elem = CGF.Builder.CreateConstArrayGEP(
3158 CopyprivateList, I, CGF.getPointerSize());
3159 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00003160 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003161 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
3162 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003163 }
3164 // Build function that copies private values from single region to all other
3165 // threads in the corresponding parallel region.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003166 llvm::Value *CpyFn = emitCopyprivateCopyFunction(
Alexey Bataeva63048e2015-03-23 06:18:07 +00003167 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003168 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps, Loc);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003169 llvm::Value *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00003170 Address CL =
3171 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
3172 CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003173 llvm::Value *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003174 llvm::Value *Args[] = {
3175 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
3176 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00003177 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00003178 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00003179 CpyFn, // void (*) (void *, void *) <copy_func>
3180 DidItVal // i32 did_it
3181 };
3182 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
3183 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003184}
3185
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003186void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
3187 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00003188 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003189 if (!CGF.HaveInsertPoint())
3190 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003191 // __kmpc_ordered(ident_t *, gtid);
3192 // OrderedOpGen();
3193 // __kmpc_end_ordered(ident_t *, gtid);
3194 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00003195 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003196 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003197 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
3198 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
3199 Args);
3200 OrderedOpGen.setAction(Action);
3201 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
3202 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003203 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003204 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003205}
3206
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003207void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00003208 OpenMPDirectiveKind Kind, bool EmitChecks,
3209 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003210 if (!CGF.HaveInsertPoint())
3211 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00003212 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003213 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003214 unsigned Flags;
3215 if (Kind == OMPD_for)
3216 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
3217 else if (Kind == OMPD_sections)
3218 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
3219 else if (Kind == OMPD_single)
3220 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
3221 else if (Kind == OMPD_barrier)
3222 Flags = OMP_IDENT_BARRIER_EXPL;
3223 else
3224 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003225 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
3226 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003227 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
3228 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003229 if (auto *OMPRegionInfo =
3230 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00003231 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003232 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003233 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00003234 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003235 // if (__kmpc_cancel_barrier()) {
3236 // exit from construct;
3237 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003238 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
3239 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
3240 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003241 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
3242 CGF.EmitBlock(ExitBB);
3243 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003244 CodeGenFunction::JumpDest CancelDestination =
Alexey Bataev25e5b442015-09-15 12:52:43 +00003245 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003246 CGF.EmitBranchThroughCleanup(CancelDestination);
3247 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
3248 }
3249 return;
3250 }
3251 }
3252 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00003253}
3254
Alexander Musmanc6388682014-12-15 07:07:06 +00003255/// \brief Map the OpenMP loop schedule to the runtime enumeration.
3256static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003257 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003258 switch (ScheduleKind) {
3259 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003260 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
3261 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00003262 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003263 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003264 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003265 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003266 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003267 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
3268 case OMPC_SCHEDULE_auto:
3269 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00003270 case OMPC_SCHEDULE_unknown:
3271 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003272 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00003273 }
3274 llvm_unreachable("Unexpected runtime schedule");
3275}
3276
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003277/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
3278static OpenMPSchedType
3279getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
3280 // only static is allowed for dist_schedule
3281 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
3282}
3283
Alexander Musmanc6388682014-12-15 07:07:06 +00003284bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
3285 bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003286 OpenMPSchedType Schedule =
3287 getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00003288 return Schedule == OMP_sch_static;
3289}
3290
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003291bool CGOpenMPRuntime::isStaticNonchunked(
3292 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003293 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003294 return Schedule == OMP_dist_sch_static;
3295}
3296
3297
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003298bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003299 OpenMPSchedType Schedule =
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003300 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003301 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
3302 return Schedule != OMP_sch_static;
3303}
3304
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003305static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
3306 OpenMPScheduleClauseModifier M1,
3307 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00003308 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003309 switch (M1) {
3310 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003311 Modifier = OMP_sch_modifier_monotonic;
3312 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003313 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003314 Modifier = OMP_sch_modifier_nonmonotonic;
3315 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003316 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003317 if (Schedule == OMP_sch_static_chunked)
3318 Schedule = OMP_sch_static_balanced_chunked;
3319 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003320 case OMPC_SCHEDULE_MODIFIER_last:
3321 case OMPC_SCHEDULE_MODIFIER_unknown:
3322 break;
3323 }
3324 switch (M2) {
3325 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003326 Modifier = OMP_sch_modifier_monotonic;
3327 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003328 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003329 Modifier = OMP_sch_modifier_nonmonotonic;
3330 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003331 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003332 if (Schedule == OMP_sch_static_chunked)
3333 Schedule = OMP_sch_static_balanced_chunked;
3334 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003335 case OMPC_SCHEDULE_MODIFIER_last:
3336 case OMPC_SCHEDULE_MODIFIER_unknown:
3337 break;
3338 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00003339 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003340}
3341
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003342void CGOpenMPRuntime::emitForDispatchInit(
3343 CodeGenFunction &CGF, SourceLocation Loc,
3344 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
3345 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003346 if (!CGF.HaveInsertPoint())
3347 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003348 OpenMPSchedType Schedule = getRuntimeSchedule(
3349 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00003350 assert(Ordered ||
3351 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00003352 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
3353 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00003354 // Call __kmpc_dispatch_init(
3355 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
3356 // kmp_int[32|64] lower, kmp_int[32|64] upper,
3357 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00003358
John McCall7f416cc2015-09-08 08:05:57 +00003359 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003360 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
3361 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00003362 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003363 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3364 CGF.Builder.getInt32(addMonoNonMonoModifier(
3365 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003366 DispatchValues.LB, // Lower
3367 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003368 CGF.Builder.getIntN(IVSize, 1), // Stride
3369 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00003370 };
3371 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
3372}
3373
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003374static void emitForStaticInitCall(
3375 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
3376 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
3377 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003378 const CGOpenMPRuntime::StaticRTInput &Values) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003379 if (!CGF.HaveInsertPoint())
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003380 return;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003381
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003382 assert(!Values.Ordered);
3383 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
3384 Schedule == OMP_sch_static_balanced_chunked ||
3385 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
3386 Schedule == OMP_dist_sch_static ||
3387 Schedule == OMP_dist_sch_static_chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003388
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003389 // Call __kmpc_for_static_init(
3390 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
3391 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
3392 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
3393 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
3394 llvm::Value *Chunk = Values.Chunk;
3395 if (Chunk == nullptr) {
3396 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
3397 Schedule == OMP_dist_sch_static) &&
3398 "expected static non-chunked schedule");
3399 // If the Chunk was not specified in the clause - use default value 1.
3400 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3401 } else {
3402 assert((Schedule == OMP_sch_static_chunked ||
3403 Schedule == OMP_sch_static_balanced_chunked ||
3404 Schedule == OMP_ord_static_chunked ||
3405 Schedule == OMP_dist_sch_static_chunked) &&
3406 "expected static chunked schedule");
3407 }
3408 llvm::Value *Args[] = {
3409 UpdateLocation,
3410 ThreadId,
3411 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3412 M2)), // Schedule type
3413 Values.IL.getPointer(), // &isLastIter
3414 Values.LB.getPointer(), // &LB
3415 Values.UB.getPointer(), // &UB
3416 Values.ST.getPointer(), // &Stride
3417 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3418 Chunk // Chunk
3419 };
3420 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003421}
3422
John McCall7f416cc2015-09-08 08:05:57 +00003423void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3424 SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003425 OpenMPDirectiveKind DKind,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003426 const OpenMPScheduleTy &ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003427 const StaticRTInput &Values) {
3428 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3429 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3430 assert(isOpenMPWorksharingDirective(DKind) &&
3431 "Expected loop-based or sections-based directive.");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003432 llvm::Value *UpdatedLocation = emitUpdateLocation(CGF, Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003433 isOpenMPLoopDirective(DKind)
3434 ? OMP_IDENT_WORK_LOOP
3435 : OMP_IDENT_WORK_SECTIONS);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003436 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3437 llvm::Constant *StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003438 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003439 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003440 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003441}
John McCall7f416cc2015-09-08 08:05:57 +00003442
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003443void CGOpenMPRuntime::emitDistributeStaticInit(
3444 CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003445 OpenMPDistScheduleClauseKind SchedKind,
3446 const CGOpenMPRuntime::StaticRTInput &Values) {
3447 OpenMPSchedType ScheduleNum =
3448 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003449 llvm::Value *UpdatedLocation =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003450 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003451 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3452 llvm::Constant *StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003453 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003454 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3455 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003456 OMPC_SCHEDULE_MODIFIER_unknown, Values);
Alexander Musmanc6388682014-12-15 07:07:06 +00003457}
3458
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003459void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
Alexey Bataevf43f7142017-09-06 16:17:35 +00003460 SourceLocation Loc,
3461 OpenMPDirectiveKind DKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003462 if (!CGF.HaveInsertPoint())
3463 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003464 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataevf43f7142017-09-06 16:17:35 +00003465 llvm::Value *Args[] = {
3466 emitUpdateLocation(CGF, Loc,
3467 isOpenMPDistributeDirective(DKind)
3468 ? OMP_IDENT_WORK_DISTRIBUTE
3469 : isOpenMPLoopDirective(DKind)
3470 ? OMP_IDENT_WORK_LOOP
3471 : OMP_IDENT_WORK_SECTIONS),
3472 getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003473 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3474 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003475}
3476
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003477void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3478 SourceLocation Loc,
3479 unsigned IVSize,
3480 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003481 if (!CGF.HaveInsertPoint())
3482 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003483 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003484 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003485 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3486}
3487
Alexander Musman92bdaab2015-03-12 13:37:50 +00003488llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3489 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003490 bool IVSigned, Address IL,
3491 Address LB, Address UB,
3492 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003493 // Call __kmpc_dispatch_next(
3494 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3495 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3496 // kmp_int[32|64] *p_stride);
3497 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003498 emitUpdateLocation(CGF, Loc),
3499 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003500 IL.getPointer(), // &isLastIter
3501 LB.getPointer(), // &Lower
3502 UB.getPointer(), // &Upper
3503 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003504 };
3505 llvm::Value *Call =
3506 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3507 return CGF.EmitScalarConversion(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003508 Call, CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/1),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003509 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003510}
3511
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003512void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3513 llvm::Value *NumThreads,
3514 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003515 if (!CGF.HaveInsertPoint())
3516 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003517 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3518 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003519 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003520 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003521 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3522 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003523}
3524
Alexey Bataev7f210c62015-06-18 13:40:03 +00003525void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3526 OpenMPProcBindClauseKind ProcBind,
3527 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003528 if (!CGF.HaveInsertPoint())
3529 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003530 // Constants for proc bind value accepted by the runtime.
3531 enum ProcBindTy {
3532 ProcBindFalse = 0,
3533 ProcBindTrue,
3534 ProcBindMaster,
3535 ProcBindClose,
3536 ProcBindSpread,
3537 ProcBindIntel,
3538 ProcBindDefault
3539 } RuntimeProcBind;
3540 switch (ProcBind) {
3541 case OMPC_PROC_BIND_master:
3542 RuntimeProcBind = ProcBindMaster;
3543 break;
3544 case OMPC_PROC_BIND_close:
3545 RuntimeProcBind = ProcBindClose;
3546 break;
3547 case OMPC_PROC_BIND_spread:
3548 RuntimeProcBind = ProcBindSpread;
3549 break;
3550 case OMPC_PROC_BIND_unknown:
3551 llvm_unreachable("Unsupported proc_bind value.");
3552 }
3553 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3554 llvm::Value *Args[] = {
3555 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3556 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3557 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3558}
3559
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003560void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3561 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003562 if (!CGF.HaveInsertPoint())
3563 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003564 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003565 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3566 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003567}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003568
Alexey Bataev62b63b12015-03-10 07:28:44 +00003569namespace {
3570/// \brief Indexes of fields for type kmp_task_t.
3571enum KmpTaskTFields {
3572 /// \brief List of shared variables.
3573 KmpTaskTShareds,
3574 /// \brief Task routine.
3575 KmpTaskTRoutine,
3576 /// \brief Partition id for the untied tasks.
3577 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003578 /// Function with call of destructors for private variables.
3579 Data1,
3580 /// Task priority.
3581 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003582 /// (Taskloops only) Lower bound.
3583 KmpTaskTLowerBound,
3584 /// (Taskloops only) Upper bound.
3585 KmpTaskTUpperBound,
3586 /// (Taskloops only) Stride.
3587 KmpTaskTStride,
3588 /// (Taskloops only) Is last iteration flag.
3589 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003590 /// (Taskloops only) Reduction data.
3591 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003592};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003593} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003594
Samuel Antaoee8fb302016-01-06 13:42:12 +00003595bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003596 return OffloadEntriesTargetRegion.empty() &&
3597 OffloadEntriesDeviceGlobalVar.empty();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003598}
3599
3600/// \brief Initialize target region entry.
3601void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3602 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3603 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003604 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003605 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3606 "only required for the device "
3607 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003608 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003609 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003610 OMPTargetRegionEntryTargetRegion);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003611 ++OffloadingEntriesNum;
3612}
3613
3614void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3615 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3616 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003617 llvm::Constant *Addr, llvm::Constant *ID,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003618 OMPTargetRegionEntryKind Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003619 // If we are emitting code for a target, the entry is already initialized,
3620 // only has to be registered.
3621 if (CGM.getLangOpts().OpenMPIsDevice) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00003622 if (!hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum)) {
3623 unsigned DiagID = CGM.getDiags().getCustomDiagID(
3624 DiagnosticsEngine::Error,
3625 "Unable to find target region on line '%0' in the device code.");
3626 CGM.getDiags().Report(DiagID) << LineNum;
3627 return;
3628 }
Samuel Antao2de62b02016-02-13 23:35:10 +00003629 auto &Entry =
3630 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003631 assert(Entry.isValid() && "Entry not initialized!");
3632 Entry.setAddress(Addr);
3633 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003634 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003635 } else {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003636 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003637 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00003638 ++OffloadingEntriesNum;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003639 }
3640}
3641
3642bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003643 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3644 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003645 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3646 if (PerDevice == OffloadEntriesTargetRegion.end())
3647 return false;
3648 auto PerFile = PerDevice->second.find(FileID);
3649 if (PerFile == PerDevice->second.end())
3650 return false;
3651 auto PerParentName = PerFile->second.find(ParentName);
3652 if (PerParentName == PerFile->second.end())
3653 return false;
3654 auto PerLine = PerParentName->second.find(LineNum);
3655 if (PerLine == PerParentName->second.end())
3656 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003657 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003658 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003659 return false;
3660 return true;
3661}
3662
3663void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3664 const OffloadTargetRegionEntryInfoActTy &Action) {
3665 // Scan all target region entries and perform the provided action.
Alexey Bataev03f270c2018-03-30 18:31:07 +00003666 for (const auto &D : OffloadEntriesTargetRegion)
3667 for (const auto &F : D.second)
3668 for (const auto &P : F.second)
3669 for (const auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003670 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003671}
3672
Alexey Bataev03f270c2018-03-30 18:31:07 +00003673void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3674 initializeDeviceGlobalVarEntryInfo(StringRef Name,
3675 OMPTargetGlobalVarEntryKind Flags,
3676 unsigned Order) {
3677 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3678 "only required for the device "
3679 "code generation.");
3680 OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags);
3681 ++OffloadingEntriesNum;
3682}
Samuel Antaoee8fb302016-01-06 13:42:12 +00003683
Alexey Bataev03f270c2018-03-30 18:31:07 +00003684void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3685 registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr,
3686 CharUnits VarSize,
3687 OMPTargetGlobalVarEntryKind Flags,
3688 llvm::GlobalValue::LinkageTypes Linkage) {
3689 if (CGM.getLangOpts().OpenMPIsDevice) {
3690 auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
3691 assert(Entry.isValid() && Entry.getFlags() == Flags &&
3692 "Entry not initialized!");
3693 assert((!Entry.getAddress() || Entry.getAddress() == Addr) &&
3694 "Resetting with the new address.");
3695 if (Entry.getAddress() && hasDeviceGlobalVarEntryInfo(VarName))
3696 return;
3697 Entry.setAddress(Addr);
3698 Entry.setVarSize(VarSize);
3699 Entry.setLinkage(Linkage);
3700 } else {
3701 if (hasDeviceGlobalVarEntryInfo(VarName))
3702 return;
3703 OffloadEntriesDeviceGlobalVar.try_emplace(
3704 VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage);
3705 ++OffloadingEntriesNum;
3706 }
3707}
3708
3709void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3710 actOnDeviceGlobalVarEntriesInfo(
3711 const OffloadDeviceGlobalVarEntryInfoActTy &Action) {
3712 // Scan all target region entries and perform the provided action.
3713 for (const auto &E : OffloadEntriesDeviceGlobalVar)
3714 Action(E.getKey(), E.getValue());
Samuel Antaoee8fb302016-01-06 13:42:12 +00003715}
3716
3717llvm::Function *
3718CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003719 // If we don't have entries or if we are emitting code for the device, we
3720 // don't need to do anything.
3721 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3722 return nullptr;
3723
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003724 llvm::Module &M = CGM.getModule();
3725 ASTContext &C = CGM.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003726
3727 // Get list of devices we care about
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003728 const std::vector<llvm::Triple> &Devices = CGM.getLangOpts().OMPTargetTriples;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003729
3730 // We should be creating an offloading descriptor only if there are devices
3731 // specified.
3732 assert(!Devices.empty() && "No OpenMP offloading devices??");
3733
3734 // Create the external variables that will point to the begin and end of the
3735 // host entries section. These will be defined by the linker.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003736 llvm::Type *OffloadEntryTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00003737 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
Alexey Bataev18fa2322018-05-02 14:20:50 +00003738 std::string EntriesBeginName = getName({"omp_offloading", "entries_begin"});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003739 auto *HostEntriesBegin = new llvm::GlobalVariable(
Samuel Antaoee8fb302016-01-06 13:42:12 +00003740 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003741 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003742 EntriesBeginName);
3743 std::string EntriesEndName = getName({"omp_offloading", "entries_end"});
3744 auto *HostEntriesEnd =
3745 new llvm::GlobalVariable(M, OffloadEntryTy, /*isConstant=*/true,
3746 llvm::GlobalValue::ExternalLinkage,
3747 /*Initializer=*/nullptr, EntriesEndName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003748
3749 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003750 auto *DeviceImageTy = cast<llvm::StructType>(
3751 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003752 ConstantInitBuilder DeviceImagesBuilder(CGM);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003753 ConstantArrayBuilder DeviceImagesEntries =
3754 DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003755
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003756 for (const llvm::Triple &Device : Devices) {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003757 StringRef T = Device.getTriple();
Alexey Bataev18fa2322018-05-02 14:20:50 +00003758 std::string BeginName = getName({"omp_offloading", "img_start", ""});
Samuel Antaoee8fb302016-01-06 13:42:12 +00003759 auto *ImgBegin = new llvm::GlobalVariable(
3760 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003761 /*Initializer=*/nullptr, Twine(BeginName).concat(T));
3762 std::string EndName = getName({"omp_offloading", "img_end", ""});
Samuel Antaoee8fb302016-01-06 13:42:12 +00003763 auto *ImgEnd = new llvm::GlobalVariable(
3764 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003765 /*Initializer=*/nullptr, Twine(EndName).concat(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003766
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003767 llvm::Constant *Data[] = {ImgBegin, ImgEnd, HostEntriesBegin,
3768 HostEntriesEnd};
3769 createConstantGlobalStructAndAddToParent(CGM, getTgtDeviceImageQTy(), Data,
3770 DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003771 }
3772
3773 // Create device images global array.
Alexey Bataev18fa2322018-05-02 14:20:50 +00003774 std::string ImagesName = getName({"omp_offloading", "device_images"});
John McCall6c9f1fdb2016-11-19 08:17:24 +00003775 llvm::GlobalVariable *DeviceImages =
Alexey Bataev18fa2322018-05-02 14:20:50 +00003776 DeviceImagesEntries.finishAndCreateGlobal(ImagesName,
3777 CGM.getPointerAlign(),
3778 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003779 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003780
3781 // This is a Zero array to be used in the creation of the constant expressions
3782 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3783 llvm::Constant::getNullValue(CGM.Int32Ty)};
3784
3785 // Create the target region descriptor.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003786 llvm::Constant *Data[] = {
3787 llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
3788 llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3789 DeviceImages, Index),
3790 HostEntriesBegin, HostEntriesEnd};
Alexey Bataev18fa2322018-05-02 14:20:50 +00003791 std::string Descriptor = getName({"omp_offloading", "descriptor"});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003792 llvm::GlobalVariable *Desc = createConstantGlobalStruct(
Alexey Bataev18fa2322018-05-02 14:20:50 +00003793 CGM, getTgtBinaryDescriptorQTy(), Data, Descriptor);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003794
3795 // Emit code to register or unregister the descriptor at execution
3796 // startup or closing, respectively.
3797
Alexey Bataev03f270c2018-03-30 18:31:07 +00003798 llvm::Function *UnRegFn;
3799 {
3800 FunctionArgList Args;
3801 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
3802 Args.push_back(&DummyPtr);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003803
Alexey Bataev03f270c2018-03-30 18:31:07 +00003804 CodeGenFunction CGF(CGM);
3805 // Disable debug info for global (de-)initializer because they are not part
3806 // of some particular construct.
3807 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003808 const auto &FI =
3809 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3810 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003811 std::string UnregName = getName({"omp_offloading", "descriptor_unreg"});
3812 UnRegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, UnregName, FI);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003813 CGF.StartFunction(GlobalDecl(), C.VoidTy, UnRegFn, FI, Args);
3814 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3815 Desc);
3816 CGF.FinishFunction();
3817 }
3818 llvm::Function *RegFn;
3819 {
3820 CodeGenFunction CGF(CGM);
3821 // Disable debug info for global (de-)initializer because they are not part
3822 // of some particular construct.
3823 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003824 const auto &FI = CGM.getTypes().arrangeNullaryFunction();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003825 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003826 std::string Descriptor = getName({"omp_offloading", "descriptor_reg"});
3827 RegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, Descriptor, FI);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003828 CGF.StartFunction(GlobalDecl(), C.VoidTy, RegFn, FI, FunctionArgList());
3829 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib), Desc);
3830 // Create a variable to drive the registration and unregistration of the
3831 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3832 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(),
3833 SourceLocation(), nullptr, C.CharTy,
3834 ImplicitParamDecl::Other);
3835 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3836 CGF.FinishFunction();
3837 }
George Rokos29d0f002017-05-27 03:03:13 +00003838 if (CGM.supportsCOMDAT()) {
3839 // It is sufficient to call registration function only once, so create a
3840 // COMDAT group for registration/unregistration functions and associated
3841 // data. That would reduce startup time and code size. Registration
3842 // function serves as a COMDAT group key.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003843 llvm::Comdat *ComdatKey = M.getOrInsertComdat(RegFn->getName());
George Rokos29d0f002017-05-27 03:03:13 +00003844 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3845 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3846 RegFn->setComdat(ComdatKey);
3847 UnRegFn->setComdat(ComdatKey);
3848 DeviceImages->setComdat(ComdatKey);
3849 Desc->setComdat(ComdatKey);
3850 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003851 return RegFn;
3852}
3853
Alexey Bataev03f270c2018-03-30 18:31:07 +00003854void CGOpenMPRuntime::createOffloadEntry(
3855 llvm::Constant *ID, llvm::Constant *Addr, uint64_t Size, int32_t Flags,
3856 llvm::GlobalValue::LinkageTypes Linkage) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003857 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003858 llvm::Module &M = CGM.getModule();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003859 llvm::LLVMContext &C = M.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003860
3861 // Create constant string with the name.
3862 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3863
Alexey Bataev18fa2322018-05-02 14:20:50 +00003864 std::string StringName = getName({"omp_offloading", "entry_name"});
3865 auto *Str = new llvm::GlobalVariable(
3866 M, StrPtrInit->getType(), /*isConstant=*/true,
3867 llvm::GlobalValue::InternalLinkage, StrPtrInit, StringName);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003868 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003869
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003870 llvm::Constant *Data[] = {llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy),
3871 llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy),
3872 llvm::ConstantInt::get(CGM.SizeTy, Size),
3873 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
3874 llvm::ConstantInt::get(CGM.Int32Ty, 0)};
Alexey Bataev18fa2322018-05-02 14:20:50 +00003875 std::string EntryName = getName({"omp_offloading", "entry", ""});
3876 llvm::GlobalVariable *Entry =
3877 createConstantGlobalStruct(CGM, getTgtOffloadEntryQTy(), Data,
3878 Twine(EntryName).concat(Name), Linkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003879
3880 // The entry has to be created in the section the linker expects it to be.
Alexey Bataev18fa2322018-05-02 14:20:50 +00003881 std::string Section = getName({"omp_offloading", "entries"});
3882 Entry->setSection(Section);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003883}
3884
3885void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3886 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003887 // can easily figure out what to emit. The produced metadata looks like
3888 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003889 //
3890 // !omp_offload.info = !{!1, ...}
3891 //
3892 // Right now we only generate metadata for function that contain target
3893 // regions.
3894
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003895 // If we do not have entries, we don't need to do anything.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003896 if (OffloadEntriesInfoManager.empty())
3897 return;
3898
3899 llvm::Module &M = CGM.getModule();
3900 llvm::LLVMContext &C = M.getContext();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003901 SmallVector<const OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
Samuel Antaoee8fb302016-01-06 13:42:12 +00003902 OrderedEntries(OffloadEntriesInfoManager.size());
3903
Simon Pilgrim2c518802017-03-30 14:13:19 +00003904 // Auxiliary methods to create metadata values and strings.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003905 auto &&GetMDInt = [this](unsigned V) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003906 return llvm::ConstantAsMetadata::get(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003907 llvm::ConstantInt::get(CGM.Int32Ty, V));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003908 };
3909
Alexey Bataev03f270c2018-03-30 18:31:07 +00003910 auto &&GetMDString = [&C](StringRef V) { return llvm::MDString::get(C, V); };
3911
3912 // Create the offloading info metadata node.
3913 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003914
3915 // Create function that emits metadata for each target region entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00003916 auto &&TargetRegionMetadataEmitter =
3917 [&C, MD, &OrderedEntries, &GetMDInt, &GetMDString](
3918 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3919 unsigned Line,
3920 const OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3921 // Generate metadata for target regions. Each entry of this metadata
3922 // contains:
3923 // - Entry 0 -> Kind of this type of metadata (0).
3924 // - Entry 1 -> Device ID of the file where the entry was identified.
3925 // - Entry 2 -> File ID of the file where the entry was identified.
3926 // - Entry 3 -> Mangled name of the function where the entry was
3927 // identified.
3928 // - Entry 4 -> Line in the file where the entry was identified.
3929 // - Entry 5 -> Order the entry was created.
3930 // The first element of the metadata node is the kind.
3931 llvm::Metadata *Ops[] = {GetMDInt(E.getKind()), GetMDInt(DeviceID),
3932 GetMDInt(FileID), GetMDString(ParentName),
3933 GetMDInt(Line), GetMDInt(E.getOrder())};
Samuel Antaoee8fb302016-01-06 13:42:12 +00003934
Alexey Bataev03f270c2018-03-30 18:31:07 +00003935 // Save this entry in the right position of the ordered entries array.
3936 OrderedEntries[E.getOrder()] = &E;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003937
Alexey Bataev03f270c2018-03-30 18:31:07 +00003938 // Add metadata to the named metadata node.
3939 MD->addOperand(llvm::MDNode::get(C, Ops));
3940 };
Samuel Antaoee8fb302016-01-06 13:42:12 +00003941
3942 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3943 TargetRegionMetadataEmitter);
3944
Alexey Bataev03f270c2018-03-30 18:31:07 +00003945 // Create function that emits metadata for each device global variable entry;
3946 auto &&DeviceGlobalVarMetadataEmitter =
3947 [&C, &OrderedEntries, &GetMDInt, &GetMDString,
3948 MD](StringRef MangledName,
3949 const OffloadEntriesInfoManagerTy::OffloadEntryInfoDeviceGlobalVar
3950 &E) {
3951 // Generate metadata for global variables. Each entry of this metadata
3952 // contains:
3953 // - Entry 0 -> Kind of this type of metadata (1).
3954 // - Entry 1 -> Mangled name of the variable.
3955 // - Entry 2 -> Declare target kind.
3956 // - Entry 3 -> Order the entry was created.
3957 // The first element of the metadata node is the kind.
3958 llvm::Metadata *Ops[] = {
3959 GetMDInt(E.getKind()), GetMDString(MangledName),
3960 GetMDInt(E.getFlags()), GetMDInt(E.getOrder())};
3961
3962 // Save this entry in the right position of the ordered entries array.
3963 OrderedEntries[E.getOrder()] = &E;
3964
3965 // Add metadata to the named metadata node.
3966 MD->addOperand(llvm::MDNode::get(C, Ops));
3967 };
3968
3969 OffloadEntriesInfoManager.actOnDeviceGlobalVarEntriesInfo(
3970 DeviceGlobalVarMetadataEmitter);
3971
3972 for (const auto *E : OrderedEntries) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003973 assert(E && "All ordered entries must exist!");
Alexey Bataev03f270c2018-03-30 18:31:07 +00003974 if (const auto *CE =
Samuel Antaoee8fb302016-01-06 13:42:12 +00003975 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3976 E)) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00003977 if (!CE->getID() || !CE->getAddress()) {
3978 unsigned DiagID = CGM.getDiags().getCustomDiagID(
3979 DiagnosticsEngine::Error,
3980 "Offloading entry for target region is incorect: either the "
3981 "address or the ID is invalid.");
3982 CGM.getDiags().Report(DiagID);
3983 continue;
3984 }
Alexey Bataev34f8a702018-03-28 14:28:54 +00003985 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0,
Alexey Bataev03f270c2018-03-30 18:31:07 +00003986 CE->getFlags(), llvm::GlobalValue::WeakAnyLinkage);
3987 } else if (const auto *CE =
3988 dyn_cast<OffloadEntriesInfoManagerTy::
3989 OffloadEntryInfoDeviceGlobalVar>(E)) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00003990 if (!CE->getAddress()) {
3991 unsigned DiagID = CGM.getDiags().getCustomDiagID(
3992 DiagnosticsEngine::Error,
3993 "Offloading entry for declare target varible is inccorect: the "
3994 "address is invalid.");
3995 CGM.getDiags().Report(DiagID);
3996 continue;
3997 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00003998 createOffloadEntry(CE->getAddress(), CE->getAddress(),
3999 CE->getVarSize().getQuantity(), CE->getFlags(),
4000 CE->getLinkage());
4001 } else {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004002 llvm_unreachable("Unsupported entry kind.");
Alexey Bataev03f270c2018-03-30 18:31:07 +00004003 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004004 }
4005}
4006
4007/// \brief Loads all the offload entries information from the host IR
4008/// metadata.
4009void CGOpenMPRuntime::loadOffloadInfoMetadata() {
4010 // If we are in target mode, load the metadata from the host IR. This code has
4011 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
4012
4013 if (!CGM.getLangOpts().OpenMPIsDevice)
4014 return;
4015
4016 if (CGM.getLangOpts().OMPHostIRFile.empty())
4017 return;
4018
4019 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004020 if (auto EC = Buf.getError()) {
4021 CGM.getDiags().Report(diag::err_cannot_open_file)
4022 << CGM.getLangOpts().OMPHostIRFile << EC.message();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004023 return;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004024 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004025
4026 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00004027 auto ME = expectedToErrorOrAndEmitErrors(
4028 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004029
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004030 if (auto EC = ME.getError()) {
4031 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4032 DiagnosticsEngine::Error, "Unable to parse host IR file '%0':'%1'");
4033 CGM.getDiags().Report(DiagID)
4034 << CGM.getLangOpts().OMPHostIRFile << EC.message();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004035 return;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004036 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004037
4038 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
4039 if (!MD)
4040 return;
4041
George Burgess IV00f70bd2018-03-01 05:43:23 +00004042 for (llvm::MDNode *MN : MD->operands()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004043 auto &&GetMDInt = [MN](unsigned Idx) {
4044 auto *V = cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004045 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
4046 };
4047
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004048 auto &&GetMDString = [MN](unsigned Idx) {
4049 auto *V = cast<llvm::MDString>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004050 return V->getString();
4051 };
4052
Alexey Bataev03f270c2018-03-30 18:31:07 +00004053 switch (GetMDInt(0)) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004054 default:
4055 llvm_unreachable("Unexpected metadata!");
4056 break;
4057 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
Alexey Bataev34f8a702018-03-28 14:28:54 +00004058 OffloadingEntryInfoTargetRegion:
Samuel Antaoee8fb302016-01-06 13:42:12 +00004059 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
Alexey Bataev03f270c2018-03-30 18:31:07 +00004060 /*DeviceID=*/GetMDInt(1), /*FileID=*/GetMDInt(2),
4061 /*ParentName=*/GetMDString(3), /*Line=*/GetMDInt(4),
4062 /*Order=*/GetMDInt(5));
4063 break;
4064 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
4065 OffloadingEntryInfoDeviceGlobalVar:
4066 OffloadEntriesInfoManager.initializeDeviceGlobalVarEntryInfo(
4067 /*MangledName=*/GetMDString(1),
4068 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
4069 /*Flags=*/GetMDInt(2)),
4070 /*Order=*/GetMDInt(3));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004071 break;
4072 }
4073 }
4074}
4075
Alexey Bataev62b63b12015-03-10 07:28:44 +00004076void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
4077 if (!KmpRoutineEntryPtrTy) {
4078 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004079 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004080 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
4081 FunctionProtoType::ExtProtoInfo EPI;
4082 KmpRoutineEntryPtrQTy = C.getPointerType(
4083 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
4084 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
4085 }
4086}
4087
Samuel Antaoee8fb302016-01-06 13:42:12 +00004088QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004089 // Make sure the type of the entry is already created. This is the type we
4090 // have to create:
4091 // struct __tgt_offload_entry{
4092 // void *addr; // Pointer to the offload entry info.
4093 // // (function or global)
4094 // char *name; // Name of the function or global.
4095 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00004096 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
4097 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004098 // };
4099 if (TgtOffloadEntryQTy.isNull()) {
4100 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004101 RecordDecl *RD = C.buildImplicitRecord("__tgt_offload_entry");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004102 RD->startDefinition();
4103 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4104 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
4105 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00004106 addFieldToRecordDecl(
4107 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4108 addFieldToRecordDecl(
4109 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004110 RD->completeDefinition();
Jonas Hahnfeld5e4df282018-01-18 15:38:03 +00004111 RD->addAttr(PackedAttr::CreateImplicit(C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004112 TgtOffloadEntryQTy = C.getRecordType(RD);
4113 }
4114 return TgtOffloadEntryQTy;
4115}
4116
4117QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
4118 // These are the types we need to build:
4119 // struct __tgt_device_image{
4120 // void *ImageStart; // Pointer to the target code start.
4121 // void *ImageEnd; // Pointer to the target code end.
4122 // // We also add the host entries to the device image, as it may be useful
4123 // // for the target runtime to have access to that information.
4124 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
4125 // // the entries.
4126 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4127 // // entries (non inclusive).
4128 // };
4129 if (TgtDeviceImageQTy.isNull()) {
4130 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004131 RecordDecl *RD = C.buildImplicitRecord("__tgt_device_image");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004132 RD->startDefinition();
4133 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4134 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4135 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4136 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4137 RD->completeDefinition();
4138 TgtDeviceImageQTy = C.getRecordType(RD);
4139 }
4140 return TgtDeviceImageQTy;
4141}
4142
4143QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
4144 // struct __tgt_bin_desc{
4145 // int32_t NumDevices; // Number of devices supported.
4146 // __tgt_device_image *DeviceImages; // Arrays of device images
4147 // // (one per device).
4148 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
4149 // // entries.
4150 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4151 // // entries (non inclusive).
4152 // };
4153 if (TgtBinaryDescriptorQTy.isNull()) {
4154 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004155 RecordDecl *RD = C.buildImplicitRecord("__tgt_bin_desc");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004156 RD->startDefinition();
4157 addFieldToRecordDecl(
4158 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4159 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
4160 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4161 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4162 RD->completeDefinition();
4163 TgtBinaryDescriptorQTy = C.getRecordType(RD);
4164 }
4165 return TgtBinaryDescriptorQTy;
4166}
4167
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004168namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00004169struct PrivateHelpersTy {
4170 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
4171 const VarDecl *PrivateElemInit)
4172 : Original(Original), PrivateCopy(PrivateCopy),
4173 PrivateElemInit(PrivateElemInit) {}
4174 const VarDecl *Original;
4175 const VarDecl *PrivateCopy;
4176 const VarDecl *PrivateElemInit;
4177};
4178typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00004179} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004180
Alexey Bataev9e034042015-05-05 04:05:12 +00004181static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00004182createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004183 if (!Privates.empty()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004184 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004185 // Build struct .kmp_privates_t. {
4186 // /* private vars */
4187 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004188 RecordDecl *RD = C.buildImplicitRecord(".kmp_privates.t");
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004189 RD->startDefinition();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004190 for (const auto &Pair : Privates) {
4191 const VarDecl *VD = Pair.second.Original;
4192 QualType Type = VD->getType().getNonReferenceType();
4193 FieldDecl *FD = addFieldToRecordDecl(C, RD, Type);
Alexey Bataevc71a4092015-09-11 10:29:41 +00004194 if (VD->hasAttrs()) {
4195 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
4196 E(VD->getAttrs().end());
4197 I != E; ++I)
4198 FD->addAttr(*I);
4199 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004200 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004201 RD->completeDefinition();
4202 return RD;
4203 }
4204 return nullptr;
4205}
4206
Alexey Bataev9e034042015-05-05 04:05:12 +00004207static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00004208createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
4209 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004210 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004211 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004212 // Build struct kmp_task_t {
4213 // void * shareds;
4214 // kmp_routine_entry_t routine;
4215 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00004216 // kmp_cmplrdata_t data1;
4217 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00004218 // For taskloops additional fields:
4219 // kmp_uint64 lb;
4220 // kmp_uint64 ub;
4221 // kmp_int64 st;
4222 // kmp_int32 liter;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004223 // void * reductions;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004224 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004225 RecordDecl *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004226 UD->startDefinition();
4227 addFieldToRecordDecl(C, UD, KmpInt32Ty);
4228 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
4229 UD->completeDefinition();
4230 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004231 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t");
Alexey Bataev62b63b12015-03-10 07:28:44 +00004232 RD->startDefinition();
4233 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4234 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
4235 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004236 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
4237 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004238 if (isOpenMPTaskLoopDirective(Kind)) {
4239 QualType KmpUInt64Ty =
4240 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4241 QualType KmpInt64Ty =
4242 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4243 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4244 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4245 addFieldToRecordDecl(C, RD, KmpInt64Ty);
4246 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004247 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004248 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004249 RD->completeDefinition();
4250 return RD;
4251}
4252
4253static RecordDecl *
4254createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004255 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004256 ASTContext &C = CGM.getContext();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004257 // Build struct kmp_task_t_with_privates {
4258 // kmp_task_t task_data;
4259 // .kmp_privates_t. privates;
4260 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004261 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004262 RD->startDefinition();
4263 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004264 if (const RecordDecl *PrivateRD = createPrivatesRecordDecl(CGM, Privates))
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004265 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004266 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004267 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004268}
4269
4270/// \brief Emit a proxy function which accepts kmp_task_t as the second
4271/// argument.
4272/// \code
4273/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004274/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00004275/// For taskloops:
4276/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004277/// tt->reductions, tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004278/// return 0;
4279/// }
4280/// \endcode
4281static llvm::Value *
4282emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00004283 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
4284 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004285 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004286 QualType SharedsPtrTy, llvm::Value *TaskFunction,
4287 llvm::Value *TaskPrivatesMap) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004288 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004289 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004290 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4291 ImplicitParamDecl::Other);
4292 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4293 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4294 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004295 Args.push_back(&GtidArg);
4296 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004297 const auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004298 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004299 llvm::FunctionType *TaskEntryTy =
4300 CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004301 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_entry", ""});
4302 auto *TaskEntry = llvm::Function::Create(
4303 TaskEntryTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004304 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskEntry, TaskEntryFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004305 TaskEntry->setDoesNotRecurse();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004306 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004307 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args,
4308 Loc, Loc);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004309
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004310 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00004311 // tt,
4312 // For taskloops:
4313 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
4314 // tt->task_data.shareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004315 llvm::Value *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00004316 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00004317 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4318 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4319 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004320 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004321 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004322 LValue Base =
4323 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004324 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004325 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004326 LValue PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
4327 llvm::Value *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004328
4329 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004330 LValue SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
4331 llvm::Value *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev1e491372018-01-23 18:44:14 +00004332 CGF.EmitLoadOfScalar(SharedsLVal, Loc),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004333 CGF.ConvertTypeForMem(SharedsPtrTy));
4334
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004335 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4336 llvm::Value *PrivatesParam;
4337 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004338 LValue PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004339 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004340 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004341 } else {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004342 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004343 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004344
Alexey Bataev7292c292016-04-25 12:22:29 +00004345 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
4346 TaskPrivatesMap,
4347 CGF.Builder
4348 .CreatePointerBitCastOrAddrSpaceCast(
4349 TDBase.getAddress(), CGF.VoidPtrTy)
4350 .getPointer()};
4351 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
4352 std::end(CommonArgs));
4353 if (isOpenMPTaskLoopDirective(Kind)) {
4354 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004355 LValue LBLVal = CGF.EmitLValueForField(Base, *LBFI);
4356 llvm::Value *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004357 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004358 LValue UBLVal = CGF.EmitLValueForField(Base, *UBFI);
4359 llvm::Value *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004360 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004361 LValue StLVal = CGF.EmitLValueForField(Base, *StFI);
4362 llvm::Value *StParam = CGF.EmitLoadOfScalar(StLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004363 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004364 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4365 llvm::Value *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004366 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004367 LValue RLVal = CGF.EmitLValueForField(Base, *RFI);
4368 llvm::Value *RParam = CGF.EmitLoadOfScalar(RLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004369 CallArgs.push_back(LBParam);
4370 CallArgs.push_back(UBParam);
4371 CallArgs.push_back(StParam);
4372 CallArgs.push_back(LIParam);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004373 CallArgs.push_back(RParam);
Alexey Bataev7292c292016-04-25 12:22:29 +00004374 }
4375 CallArgs.push_back(SharedsParam);
4376
Alexey Bataev3c595a62017-08-14 15:01:03 +00004377 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
4378 CallArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004379 CGF.EmitStoreThroughLValue(RValue::get(CGF.Builder.getInt32(/*C=*/0)),
4380 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004381 CGF.FinishFunction();
4382 return TaskEntry;
4383}
4384
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004385static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
4386 SourceLocation Loc,
4387 QualType KmpInt32Ty,
4388 QualType KmpTaskTWithPrivatesPtrQTy,
4389 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004390 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004391 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004392 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4393 ImplicitParamDecl::Other);
4394 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4395 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4396 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004397 Args.push_back(&GtidArg);
4398 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004399 const auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004400 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004401 llvm::FunctionType *DestructorFnTy =
4402 CGM.getTypes().GetFunctionType(DestructorFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004403 std::string Name =
4404 CGM.getOpenMPRuntime().getName({"omp_task_destructor", ""});
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004405 auto *DestructorFn =
4406 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00004407 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004408 CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004409 DestructorFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004410 DestructorFn->setDoesNotRecurse();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004411 CodeGenFunction CGF(CGM);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004412 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004413 Args, Loc, Loc);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004414
Alexey Bataev31300ed2016-02-04 11:27:03 +00004415 LValue Base = CGF.EmitLoadOfPointerLValue(
4416 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4417 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004418 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004419 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
4420 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004421 Base = CGF.EmitLValueForField(Base, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004422 for (const auto *Field :
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004423 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004424 if (QualType::DestructionKind DtorKind =
4425 Field->getType().isDestructedType()) {
4426 LValue FieldLValue = CGF.EmitLValueForField(Base, Field);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004427 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
4428 }
4429 }
4430 CGF.FinishFunction();
4431 return DestructorFn;
4432}
4433
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004434/// \brief Emit a privates mapping function for correct handling of private and
4435/// firstprivate variables.
4436/// \code
4437/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
4438/// **noalias priv1,..., <tyn> **noalias privn) {
4439/// *priv1 = &.privates.priv1;
4440/// ...;
4441/// *privn = &.privates.privn;
4442/// }
4443/// \endcode
4444static llvm::Value *
4445emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00004446 ArrayRef<const Expr *> PrivateVars,
4447 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004448 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004449 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004450 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004451 ASTContext &C = CGM.getContext();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004452 FunctionArgList Args;
4453 ImplicitParamDecl TaskPrivatesArg(
4454 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00004455 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
4456 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004457 Args.push_back(&TaskPrivatesArg);
4458 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
4459 unsigned Counter = 1;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004460 for (const Expr *E : PrivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004461 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004462 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4463 C.getPointerType(C.getPointerType(E->getType()))
4464 .withConst()
4465 .withRestrict(),
4466 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004467 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004468 PrivateVarsPos[VD] = Counter;
4469 ++Counter;
4470 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004471 for (const Expr *E : FirstprivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004472 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004473 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4474 C.getPointerType(C.getPointerType(E->getType()))
4475 .withConst()
4476 .withRestrict(),
4477 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004478 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004479 PrivateVarsPos[VD] = Counter;
4480 ++Counter;
4481 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004482 for (const Expr *E : LastprivateVars) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004483 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004484 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4485 C.getPointerType(C.getPointerType(E->getType()))
4486 .withConst()
4487 .withRestrict(),
4488 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004489 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004490 PrivateVarsPos[VD] = Counter;
4491 ++Counter;
4492 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004493 const auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004494 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004495 llvm::FunctionType *TaskPrivatesMapTy =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004496 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004497 std::string Name =
4498 CGM.getOpenMPRuntime().getName({"omp_task_privates_map", ""});
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004499 auto *TaskPrivatesMap = llvm::Function::Create(
Alexey Bataev18fa2322018-05-02 14:20:50 +00004500 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage, Name,
4501 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004502 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004503 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00004504 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00004505 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00004506 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004507 CodeGenFunction CGF(CGM);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004508 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004509 TaskPrivatesMapFnInfo, Args, Loc, Loc);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004510
4511 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00004512 LValue Base = CGF.EmitLoadOfPointerLValue(
4513 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4514 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004515 const auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004516 Counter = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004517 for (const FieldDecl *Field : PrivatesQTyRD->fields()) {
4518 LValue FieldLVal = CGF.EmitLValueForField(Base, Field);
4519 const VarDecl *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
4520 LValue RefLVal =
4521 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
4522 LValue RefLoadLVal = CGF.EmitLoadOfPointerLValue(
Alexey Bataev31300ed2016-02-04 11:27:03 +00004523 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00004524 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004525 ++Counter;
4526 }
4527 CGF.FinishFunction();
4528 return TaskPrivatesMap;
4529}
4530
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004531static bool stable_sort_comparator(const PrivateDataTy P1,
4532 const PrivateDataTy P2) {
4533 return P1.first > P2.first;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004534}
4535
Alexey Bataevf93095a2016-05-05 08:46:22 +00004536/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00004537static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004538 const OMPExecutableDirective &D,
4539 Address KmpTaskSharedsPtr, LValue TDBase,
4540 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4541 QualType SharedsTy, QualType SharedsPtrTy,
4542 const OMPTaskDataTy &Data,
4543 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004544 ASTContext &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004545 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4546 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004547 OpenMPDirectiveKind Kind = isOpenMPTaskLoopDirective(D.getDirectiveKind())
4548 ? OMPD_taskloop
4549 : OMPD_task;
4550 const CapturedStmt &CS = *D.getCapturedStmt(Kind);
4551 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004552 LValue SrcBase;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004553 bool IsTargetTask =
4554 isOpenMPTargetDataManagementDirective(D.getDirectiveKind()) ||
4555 isOpenMPTargetExecutionDirective(D.getDirectiveKind());
4556 // For target-based directives skip 3 firstprivate arrays BasePointersArray,
4557 // PointersArray and SizesArray. The original variables for these arrays are
4558 // not captured and we get their addresses explicitly.
4559 if ((!IsTargetTask && !Data.FirstprivateVars.empty()) ||
Alexey Bataev8451efa2018-01-15 19:06:12 +00004560 (IsTargetTask && KmpTaskSharedsPtr.isValid())) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004561 SrcBase = CGF.MakeAddrLValue(
4562 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4563 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4564 SharedsTy);
4565 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004566 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004567 for (const PrivateDataTy &Pair : Privates) {
4568 const VarDecl *VD = Pair.second.PrivateCopy;
4569 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004570 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4571 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004572 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004573 if (const VarDecl *Elem = Pair.second.PrivateElemInit) {
4574 const VarDecl *OriginalVD = Pair.second.Original;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004575 // Check if the variable is the target-based BasePointersArray,
4576 // PointersArray or SizesArray.
4577 LValue SharedRefLValue;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004578 QualType Type = OriginalVD->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004579 const FieldDecl *SharedField = CapturesInfo.lookup(OriginalVD);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004580 if (IsTargetTask && !SharedField) {
4581 assert(isa<ImplicitParamDecl>(OriginalVD) &&
4582 isa<CapturedDecl>(OriginalVD->getDeclContext()) &&
4583 cast<CapturedDecl>(OriginalVD->getDeclContext())
4584 ->getNumParams() == 0 &&
4585 isa<TranslationUnitDecl>(
4586 cast<CapturedDecl>(OriginalVD->getDeclContext())
4587 ->getDeclContext()) &&
4588 "Expected artificial target data variable.");
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004589 SharedRefLValue =
4590 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type);
4591 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004592 SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4593 SharedRefLValue = CGF.MakeAddrLValue(
4594 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
4595 SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl),
4596 SharedRefLValue.getTBAAInfo());
4597 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004598 if (Type->isArrayType()) {
4599 // Initialize firstprivate array.
4600 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4601 // Perform simple memcpy.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004602 CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004603 } else {
4604 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00004605 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00004606 CGF.EmitOMPAggregateAssign(
4607 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4608 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4609 Address SrcElement) {
4610 // Clean up any temporaries needed by the initialization.
4611 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4612 InitScope.addPrivate(
4613 Elem, [SrcElement]() -> Address { return SrcElement; });
4614 (void)InitScope.Privatize();
4615 // Emit initialization for single element.
4616 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4617 CGF, &CapturesInfo);
4618 CGF.EmitAnyExprToMem(Init, DestElement,
4619 Init->getType().getQualifiers(),
4620 /*IsInitializer=*/false);
4621 });
4622 }
4623 } else {
4624 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4625 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4626 return SharedRefLValue.getAddress();
4627 });
4628 (void)InitScope.Privatize();
4629 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4630 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4631 /*capturedByInit=*/false);
4632 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004633 } else {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004634 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004635 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004636 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004637 ++FI;
4638 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004639}
4640
4641/// Check if duplication function is required for taskloops.
4642static bool checkInitIsRequired(CodeGenFunction &CGF,
4643 ArrayRef<PrivateDataTy> Privates) {
4644 bool InitRequired = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004645 for (const PrivateDataTy &Pair : Privates) {
4646 const VarDecl *VD = Pair.second.PrivateCopy;
4647 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004648 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4649 !CGF.isTrivialInitializer(Init));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004650 if (InitRequired)
4651 break;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004652 }
4653 return InitRequired;
4654}
4655
4656
4657/// Emit task_dup function (for initialization of
4658/// private/firstprivate/lastprivate vars and last_iter flag)
4659/// \code
4660/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4661/// lastpriv) {
4662/// // setup lastprivate flag
4663/// task_dst->last = lastpriv;
4664/// // could be constructor calls here...
4665/// }
4666/// \endcode
4667static llvm::Value *
4668emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4669 const OMPExecutableDirective &D,
4670 QualType KmpTaskTWithPrivatesPtrQTy,
4671 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4672 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4673 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4674 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004675 ASTContext &C = CGM.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004676 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004677 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4678 KmpTaskTWithPrivatesPtrQTy,
4679 ImplicitParamDecl::Other);
4680 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4681 KmpTaskTWithPrivatesPtrQTy,
4682 ImplicitParamDecl::Other);
4683 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4684 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004685 Args.push_back(&DstArg);
4686 Args.push_back(&SrcArg);
4687 Args.push_back(&LastprivArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004688 const auto &TaskDupFnInfo =
Alexey Bataevf93095a2016-05-05 08:46:22 +00004689 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004690 llvm::FunctionType *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004691 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_dup", ""});
4692 auto *TaskDup = llvm::Function::Create(
4693 TaskDupTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004694 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskDup, TaskDupFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004695 TaskDup->setDoesNotRecurse();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004696 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004697 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args, Loc,
4698 Loc);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004699
4700 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4701 CGF.GetAddrOfLocalVar(&DstArg),
4702 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4703 // task_dst->liter = lastpriv;
4704 if (WithLastIter) {
4705 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4706 LValue Base = CGF.EmitLValueForField(
4707 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4708 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4709 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4710 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4711 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4712 }
4713
4714 // Emit initial values for private copies (if any).
4715 assert(!Privates.empty());
4716 Address KmpTaskSharedsPtr = Address::invalid();
4717 if (!Data.FirstprivateVars.empty()) {
4718 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4719 CGF.GetAddrOfLocalVar(&SrcArg),
4720 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4721 LValue Base = CGF.EmitLValueForField(
4722 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4723 KmpTaskSharedsPtr = Address(
4724 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4725 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4726 KmpTaskTShareds)),
4727 Loc),
4728 CGF.getNaturalTypeAlignment(SharedsTy));
4729 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004730 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4731 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004732 CGF.FinishFunction();
4733 return TaskDup;
4734}
4735
Alexey Bataev8a831592016-05-10 10:36:51 +00004736/// Checks if destructor function is required to be generated.
4737/// \return true if cleanups are required, false otherwise.
4738static bool
4739checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4740 bool NeedsCleanup = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004741 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4742 const auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4743 for (const FieldDecl *FD : PrivateRD->fields()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004744 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4745 if (NeedsCleanup)
4746 break;
4747 }
4748 return NeedsCleanup;
4749}
4750
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004751CGOpenMPRuntime::TaskResultTy
4752CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4753 const OMPExecutableDirective &D,
4754 llvm::Value *TaskFunction, QualType SharedsTy,
4755 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004756 ASTContext &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004757 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004758 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004759 auto I = Data.PrivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004760 for (const Expr *E : Data.PrivateVars) {
4761 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004762 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004763 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004764 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004765 /*PrivateElemInit=*/nullptr));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004766 ++I;
4767 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004768 I = Data.FirstprivateCopies.begin();
4769 auto IElemInitRef = Data.FirstprivateInits.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004770 for (const Expr *E : Data.FirstprivateVars) {
4771 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004772 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004773 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004774 PrivateHelpersTy(
4775 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004776 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl())));
Richard Trieucc3949d2016-02-18 22:34:54 +00004777 ++I;
4778 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004779 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004780 I = Data.LastprivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004781 for (const Expr *E : Data.LastprivateVars) {
4782 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004783 Privates.emplace_back(
Alexey Bataevf93095a2016-05-05 08:46:22 +00004784 C.getDeclAlign(VD),
4785 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004786 /*PrivateElemInit=*/nullptr));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004787 ++I;
4788 }
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004789 std::stable_sort(Privates.begin(), Privates.end(), stable_sort_comparator);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004790 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004791 // Build type kmp_routine_entry_t (if not built yet).
4792 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004793 // Build type kmp_task_t (if not built yet).
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004794 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
4795 if (SavedKmpTaskloopTQTy.isNull()) {
4796 SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4797 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4798 }
4799 KmpTaskTQTy = SavedKmpTaskloopTQTy;
Alexey Bataev3a03a7f2017-10-11 15:56:38 +00004800 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004801 assert((D.getDirectiveKind() == OMPD_task ||
4802 isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||
4803 isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) &&
4804 "Expected taskloop, task or target directive");
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004805 if (SavedKmpTaskTQTy.isNull()) {
4806 SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4807 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4808 }
4809 KmpTaskTQTy = SavedKmpTaskTQTy;
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004810 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004811 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004812 // Build particular struct kmp_task_t for the given task.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004813 const RecordDecl *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004814 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004815 QualType KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004816 QualType KmpTaskTWithPrivatesPtrQTy =
4817 C.getPointerType(KmpTaskTWithPrivatesQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004818 llvm::Type *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4819 llvm::Type *KmpTaskTWithPrivatesPtrTy =
4820 KmpTaskTWithPrivatesTy->getPointerTo();
4821 llvm::Value *KmpTaskTWithPrivatesTySize =
4822 CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004823 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4824
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004825 // Emit initial values for private copies (if any).
4826 llvm::Value *TaskPrivatesMap = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004827 llvm::Type *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00004828 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004829 if (!Privates.empty()) {
4830 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004831 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4832 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4833 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004834 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4835 TaskPrivatesMap, TaskPrivatesMapTy);
4836 } else {
4837 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4838 cast<llvm::PointerType>(TaskPrivatesMapTy));
4839 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004840 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4841 // kmp_task_t *tt);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004842 llvm::Value *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004843 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4844 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4845 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004846
4847 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4848 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4849 // kmp_routine_entry_t *task_entry);
4850 // Task flags. Format is taken from
4851 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4852 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004853 enum {
4854 TiedFlag = 0x1,
4855 FinalFlag = 0x2,
4856 DestructorsFlag = 0x8,
4857 PriorityFlag = 0x20
4858 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004859 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004860 bool NeedsCleanup = false;
4861 if (!Privates.empty()) {
4862 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4863 if (NeedsCleanup)
4864 Flags = Flags | DestructorsFlag;
4865 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004866 if (Data.Priority.getInt())
4867 Flags = Flags | PriorityFlag;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004868 llvm::Value *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004869 Data.Final.getPointer()
4870 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00004871 CGF.Builder.getInt32(FinalFlag),
4872 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004873 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004874 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004875 llvm::Value *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004876 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4877 getThreadID(CGF, Loc), TaskFlags,
4878 KmpTaskTWithPrivatesTySize, SharedsSize,
4879 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4880 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004881 llvm::Value *NewTask = CGF.EmitRuntimeCall(
Alexey Bataev62b63b12015-03-10 07:28:44 +00004882 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004883 llvm::Value *NewTaskNewTaskTTy =
4884 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4885 NewTask, KmpTaskTWithPrivatesPtrTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004886 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4887 KmpTaskTWithPrivatesQTy);
4888 LValue TDBase =
4889 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004890 // Fill the data in the resulting kmp_task_t record.
4891 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00004892 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004893 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00004894 KmpTaskSharedsPtr =
4895 Address(CGF.EmitLoadOfScalar(
4896 CGF.EmitLValueForField(
4897 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4898 KmpTaskTShareds)),
4899 Loc),
4900 CGF.getNaturalTypeAlignment(SharedsTy));
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004901 LValue Dest = CGF.MakeAddrLValue(KmpTaskSharedsPtr, SharedsTy);
4902 LValue Src = CGF.MakeAddrLValue(Shareds, SharedsTy);
Richard Smithe78fac52018-04-05 20:52:58 +00004903 CGF.EmitAggregateCopy(Dest, Src, SharedsTy, AggValueSlot::DoesNotOverlap);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004904 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004905 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00004906 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004907 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004908 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4909 SharedsTy, SharedsPtrTy, Data, Privates,
4910 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004911 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4912 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4913 Result.TaskDupFn = emitTaskDupFunction(
4914 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4915 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4916 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004917 }
4918 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00004919 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4920 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00004921 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00004922 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004923 const RecordDecl *KmpCmplrdataUD =
4924 (*FI)->getType()->getAsUnionType()->getDecl();
Alexey Bataevad537bb2016-05-30 09:06:50 +00004925 if (NeedsCleanup) {
4926 llvm::Value *DestructorFn = emitDestructorsFunction(
4927 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4928 KmpTaskTWithPrivatesQTy);
4929 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4930 LValue DestructorsLV = CGF.EmitLValueForField(
4931 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4932 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4933 DestructorFn, KmpRoutineEntryPtrTy),
4934 DestructorsLV);
4935 }
4936 // Set priority.
4937 if (Data.Priority.getInt()) {
4938 LValue Data2LV = CGF.EmitLValueForField(
4939 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
4940 LValue PriorityLV = CGF.EmitLValueForField(
4941 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
4942 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
4943 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004944 Result.NewTask = NewTask;
4945 Result.TaskEntry = TaskEntry;
4946 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
4947 Result.TDBase = TDBase;
4948 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
4949 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00004950}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004951
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004952void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
4953 const OMPExecutableDirective &D,
4954 llvm::Value *TaskFunction,
4955 QualType SharedsTy, Address Shareds,
4956 const Expr *IfCond,
4957 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004958 if (!CGF.HaveInsertPoint())
4959 return;
4960
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004961 TaskResultTy Result =
4962 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4963 llvm::Value *NewTask = Result.NewTask;
4964 llvm::Value *TaskEntry = Result.TaskEntry;
4965 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
4966 LValue TDBase = Result.TDBase;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004967 const RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
4968 ASTContext &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004969 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00004970 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004971 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00004972 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004973 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00004974 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004975 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
4976 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004977 QualType FlagsTy =
4978 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004979 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
4980 if (KmpDependInfoTy.isNull()) {
4981 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
4982 KmpDependInfoRD->startDefinition();
4983 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
4984 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
4985 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
4986 KmpDependInfoRD->completeDefinition();
4987 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004988 } else {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004989 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004990 }
John McCall7f416cc2015-09-08 08:05:57 +00004991 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004992 // Define type kmp_depend_info[<Dependences.size()>];
4993 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00004994 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004995 ArrayType::Normal, /*IndexTypeQuals=*/0);
4996 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00004997 DependenciesArray =
4998 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004999 for (unsigned I = 0; I < NumDependencies; ++I) {
5000 const Expr *E = Data.Dependences[I].second;
5001 LValue Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005002 llvm::Value *Size;
5003 QualType Ty = E->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005004 if (const auto *ASE =
5005 dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005006 LValue UpAddrLVal =
5007 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
5008 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00005009 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005010 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00005011 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005012 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
5013 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005014 } else {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005015 Size = CGF.getTypeSize(Ty);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005016 }
5017 LValue Base = CGF.MakeAddrLValue(
5018 CGF.Builder.CreateConstArrayGEP(DependenciesArray, I, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005019 KmpDependInfoTy);
5020 // deps[i].base_addr = &<Dependences[i].second>;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005021 LValue BaseAddrLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005022 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00005023 CGF.EmitStoreOfScalar(
5024 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
5025 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005026 // deps[i].len = sizeof(<Dependences[i].second>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005027 LValue LenLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005028 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
5029 CGF.EmitStoreOfScalar(Size, LenLVal);
5030 // deps[i].flags = <Dependences[i].first>;
5031 RTLDependenceKindTy DepKind;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005032 switch (Data.Dependences[I].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005033 case OMPC_DEPEND_in:
5034 DepKind = DepIn;
5035 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00005036 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005037 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005038 case OMPC_DEPEND_inout:
5039 DepKind = DepInOut;
5040 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00005041 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005042 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005043 case OMPC_DEPEND_unknown:
5044 llvm_unreachable("Unknown task dependence type");
5045 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005046 LValue FlagsLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005047 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
5048 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
5049 FlagsLVal);
5050 }
John McCall7f416cc2015-09-08 08:05:57 +00005051 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5052 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005053 CGF.VoidPtrTy);
5054 }
5055
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005056 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev62b63b12015-03-10 07:28:44 +00005057 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005058 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
5059 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
5060 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
5061 // list is not empty
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005062 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5063 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00005064 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
5065 llvm::Value *DepTaskArgs[7];
5066 if (NumDependencies) {
5067 DepTaskArgs[0] = UpLoc;
5068 DepTaskArgs[1] = ThreadID;
5069 DepTaskArgs[2] = NewTask;
5070 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
5071 DepTaskArgs[4] = DependenciesArray.getPointer();
5072 DepTaskArgs[5] = CGF.Builder.getInt32(0);
5073 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5074 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005075 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
5076 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005077 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005078 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005079 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005080 LValue PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005081 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
5082 }
John McCall7f416cc2015-09-08 08:05:57 +00005083 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005084 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00005085 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00005086 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005087 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00005088 TaskArgs);
5089 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00005090 // Check if parent region is untied and build return for untied task;
5091 if (auto *Region =
5092 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5093 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00005094 };
John McCall7f416cc2015-09-08 08:05:57 +00005095
5096 llvm::Value *DepWaitTaskArgs[6];
5097 if (NumDependencies) {
5098 DepWaitTaskArgs[0] = UpLoc;
5099 DepWaitTaskArgs[1] = ThreadID;
5100 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
5101 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
5102 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
5103 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5104 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005105 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00005106 NumDependencies, &DepWaitTaskArgs,
5107 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005108 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005109 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
5110 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
5111 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
5112 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
5113 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00005114 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005115 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005116 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005117 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00005118 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
5119 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005120 Action.Enter(CGF);
5121 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00005122 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00005123 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005124 };
5125
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005126 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
5127 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005128 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
5129 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005130 RegionCodeGenTy RCG(CodeGen);
5131 CommonActionTy Action(
5132 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
5133 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
5134 RCG.setAction(Action);
5135 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005136 };
John McCall7f416cc2015-09-08 08:05:57 +00005137
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005138 if (IfCond) {
Alexey Bataev1d677132015-04-22 13:57:31 +00005139 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005140 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005141 RegionCodeGenTy ThenRCG(ThenCodeGen);
5142 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00005143 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00005144}
5145
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005146void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
5147 const OMPLoopDirective &D,
5148 llvm::Value *TaskFunction,
5149 QualType SharedsTy, Address Shareds,
5150 const Expr *IfCond,
5151 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005152 if (!CGF.HaveInsertPoint())
5153 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005154 TaskResultTy Result =
5155 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005156 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev7292c292016-04-25 12:22:29 +00005157 // libcall.
5158 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
5159 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
5160 // sched, kmp_uint64 grainsize, void *task_dup);
5161 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5162 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
5163 llvm::Value *IfVal;
5164 if (IfCond) {
5165 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
5166 /*isSigned=*/true);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005167 } else {
Alexey Bataev7292c292016-04-25 12:22:29 +00005168 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005169 }
Alexey Bataev7292c292016-04-25 12:22:29 +00005170
5171 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005172 Result.TDBase,
5173 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005174 const auto *LBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005175 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
5176 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
5177 /*IsInitializer=*/true);
5178 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005179 Result.TDBase,
5180 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005181 const auto *UBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005182 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
5183 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
5184 /*IsInitializer=*/true);
5185 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005186 Result.TDBase,
5187 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005188 const auto *StVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005189 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
5190 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
5191 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005192 // Store reductions address.
5193 LValue RedLVal = CGF.EmitLValueForField(
5194 Result.TDBase,
5195 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005196 if (Data.Reductions) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005197 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005198 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005199 CGF.EmitNullInitialization(RedLVal.getAddress(),
5200 CGF.getContext().VoidPtrTy);
5201 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005202 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00005203 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00005204 UpLoc,
5205 ThreadID,
5206 Result.NewTask,
5207 IfVal,
5208 LBLVal.getPointer(),
5209 UBLVal.getPointer(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005210 CGF.EmitLoadOfScalar(StLVal, Loc),
Alexey Bataev33446032017-07-12 18:09:32 +00005211 llvm::ConstantInt::getNullValue(
5212 CGF.IntTy), // Always 0 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005213 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005214 CGF.IntTy, Data.Schedule.getPointer()
5215 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005216 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005217 Data.Schedule.getPointer()
5218 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005219 /*isSigned=*/false)
5220 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00005221 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5222 Result.TaskDupFn, CGF.VoidPtrTy)
5223 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00005224 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
5225}
5226
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005227/// \brief Emit reduction operation for each element of array (required for
5228/// array sections) LHS op = RHS.
5229/// \param Type Type of array.
5230/// \param LHSVar Variable on the left side of the reduction operation
5231/// (references element of array in original variable).
5232/// \param RHSVar Variable on the right side of the reduction operation
5233/// (references element of array in original variable).
5234/// \param RedOpGen Generator of reduction operation with use of LHSVar and
5235/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00005236static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005237 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
5238 const VarDecl *RHSVar,
5239 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
5240 const Expr *, const Expr *)> &RedOpGen,
5241 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
5242 const Expr *UpExpr = nullptr) {
5243 // Perform element-by-element initialization.
5244 QualType ElementTy;
5245 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
5246 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
5247
5248 // Drill down to the base element type on both arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005249 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
5250 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005251
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005252 llvm::Value *RHSBegin = RHSAddr.getPointer();
5253 llvm::Value *LHSBegin = LHSAddr.getPointer();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005254 // Cast from pointer to array type to pointer to single element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005255 llvm::Value *LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005256 // The basic structure here is a while-do loop.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005257 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
5258 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
5259 llvm::Value *IsEmpty =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005260 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
5261 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
5262
5263 // Enter the loop body, making that address the current address.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005264 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005265 CGF.EmitBlock(BodyBB);
5266
5267 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
5268
5269 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
5270 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
5271 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
5272 Address RHSElementCurrent =
5273 Address(RHSElementPHI,
5274 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5275
5276 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
5277 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
5278 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
5279 Address LHSElementCurrent =
5280 Address(LHSElementPHI,
5281 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5282
5283 // Emit copy.
5284 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005285 Scope.addPrivate(LHSVar, [=]() { return LHSElementCurrent; });
5286 Scope.addPrivate(RHSVar, [=]() { return RHSElementCurrent; });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005287 Scope.Privatize();
5288 RedOpGen(CGF, XExpr, EExpr, UpExpr);
5289 Scope.ForceCleanup();
5290
5291 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005292 llvm::Value *LHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005293 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005294 llvm::Value *RHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005295 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
5296 // Check whether we've reached the end.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005297 llvm::Value *Done =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005298 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
5299 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
5300 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
5301 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
5302
5303 // Done.
5304 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
5305}
5306
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005307/// Emit reduction combiner. If the combiner is a simple expression emit it as
5308/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
5309/// UDR combiner function.
5310static void emitReductionCombiner(CodeGenFunction &CGF,
5311 const Expr *ReductionOp) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005312 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
5313 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
5314 if (const auto *DRE =
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005315 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005316 if (const auto *DRD =
5317 dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005318 std::pair<llvm::Function *, llvm::Function *> Reduction =
5319 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
5320 RValue Func = RValue::get(Reduction.first);
5321 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
5322 CGF.EmitIgnoredExpr(ReductionOp);
5323 return;
5324 }
5325 CGF.EmitIgnoredExpr(ReductionOp);
5326}
5327
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005328llvm::Value *CGOpenMPRuntime::emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005329 CodeGenModule &CGM, SourceLocation Loc, llvm::Type *ArgsType,
5330 ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs,
5331 ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005332 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005333
5334 // void reduction_func(void *LHSArg, void *RHSArg);
5335 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005336 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5337 ImplicitParamDecl::Other);
5338 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5339 ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005340 Args.push_back(&LHSArg);
5341 Args.push_back(&RHSArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005342 const auto &CGFI =
5343 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005344 std::string Name = getName({"omp", "reduction", "reduction_func"});
5345 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
5346 llvm::GlobalValue::InternalLinkage, Name,
5347 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005348 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005349 Fn->setDoesNotRecurse();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005350 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005351 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005352
5353 // Dst = (void*[n])(LHSArg);
5354 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00005355 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5356 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
5357 ArgsType), CGF.getPointerAlign());
5358 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5359 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
5360 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005361
5362 // ...
5363 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
5364 // ...
5365 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005366 auto IPriv = Privates.begin();
5367 unsigned Idx = 0;
5368 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005369 const auto *RHSVar =
5370 cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
5371 Scope.addPrivate(RHSVar, [&CGF, RHS, Idx, RHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005372 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005373 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005374 const auto *LHSVar =
5375 cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
5376 Scope.addPrivate(LHSVar, [&CGF, LHS, Idx, LHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005377 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005378 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005379 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00005380 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005381 // Get array size and emit VLA type.
5382 ++Idx;
5383 Address Elem =
5384 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
5385 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005386 const VariableArrayType *VLA =
5387 CGF.getContext().getAsVariableArrayType(PrivTy);
5388 const auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005389 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00005390 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005391 CGF.EmitVariablyModifiedType(PrivTy);
5392 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005393 }
5394 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005395 IPriv = Privates.begin();
5396 auto ILHS = LHSExprs.begin();
5397 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005398 for (const Expr *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005399 if ((*IPriv)->getType()->isArrayType()) {
5400 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005401 const auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5402 const auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005403 EmitOMPAggregateReduction(
5404 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5405 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5406 emitReductionCombiner(CGF, E);
5407 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005408 } else {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005409 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005410 emitReductionCombiner(CGF, E);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005411 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005412 ++IPriv;
5413 ++ILHS;
5414 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005415 }
5416 Scope.ForceCleanup();
5417 CGF.FinishFunction();
5418 return Fn;
5419}
5420
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005421void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
5422 const Expr *ReductionOp,
5423 const Expr *PrivateRef,
5424 const DeclRefExpr *LHS,
5425 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005426 if (PrivateRef->getType()->isArrayType()) {
5427 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005428 const auto *LHSVar = cast<VarDecl>(LHS->getDecl());
5429 const auto *RHSVar = cast<VarDecl>(RHS->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005430 EmitOMPAggregateReduction(
5431 CGF, PrivateRef->getType(), LHSVar, RHSVar,
5432 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5433 emitReductionCombiner(CGF, ReductionOp);
5434 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005435 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005436 // Emit reduction for array subscript or single variable.
5437 emitReductionCombiner(CGF, ReductionOp);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005438 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005439}
5440
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005441void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005442 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005443 ArrayRef<const Expr *> LHSExprs,
5444 ArrayRef<const Expr *> RHSExprs,
5445 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005446 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005447 if (!CGF.HaveInsertPoint())
5448 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005449
5450 bool WithNowait = Options.WithNowait;
5451 bool SimpleReduction = Options.SimpleReduction;
5452
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005453 // Next code should be emitted for reduction:
5454 //
5455 // static kmp_critical_name lock = { 0 };
5456 //
5457 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
5458 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
5459 // ...
5460 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
5461 // *(Type<n>-1*)rhs[<n>-1]);
5462 // }
5463 //
5464 // ...
5465 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
5466 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5467 // RedList, reduce_func, &<lock>)) {
5468 // case 1:
5469 // ...
5470 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5471 // ...
5472 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5473 // break;
5474 // case 2:
5475 // ...
5476 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5477 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00005478 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005479 // break;
5480 // default:;
5481 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005482 //
5483 // if SimpleReduction is true, only the next code is generated:
5484 // ...
5485 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5486 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005487
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005488 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005489
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005490 if (SimpleReduction) {
5491 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005492 auto IPriv = Privates.begin();
5493 auto ILHS = LHSExprs.begin();
5494 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005495 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005496 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5497 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005498 ++IPriv;
5499 ++ILHS;
5500 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005501 }
5502 return;
5503 }
5504
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005505 // 1. Build a list of reduction variables.
5506 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005507 auto Size = RHSExprs.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005508 for (const Expr *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005509 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005510 // Reserve place for array size.
5511 ++Size;
5512 }
5513 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005514 QualType ReductionArrayTy =
5515 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
5516 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00005517 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005518 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005519 auto IPriv = Privates.begin();
5520 unsigned Idx = 0;
5521 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00005522 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005523 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00005524 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005525 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00005526 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
5527 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005528 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005529 // Store array size.
5530 ++Idx;
5531 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
5532 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00005533 llvm::Value *Size = CGF.Builder.CreateIntCast(
5534 CGF.getVLASize(
5535 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
Sander de Smalen891af03a2018-02-03 13:55:59 +00005536 .NumElts,
Alexey Bataev1189bd02016-01-26 12:20:39 +00005537 CGF.SizeTy, /*isSigned=*/false);
5538 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
5539 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005540 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005541 }
5542
5543 // 2. Emit reduce_func().
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005544 llvm::Value *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005545 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
5546 Privates, LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005547
5548 // 3. Create static kmp_critical_name lock = { 0 };
Alexey Bataev18fa2322018-05-02 14:20:50 +00005549 std::string Name = getName({"reduction"});
5550 llvm::Value *Lock = getCriticalRegionLock(Name);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005551
5552 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5553 // RedList, reduce_func, &<lock>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005554 llvm::Value *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
5555 llvm::Value *ThreadId = getThreadID(CGF, Loc);
5556 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
5557 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Samuel Antao4c8035b2016-12-12 18:00:20 +00005558 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005559 llvm::Value *Args[] = {
5560 IdentTLoc, // ident_t *<loc>
5561 ThreadId, // i32 <gtid>
5562 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5563 ReductionArrayTySize, // size_type sizeof(RedList)
5564 RL, // void *RedList
5565 ReductionFn, // void (*) (void *, void *) <reduce_func>
5566 Lock // kmp_critical_name *&<lock>
5567 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005568 llvm::Value *Res = CGF.EmitRuntimeCall(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005569 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5570 : OMPRTL__kmpc_reduce),
5571 Args);
5572
5573 // 5. Build switch(res)
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005574 llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5575 llvm::SwitchInst *SwInst =
5576 CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005577
5578 // 6. Build case 1:
5579 // ...
5580 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5581 // ...
5582 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5583 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005584 llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005585 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5586 CGF.EmitBlock(Case1BB);
5587
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005588 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5589 llvm::Value *EndArgs[] = {
5590 IdentTLoc, // ident_t *<loc>
5591 ThreadId, // i32 <gtid>
5592 Lock // kmp_critical_name *&<lock>
5593 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005594 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps](
5595 CodeGenFunction &CGF, PrePostActionTy &Action) {
5596 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005597 auto IPriv = Privates.begin();
5598 auto ILHS = LHSExprs.begin();
5599 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005600 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005601 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5602 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005603 ++IPriv;
5604 ++ILHS;
5605 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005606 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005607 };
5608 RegionCodeGenTy RCG(CodeGen);
5609 CommonActionTy Action(
5610 nullptr, llvm::None,
5611 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5612 : OMPRTL__kmpc_end_reduce),
5613 EndArgs);
5614 RCG.setAction(Action);
5615 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005616
5617 CGF.EmitBranch(DefaultBB);
5618
5619 // 7. Build case 2:
5620 // ...
5621 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5622 // ...
5623 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005624 llvm::BasicBlock *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005625 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5626 CGF.EmitBlock(Case2BB);
5627
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005628 auto &&AtomicCodeGen = [Loc, Privates, LHSExprs, RHSExprs, ReductionOps](
5629 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005630 auto ILHS = LHSExprs.begin();
5631 auto IRHS = RHSExprs.begin();
5632 auto IPriv = Privates.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005633 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005634 const Expr *XExpr = nullptr;
5635 const Expr *EExpr = nullptr;
5636 const Expr *UpExpr = nullptr;
5637 BinaryOperatorKind BO = BO_Comma;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005638 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005639 if (BO->getOpcode() == BO_Assign) {
5640 XExpr = BO->getLHS();
5641 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005642 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005643 }
5644 // Try to emit update expression as a simple atomic.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005645 const Expr *RHSExpr = UpExpr;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005646 if (RHSExpr) {
5647 // Analyze RHS part of the whole expression.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005648 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005649 RHSExpr->IgnoreParenImpCasts())) {
5650 // If this is a conditional operator, analyze its condition for
5651 // min/max reduction operator.
5652 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005653 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005654 if (const auto *BORHS =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005655 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5656 EExpr = BORHS->getRHS();
5657 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005658 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005659 }
5660 if (XExpr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005661 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005662 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005663 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5664 const Expr *EExpr, const Expr *UpExpr) {
5665 LValue X = CGF.EmitLValue(XExpr);
5666 RValue E;
5667 if (EExpr)
5668 E = CGF.EmitAnyExpr(EExpr);
5669 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005670 X, E, BO, /*IsXLHSInRHSPart=*/true,
5671 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005672 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005673 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5674 PrivateScope.addPrivate(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005675 VD, [&CGF, VD, XRValue, Loc]() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005676 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5677 CGF.emitOMPSimpleStore(
5678 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5679 VD->getType().getNonReferenceType(), Loc);
5680 return LHSTemp;
5681 });
5682 (void)PrivateScope.Privatize();
5683 return CGF.EmitAnyExpr(UpExpr);
5684 });
5685 };
5686 if ((*IPriv)->getType()->isArrayType()) {
5687 // Emit atomic reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005688 const auto *RHSVar =
5689 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005690 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5691 AtomicRedGen, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005692 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005693 // Emit atomic reduction for array subscript or single variable.
5694 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005695 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005696 } else {
5697 // Emit as a critical region.
5698 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005699 const Expr *, const Expr *) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005700 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005701 std::string Name = RT.getName({"atomic_reduction"});
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005702 RT.emitCriticalRegion(
Alexey Bataev18fa2322018-05-02 14:20:50 +00005703 CGF, Name,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005704 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5705 Action.Enter(CGF);
5706 emitReductionCombiner(CGF, E);
5707 },
5708 Loc);
5709 };
5710 if ((*IPriv)->getType()->isArrayType()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005711 const auto *LHSVar =
5712 cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5713 const auto *RHSVar =
5714 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005715 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5716 CritRedGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005717 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005718 CritRedGen(CGF, nullptr, nullptr, nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005719 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005720 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005721 ++ILHS;
5722 ++IRHS;
5723 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005724 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005725 };
5726 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5727 if (!WithNowait) {
5728 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5729 llvm::Value *EndArgs[] = {
5730 IdentTLoc, // ident_t *<loc>
5731 ThreadId, // i32 <gtid>
5732 Lock // kmp_critical_name *&<lock>
5733 };
5734 CommonActionTy Action(nullptr, llvm::None,
5735 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5736 EndArgs);
5737 AtomicRCG.setAction(Action);
5738 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005739 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005740 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005741 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005742
5743 CGF.EmitBranch(DefaultBB);
5744 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5745}
5746
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005747/// Generates unique name for artificial threadprivate variables.
Alexey Bataev1c44e152018-03-06 18:59:43 +00005748/// Format is: <Prefix> "." <Decl_mangled_name> "_" "<Decl_start_loc_raw_enc>"
5749static std::string generateUniqueName(CodeGenModule &CGM, StringRef Prefix,
5750 const Expr *Ref) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005751 SmallString<256> Buffer;
5752 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev1c44e152018-03-06 18:59:43 +00005753 const clang::DeclRefExpr *DE;
5754 const VarDecl *D = ::getBaseDecl(Ref, DE);
5755 if (!D)
5756 D = cast<VarDecl>(cast<DeclRefExpr>(Ref)->getDecl());
5757 D = D->getCanonicalDecl();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005758 std::string Name = CGM.getOpenMPRuntime().getName(
5759 {D->isLocalVarDeclOrParm() ? D->getName() : CGM.getMangledName(D)});
5760 Out << Prefix << Name << "_"
5761 << D->getCanonicalDecl()->getLocStart().getRawEncoding();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005762 return Out.str();
5763}
5764
5765/// Emits reduction initializer function:
5766/// \code
5767/// void @.red_init(void* %arg) {
5768/// %0 = bitcast void* %arg to <type>*
5769/// store <type> <init>, <type>* %0
5770/// ret void
5771/// }
5772/// \endcode
5773static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5774 SourceLocation Loc,
5775 ReductionCodeGen &RCG, unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005776 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005777 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005778 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5779 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005780 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005781 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005782 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005783 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005784 std::string Name = CGM.getOpenMPRuntime().getName({"red_init", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005785 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005786 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005787 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005788 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005789 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005790 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005791 Address PrivateAddr = CGF.EmitLoadOfPointer(
5792 CGF.GetAddrOfLocalVar(&Param),
5793 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5794 llvm::Value *Size = nullptr;
5795 // If the size of the reduction item is non-constant, load it from global
5796 // threadprivate variable.
5797 if (RCG.getSizes(N).second) {
5798 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5799 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005800 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005801 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5802 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005803 }
5804 RCG.emitAggregateType(CGF, N, Size);
5805 LValue SharedLVal;
5806 // If initializer uses initializer from declare reduction construct, emit a
5807 // pointer to the address of the original reduction item (reuired by reduction
5808 // initializer)
5809 if (RCG.usesReductionInitializer(N)) {
5810 Address SharedAddr =
5811 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5812 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00005813 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataev21dab122018-03-09 15:20:30 +00005814 SharedAddr = CGF.EmitLoadOfPointer(
5815 SharedAddr,
5816 CGM.getContext().VoidPtrTy.castAs<PointerType>()->getTypePtr());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005817 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5818 } else {
5819 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5820 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5821 CGM.getContext().VoidPtrTy);
5822 }
5823 // Emit the initializer:
5824 // %0 = bitcast void* %arg to <type>*
5825 // store <type> <init>, <type>* %0
5826 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5827 [](CodeGenFunction &) { return false; });
5828 CGF.FinishFunction();
5829 return Fn;
5830}
5831
5832/// Emits reduction combiner function:
5833/// \code
5834/// void @.red_comb(void* %arg0, void* %arg1) {
5835/// %lhs = bitcast void* %arg0 to <type>*
5836/// %rhs = bitcast void* %arg1 to <type>*
5837/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5838/// store <type> %2, <type>* %lhs
5839/// ret void
5840/// }
5841/// \endcode
5842static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5843 SourceLocation Loc,
5844 ReductionCodeGen &RCG, unsigned N,
5845 const Expr *ReductionOp,
5846 const Expr *LHS, const Expr *RHS,
5847 const Expr *PrivateRef) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005848 ASTContext &C = CGM.getContext();
5849 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5850 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005851 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005852 ImplicitParamDecl ParamInOut(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
5853 C.VoidPtrTy, ImplicitParamDecl::Other);
5854 ImplicitParamDecl ParamIn(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5855 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005856 Args.emplace_back(&ParamInOut);
5857 Args.emplace_back(&ParamIn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005858 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005859 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005860 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005861 std::string Name = CGM.getOpenMPRuntime().getName({"red_comb", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005862 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005863 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005864 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005865 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005866 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005867 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005868 llvm::Value *Size = nullptr;
5869 // If the size of the reduction item is non-constant, load it from global
5870 // threadprivate variable.
5871 if (RCG.getSizes(N).second) {
5872 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5873 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005874 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005875 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5876 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005877 }
5878 RCG.emitAggregateType(CGF, N, Size);
5879 // Remap lhs and rhs variables to the addresses of the function arguments.
5880 // %lhs = bitcast void* %arg0 to <type>*
5881 // %rhs = bitcast void* %arg1 to <type>*
5882 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005883 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005884 // Pull out the pointer to the variable.
5885 Address PtrAddr = CGF.EmitLoadOfPointer(
5886 CGF.GetAddrOfLocalVar(&ParamInOut),
5887 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5888 return CGF.Builder.CreateElementBitCast(
5889 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
5890 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005891 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005892 // Pull out the pointer to the variable.
5893 Address PtrAddr = CGF.EmitLoadOfPointer(
5894 CGF.GetAddrOfLocalVar(&ParamIn),
5895 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5896 return CGF.Builder.CreateElementBitCast(
5897 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
5898 });
5899 PrivateScope.Privatize();
5900 // Emit the combiner body:
5901 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
5902 // store <type> %2, <type>* %lhs
5903 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
5904 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
5905 cast<DeclRefExpr>(RHS));
5906 CGF.FinishFunction();
5907 return Fn;
5908}
5909
5910/// Emits reduction finalizer function:
5911/// \code
5912/// void @.red_fini(void* %arg) {
5913/// %0 = bitcast void* %arg to <type>*
5914/// <destroy>(<type>* %0)
5915/// ret void
5916/// }
5917/// \endcode
5918static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
5919 SourceLocation Loc,
5920 ReductionCodeGen &RCG, unsigned N) {
5921 if (!RCG.needCleanups(N))
5922 return nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005923 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005924 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005925 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5926 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005927 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005928 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005929 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005930 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005931 std::string Name = CGM.getOpenMPRuntime().getName({"red_fini", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005932 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005933 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005934 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005935 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005936 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005937 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005938 Address PrivateAddr = CGF.EmitLoadOfPointer(
5939 CGF.GetAddrOfLocalVar(&Param),
5940 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5941 llvm::Value *Size = nullptr;
5942 // If the size of the reduction item is non-constant, load it from global
5943 // threadprivate variable.
5944 if (RCG.getSizes(N).second) {
5945 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5946 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005947 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005948 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5949 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005950 }
5951 RCG.emitAggregateType(CGF, N, Size);
5952 // Emit the finalizer body:
5953 // <destroy>(<type>* %0)
5954 RCG.emitCleanups(CGF, N, PrivateAddr);
5955 CGF.FinishFunction();
5956 return Fn;
5957}
5958
5959llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
5960 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
5961 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
5962 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
5963 return nullptr;
5964
5965 // Build typedef struct:
5966 // kmp_task_red_input {
5967 // void *reduce_shar; // shared reduction item
5968 // size_t reduce_size; // size of data item
5969 // void *reduce_init; // data initialization routine
5970 // void *reduce_fini; // data finalization routine
5971 // void *reduce_comb; // data combiner routine
5972 // kmp_task_red_flags_t flags; // flags for additional info from compiler
5973 // } kmp_task_red_input_t;
5974 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005975 RecordDecl *RD = C.buildImplicitRecord("kmp_task_red_input_t");
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005976 RD->startDefinition();
5977 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5978 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
5979 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5980 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5981 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5982 const FieldDecl *FlagsFD = addFieldToRecordDecl(
5983 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
5984 RD->completeDefinition();
5985 QualType RDType = C.getRecordType(RD);
5986 unsigned Size = Data.ReductionVars.size();
5987 llvm::APInt ArraySize(/*numBits=*/64, Size);
5988 QualType ArrayRDType = C.getConstantArrayType(
5989 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5990 // kmp_task_red_input_t .rd_input.[Size];
5991 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
5992 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
5993 Data.ReductionOps);
5994 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
5995 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
5996 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
5997 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
5998 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
5999 TaskRedInput.getPointer(), Idxs,
6000 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
6001 ".rd_input.gep.");
6002 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
6003 // ElemLVal.reduce_shar = &Shareds[Cnt];
6004 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
6005 RCG.emitSharedLValue(CGF, Cnt);
6006 llvm::Value *CastedShared =
6007 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
6008 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
6009 RCG.emitAggregateType(CGF, Cnt);
6010 llvm::Value *SizeValInChars;
6011 llvm::Value *SizeVal;
6012 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
6013 // We use delayed creation/initialization for VLAs, array sections and
6014 // custom reduction initializations. It is required because runtime does not
6015 // provide the way to pass the sizes of VLAs/array sections to
6016 // initializer/combiner/finalizer functions and does not pass the pointer to
6017 // original reduction item to the initializer. Instead threadprivate global
6018 // variables are used to store these values and use them in the functions.
6019 bool DelayedCreation = !!SizeVal;
6020 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
6021 /*isSigned=*/false);
6022 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
6023 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
6024 // ElemLVal.reduce_init = init;
6025 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
6026 llvm::Value *InitAddr =
6027 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
6028 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
6029 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
6030 // ElemLVal.reduce_fini = fini;
6031 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
6032 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
6033 llvm::Value *FiniAddr = Fini
6034 ? CGF.EmitCastToVoidPtr(Fini)
6035 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
6036 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
6037 // ElemLVal.reduce_comb = comb;
6038 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
6039 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
6040 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
6041 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
6042 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
6043 // ElemLVal.flags = 0;
6044 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
6045 if (DelayedCreation) {
6046 CGF.EmitStoreOfScalar(
6047 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
6048 FlagsLVal);
6049 } else
6050 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
6051 }
6052 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
6053 // *data);
6054 llvm::Value *Args[] = {
6055 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6056 /*isSigned=*/true),
6057 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
6058 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
6059 CGM.VoidPtrTy)};
6060 return CGF.EmitRuntimeCall(
6061 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
6062}
6063
6064void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
6065 SourceLocation Loc,
6066 ReductionCodeGen &RCG,
6067 unsigned N) {
6068 auto Sizes = RCG.getSizes(N);
6069 // Emit threadprivate global variable if the type is non-constant
6070 // (Sizes.second = nullptr).
6071 if (Sizes.second) {
6072 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
6073 /*isSigned=*/false);
6074 Address SizeAddr = getAddrOfArtificialThreadPrivate(
6075 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00006076 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006077 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
6078 }
6079 // Store address of the original reduction item if custom initializer is used.
6080 if (RCG.usesReductionInitializer(N)) {
6081 Address SharedAddr = getAddrOfArtificialThreadPrivate(
6082 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00006083 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006084 CGF.Builder.CreateStore(
6085 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6086 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
6087 SharedAddr, /*IsVolatile=*/false);
6088 }
6089}
6090
6091Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
6092 SourceLocation Loc,
6093 llvm::Value *ReductionsPtr,
6094 LValue SharedLVal) {
6095 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
6096 // *d);
6097 llvm::Value *Args[] = {
6098 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6099 /*isSigned=*/true),
6100 ReductionsPtr,
6101 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
6102 CGM.VoidPtrTy)};
6103 return Address(
6104 CGF.EmitRuntimeCall(
6105 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
6106 SharedLVal.getAlignment());
6107}
6108
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006109void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
6110 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006111 if (!CGF.HaveInsertPoint())
6112 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006113 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
6114 // global_tid);
6115 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
6116 // Ignore return result until untied tasks are supported.
6117 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00006118 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
6119 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006120}
6121
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006122void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006123 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006124 const RegionCodeGenTy &CodeGen,
6125 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006126 if (!CGF.HaveInsertPoint())
6127 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00006128 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006129 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00006130}
6131
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006132namespace {
6133enum RTCancelKind {
6134 CancelNoreq = 0,
6135 CancelParallel = 1,
6136 CancelLoop = 2,
6137 CancelSections = 3,
6138 CancelTaskgroup = 4
6139};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00006140} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006141
6142static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
6143 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00006144 if (CancelRegion == OMPD_parallel)
6145 CancelKind = CancelParallel;
6146 else if (CancelRegion == OMPD_for)
6147 CancelKind = CancelLoop;
6148 else if (CancelRegion == OMPD_sections)
6149 CancelKind = CancelSections;
6150 else {
6151 assert(CancelRegion == OMPD_taskgroup);
6152 CancelKind = CancelTaskgroup;
6153 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006154 return CancelKind;
6155}
6156
6157void CGOpenMPRuntime::emitCancellationPointCall(
6158 CodeGenFunction &CGF, SourceLocation Loc,
6159 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006160 if (!CGF.HaveInsertPoint())
6161 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006162 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
6163 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006164 if (auto *OMPRegionInfo =
6165 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00006166 // For 'cancellation point taskgroup', the task region info may not have a
6167 // cancel. This may instead happen in another adjacent task.
6168 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006169 llvm::Value *Args[] = {
6170 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
6171 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006172 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006173 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006174 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
6175 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006176 // exit from construct;
6177 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006178 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6179 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6180 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006181 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6182 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006183 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006184 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev25e5b442015-09-15 12:52:43 +00006185 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006186 CGF.EmitBranchThroughCleanup(CancelDest);
6187 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6188 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006189 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006190}
6191
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006192void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00006193 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006194 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006195 if (!CGF.HaveInsertPoint())
6196 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006197 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
6198 // kmp_int32 cncl_kind);
6199 if (auto *OMPRegionInfo =
6200 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006201 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
6202 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006203 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00006204 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006205 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00006206 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
6207 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006208 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006209 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00006210 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00006211 // exit from construct;
6212 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006213 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6214 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6215 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev87933c72015-09-18 08:07:34 +00006216 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6217 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00006218 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006219 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev87933c72015-09-18 08:07:34 +00006220 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
6221 CGF.EmitBranchThroughCleanup(CancelDest);
6222 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6223 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006224 if (IfCond) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006225 emitOMPIfClause(CGF, IfCond, ThenGen,
6226 [](CodeGenFunction &, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006227 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006228 RegionCodeGenTy ThenRCG(ThenGen);
6229 ThenRCG(CGF);
6230 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006231 }
6232}
Samuel Antaobed3c462015-10-02 16:14:20 +00006233
Samuel Antaoee8fb302016-01-06 13:42:12 +00006234void CGOpenMPRuntime::emitTargetOutlinedFunction(
6235 const OMPExecutableDirective &D, StringRef ParentName,
6236 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006237 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00006238 assert(!ParentName.empty() && "Invalid target region parent name!");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006239 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
6240 IsOffloadEntry, CodeGen);
6241}
6242
6243void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
6244 const OMPExecutableDirective &D, StringRef ParentName,
6245 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
6246 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00006247 // Create a unique name for the entry function using the source location
6248 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00006249 //
Samuel Antao2de62b02016-02-13 23:35:10 +00006250 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00006251 //
6252 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00006253 // mangled name of the function that encloses the target region and BB is the
6254 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00006255
6256 unsigned DeviceID;
6257 unsigned FileID;
6258 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00006259 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00006260 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006261 SmallString<64> EntryFnName;
6262 {
6263 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00006264 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
6265 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00006266 }
6267
Alexey Bataev475a7442018-01-12 19:39:11 +00006268 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006269
Samuel Antaobed3c462015-10-02 16:14:20 +00006270 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006271 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00006272 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006273
Samuel Antao6d004262016-06-16 18:39:34 +00006274 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006275
6276 // If this target outline function is not an offload entry, we don't need to
6277 // register it.
6278 if (!IsOffloadEntry)
6279 return;
6280
6281 // The target region ID is used by the runtime library to identify the current
6282 // target region, so it only has to be unique and not necessarily point to
6283 // anything. It could be the pointer to the outlined function that implements
6284 // the target region, but we aren't using that so that the compiler doesn't
6285 // need to keep that, and could therefore inline the host function if proven
6286 // worthwhile during optimization. In the other hand, if emitting code for the
6287 // device, the ID has to be the function address so that it can retrieved from
6288 // the offloading entry and launched by the runtime library. We also mark the
6289 // outlined function to have external linkage in case we are emitting code for
6290 // the device, because these functions will be entry points to the device.
6291
6292 if (CGM.getLangOpts().OpenMPIsDevice) {
6293 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
6294 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
Rafael Espindolacbca4872018-01-11 22:15:12 +00006295 OutlinedFn->setDSOLocal(false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006296 } else {
Alexey Bataev18fa2322018-05-02 14:20:50 +00006297 std::string Name = getName({"omp_offload", "region_id"});
Samuel Antaoee8fb302016-01-06 13:42:12 +00006298 OutlinedFnID = new llvm::GlobalVariable(
6299 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
6300 llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00006301 llvm::Constant::getNullValue(CGM.Int8Ty), Name);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006302 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00006303
6304 // Register the information for the entry associated with this target region.
6305 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00006306 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
Alexey Bataev03f270c2018-03-30 18:31:07 +00006307 OffloadEntriesInfoManagerTy::OMPTargetRegionEntryTargetRegion);
Samuel Antaobed3c462015-10-02 16:14:20 +00006308}
6309
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006310/// discard all CompoundStmts intervening between two constructs
6311static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006312 while (const auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006313 Body = CS->body_front();
6314
6315 return Body;
6316}
6317
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006318/// Emit the number of teams for a target directive. Inspect the num_teams
6319/// clause associated with a teams construct combined or closely nested
6320/// with the target directive.
6321///
6322/// Emit a team of size one for directives such as 'target parallel' that
6323/// have no associated teams construct.
6324///
6325/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006326static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006327emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6328 CodeGenFunction &CGF,
6329 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006330 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6331 "teams directive expected to be "
6332 "emitted only for the host!");
6333
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006334 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006335
6336 // If the target directive is combined with a teams directive:
6337 // Return the value in the num_teams clause, if any.
6338 // Otherwise, return 0 to denote the runtime default.
6339 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
6340 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
6341 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006342 llvm::Value *NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
6343 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006344 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6345 /*IsSigned=*/true);
6346 }
6347
6348 // The default value is 0.
6349 return Bld.getInt32(0);
6350 }
6351
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006352 // If the target directive is combined with a parallel directive but not a
6353 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006354 if (isOpenMPParallelDirective(D.getDirectiveKind()))
6355 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006356
6357 // If the current target region has a teams region enclosed, we need to get
6358 // the number of teams to pass to the runtime function call. This is done
6359 // by generating the expression in a inlined region. This is required because
6360 // the expression is captured in the enclosing target environment when the
6361 // teams directive is not combined with target.
6362
Alexey Bataev475a7442018-01-12 19:39:11 +00006363 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006364
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006365 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006366 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006367 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006368 if (const auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006369 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6370 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6371 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
6372 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6373 /*IsSigned=*/true);
6374 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006375
Alexey Bataev50a1c782017-12-01 21:31:08 +00006376 // If we have an enclosed teams directive but no num_teams clause we use
6377 // the default value 0.
6378 return Bld.getInt32(0);
6379 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006380 }
6381
6382 // No teams associated with the directive.
6383 return nullptr;
6384}
6385
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006386/// Emit the number of threads for a target directive. Inspect the
6387/// thread_limit clause associated with a teams construct combined or closely
6388/// nested with the target directive.
6389///
6390/// Emit the num_threads clause for directives such as 'target parallel' that
6391/// have no associated teams construct.
6392///
6393/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006394static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006395emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6396 CodeGenFunction &CGF,
6397 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006398 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6399 "teams directive expected to be "
6400 "emitted only for the host!");
6401
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006402 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006403
6404 //
6405 // If the target directive is combined with a teams directive:
6406 // Return the value in the thread_limit clause, if any.
6407 //
6408 // If the target directive is combined with a parallel directive:
6409 // Return the value in the num_threads clause, if any.
6410 //
6411 // If both clauses are set, select the minimum of the two.
6412 //
6413 // If neither teams or parallel combined directives set the number of threads
6414 // in a team, return 0 to denote the runtime default.
6415 //
6416 // If this is not a teams directive return nullptr.
6417
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006418 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
6419 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006420 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
6421 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006422 llvm::Value *ThreadLimitVal = nullptr;
6423
6424 if (const auto *ThreadLimitClause =
6425 D.getSingleClause<OMPThreadLimitClause>()) {
6426 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006427 llvm::Value *ThreadLimit =
6428 CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
6429 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006430 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6431 /*IsSigned=*/true);
6432 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006433
6434 if (const auto *NumThreadsClause =
6435 D.getSingleClause<OMPNumThreadsClause>()) {
6436 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
6437 llvm::Value *NumThreads =
6438 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
6439 /*IgnoreResultAssign*/ true);
6440 NumThreadsVal =
6441 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
6442 }
6443
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006444 // Select the lesser of thread_limit and num_threads.
6445 if (NumThreadsVal)
6446 ThreadLimitVal = ThreadLimitVal
6447 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
6448 ThreadLimitVal),
6449 NumThreadsVal, ThreadLimitVal)
6450 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00006451
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006452 // Set default value passed to the runtime if either teams or a target
6453 // parallel type directive is found but no clause is specified.
6454 if (!ThreadLimitVal)
6455 ThreadLimitVal = DefaultThreadLimitVal;
6456
6457 return ThreadLimitVal;
6458 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00006459
Samuel Antaob68e2db2016-03-03 16:20:23 +00006460 // If the current target region has a teams region enclosed, we need to get
6461 // the thread limit to pass to the runtime function call. This is done
6462 // by generating the expression in a inlined region. This is required because
6463 // the expression is captured in the enclosing target environment when the
6464 // teams directive is not combined with target.
6465
Alexey Bataev475a7442018-01-12 19:39:11 +00006466 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006467
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006468 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006469 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006470 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006471 if (const auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006472 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6473 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6474 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
6475 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6476 /*IsSigned=*/true);
6477 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006478
Alexey Bataev50a1c782017-12-01 21:31:08 +00006479 // If we have an enclosed teams directive but no thread_limit clause we
6480 // use the default value 0.
6481 return CGF.Builder.getInt32(0);
6482 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006483 }
6484
6485 // No teams associated with the directive.
6486 return nullptr;
6487}
6488
Samuel Antao86ace552016-04-27 22:40:57 +00006489namespace {
6490// \brief Utility to handle information from clauses associated with a given
6491// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
6492// It provides a convenient interface to obtain the information and generate
6493// code for that information.
6494class MappableExprsHandler {
6495public:
6496 /// \brief Values for bit flags used to specify the mapping type for
6497 /// offloading.
6498 enum OpenMPOffloadMappingFlags {
Samuel Antao86ace552016-04-27 22:40:57 +00006499 /// \brief Allocate memory on the device and move data from host to device.
6500 OMP_MAP_TO = 0x01,
6501 /// \brief Allocate memory on the device and move data from device to host.
6502 OMP_MAP_FROM = 0x02,
6503 /// \brief Always perform the requested mapping action on the element, even
6504 /// if it was already mapped before.
6505 OMP_MAP_ALWAYS = 0x04,
Samuel Antao86ace552016-04-27 22:40:57 +00006506 /// \brief Delete the element from the device environment, ignoring the
6507 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00006508 OMP_MAP_DELETE = 0x08,
George Rokos065755d2017-11-07 18:27:04 +00006509 /// \brief The element being mapped is a pointer-pointee pair; both the
6510 /// pointer and the pointee should be mapped.
6511 OMP_MAP_PTR_AND_OBJ = 0x10,
6512 /// \brief This flags signals that the base address of an entry should be
6513 /// passed to the target kernel as an argument.
6514 OMP_MAP_TARGET_PARAM = 0x20,
Samuel Antaocc10b852016-07-28 14:23:26 +00006515 /// \brief Signal that the runtime library has to return the device pointer
George Rokos065755d2017-11-07 18:27:04 +00006516 /// in the current position for the data being mapped. Used when we have the
6517 /// use_device_ptr clause.
6518 OMP_MAP_RETURN_PARAM = 0x40,
Samuel Antaod486f842016-05-26 16:53:38 +00006519 /// \brief This flag signals that the reference being passed is a pointer to
6520 /// private data.
George Rokos065755d2017-11-07 18:27:04 +00006521 OMP_MAP_PRIVATE = 0x80,
Samuel Antao86ace552016-04-27 22:40:57 +00006522 /// \brief Pass the element to the device by value.
George Rokos065755d2017-11-07 18:27:04 +00006523 OMP_MAP_LITERAL = 0x100,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006524 /// Implicit map
6525 OMP_MAP_IMPLICIT = 0x200,
Samuel Antao86ace552016-04-27 22:40:57 +00006526 };
6527
Samuel Antaocc10b852016-07-28 14:23:26 +00006528 /// Class that associates information with a base pointer to be passed to the
6529 /// runtime library.
6530 class BasePointerInfo {
6531 /// The base pointer.
6532 llvm::Value *Ptr = nullptr;
6533 /// The base declaration that refers to this device pointer, or null if
6534 /// there is none.
6535 const ValueDecl *DevPtrDecl = nullptr;
6536
6537 public:
6538 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
6539 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
6540 llvm::Value *operator*() const { return Ptr; }
6541 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
6542 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
6543 };
6544
6545 typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00006546 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
George Rokos63bc9d62017-11-21 18:25:12 +00006547 typedef SmallVector<uint64_t, 16> MapFlagsArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00006548
6549private:
6550 /// \brief Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00006551 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00006552
6553 /// \brief Function the directive is being generated for.
6554 CodeGenFunction &CGF;
6555
Samuel Antaod486f842016-05-26 16:53:38 +00006556 /// \brief Set of all first private variables in the current directive.
6557 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
Alexey Bataev3f96fe62017-12-13 17:31:39 +00006558 /// Set of all reduction variables in the current directive.
6559 llvm::SmallPtrSet<const VarDecl *, 8> ReductionDecls;
Samuel Antaod486f842016-05-26 16:53:38 +00006560
Samuel Antao6890b092016-07-28 14:25:09 +00006561 /// Map between device pointer declarations and their expression components.
6562 /// The key value for declarations in 'this' is null.
6563 llvm::DenseMap<
6564 const ValueDecl *,
6565 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6566 DevPointersMap;
6567
Samuel Antao86ace552016-04-27 22:40:57 +00006568 llvm::Value *getExprTypeSize(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006569 QualType ExprTy = E->getType().getCanonicalType();
Samuel Antao86ace552016-04-27 22:40:57 +00006570
6571 // Reference types are ignored for mapping purposes.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006572 if (const auto *RefTy = ExprTy->getAs<ReferenceType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006573 ExprTy = RefTy->getPointeeType().getCanonicalType();
6574
6575 // Given that an array section is considered a built-in type, we need to
6576 // do the calculation based on the length of the section instead of relying
6577 // on CGF.getTypeSize(E->getType()).
6578 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6579 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6580 OAE->getBase()->IgnoreParenImpCasts())
6581 .getCanonicalType();
6582
6583 // If there is no length associated with the expression, that means we
6584 // are using the whole length of the base.
6585 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6586 return CGF.getTypeSize(BaseTy);
6587
6588 llvm::Value *ElemSize;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006589 if (const auto *PTy = BaseTy->getAs<PointerType>()) {
Samuel Antao86ace552016-04-27 22:40:57 +00006590 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006591 } else {
6592 const auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
Samuel Antao86ace552016-04-27 22:40:57 +00006593 assert(ATy && "Expecting array type if not a pointer type.");
6594 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6595 }
6596
6597 // If we don't have a length at this point, that is because we have an
6598 // array section with a single element.
6599 if (!OAE->getLength())
6600 return ElemSize;
6601
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006602 llvm::Value *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
Samuel Antao86ace552016-04-27 22:40:57 +00006603 LengthVal =
6604 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6605 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6606 }
6607 return CGF.getTypeSize(ExprTy);
6608 }
6609
6610 /// \brief Return the corresponding bits for a given map clause modifier. Add
6611 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006612 /// map as the first one of a series of maps that relate to the same map
6613 /// expression.
George Rokos63bc9d62017-11-21 18:25:12 +00006614 uint64_t getMapTypeBits(OpenMPMapClauseKind MapType,
Samuel Antao86ace552016-04-27 22:40:57 +00006615 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
George Rokos065755d2017-11-07 18:27:04 +00006616 bool AddIsTargetParamFlag) const {
George Rokos63bc9d62017-11-21 18:25:12 +00006617 uint64_t Bits = 0u;
Samuel Antao86ace552016-04-27 22:40:57 +00006618 switch (MapType) {
6619 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006620 case OMPC_MAP_release:
6621 // alloc and release is the default behavior in the runtime library, i.e.
6622 // if we don't pass any bits alloc/release that is what the runtime is
6623 // going to do. Therefore, we don't need to signal anything for these two
6624 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006625 break;
6626 case OMPC_MAP_to:
6627 Bits = OMP_MAP_TO;
6628 break;
6629 case OMPC_MAP_from:
6630 Bits = OMP_MAP_FROM;
6631 break;
6632 case OMPC_MAP_tofrom:
6633 Bits = OMP_MAP_TO | OMP_MAP_FROM;
6634 break;
6635 case OMPC_MAP_delete:
6636 Bits = OMP_MAP_DELETE;
6637 break;
Samuel Antao86ace552016-04-27 22:40:57 +00006638 default:
6639 llvm_unreachable("Unexpected map type!");
6640 break;
6641 }
6642 if (AddPtrFlag)
George Rokos065755d2017-11-07 18:27:04 +00006643 Bits |= OMP_MAP_PTR_AND_OBJ;
6644 if (AddIsTargetParamFlag)
6645 Bits |= OMP_MAP_TARGET_PARAM;
Samuel Antao86ace552016-04-27 22:40:57 +00006646 if (MapTypeModifier == OMPC_MAP_always)
6647 Bits |= OMP_MAP_ALWAYS;
6648 return Bits;
6649 }
6650
6651 /// \brief Return true if the provided expression is a final array section. A
6652 /// final array section, is one whose length can't be proved to be one.
6653 bool isFinalArraySectionExpression(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006654 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antao86ace552016-04-27 22:40:57 +00006655
6656 // It is not an array section and therefore not a unity-size one.
6657 if (!OASE)
6658 return false;
6659
6660 // An array section with no colon always refer to a single element.
6661 if (OASE->getColonLoc().isInvalid())
6662 return false;
6663
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006664 const Expr *Length = OASE->getLength();
Samuel Antao86ace552016-04-27 22:40:57 +00006665
6666 // If we don't have a length we have to check if the array has size 1
6667 // for this dimension. Also, we should always expect a length if the
6668 // base type is pointer.
6669 if (!Length) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006670 QualType BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6671 OASE->getBase()->IgnoreParenImpCasts())
6672 .getCanonicalType();
6673 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antao86ace552016-04-27 22:40:57 +00006674 return ATy->getSize().getSExtValue() != 1;
6675 // If we don't have a constant dimension length, we have to consider
6676 // the current section as having any size, so it is not necessarily
6677 // unitary. If it happen to be unity size, that's user fault.
6678 return true;
6679 }
6680
6681 // Check if the length evaluates to 1.
6682 llvm::APSInt ConstLength;
6683 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
6684 return true; // Can have more that size 1.
6685
6686 return ConstLength.getSExtValue() != 1;
6687 }
6688
Alexey Bataev92327c52018-03-26 16:40:55 +00006689 /// \brief Return the adjusted map modifiers if the declaration a capture
6690 /// refers to appears in a first-private clause. This is expected to be used
6691 /// only with directives that start with 'target'.
6692 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
6693 unsigned CurrentModifiers) {
6694 assert(Cap.capturesVariable() && "Expected capture by reference only!");
6695
6696 // A first private variable captured by reference will use only the
6697 // 'private ptr' and 'map to' flag. Return the right flags if the captured
6698 // declaration is known as first-private in this handler.
6699 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
6700 return MappableExprsHandler::OMP_MAP_PRIVATE |
6701 MappableExprsHandler::OMP_MAP_TO;
6702 // Reduction variable will use only the 'private ptr' and 'map to_from'
6703 // flag.
6704 if (ReductionDecls.count(Cap.getCapturedVar())) {
6705 return MappableExprsHandler::OMP_MAP_TO |
6706 MappableExprsHandler::OMP_MAP_FROM;
6707 }
6708
6709 // We didn't modify anything.
6710 return CurrentModifiers;
6711 }
6712
6713public:
6714 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
6715 : CurDir(Dir), CGF(CGF) {
6716 // Extract firstprivate clause information.
6717 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006718 for (const Expr *D : C->varlists())
Alexey Bataev92327c52018-03-26 16:40:55 +00006719 FirstPrivateDecls.insert(
6720 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
6721 for (const auto *C : Dir.getClausesOfKind<OMPReductionClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006722 for (const Expr *D : C->varlists()) {
Alexey Bataev92327c52018-03-26 16:40:55 +00006723 ReductionDecls.insert(
6724 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
6725 }
6726 }
6727 // Extract device pointer clause information.
6728 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006729 for (const auto &L : C->component_lists())
Alexey Bataev92327c52018-03-26 16:40:55 +00006730 DevPointersMap[L.first].push_back(L.second);
6731 }
6732
Samuel Antao86ace552016-04-27 22:40:57 +00006733 /// \brief Generate the base pointers, section pointers, sizes and map type
6734 /// bits for the provided map type, map modifier, and expression components.
6735 /// \a IsFirstComponent should be set to true if the provided set of
6736 /// components is the first associated with a capture.
6737 void generateInfoForComponentList(
6738 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6739 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006740 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006741 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006742 bool IsFirstComponentList, bool IsImplicit) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006743
6744 // The following summarizes what has to be generated for each map and the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006745 // types below. The generated information is expressed in this order:
Samuel Antao86ace552016-04-27 22:40:57 +00006746 // base pointer, section pointer, size, flags
6747 // (to add to the ones that come from the map type and modifier).
6748 //
6749 // double d;
6750 // int i[100];
6751 // float *p;
6752 //
6753 // struct S1 {
6754 // int i;
6755 // float f[50];
6756 // }
6757 // struct S2 {
6758 // int i;
6759 // float f[50];
6760 // S1 s;
6761 // double *p;
6762 // struct S2 *ps;
6763 // }
6764 // S2 s;
6765 // S2 *ps;
6766 //
6767 // map(d)
6768 // &d, &d, sizeof(double), noflags
6769 //
6770 // map(i)
6771 // &i, &i, 100*sizeof(int), noflags
6772 //
6773 // map(i[1:23])
6774 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
6775 //
6776 // map(p)
6777 // &p, &p, sizeof(float*), noflags
6778 //
6779 // map(p[1:24])
6780 // p, &p[1], 24*sizeof(float), noflags
6781 //
6782 // map(s)
6783 // &s, &s, sizeof(S2), noflags
6784 //
6785 // map(s.i)
6786 // &s, &(s.i), sizeof(int), noflags
6787 //
6788 // map(s.s.f)
6789 // &s, &(s.i.f), 50*sizeof(int), noflags
6790 //
6791 // map(s.p)
6792 // &s, &(s.p), sizeof(double*), noflags
6793 //
6794 // map(s.p[:22], s.a s.b)
6795 // &s, &(s.p), sizeof(double*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006796 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006797 //
6798 // map(s.ps)
6799 // &s, &(s.ps), sizeof(S2*), noflags
6800 //
6801 // map(s.ps->s.i)
6802 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006803 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006804 //
6805 // map(s.ps->ps)
6806 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006807 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006808 //
6809 // map(s.ps->ps->ps)
6810 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006811 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
6812 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006813 //
6814 // map(s.ps->ps->s.f[:22])
6815 // &s, &(s.ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006816 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag
6817 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006818 //
6819 // map(ps)
6820 // &ps, &ps, sizeof(S2*), noflags
6821 //
6822 // map(ps->i)
6823 // ps, &(ps->i), sizeof(int), noflags
6824 //
6825 // map(ps->s.f)
6826 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
6827 //
6828 // map(ps->p)
6829 // ps, &(ps->p), sizeof(double*), noflags
6830 //
6831 // map(ps->p[:22])
6832 // ps, &(ps->p), sizeof(double*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006833 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006834 //
6835 // map(ps->ps)
6836 // ps, &(ps->ps), sizeof(S2*), noflags
6837 //
6838 // map(ps->ps->s.i)
6839 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006840 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006841 //
6842 // map(ps->ps->ps)
6843 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006844 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006845 //
6846 // map(ps->ps->ps->ps)
6847 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006848 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
6849 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006850 //
6851 // map(ps->ps->ps->s.f[:22])
6852 // ps, &(ps->ps), sizeof(S2*), noflags
George Rokos065755d2017-11-07 18:27:04 +00006853 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag
6854 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag
Samuel Antao86ace552016-04-27 22:40:57 +00006855
6856 // Track if the map information being generated is the first for a capture.
6857 bool IsCaptureFirstInfo = IsFirstComponentList;
Alexey Bataev92327c52018-03-26 16:40:55 +00006858 bool IsLink = false; // Is this variable a "declare target link"?
Samuel Antao86ace552016-04-27 22:40:57 +00006859
6860 // Scan the components from the base to the complete expression.
6861 auto CI = Components.rbegin();
6862 auto CE = Components.rend();
6863 auto I = CI;
6864
6865 // Track if the map information being generated is the first for a list of
6866 // components.
6867 bool IsExpressionFirstInfo = true;
6868 llvm::Value *BP = nullptr;
6869
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006870 if (const auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
Samuel Antao86ace552016-04-27 22:40:57 +00006871 // The base is the 'this' pointer. The content of the pointer is going
6872 // to be the base of the field being mapped.
6873 BP = CGF.EmitScalarExpr(ME->getBase());
6874 } else {
6875 // The base is the reference to the variable.
6876 // BP = &Var.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006877 BP = CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Alexey Bataev92327c52018-03-26 16:40:55 +00006878 if (const auto *VD =
6879 dyn_cast_or_null<VarDecl>(I->getAssociatedDeclaration())) {
6880 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev2c1dffe2018-04-16 20:34:41 +00006881 isDeclareTargetDeclaration(VD))
6882 if (*Res == OMPDeclareTargetDeclAttr::MT_Link) {
6883 IsLink = true;
6884 BP = CGF.CGM.getOpenMPRuntime()
6885 .getAddrOfDeclareTargetLink(VD)
6886 .getPointer();
6887 }
Alexey Bataev92327c52018-03-26 16:40:55 +00006888 }
Samuel Antao86ace552016-04-27 22:40:57 +00006889
6890 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00006891 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00006892 // reference. References are ignored for mapping purposes.
6893 QualType Ty =
6894 I->getAssociatedDeclaration()->getType().getNonReferenceType();
6895 if (Ty->isAnyPointerType() && std::next(I) != CE) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006896 LValue PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
Samuel Antao86ace552016-04-27 22:40:57 +00006897 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
Samuel Antao403ffd42016-07-27 22:49:49 +00006898 Ty->castAs<PointerType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006899 .getPointer();
6900
6901 // We do not need to generate individual map information for the
6902 // pointer, it can be associated with the combined storage.
6903 ++I;
6904 }
6905 }
6906
George Rokos63bc9d62017-11-21 18:25:12 +00006907 uint64_t DefaultFlags = IsImplicit ? OMP_MAP_IMPLICIT : 0;
Samuel Antao86ace552016-04-27 22:40:57 +00006908 for (; I != CE; ++I) {
6909 auto Next = std::next(I);
6910
6911 // We need to generate the addresses and sizes if this is the last
6912 // component, if the component is a pointer or if it is an array section
6913 // whose length can't be proved to be one. If this is a pointer, it
6914 // becomes the base address for the following components.
6915
6916 // A final array section, is one whose length can't be proved to be one.
6917 bool IsFinalArraySection =
6918 isFinalArraySectionExpression(I->getAssociatedExpression());
6919
6920 // Get information on whether the element is a pointer. Have to do a
6921 // special treatment for array sections given that they are built-in
6922 // types.
6923 const auto *OASE =
6924 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
6925 bool IsPointer =
6926 (OASE &&
6927 OMPArraySectionExpr::getBaseOriginalType(OASE)
6928 .getCanonicalType()
6929 ->isAnyPointerType()) ||
6930 I->getAssociatedExpression()->getType()->isAnyPointerType();
6931
6932 if (Next == CE || IsPointer || IsFinalArraySection) {
Samuel Antao86ace552016-04-27 22:40:57 +00006933 // If this is not the last component, we expect the pointer to be
6934 // associated with an array expression or member expression.
6935 assert((Next == CE ||
6936 isa<MemberExpr>(Next->getAssociatedExpression()) ||
6937 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
6938 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
6939 "Unexpected expression");
6940
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006941 llvm::Value *LB =
6942 CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getPointer();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006943 llvm::Value *Size = getExprTypeSize(I->getAssociatedExpression());
Samuel Antao86ace552016-04-27 22:40:57 +00006944
Samuel Antao03a3cec2016-07-27 22:52:16 +00006945 // If we have a member expression and the current component is a
6946 // reference, we have to map the reference too. Whenever we have a
6947 // reference, the section that reference refers to is going to be a
6948 // load instruction from the storage assigned to the reference.
6949 if (isa<MemberExpr>(I->getAssociatedExpression()) &&
6950 I->getAssociatedDeclaration()->getType()->isReferenceType()) {
6951 auto *LI = cast<llvm::LoadInst>(LB);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006952 llvm::Value *RefAddr = LI->getPointerOperand();
Samuel Antao03a3cec2016-07-27 22:52:16 +00006953
6954 BasePointers.push_back(BP);
6955 Pointers.push_back(RefAddr);
6956 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006957 Types.push_back(DefaultFlags |
6958 getMapTypeBits(
6959 /*MapType*/ OMPC_MAP_alloc,
6960 /*MapTypeModifier=*/OMPC_MAP_unknown,
6961 !IsExpressionFirstInfo, IsCaptureFirstInfo));
Samuel Antao03a3cec2016-07-27 22:52:16 +00006962 IsExpressionFirstInfo = false;
6963 IsCaptureFirstInfo = false;
6964 // The reference will be the next base address.
6965 BP = RefAddr;
6966 }
6967
6968 BasePointers.push_back(BP);
Samuel Antao86ace552016-04-27 22:40:57 +00006969 Pointers.push_back(LB);
6970 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00006971
Samuel Antao6782e942016-05-26 16:48:10 +00006972 // We need to add a pointer flag for each map that comes from the
6973 // same expression except for the first one. We also need to signal
6974 // this map is the first one that relates with the current capture
6975 // (there is a set of entries for each capture).
Alexey Bataev92327c52018-03-26 16:40:55 +00006976 Types.push_back(DefaultFlags |
6977 getMapTypeBits(MapType, MapTypeModifier,
6978 !IsExpressionFirstInfo || IsLink,
6979 IsCaptureFirstInfo && !IsLink));
Samuel Antao86ace552016-04-27 22:40:57 +00006980
6981 // If we have a final array section, we are done with this expression.
6982 if (IsFinalArraySection)
6983 break;
6984
6985 // The pointer becomes the base for the next element.
6986 if (Next != CE)
6987 BP = LB;
6988
6989 IsExpressionFirstInfo = false;
6990 IsCaptureFirstInfo = false;
Samuel Antao86ace552016-04-27 22:40:57 +00006991 }
6992 }
6993 }
6994
Samuel Antao86ace552016-04-27 22:40:57 +00006995 /// \brief Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00006996 /// types for the extracted mappable expressions. Also, for each item that
6997 /// relates with a device pointer, a pair of the relevant declaration and
6998 /// index where it occurs is appended to the device pointers info array.
6999 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007000 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7001 MapFlagsArrayTy &Types) const {
7002 BasePointers.clear();
7003 Pointers.clear();
7004 Sizes.clear();
7005 Types.clear();
7006
7007 struct MapInfo {
Samuel Antaocc10b852016-07-28 14:23:26 +00007008 /// Kind that defines how a device pointer has to be returned.
7009 enum ReturnPointerKind {
7010 // Don't have to return any pointer.
7011 RPK_None,
7012 // Pointer is the base of the declaration.
7013 RPK_Base,
7014 // Pointer is a member of the base declaration - 'this'
7015 RPK_Member,
7016 // Pointer is a reference and a member of the base declaration - 'this'
7017 RPK_MemberReference,
7018 };
Samuel Antao86ace552016-04-27 22:40:57 +00007019 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007020 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
7021 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
7022 ReturnPointerKind ReturnDevicePointer = RPK_None;
7023 bool IsImplicit = false;
Hans Wennborgbc1b58d2016-07-30 00:41:37 +00007024
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007025 MapInfo() = default;
Samuel Antaocc10b852016-07-28 14:23:26 +00007026 MapInfo(
7027 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
7028 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007029 ReturnPointerKind ReturnDevicePointer, bool IsImplicit)
Samuel Antaocc10b852016-07-28 14:23:26 +00007030 : Components(Components), MapType(MapType),
7031 MapTypeModifier(MapTypeModifier),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007032 ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
Samuel Antao86ace552016-04-27 22:40:57 +00007033 };
7034
7035 // We have to process the component lists that relate with the same
7036 // declaration in a single chunk so that we can generate the map flags
7037 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00007038 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00007039
7040 // Helper function to fill the information map for the different supported
7041 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00007042 auto &&InfoGen = [&Info](
7043 const ValueDecl *D,
7044 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
7045 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007046 MapInfo::ReturnPointerKind ReturnDevicePointer, bool IsImplicit) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007047 const ValueDecl *VD =
7048 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007049 Info[VD].emplace_back(L, MapType, MapModifier, ReturnDevicePointer,
7050 IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007051 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00007052
Paul Robinson78fb1322016-08-01 22:12:46 +00007053 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007054 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
7055 for (const auto &L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00007056 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007057 MapInfo::RPK_None, C->isImplicit());
7058 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007059 for (const auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
7060 for (const auto &L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00007061 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007062 MapInfo::RPK_None, C->isImplicit());
7063 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007064 for (const auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
7065 for (const auto &L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00007066 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007067 MapInfo::RPK_None, C->isImplicit());
7068 }
Samuel Antao86ace552016-04-27 22:40:57 +00007069
Samuel Antaocc10b852016-07-28 14:23:26 +00007070 // Look at the use_device_ptr clause information and mark the existing map
7071 // entries as such. If there is no map information for an entry in the
7072 // use_device_ptr list, we create one with map type 'alloc' and zero size
7073 // section. It is the user fault if that was not mapped before.
Paul Robinson78fb1322016-08-01 22:12:46 +00007074 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007075 for (const auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
7076 for (const auto &L : C->component_lists()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007077 assert(!L.second.empty() && "Not expecting empty list of components!");
7078 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
7079 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007080 const Expr *IE = L.second.back().getAssociatedExpression();
Samuel Antaocc10b852016-07-28 14:23:26 +00007081 // If the first component is a member expression, we have to look into
7082 // 'this', which maps to null in the map of map information. Otherwise
7083 // look directly for the information.
7084 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
7085
7086 // We potentially have map information for this declaration already.
7087 // Look for the first set of components that refer to it.
7088 if (It != Info.end()) {
7089 auto CI = std::find_if(
7090 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
7091 return MI.Components.back().getAssociatedDeclaration() == VD;
7092 });
7093 // If we found a map entry, signal that the pointer has to be returned
7094 // and move on to the next declaration.
7095 if (CI != It->second.end()) {
7096 CI->ReturnDevicePointer = isa<MemberExpr>(IE)
7097 ? (VD->getType()->isReferenceType()
7098 ? MapInfo::RPK_MemberReference
7099 : MapInfo::RPK_Member)
7100 : MapInfo::RPK_Base;
7101 continue;
7102 }
7103 }
7104
7105 // We didn't find any match in our map information - generate a zero
7106 // size array section.
Paul Robinson78fb1322016-08-01 22:12:46 +00007107 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Alexey Bataev1e491372018-01-23 18:44:14 +00007108 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(this->CGF.EmitLValue(IE),
7109 IE->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +00007110 BasePointers.push_back({Ptr, VD});
7111 Pointers.push_back(Ptr);
Paul Robinson15c84002016-07-29 20:46:16 +00007112 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
George Rokos065755d2017-11-07 18:27:04 +00007113 Types.push_back(OMP_MAP_RETURN_PARAM | OMP_MAP_TARGET_PARAM);
Samuel Antaocc10b852016-07-28 14:23:26 +00007114 }
7115
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007116 for (const auto &M : Info) {
Samuel Antao86ace552016-04-27 22:40:57 +00007117 // We need to know when we generate information for the first component
7118 // associated with a capture, because the mapping flags depend on it.
7119 bool IsFirstComponentList = true;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007120 for (const MapInfo &L : M.second) {
Samuel Antao86ace552016-04-27 22:40:57 +00007121 assert(!L.Components.empty() &&
7122 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00007123
7124 // Remember the current base pointer index.
7125 unsigned CurrentBasePointersIdx = BasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00007126 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007127 this->generateInfoForComponentList(
7128 L.MapType, L.MapTypeModifier, L.Components, BasePointers, Pointers,
7129 Sizes, Types, IsFirstComponentList, L.IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007130
7131 // If this entry relates with a device pointer, set the relevant
7132 // declaration and add the 'return pointer' flag.
7133 if (IsFirstComponentList &&
7134 L.ReturnDevicePointer != MapInfo::RPK_None) {
7135 // If the pointer is not the base of the map, we need to skip the
7136 // base. If it is a reference in a member field, we also need to skip
7137 // the map of the reference.
7138 if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
7139 ++CurrentBasePointersIdx;
7140 if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
7141 ++CurrentBasePointersIdx;
7142 }
7143 assert(BasePointers.size() > CurrentBasePointersIdx &&
7144 "Unexpected number of mapped base pointers.");
7145
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007146 const ValueDecl *RelevantVD =
7147 L.Components.back().getAssociatedDeclaration();
Samuel Antaocc10b852016-07-28 14:23:26 +00007148 assert(RelevantVD &&
7149 "No relevant declaration related with device pointer??");
7150
7151 BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
George Rokos065755d2017-11-07 18:27:04 +00007152 Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PARAM;
Samuel Antaocc10b852016-07-28 14:23:26 +00007153 }
Samuel Antao86ace552016-04-27 22:40:57 +00007154 IsFirstComponentList = false;
7155 }
7156 }
7157 }
7158
7159 /// \brief Generate the base pointers, section pointers, sizes and map types
7160 /// associated to a given capture.
7161 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00007162 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007163 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007164 MapValuesArrayTy &Pointers,
7165 MapValuesArrayTy &Sizes,
7166 MapFlagsArrayTy &Types) const {
7167 assert(!Cap->capturesVariableArrayType() &&
7168 "Not expecting to generate map info for a variable array type!");
7169
7170 BasePointers.clear();
7171 Pointers.clear();
7172 Sizes.clear();
7173 Types.clear();
7174
Samuel Antao6890b092016-07-28 14:25:09 +00007175 // We need to know when we generating information for the first component
7176 // associated with a capture, because the mapping flags depend on it.
7177 bool IsFirstComponentList = true;
7178
Samuel Antao86ace552016-04-27 22:40:57 +00007179 const ValueDecl *VD =
7180 Cap->capturesThis()
7181 ? nullptr
George Burgess IV00f70bd2018-03-01 05:43:23 +00007182 : Cap->getCapturedVar()->getCanonicalDecl();
Samuel Antao86ace552016-04-27 22:40:57 +00007183
Samuel Antao6890b092016-07-28 14:25:09 +00007184 // If this declaration appears in a is_device_ptr clause we just have to
7185 // pass the pointer by value. If it is a reference to a declaration, we just
7186 // pass its value, otherwise, if it is a member expression, we need to map
7187 // 'to' the field.
7188 if (!VD) {
7189 auto It = DevPointersMap.find(VD);
7190 if (It != DevPointersMap.end()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007191 for (ArrayRef<OMPClauseMappableExprCommon::MappableComponent> L :
7192 It->second) {
Samuel Antao6890b092016-07-28 14:25:09 +00007193 generateInfoForComponentList(
7194 /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007195 BasePointers, Pointers, Sizes, Types, IsFirstComponentList,
7196 /*IsImplicit=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +00007197 IsFirstComponentList = false;
7198 }
7199 return;
7200 }
7201 } else if (DevPointersMap.count(VD)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007202 BasePointers.emplace_back(Arg, VD);
Samuel Antao6890b092016-07-28 14:25:09 +00007203 Pointers.push_back(Arg);
7204 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
George Rokos065755d2017-11-07 18:27:04 +00007205 Types.push_back(OMP_MAP_LITERAL | OMP_MAP_TARGET_PARAM);
Samuel Antao6890b092016-07-28 14:25:09 +00007206 return;
7207 }
7208
Paul Robinson78fb1322016-08-01 22:12:46 +00007209 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007210 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
7211 for (const auto &L : C->decl_component_lists(VD)) {
Samuel Antao86ace552016-04-27 22:40:57 +00007212 assert(L.first == VD &&
7213 "We got information for the wrong declaration??");
7214 assert(!L.second.empty() &&
7215 "Not expecting declaration with no component lists.");
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007216 generateInfoForComponentList(
7217 C->getMapType(), C->getMapTypeModifier(), L.second, BasePointers,
7218 Pointers, Sizes, Types, IsFirstComponentList, C->isImplicit());
Samuel Antao86ace552016-04-27 22:40:57 +00007219 IsFirstComponentList = false;
7220 }
7221
7222 return;
7223 }
Samuel Antaod486f842016-05-26 16:53:38 +00007224
7225 /// \brief Generate the default map information for a given capture \a CI,
7226 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00007227 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
7228 const FieldDecl &RI, llvm::Value *CV,
7229 MapBaseValuesArrayTy &CurBasePointers,
7230 MapValuesArrayTy &CurPointers,
7231 MapValuesArrayTy &CurSizes,
7232 MapFlagsArrayTy &CurMapTypes) {
Samuel Antaod486f842016-05-26 16:53:38 +00007233
7234 // Do the default mapping.
7235 if (CI.capturesThis()) {
7236 CurBasePointers.push_back(CV);
7237 CurPointers.push_back(CV);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007238 const auto *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007239 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
7240 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00007241 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00007242 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007243 CurBasePointers.push_back(CV);
7244 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00007245 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007246 // We have to signal to the runtime captures passed by value that are
7247 // not pointers.
George Rokos065755d2017-11-07 18:27:04 +00007248 CurMapTypes.push_back(OMP_MAP_LITERAL);
Samuel Antaod486f842016-05-26 16:53:38 +00007249 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
7250 } else {
7251 // Pointers are implicitly mapped with a zero size and no flags
7252 // (other than first map that is added for all implicit maps).
7253 CurMapTypes.push_back(0u);
Samuel Antaod486f842016-05-26 16:53:38 +00007254 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
7255 }
7256 } else {
7257 assert(CI.capturesVariable() && "Expected captured reference.");
7258 CurBasePointers.push_back(CV);
7259 CurPointers.push_back(CV);
7260
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007261 const auto *PtrTy = cast<ReferenceType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007262 QualType ElementType = PtrTy->getPointeeType();
7263 CurSizes.push_back(CGF.getTypeSize(ElementType));
7264 // The default map type for a scalar/complex type is 'to' because by
7265 // default the value doesn't have to be retrieved. For an aggregate
7266 // type, the default is 'tofrom'.
Alexey Bataev3f96fe62017-12-13 17:31:39 +00007267 CurMapTypes.emplace_back(adjustMapModifiersForPrivateClauses(
7268 CI, ElementType->isAggregateType() ? (OMP_MAP_TO | OMP_MAP_FROM)
7269 : OMP_MAP_TO));
Samuel Antaod486f842016-05-26 16:53:38 +00007270 }
George Rokos065755d2017-11-07 18:27:04 +00007271 // Every default map produces a single argument which is a target parameter.
7272 CurMapTypes.back() |= OMP_MAP_TARGET_PARAM;
Samuel Antaod486f842016-05-26 16:53:38 +00007273 }
Samuel Antao86ace552016-04-27 22:40:57 +00007274};
Samuel Antaodf158d52016-04-27 22:58:19 +00007275
7276enum OpenMPOffloadingReservedDeviceIDs {
7277 /// \brief Device ID if the device was not defined, runtime should get it
7278 /// from environment variables in the spec.
7279 OMP_DEVICEID_UNDEF = -1,
7280};
7281} // anonymous namespace
7282
7283/// \brief Emit the arrays used to pass the captures and map information to the
7284/// offloading runtime library. If there is no map or capture information,
7285/// return nullptr by reference.
7286static void
Samuel Antaocc10b852016-07-28 14:23:26 +00007287emitOffloadingArrays(CodeGenFunction &CGF,
7288 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00007289 MappableExprsHandler::MapValuesArrayTy &Pointers,
7290 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00007291 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
7292 CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007293 CodeGenModule &CGM = CGF.CGM;
7294 ASTContext &Ctx = CGF.getContext();
Samuel Antaodf158d52016-04-27 22:58:19 +00007295
Samuel Antaocc10b852016-07-28 14:23:26 +00007296 // Reset the array information.
7297 Info.clearArrayInfo();
7298 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00007299
Samuel Antaocc10b852016-07-28 14:23:26 +00007300 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007301 // Detect if we have any capture size requiring runtime evaluation of the
7302 // size so that a constant array could be eventually used.
7303 bool hasRuntimeEvaluationCaptureSize = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007304 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00007305 if (!isa<llvm::Constant>(S)) {
7306 hasRuntimeEvaluationCaptureSize = true;
7307 break;
7308 }
7309
Samuel Antaocc10b852016-07-28 14:23:26 +00007310 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00007311 QualType PointerArrayType =
7312 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
7313 /*IndexTypeQuals=*/0);
7314
Samuel Antaocc10b852016-07-28 14:23:26 +00007315 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007316 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00007317 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007318 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
7319
7320 // If we don't have any VLA types or other types that require runtime
7321 // evaluation, we can use a constant array for the map sizes, otherwise we
7322 // need to fill up the arrays as we do for the pointers.
7323 if (hasRuntimeEvaluationCaptureSize) {
7324 QualType SizeArrayType = Ctx.getConstantArrayType(
7325 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
7326 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00007327 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007328 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
7329 } else {
7330 // We expect all the sizes to be constant, so we collect them to create
7331 // a constant array.
7332 SmallVector<llvm::Constant *, 16> ConstSizes;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007333 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00007334 ConstSizes.push_back(cast<llvm::Constant>(S));
7335
7336 auto *SizesArrayInit = llvm::ConstantArray::get(
7337 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
Alexey Bataev18fa2322018-05-02 14:20:50 +00007338 std::string Name = CGM.getOpenMPRuntime().getName({"offload_sizes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00007339 auto *SizesArrayGbl = new llvm::GlobalVariable(
7340 CGM.getModule(), SizesArrayInit->getType(),
7341 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00007342 SizesArrayInit, Name);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00007343 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00007344 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00007345 }
7346
7347 // The map types are always constant so we don't need to generate code to
7348 // fill arrays. Instead, we create an array constant.
7349 llvm::Constant *MapTypesArrayInit =
7350 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
Alexey Bataev18fa2322018-05-02 14:20:50 +00007351 std::string MaptypesName =
7352 CGM.getOpenMPRuntime().getName({"offload_maptypes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00007353 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
7354 CGM.getModule(), MapTypesArrayInit->getType(),
7355 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00007356 MapTypesArrayInit, MaptypesName);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00007357 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00007358 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00007359
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007360 for (unsigned I = 0; I < Info.NumberOfPtrs; ++I) {
7361 llvm::Value *BPVal = *BasePointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00007362 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007363 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007364 Info.BasePointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00007365 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7366 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00007367 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
7368 CGF.Builder.CreateStore(BPVal, BPAddr);
7369
Samuel Antaocc10b852016-07-28 14:23:26 +00007370 if (Info.requiresDevicePointerInfo())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007371 if (const ValueDecl *DevVD = BasePointers[I].getDevicePtrDecl())
Alexey Bataev43a919f2018-04-13 17:48:43 +00007372 Info.CaptureDeviceAddrMap.try_emplace(DevVD, BPAddr);
Samuel Antaocc10b852016-07-28 14:23:26 +00007373
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007374 llvm::Value *PVal = Pointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00007375 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007376 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007377 Info.PointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00007378 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7379 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00007380 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
7381 CGF.Builder.CreateStore(PVal, PAddr);
7382
7383 if (hasRuntimeEvaluationCaptureSize) {
7384 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007385 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
7386 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007387 /*Idx0=*/0,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007388 /*Idx1=*/I);
Samuel Antaodf158d52016-04-27 22:58:19 +00007389 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
7390 CGF.Builder.CreateStore(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007391 CGF.Builder.CreateIntCast(Sizes[I], CGM.SizeTy, /*isSigned=*/true),
Samuel Antaodf158d52016-04-27 22:58:19 +00007392 SAddr);
7393 }
7394 }
7395 }
7396}
7397/// \brief Emit the arguments to be passed to the runtime library based on the
7398/// arrays of pointers, sizes and map types.
7399static void emitOffloadingArraysArgument(
7400 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
7401 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007402 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007403 CodeGenModule &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00007404 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007405 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007406 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
7407 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007408 /*Idx0=*/0, /*Idx1=*/0);
7409 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007410 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
7411 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007412 /*Idx0=*/0,
7413 /*Idx1=*/0);
7414 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007415 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007416 /*Idx0=*/0, /*Idx1=*/0);
7417 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
George Rokos63bc9d62017-11-21 18:25:12 +00007418 llvm::ArrayType::get(CGM.Int64Ty, Info.NumberOfPtrs),
Samuel Antaocc10b852016-07-28 14:23:26 +00007419 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007420 /*Idx0=*/0,
7421 /*Idx1=*/0);
7422 } else {
7423 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
7424 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
7425 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
7426 MapTypesArrayArg =
George Rokos63bc9d62017-11-21 18:25:12 +00007427 llvm::ConstantPointerNull::get(CGM.Int64Ty->getPointerTo());
Samuel Antaodf158d52016-04-27 22:58:19 +00007428 }
Samuel Antao86ace552016-04-27 22:40:57 +00007429}
7430
Samuel Antaobed3c462015-10-02 16:14:20 +00007431void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
7432 const OMPExecutableDirective &D,
7433 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00007434 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00007435 const Expr *IfCond, const Expr *Device) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00007436 if (!CGF.HaveInsertPoint())
7437 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00007438
Samuel Antaoee8fb302016-01-06 13:42:12 +00007439 assert(OutlinedFn && "Invalid outlined function!");
7440
Alexey Bataev8451efa2018-01-15 19:06:12 +00007441 const bool RequiresOuterTask = D.hasClausesOfKind<OMPDependClause>();
7442 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Alexey Bataev475a7442018-01-12 19:39:11 +00007443 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Alexey Bataev8451efa2018-01-15 19:06:12 +00007444 auto &&ArgsCodegen = [&CS, &CapturedVars](CodeGenFunction &CGF,
7445 PrePostActionTy &) {
7446 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7447 };
7448 emitInlinedDirective(CGF, OMPD_unknown, ArgsCodegen);
Samuel Antao86ace552016-04-27 22:40:57 +00007449
Alexey Bataev8451efa2018-01-15 19:06:12 +00007450 CodeGenFunction::OMPTargetDataInfo InputInfo;
7451 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00007452 // Fill up the pointer arrays and transfer execution to the device.
Alexey Bataev8451efa2018-01-15 19:06:12 +00007453 auto &&ThenGen = [this, Device, OutlinedFn, OutlinedFnID, &D, &InputInfo,
7454 &MapTypesArray, &CS, RequiresOuterTask,
7455 &CapturedVars](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobed3c462015-10-02 16:14:20 +00007456 // On top of the arrays that were filled up, the target offloading call
7457 // takes as arguments the device id as well as the host pointer. The host
7458 // pointer is used by the runtime library to identify the current target
7459 // region, so it only has to be unique and not necessarily point to
7460 // anything. It could be the pointer to the outlined function that
7461 // implements the target region, but we aren't using that so that the
7462 // compiler doesn't need to keep that, and could therefore inline the host
7463 // function if proven worthwhile during optimization.
7464
Samuel Antaoee8fb302016-01-06 13:42:12 +00007465 // From this point on, we need to have an ID of the target region defined.
7466 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00007467
7468 // Emit device ID if any.
7469 llvm::Value *DeviceID;
George Rokos63bc9d62017-11-21 18:25:12 +00007470 if (Device) {
Samuel Antaobed3c462015-10-02 16:14:20 +00007471 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007472 CGF.Int64Ty, /*isSigned=*/true);
7473 } else {
7474 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7475 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007476
Samuel Antaodf158d52016-04-27 22:58:19 +00007477 // Emit the number of elements in the offloading arrays.
Alexey Bataev8451efa2018-01-15 19:06:12 +00007478 llvm::Value *PointerNum =
7479 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaodf158d52016-04-27 22:58:19 +00007480
Samuel Antaob68e2db2016-03-03 16:20:23 +00007481 // Return value of the runtime offloading call.
7482 llvm::Value *Return;
7483
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007484 llvm::Value *NumTeams = emitNumTeamsForTargetDirective(*this, CGF, D);
7485 llvm::Value *NumThreads = emitNumThreadsForTargetDirective(*this, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007486
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007487 bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007488 // The target region is an outlined function launched by the runtime
7489 // via calls __tgt_target() or __tgt_target_teams().
7490 //
7491 // __tgt_target() launches a target region with one team and one thread,
7492 // executing a serial region. This master thread may in turn launch
7493 // more threads within its team upon encountering a parallel region,
7494 // however, no additional teams can be launched on the device.
7495 //
7496 // __tgt_target_teams() launches a target region with one or more teams,
7497 // each with one or more threads. This call is required for target
7498 // constructs such as:
7499 // 'target teams'
7500 // 'target' / 'teams'
7501 // 'target teams distribute parallel for'
7502 // 'target parallel'
7503 // and so on.
7504 //
7505 // Note that on the host and CPU targets, the runtime implementation of
7506 // these calls simply call the outlined function without forking threads.
7507 // The outlined functions themselves have runtime calls to
7508 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
7509 // the compiler in emitTeamsCall() and emitParallelCall().
7510 //
7511 // In contrast, on the NVPTX target, the implementation of
7512 // __tgt_target_teams() launches a GPU kernel with the requested number
7513 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00007514 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007515 // If we have NumTeams defined this means that we have an enclosed teams
7516 // region. Therefore we also expect to have NumThreads defined. These two
7517 // values should be defined in the presence of a teams directive,
7518 // regardless of having any clauses associated. If the user is using teams
7519 // but no clauses, these two values will be the default that should be
7520 // passed to the runtime library - a 32-bit integer with the value zero.
7521 assert(NumThreads && "Thread limit expression should be available along "
7522 "with number of teams.");
Alexey Bataev8451efa2018-01-15 19:06:12 +00007523 llvm::Value *OffloadingArgs[] = {DeviceID,
7524 OutlinedFnID,
7525 PointerNum,
7526 InputInfo.BasePointersArray.getPointer(),
7527 InputInfo.PointersArray.getPointer(),
7528 InputInfo.SizesArray.getPointer(),
7529 MapTypesArray,
7530 NumTeams,
7531 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00007532 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00007533 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_teams_nowait
7534 : OMPRTL__tgt_target_teams),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007535 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007536 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00007537 llvm::Value *OffloadingArgs[] = {DeviceID,
7538 OutlinedFnID,
7539 PointerNum,
7540 InputInfo.BasePointersArray.getPointer(),
7541 InputInfo.PointersArray.getPointer(),
7542 InputInfo.SizesArray.getPointer(),
7543 MapTypesArray};
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007544 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00007545 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_nowait
7546 : OMPRTL__tgt_target),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007547 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007548 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007549
Alexey Bataev2a007e02017-10-02 14:20:58 +00007550 // Check the error code and execute the host version if required.
7551 llvm::BasicBlock *OffloadFailedBlock =
7552 CGF.createBasicBlock("omp_offload.failed");
7553 llvm::BasicBlock *OffloadContBlock =
7554 CGF.createBasicBlock("omp_offload.cont");
7555 llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
7556 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
7557
7558 CGF.EmitBlock(OffloadFailedBlock);
Alexey Bataev8451efa2018-01-15 19:06:12 +00007559 if (RequiresOuterTask) {
7560 CapturedVars.clear();
7561 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7562 }
7563 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, CapturedVars);
Alexey Bataev2a007e02017-10-02 14:20:58 +00007564 CGF.EmitBranch(OffloadContBlock);
7565
7566 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00007567 };
7568
Samuel Antaoee8fb302016-01-06 13:42:12 +00007569 // Notify that the host version must be executed.
Alexey Bataev8451efa2018-01-15 19:06:12 +00007570 auto &&ElseGen = [this, &D, OutlinedFn, &CS, &CapturedVars,
7571 RequiresOuterTask](CodeGenFunction &CGF,
7572 PrePostActionTy &) {
7573 if (RequiresOuterTask) {
7574 CapturedVars.clear();
7575 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7576 }
7577 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, CapturedVars);
7578 };
7579
7580 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray,
7581 &CapturedVars, RequiresOuterTask,
7582 &CS](CodeGenFunction &CGF, PrePostActionTy &) {
7583 // Fill up the arrays with all the captured variables.
7584 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
7585 MappableExprsHandler::MapValuesArrayTy Pointers;
7586 MappableExprsHandler::MapValuesArrayTy Sizes;
7587 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7588
7589 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
7590 MappableExprsHandler::MapValuesArrayTy CurPointers;
7591 MappableExprsHandler::MapValuesArrayTy CurSizes;
7592 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
7593
7594 // Get mappable expression information.
7595 MappableExprsHandler MEHandler(D, CGF);
7596
7597 auto RI = CS.getCapturedRecordDecl()->field_begin();
7598 auto CV = CapturedVars.begin();
7599 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
7600 CE = CS.capture_end();
7601 CI != CE; ++CI, ++RI, ++CV) {
7602 CurBasePointers.clear();
7603 CurPointers.clear();
7604 CurSizes.clear();
7605 CurMapTypes.clear();
7606
7607 // VLA sizes are passed to the outlined region by copy and do not have map
7608 // information associated.
7609 if (CI->capturesVariableArrayType()) {
7610 CurBasePointers.push_back(*CV);
7611 CurPointers.push_back(*CV);
7612 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
7613 // Copy to the device as an argument. No need to retrieve it.
7614 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_LITERAL |
7615 MappableExprsHandler::OMP_MAP_TARGET_PARAM);
7616 } else {
7617 // If we have any information in the map clause, we use it, otherwise we
7618 // just do a default mapping.
7619 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
7620 CurSizes, CurMapTypes);
7621 if (CurBasePointers.empty())
7622 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
7623 CurPointers, CurSizes, CurMapTypes);
7624 }
7625 // We expect to have at least an element of information for this capture.
7626 assert(!CurBasePointers.empty() &&
7627 "Non-existing map pointer for capture!");
7628 assert(CurBasePointers.size() == CurPointers.size() &&
7629 CurBasePointers.size() == CurSizes.size() &&
7630 CurBasePointers.size() == CurMapTypes.size() &&
7631 "Inconsistent map information sizes!");
7632
7633 // We need to append the results of this capture to what we already have.
7634 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
7635 Pointers.append(CurPointers.begin(), CurPointers.end());
7636 Sizes.append(CurSizes.begin(), CurSizes.end());
7637 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
7638 }
Alexey Bataev92327c52018-03-26 16:40:55 +00007639 // Map other list items in the map clause which are not captured variables
7640 // but "declare target link" global variables.
7641 for (const auto *C : D.getClausesOfKind<OMPMapClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007642 for (const auto &L : C->component_lists()) {
Alexey Bataev92327c52018-03-26 16:40:55 +00007643 if (!L.first)
7644 continue;
7645 const auto *VD = dyn_cast<VarDecl>(L.first);
7646 if (!VD)
7647 continue;
7648 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
7649 isDeclareTargetDeclaration(VD);
7650 if (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link)
7651 continue;
7652 MEHandler.generateInfoForComponentList(
7653 C->getMapType(), C->getMapTypeModifier(), L.second, BasePointers,
7654 Pointers, Sizes, MapTypes, /*IsFirstComponentList=*/true,
7655 C->isImplicit());
7656 }
7657 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00007658
7659 TargetDataInfo Info;
7660 // Fill up the arrays and create the arguments.
7661 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
7662 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
7663 Info.PointersArray, Info.SizesArray,
7664 Info.MapTypesArray, Info);
7665 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
7666 InputInfo.BasePointersArray =
7667 Address(Info.BasePointersArray, CGM.getPointerAlign());
7668 InputInfo.PointersArray =
7669 Address(Info.PointersArray, CGM.getPointerAlign());
7670 InputInfo.SizesArray = Address(Info.SizesArray, CGM.getPointerAlign());
7671 MapTypesArray = Info.MapTypesArray;
7672 if (RequiresOuterTask)
7673 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
7674 else
7675 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
7676 };
7677
7678 auto &&TargetElseGen = [this, &ElseGen, &D, RequiresOuterTask](
7679 CodeGenFunction &CGF, PrePostActionTy &) {
7680 if (RequiresOuterTask) {
7681 CodeGenFunction::OMPTargetDataInfo InputInfo;
7682 CGF.EmitOMPTargetTaskBasedDirective(D, ElseGen, InputInfo);
7683 } else {
7684 emitInlinedDirective(CGF, D.getDirectiveKind(), ElseGen);
7685 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00007686 };
7687
7688 // If we have a target function ID it means that we need to support
7689 // offloading, otherwise, just execute on the host. We need to execute on host
7690 // regardless of the conditional in the if clause if, e.g., the user do not
7691 // specify target triples.
7692 if (OutlinedFnID) {
Alexey Bataev8451efa2018-01-15 19:06:12 +00007693 if (IfCond) {
7694 emitOMPIfClause(CGF, IfCond, TargetThenGen, TargetElseGen);
7695 } else {
7696 RegionCodeGenTy ThenRCG(TargetThenGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007697 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007698 }
7699 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00007700 RegionCodeGenTy ElseRCG(TargetElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007701 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007702 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007703}
Samuel Antaoee8fb302016-01-06 13:42:12 +00007704
7705void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
7706 StringRef ParentName) {
7707 if (!S)
7708 return;
7709
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007710 // Codegen OMP target directives that offload compute to the device.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007711 bool RequiresDeviceCodegen =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007712 isa<OMPExecutableDirective>(S) &&
7713 isOpenMPTargetExecutionDirective(
7714 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00007715
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007716 if (RequiresDeviceCodegen) {
7717 const auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007718 unsigned DeviceID;
7719 unsigned FileID;
7720 unsigned Line;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007721 getTargetEntryUniqueInfo(CGM.getContext(), E.getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00007722 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007723
7724 // Is this a target region that should not be emitted as an entry point? If
7725 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00007726 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
7727 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007728 return;
7729
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007730 switch (E.getDirectiveKind()) {
7731 case OMPD_target:
7732 CodeGenFunction::EmitOMPTargetDeviceFunction(CGM, ParentName,
7733 cast<OMPTargetDirective>(E));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007734 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007735 case OMPD_target_parallel:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00007736 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007737 CGM, ParentName, cast<OMPTargetParallelDirective>(E));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00007738 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007739 case OMPD_target_teams:
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00007740 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007741 CGM, ParentName, cast<OMPTargetTeamsDirective>(E));
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00007742 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007743 case OMPD_target_teams_distribute:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007744 CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007745 CGM, ParentName, cast<OMPTargetTeamsDistributeDirective>(E));
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007746 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007747 case OMPD_target_teams_distribute_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007748 CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007749 CGM, ParentName, cast<OMPTargetTeamsDistributeSimdDirective>(E));
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007750 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007751 case OMPD_target_parallel_for:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007752 CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007753 CGM, ParentName, cast<OMPTargetParallelForDirective>(E));
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007754 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007755 case OMPD_target_parallel_for_simd:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007756 CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007757 CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(E));
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007758 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007759 case OMPD_target_simd:
Alexey Bataevf8365372017-11-17 17:57:25 +00007760 CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007761 CGM, ParentName, cast<OMPTargetSimdDirective>(E));
Alexey Bataevf8365372017-11-17 17:57:25 +00007762 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007763 case OMPD_target_teams_distribute_parallel_for:
Carlo Bertolli52978c32018-01-03 21:12:44 +00007764 CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
7765 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007766 cast<OMPTargetTeamsDistributeParallelForDirective>(E));
Carlo Bertolli52978c32018-01-03 21:12:44 +00007767 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007768 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00007769 CodeGenFunction::
7770 EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
7771 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007772 cast<OMPTargetTeamsDistributeParallelForSimdDirective>(E));
Alexey Bataev647dd842018-01-15 20:59:40 +00007773 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007774 case OMPD_parallel:
7775 case OMPD_for:
7776 case OMPD_parallel_for:
7777 case OMPD_parallel_sections:
7778 case OMPD_for_simd:
7779 case OMPD_parallel_for_simd:
7780 case OMPD_cancel:
7781 case OMPD_cancellation_point:
7782 case OMPD_ordered:
7783 case OMPD_threadprivate:
7784 case OMPD_task:
7785 case OMPD_simd:
7786 case OMPD_sections:
7787 case OMPD_section:
7788 case OMPD_single:
7789 case OMPD_master:
7790 case OMPD_critical:
7791 case OMPD_taskyield:
7792 case OMPD_barrier:
7793 case OMPD_taskwait:
7794 case OMPD_taskgroup:
7795 case OMPD_atomic:
7796 case OMPD_flush:
7797 case OMPD_teams:
7798 case OMPD_target_data:
7799 case OMPD_target_exit_data:
7800 case OMPD_target_enter_data:
7801 case OMPD_distribute:
7802 case OMPD_distribute_simd:
7803 case OMPD_distribute_parallel_for:
7804 case OMPD_distribute_parallel_for_simd:
7805 case OMPD_teams_distribute:
7806 case OMPD_teams_distribute_simd:
7807 case OMPD_teams_distribute_parallel_for:
7808 case OMPD_teams_distribute_parallel_for_simd:
7809 case OMPD_target_update:
7810 case OMPD_declare_simd:
7811 case OMPD_declare_target:
7812 case OMPD_end_declare_target:
7813 case OMPD_declare_reduction:
7814 case OMPD_taskloop:
7815 case OMPD_taskloop_simd:
7816 case OMPD_unknown:
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007817 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
7818 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00007819 return;
7820 }
7821
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007822 if (const auto *E = dyn_cast<OMPExecutableDirective>(S)) {
Alexey Bataev475a7442018-01-12 19:39:11 +00007823 if (!E->hasAssociatedStmt() || !E->getAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00007824 return;
7825
7826 scanForTargetRegionsFunctions(
Alexey Bataev475a7442018-01-12 19:39:11 +00007827 E->getInnermostCapturedStmt()->getCapturedStmt(), ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007828 return;
7829 }
7830
7831 // If this is a lambda function, look into its body.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007832 if (const auto *L = dyn_cast<LambdaExpr>(S))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007833 S = L->getBody();
7834
7835 // Keep looking for target regions recursively.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007836 for (const Stmt *II : S->children())
Samuel Antaoee8fb302016-01-06 13:42:12 +00007837 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007838}
7839
7840bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007841 const auto *FD = cast<FunctionDecl>(GD.getDecl());
Samuel Antaoee8fb302016-01-06 13:42:12 +00007842
7843 // If emitting code for the host, we do not process FD here. Instead we do
7844 // the normal code generation.
7845 if (!CGM.getLangOpts().OpenMPIsDevice)
7846 return false;
7847
7848 // Try to detect target regions in the function.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007849 scanForTargetRegionsFunctions(FD->getBody(), CGM.getMangledName(GD));
Samuel Antaoee8fb302016-01-06 13:42:12 +00007850
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007851 // Do not to emit function if it is not marked as declare target.
Alexey Bataevfb388282018-05-01 14:09:46 +00007852 return !isDeclareTargetDeclaration(FD) &&
7853 AlreadyEmittedTargetFunctions.count(FD->getCanonicalDecl()) == 0;
Samuel Antaoee8fb302016-01-06 13:42:12 +00007854}
7855
7856bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
7857 if (!CGM.getLangOpts().OpenMPIsDevice)
7858 return false;
7859
7860 // Check if there are Ctors/Dtors in this declaration and look for target
7861 // regions in it. We use the complete variant to produce the kernel name
7862 // mangling.
7863 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007864 if (const auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
7865 for (const CXXConstructorDecl *Ctor : RD->ctors()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00007866 StringRef ParentName =
7867 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
7868 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
7869 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007870 if (const CXXDestructorDecl *Dtor = RD->getDestructor()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00007871 StringRef ParentName =
7872 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
7873 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
7874 }
7875 }
7876
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007877 // Do not to emit variable if it is not marked as declare target.
Alexey Bataev92327c52018-03-26 16:40:55 +00007878 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev03f270c2018-03-30 18:31:07 +00007879 isDeclareTargetDeclaration(cast<VarDecl>(GD.getDecl()));
Alexey Bataev92327c52018-03-26 16:40:55 +00007880 return !Res || *Res == OMPDeclareTargetDeclAttr::MT_Link;
Samuel Antaoee8fb302016-01-06 13:42:12 +00007881}
7882
Alexey Bataev03f270c2018-03-30 18:31:07 +00007883void CGOpenMPRuntime::registerTargetGlobalVariable(const VarDecl *VD,
7884 llvm::Constant *Addr) {
7885 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
7886 isDeclareTargetDeclaration(VD)) {
7887 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags;
7888 StringRef VarName;
7889 CharUnits VarSize;
7890 llvm::GlobalValue::LinkageTypes Linkage;
7891 switch (*Res) {
7892 case OMPDeclareTargetDeclAttr::MT_To:
7893 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo;
7894 VarName = CGM.getMangledName(VD);
7895 VarSize = CGM.getContext().getTypeSizeInChars(VD->getType());
7896 Linkage = CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false);
7897 break;
7898 case OMPDeclareTargetDeclAttr::MT_Link:
7899 // Map type 'to' because we do not map the original variable but the
7900 // reference.
7901 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo;
7902 if (!CGM.getLangOpts().OpenMPIsDevice) {
7903 Addr =
7904 cast<llvm::Constant>(getAddrOfDeclareTargetLink(VD).getPointer());
7905 }
7906 VarName = Addr->getName();
7907 VarSize = CGM.getPointerSize();
7908 Linkage = llvm::GlobalValue::WeakAnyLinkage;
7909 break;
7910 }
7911 OffloadEntriesInfoManager.registerDeviceGlobalVarEntryInfo(
7912 VarName, Addr, VarSize, Flags, Linkage);
7913 }
7914}
7915
Samuel Antaoee8fb302016-01-06 13:42:12 +00007916bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007917 if (isa<FunctionDecl>(GD.getDecl()))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007918 return emitTargetFunctions(GD);
7919
7920 return emitTargetGlobalVariable(GD);
7921}
7922
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007923CGOpenMPRuntime::DisableAutoDeclareTargetRAII::DisableAutoDeclareTargetRAII(
7924 CodeGenModule &CGM)
7925 : CGM(CGM) {
7926 if (CGM.getLangOpts().OpenMPIsDevice) {
7927 SavedShouldMarkAsGlobal = CGM.getOpenMPRuntime().ShouldMarkAsGlobal;
7928 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = false;
7929 }
7930}
7931
7932CGOpenMPRuntime::DisableAutoDeclareTargetRAII::~DisableAutoDeclareTargetRAII() {
7933 if (CGM.getLangOpts().OpenMPIsDevice)
7934 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = SavedShouldMarkAsGlobal;
7935}
7936
7937bool CGOpenMPRuntime::markAsGlobalTarget(const FunctionDecl *D) {
7938 if (!CGM.getLangOpts().OpenMPIsDevice || !ShouldMarkAsGlobal)
7939 return true;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007940
7941 const FunctionDecl *FD = D->getCanonicalDecl();
Alexey Bataev34f8a702018-03-28 14:28:54 +00007942 // Do not to emit function if it is marked as declare target as it was already
7943 // emitted.
7944 if (isDeclareTargetDeclaration(D)) {
7945 if (D->hasBody() && AlreadyEmittedTargetFunctions.count(FD) == 0) {
7946 if (auto *F = dyn_cast_or_null<llvm::Function>(
7947 CGM.GetGlobalValue(CGM.getMangledName(D))))
7948 return !F->isDeclaration();
7949 return false;
7950 }
7951 return true;
7952 }
7953
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00007954 // Do not mark member functions except for static.
7955 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD))
7956 if (!Method->isStatic())
7957 return true;
7958
7959 return !AlreadyEmittedTargetFunctions.insert(FD).second;
7960}
7961
Samuel Antaoee8fb302016-01-06 13:42:12 +00007962llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
7963 // If we have offloading in the current module, we need to emit the entries
7964 // now and register the offloading descriptor.
7965 createOffloadEntriesAndInfoMetadata();
7966
7967 // Create and register the offloading binary descriptors. This is the main
7968 // entity that captures all the information about offloading in the current
7969 // compilation unit.
7970 return createOffloadingBinaryDescriptorRegistration();
7971}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007972
7973void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
7974 const OMPExecutableDirective &D,
7975 SourceLocation Loc,
7976 llvm::Value *OutlinedFn,
7977 ArrayRef<llvm::Value *> CapturedVars) {
7978 if (!CGF.HaveInsertPoint())
7979 return;
7980
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007981 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007982 CodeGenFunction::RunCleanupsScope Scope(CGF);
7983
7984 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
7985 llvm::Value *Args[] = {
7986 RTLoc,
7987 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
7988 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
7989 llvm::SmallVector<llvm::Value *, 16> RealArgs;
7990 RealArgs.append(std::begin(Args), std::end(Args));
7991 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
7992
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007993 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007994 CGF.EmitRuntimeCall(RTLFn, RealArgs);
7995}
7996
7997void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00007998 const Expr *NumTeams,
7999 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008000 SourceLocation Loc) {
8001 if (!CGF.HaveInsertPoint())
8002 return;
8003
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008004 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008005
Carlo Bertollic6872252016-04-04 15:55:02 +00008006 llvm::Value *NumTeamsVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008007 NumTeams
Carlo Bertollic6872252016-04-04 15:55:02 +00008008 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
8009 CGF.CGM.Int32Ty, /* isSigned = */ true)
8010 : CGF.Builder.getInt32(0);
8011
8012 llvm::Value *ThreadLimitVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008013 ThreadLimit
Carlo Bertollic6872252016-04-04 15:55:02 +00008014 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
8015 CGF.CGM.Int32Ty, /* isSigned = */ true)
8016 : CGF.Builder.getInt32(0);
8017
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008018 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00008019 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
8020 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008021 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
8022 PushNumTeamsArgs);
8023}
Samuel Antaodf158d52016-04-27 22:58:19 +00008024
Samuel Antaocc10b852016-07-28 14:23:26 +00008025void CGOpenMPRuntime::emitTargetDataCalls(
8026 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8027 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008028 if (!CGF.HaveInsertPoint())
8029 return;
8030
Samuel Antaocc10b852016-07-28 14:23:26 +00008031 // Action used to replace the default codegen action and turn privatization
8032 // off.
8033 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00008034
8035 // Generate the code for the opening of the data environment. Capture all the
8036 // arguments of the runtime call by reference because they are used in the
8037 // closing of the region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008038 auto &&BeginThenGen = [this, &D, Device, &Info,
8039 &CodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008040 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00008041 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00008042 MappableExprsHandler::MapValuesArrayTy Pointers;
8043 MappableExprsHandler::MapValuesArrayTy Sizes;
8044 MappableExprsHandler::MapFlagsArrayTy MapTypes;
8045
8046 // Get map clause information.
8047 MappableExprsHandler MCHandler(D, CGF);
8048 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00008049
8050 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00008051 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008052
8053 llvm::Value *BasePointersArrayArg = nullptr;
8054 llvm::Value *PointersArrayArg = nullptr;
8055 llvm::Value *SizesArrayArg = nullptr;
8056 llvm::Value *MapTypesArrayArg = nullptr;
8057 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008058 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008059
8060 // Emit device ID if any.
8061 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008062 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008063 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008064 CGF.Int64Ty, /*isSigned=*/true);
8065 } else {
8066 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8067 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008068
8069 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008070 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00008071
8072 llvm::Value *OffloadingArgs[] = {
8073 DeviceID, PointerNum, BasePointersArrayArg,
8074 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008075 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_begin),
Samuel Antaodf158d52016-04-27 22:58:19 +00008076 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00008077
8078 // If device pointer privatization is required, emit the body of the region
8079 // here. It will have to be duplicated: with and without privatization.
8080 if (!Info.CaptureDeviceAddrMap.empty())
8081 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008082 };
8083
8084 // Generate code for the closing of the data region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008085 auto &&EndThenGen = [this, Device, &Info](CodeGenFunction &CGF,
8086 PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008087 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00008088
8089 llvm::Value *BasePointersArrayArg = nullptr;
8090 llvm::Value *PointersArrayArg = nullptr;
8091 llvm::Value *SizesArrayArg = nullptr;
8092 llvm::Value *MapTypesArrayArg = nullptr;
8093 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008094 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008095
8096 // Emit device ID if any.
8097 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008098 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008099 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008100 CGF.Int64Ty, /*isSigned=*/true);
8101 } else {
8102 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8103 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008104
8105 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008106 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00008107
8108 llvm::Value *OffloadingArgs[] = {
8109 DeviceID, PointerNum, BasePointersArrayArg,
8110 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008111 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_end),
Samuel Antaodf158d52016-04-27 22:58:19 +00008112 OffloadingArgs);
8113 };
8114
Samuel Antaocc10b852016-07-28 14:23:26 +00008115 // If we need device pointer privatization, we need to emit the body of the
8116 // region with no privatization in the 'else' branch of the conditional.
8117 // Otherwise, we don't have to do anything.
8118 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
8119 PrePostActionTy &) {
8120 if (!Info.CaptureDeviceAddrMap.empty()) {
8121 CodeGen.setAction(NoPrivAction);
8122 CodeGen(CGF);
8123 }
8124 };
8125
8126 // We don't have to do anything to close the region if the if clause evaluates
8127 // to false.
8128 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00008129
8130 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008131 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00008132 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00008133 RegionCodeGenTy RCG(BeginThenGen);
8134 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008135 }
8136
Samuel Antaocc10b852016-07-28 14:23:26 +00008137 // If we don't require privatization of device pointers, we emit the body in
8138 // between the runtime calls. This avoids duplicating the body code.
8139 if (Info.CaptureDeviceAddrMap.empty()) {
8140 CodeGen.setAction(NoPrivAction);
8141 CodeGen(CGF);
8142 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008143
8144 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008145 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00008146 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00008147 RegionCodeGenTy RCG(EndThenGen);
8148 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008149 }
8150}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008151
Samuel Antao8d2d7302016-05-26 18:30:22 +00008152void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00008153 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8154 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008155 if (!CGF.HaveInsertPoint())
8156 return;
8157
Samuel Antao8dd66282016-04-27 23:14:30 +00008158 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00008159 isa<OMPTargetExitDataDirective>(D) ||
8160 isa<OMPTargetUpdateDirective>(D)) &&
8161 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00008162
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008163 CodeGenFunction::OMPTargetDataInfo InputInfo;
8164 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008165 // Generate the code for the opening of the data environment.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008166 auto &&ThenGen = [this, &D, Device, &InputInfo,
8167 &MapTypesArray](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008168 // Emit device ID if any.
8169 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008170 if (Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008171 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008172 CGF.Int64Ty, /*isSigned=*/true);
8173 } else {
8174 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8175 }
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008176
8177 // Emit the number of elements in the offloading arrays.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008178 llvm::Constant *PointerNum =
8179 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008180
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008181 llvm::Value *OffloadingArgs[] = {DeviceID,
8182 PointerNum,
8183 InputInfo.BasePointersArray.getPointer(),
8184 InputInfo.PointersArray.getPointer(),
8185 InputInfo.SizesArray.getPointer(),
8186 MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00008187
Samuel Antao8d2d7302016-05-26 18:30:22 +00008188 // Select the right runtime function call for each expected standalone
8189 // directive.
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008190 const bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Samuel Antao8d2d7302016-05-26 18:30:22 +00008191 OpenMPRTLFunction RTLFn;
8192 switch (D.getDirectiveKind()) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00008193 case OMPD_target_enter_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008194 RTLFn = HasNowait ? OMPRTL__tgt_target_data_begin_nowait
8195 : OMPRTL__tgt_target_data_begin;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008196 break;
8197 case OMPD_target_exit_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008198 RTLFn = HasNowait ? OMPRTL__tgt_target_data_end_nowait
8199 : OMPRTL__tgt_target_data_end;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008200 break;
8201 case OMPD_target_update:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008202 RTLFn = HasNowait ? OMPRTL__tgt_target_data_update_nowait
8203 : OMPRTL__tgt_target_data_update;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008204 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008205 case OMPD_parallel:
8206 case OMPD_for:
8207 case OMPD_parallel_for:
8208 case OMPD_parallel_sections:
8209 case OMPD_for_simd:
8210 case OMPD_parallel_for_simd:
8211 case OMPD_cancel:
8212 case OMPD_cancellation_point:
8213 case OMPD_ordered:
8214 case OMPD_threadprivate:
8215 case OMPD_task:
8216 case OMPD_simd:
8217 case OMPD_sections:
8218 case OMPD_section:
8219 case OMPD_single:
8220 case OMPD_master:
8221 case OMPD_critical:
8222 case OMPD_taskyield:
8223 case OMPD_barrier:
8224 case OMPD_taskwait:
8225 case OMPD_taskgroup:
8226 case OMPD_atomic:
8227 case OMPD_flush:
8228 case OMPD_teams:
8229 case OMPD_target_data:
8230 case OMPD_distribute:
8231 case OMPD_distribute_simd:
8232 case OMPD_distribute_parallel_for:
8233 case OMPD_distribute_parallel_for_simd:
8234 case OMPD_teams_distribute:
8235 case OMPD_teams_distribute_simd:
8236 case OMPD_teams_distribute_parallel_for:
8237 case OMPD_teams_distribute_parallel_for_simd:
8238 case OMPD_declare_simd:
8239 case OMPD_declare_target:
8240 case OMPD_end_declare_target:
8241 case OMPD_declare_reduction:
8242 case OMPD_taskloop:
8243 case OMPD_taskloop_simd:
8244 case OMPD_target:
8245 case OMPD_target_simd:
8246 case OMPD_target_teams_distribute:
8247 case OMPD_target_teams_distribute_simd:
8248 case OMPD_target_teams_distribute_parallel_for:
8249 case OMPD_target_teams_distribute_parallel_for_simd:
8250 case OMPD_target_teams:
8251 case OMPD_target_parallel:
8252 case OMPD_target_parallel_for:
8253 case OMPD_target_parallel_for_simd:
8254 case OMPD_unknown:
8255 llvm_unreachable("Unexpected standalone target data directive.");
8256 break;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008257 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008258 CGF.EmitRuntimeCall(createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008259 };
8260
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008261 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray](
8262 CodeGenFunction &CGF, PrePostActionTy &) {
8263 // Fill up the arrays with all the mapped variables.
8264 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
8265 MappableExprsHandler::MapValuesArrayTy Pointers;
8266 MappableExprsHandler::MapValuesArrayTy Sizes;
8267 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008268
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008269 // Get map clause information.
8270 MappableExprsHandler MEHandler(D, CGF);
8271 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
8272
8273 TargetDataInfo Info;
8274 // Fill up the arrays and create the arguments.
8275 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
8276 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
8277 Info.PointersArray, Info.SizesArray,
8278 Info.MapTypesArray, Info);
8279 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
8280 InputInfo.BasePointersArray =
8281 Address(Info.BasePointersArray, CGM.getPointerAlign());
8282 InputInfo.PointersArray =
8283 Address(Info.PointersArray, CGM.getPointerAlign());
8284 InputInfo.SizesArray =
8285 Address(Info.SizesArray, CGM.getPointerAlign());
8286 MapTypesArray = Info.MapTypesArray;
8287 if (D.hasClausesOfKind<OMPDependClause>())
8288 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
8289 else
Alexey Bataev768f1f22018-01-09 19:59:25 +00008290 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008291 };
8292
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008293 if (IfCond) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008294 emitOMPIfClause(CGF, IfCond, TargetThenGen,
8295 [](CodeGenFunction &CGF, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008296 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008297 RegionCodeGenTy ThenRCG(TargetThenGen);
8298 ThenRCG(CGF);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008299 }
8300}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008301
8302namespace {
8303 /// Kind of parameter in a function with 'declare simd' directive.
8304 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
8305 /// Attribute set of the parameter.
8306 struct ParamAttrTy {
8307 ParamKindTy Kind = Vector;
8308 llvm::APSInt StrideOrArg;
8309 llvm::APSInt Alignment;
8310 };
8311} // namespace
8312
8313static unsigned evaluateCDTSize(const FunctionDecl *FD,
8314 ArrayRef<ParamAttrTy> ParamAttrs) {
8315 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
8316 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
8317 // of that clause. The VLEN value must be power of 2.
8318 // In other case the notion of the function`s "characteristic data type" (CDT)
8319 // is used to compute the vector length.
8320 // CDT is defined in the following order:
8321 // a) For non-void function, the CDT is the return type.
8322 // b) If the function has any non-uniform, non-linear parameters, then the
8323 // CDT is the type of the first such parameter.
8324 // c) If the CDT determined by a) or b) above is struct, union, or class
8325 // type which is pass-by-value (except for the type that maps to the
8326 // built-in complex data type), the characteristic data type is int.
8327 // d) If none of the above three cases is applicable, the CDT is int.
8328 // The VLEN is then determined based on the CDT and the size of vector
8329 // register of that ISA for which current vector version is generated. The
8330 // VLEN is computed using the formula below:
8331 // VLEN = sizeof(vector_register) / sizeof(CDT),
8332 // where vector register size specified in section 3.2.1 Registers and the
8333 // Stack Frame of original AMD64 ABI document.
8334 QualType RetType = FD->getReturnType();
8335 if (RetType.isNull())
8336 return 0;
8337 ASTContext &C = FD->getASTContext();
8338 QualType CDT;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008339 if (!RetType.isNull() && !RetType->isVoidType()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008340 CDT = RetType;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008341 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008342 unsigned Offset = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008343 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008344 if (ParamAttrs[Offset].Kind == Vector)
8345 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
8346 ++Offset;
8347 }
8348 if (CDT.isNull()) {
8349 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
8350 if (ParamAttrs[I + Offset].Kind == Vector) {
8351 CDT = FD->getParamDecl(I)->getType();
8352 break;
8353 }
8354 }
8355 }
8356 }
8357 if (CDT.isNull())
8358 CDT = C.IntTy;
8359 CDT = CDT->getCanonicalTypeUnqualified();
8360 if (CDT->isRecordType() || CDT->isUnionType())
8361 CDT = C.IntTy;
8362 return C.getTypeSize(CDT);
8363}
8364
8365static void
8366emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00008367 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008368 ArrayRef<ParamAttrTy> ParamAttrs,
8369 OMPDeclareSimdDeclAttr::BranchStateTy State) {
8370 struct ISADataTy {
8371 char ISA;
8372 unsigned VecRegSize;
8373 };
8374 ISADataTy ISAData[] = {
8375 {
8376 'b', 128
8377 }, // SSE
8378 {
8379 'c', 256
8380 }, // AVX
8381 {
8382 'd', 256
8383 }, // AVX2
8384 {
8385 'e', 512
8386 }, // AVX512
8387 };
8388 llvm::SmallVector<char, 2> Masked;
8389 switch (State) {
8390 case OMPDeclareSimdDeclAttr::BS_Undefined:
8391 Masked.push_back('N');
8392 Masked.push_back('M');
8393 break;
8394 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
8395 Masked.push_back('N');
8396 break;
8397 case OMPDeclareSimdDeclAttr::BS_Inbranch:
8398 Masked.push_back('M');
8399 break;
8400 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008401 for (char Mask : Masked) {
8402 for (const ISADataTy &Data : ISAData) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008403 SmallString<256> Buffer;
8404 llvm::raw_svector_ostream Out(Buffer);
8405 Out << "_ZGV" << Data.ISA << Mask;
8406 if (!VLENVal) {
8407 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
8408 evaluateCDTSize(FD, ParamAttrs));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008409 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008410 Out << VLENVal;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008411 }
8412 for (const ParamAttrTy &ParamAttr : ParamAttrs) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008413 switch (ParamAttr.Kind){
8414 case LinearWithVarStride:
8415 Out << 's' << ParamAttr.StrideOrArg;
8416 break;
8417 case Linear:
8418 Out << 'l';
8419 if (!!ParamAttr.StrideOrArg)
8420 Out << ParamAttr.StrideOrArg;
8421 break;
8422 case Uniform:
8423 Out << 'u';
8424 break;
8425 case Vector:
8426 Out << 'v';
8427 break;
8428 }
8429 if (!!ParamAttr.Alignment)
8430 Out << 'a' << ParamAttr.Alignment;
8431 }
8432 Out << '_' << Fn->getName();
8433 Fn->addFnAttr(Out.str());
8434 }
8435 }
8436}
8437
8438void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
8439 llvm::Function *Fn) {
8440 ASTContext &C = CGM.getContext();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008441 FD = FD->getMostRecentDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008442 // Map params to their positions in function decl.
8443 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
8444 if (isa<CXXMethodDecl>(FD))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008445 ParamPositions.try_emplace(FD, 0);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008446 unsigned ParamPos = ParamPositions.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008447 for (const ParmVarDecl *P : FD->parameters()) {
8448 ParamPositions.try_emplace(P->getCanonicalDecl(), ParamPos);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008449 ++ParamPos;
8450 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008451 while (FD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008452 for (const auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008453 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
8454 // Mark uniform parameters.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008455 for (const Expr *E : Attr->uniforms()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008456 E = E->IgnoreParenImpCasts();
8457 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008458 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008459 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008460 } else {
8461 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
8462 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008463 Pos = ParamPositions[PVD];
8464 }
8465 ParamAttrs[Pos].Kind = Uniform;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008466 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008467 // Get alignment info.
8468 auto NI = Attr->alignments_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008469 for (const Expr *E : Attr->aligneds()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008470 E = E->IgnoreParenImpCasts();
8471 unsigned Pos;
8472 QualType ParmTy;
8473 if (isa<CXXThisExpr>(E)) {
8474 Pos = ParamPositions[FD];
8475 ParmTy = E->getType();
8476 } else {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008477 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
8478 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008479 Pos = ParamPositions[PVD];
8480 ParmTy = PVD->getType();
8481 }
8482 ParamAttrs[Pos].Alignment =
8483 (*NI)
8484 ? (*NI)->EvaluateKnownConstInt(C)
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008485 : llvm::APSInt::getUnsigned(
8486 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
8487 .getQuantity());
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008488 ++NI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008489 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008490 // Mark linear parameters.
8491 auto SI = Attr->steps_begin();
8492 auto MI = Attr->modifiers_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008493 for (const Expr *E : Attr->linears()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008494 E = E->IgnoreParenImpCasts();
8495 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008496 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008497 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008498 } else {
8499 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
8500 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008501 Pos = ParamPositions[PVD];
8502 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008503 ParamAttrTy &ParamAttr = ParamAttrs[Pos];
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008504 ParamAttr.Kind = Linear;
8505 if (*SI) {
8506 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
8507 Expr::SE_AllowSideEffects)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008508 if (const auto *DRE =
8509 cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
8510 if (const auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008511 ParamAttr.Kind = LinearWithVarStride;
8512 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
8513 ParamPositions[StridePVD->getCanonicalDecl()]);
8514 }
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008515 }
8516 }
8517 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008518 ++SI;
8519 ++MI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008520 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008521 llvm::APSInt VLENVal;
8522 if (const Expr *VLEN = Attr->getSimdlen())
8523 VLENVal = VLEN->EvaluateKnownConstInt(C);
8524 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
8525 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
8526 CGM.getTriple().getArch() == llvm::Triple::x86_64)
8527 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008528 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008529 FD = FD->getPreviousDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008530 }
8531}
Alexey Bataev8b427062016-05-25 12:36:08 +00008532
8533namespace {
8534/// Cleanup action for doacross support.
8535class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
8536public:
8537 static const int DoacrossFinArgs = 2;
8538
8539private:
8540 llvm::Value *RTLFn;
8541 llvm::Value *Args[DoacrossFinArgs];
8542
8543public:
8544 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
8545 : RTLFn(RTLFn) {
8546 assert(CallArgs.size() == DoacrossFinArgs);
8547 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
8548 }
8549 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
8550 if (!CGF.HaveInsertPoint())
8551 return;
8552 CGF.EmitRuntimeCall(RTLFn, Args);
8553 }
8554};
8555} // namespace
8556
8557void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
8558 const OMPLoopDirective &D) {
8559 if (!CGF.HaveInsertPoint())
8560 return;
8561
8562 ASTContext &C = CGM.getContext();
8563 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
8564 RecordDecl *RD;
8565 if (KmpDimTy.isNull()) {
8566 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
8567 // kmp_int64 lo; // lower
8568 // kmp_int64 up; // upper
8569 // kmp_int64 st; // stride
8570 // };
8571 RD = C.buildImplicitRecord("kmp_dim");
8572 RD->startDefinition();
8573 addFieldToRecordDecl(C, RD, Int64Ty);
8574 addFieldToRecordDecl(C, RD, Int64Ty);
8575 addFieldToRecordDecl(C, RD, Int64Ty);
8576 RD->completeDefinition();
8577 KmpDimTy = C.getRecordType(RD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008578 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00008579 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008580 }
Alexey Bataev8b427062016-05-25 12:36:08 +00008581
8582 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
8583 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
8584 enum { LowerFD = 0, UpperFD, StrideFD };
8585 // Fill dims with data.
8586 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
8587 // dims.upper = num_iterations;
8588 LValue UpperLVal =
8589 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
8590 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
8591 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
8592 Int64Ty, D.getNumIterations()->getExprLoc());
8593 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
8594 // dims.stride = 1;
8595 LValue StrideLVal =
8596 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
8597 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
8598 StrideLVal);
8599
8600 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
8601 // kmp_int32 num_dims, struct kmp_dim * dims);
8602 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
8603 getThreadID(CGF, D.getLocStart()),
8604 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
8605 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
8606 DimsAddr.getPointer(), CGM.VoidPtrTy)};
8607
8608 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
8609 CGF.EmitRuntimeCall(RTLFn, Args);
8610 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
8611 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
8612 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
8613 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
8614 llvm::makeArrayRef(FiniArgs));
8615}
8616
8617void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
8618 const OMPDependClause *C) {
8619 QualType Int64Ty =
8620 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
8621 const Expr *CounterVal = C->getCounterValue();
8622 assert(CounterVal);
8623 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
8624 CounterVal->getType(), Int64Ty,
8625 CounterVal->getExprLoc());
8626 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
8627 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
8628 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
8629 getThreadID(CGF, C->getLocStart()),
8630 CntAddr.getPointer()};
8631 llvm::Value *RTLFn;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008632 if (C->getDependencyKind() == OMPC_DEPEND_source) {
Alexey Bataev8b427062016-05-25 12:36:08 +00008633 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008634 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00008635 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
8636 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
8637 }
8638 CGF.EmitRuntimeCall(RTLFn, Args);
8639}
8640
Alexey Bataev7ef47a62018-02-22 18:33:31 +00008641void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, SourceLocation Loc,
8642 llvm::Value *Callee,
8643 ArrayRef<llvm::Value *> Args) const {
8644 assert(Loc.isValid() && "Outlined function call location must be valid.");
Alexey Bataev3c595a62017-08-14 15:01:03 +00008645 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
8646
8647 if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008648 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00008649 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008650 return;
8651 }
8652 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00008653 CGF.EmitRuntimeCall(Callee, Args);
8654}
8655
8656void CGOpenMPRuntime::emitOutlinedFunctionCall(
8657 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
8658 ArrayRef<llvm::Value *> Args) const {
Alexey Bataev7ef47a62018-02-22 18:33:31 +00008659 emitCall(CGF, Loc, OutlinedFn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008660}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00008661
8662Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
8663 const VarDecl *NativeParam,
8664 const VarDecl *TargetParam) const {
8665 return CGF.GetAddrOfLocalVar(NativeParam);
8666}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00008667
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00008668Address CGOpenMPRuntime::getAddressOfLocalVariable(CodeGenFunction &CGF,
8669 const VarDecl *VD) {
8670 return Address::invalid();
8671}
8672
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00008673llvm::Value *CGOpenMPSIMDRuntime::emitParallelOutlinedFunction(
8674 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8675 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
8676 llvm_unreachable("Not supported in SIMD-only mode");
8677}
8678
8679llvm::Value *CGOpenMPSIMDRuntime::emitTeamsOutlinedFunction(
8680 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8681 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
8682 llvm_unreachable("Not supported in SIMD-only mode");
8683}
8684
8685llvm::Value *CGOpenMPSIMDRuntime::emitTaskOutlinedFunction(
8686 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8687 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
8688 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
8689 bool Tied, unsigned &NumberOfParts) {
8690 llvm_unreachable("Not supported in SIMD-only mode");
8691}
8692
8693void CGOpenMPSIMDRuntime::emitParallelCall(CodeGenFunction &CGF,
8694 SourceLocation Loc,
8695 llvm::Value *OutlinedFn,
8696 ArrayRef<llvm::Value *> CapturedVars,
8697 const Expr *IfCond) {
8698 llvm_unreachable("Not supported in SIMD-only mode");
8699}
8700
8701void CGOpenMPSIMDRuntime::emitCriticalRegion(
8702 CodeGenFunction &CGF, StringRef CriticalName,
8703 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
8704 const Expr *Hint) {
8705 llvm_unreachable("Not supported in SIMD-only mode");
8706}
8707
8708void CGOpenMPSIMDRuntime::emitMasterRegion(CodeGenFunction &CGF,
8709 const RegionCodeGenTy &MasterOpGen,
8710 SourceLocation Loc) {
8711 llvm_unreachable("Not supported in SIMD-only mode");
8712}
8713
8714void CGOpenMPSIMDRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
8715 SourceLocation Loc) {
8716 llvm_unreachable("Not supported in SIMD-only mode");
8717}
8718
8719void CGOpenMPSIMDRuntime::emitTaskgroupRegion(
8720 CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen,
8721 SourceLocation Loc) {
8722 llvm_unreachable("Not supported in SIMD-only mode");
8723}
8724
8725void CGOpenMPSIMDRuntime::emitSingleRegion(
8726 CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen,
8727 SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars,
8728 ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs,
8729 ArrayRef<const Expr *> AssignmentOps) {
8730 llvm_unreachable("Not supported in SIMD-only mode");
8731}
8732
8733void CGOpenMPSIMDRuntime::emitOrderedRegion(CodeGenFunction &CGF,
8734 const RegionCodeGenTy &OrderedOpGen,
8735 SourceLocation Loc,
8736 bool IsThreads) {
8737 llvm_unreachable("Not supported in SIMD-only mode");
8738}
8739
8740void CGOpenMPSIMDRuntime::emitBarrierCall(CodeGenFunction &CGF,
8741 SourceLocation Loc,
8742 OpenMPDirectiveKind Kind,
8743 bool EmitChecks,
8744 bool ForceSimpleCall) {
8745 llvm_unreachable("Not supported in SIMD-only mode");
8746}
8747
8748void CGOpenMPSIMDRuntime::emitForDispatchInit(
8749 CodeGenFunction &CGF, SourceLocation Loc,
8750 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
8751 bool Ordered, const DispatchRTInput &DispatchValues) {
8752 llvm_unreachable("Not supported in SIMD-only mode");
8753}
8754
8755void CGOpenMPSIMDRuntime::emitForStaticInit(
8756 CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind,
8757 const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values) {
8758 llvm_unreachable("Not supported in SIMD-only mode");
8759}
8760
8761void CGOpenMPSIMDRuntime::emitDistributeStaticInit(
8762 CodeGenFunction &CGF, SourceLocation Loc,
8763 OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values) {
8764 llvm_unreachable("Not supported in SIMD-only mode");
8765}
8766
8767void CGOpenMPSIMDRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
8768 SourceLocation Loc,
8769 unsigned IVSize,
8770 bool IVSigned) {
8771 llvm_unreachable("Not supported in SIMD-only mode");
8772}
8773
8774void CGOpenMPSIMDRuntime::emitForStaticFinish(CodeGenFunction &CGF,
8775 SourceLocation Loc,
8776 OpenMPDirectiveKind DKind) {
8777 llvm_unreachable("Not supported in SIMD-only mode");
8778}
8779
8780llvm::Value *CGOpenMPSIMDRuntime::emitForNext(CodeGenFunction &CGF,
8781 SourceLocation Loc,
8782 unsigned IVSize, bool IVSigned,
8783 Address IL, Address LB,
8784 Address UB, Address ST) {
8785 llvm_unreachable("Not supported in SIMD-only mode");
8786}
8787
8788void CGOpenMPSIMDRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
8789 llvm::Value *NumThreads,
8790 SourceLocation Loc) {
8791 llvm_unreachable("Not supported in SIMD-only mode");
8792}
8793
8794void CGOpenMPSIMDRuntime::emitProcBindClause(CodeGenFunction &CGF,
8795 OpenMPProcBindClauseKind ProcBind,
8796 SourceLocation Loc) {
8797 llvm_unreachable("Not supported in SIMD-only mode");
8798}
8799
8800Address CGOpenMPSIMDRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
8801 const VarDecl *VD,
8802 Address VDAddr,
8803 SourceLocation Loc) {
8804 llvm_unreachable("Not supported in SIMD-only mode");
8805}
8806
8807llvm::Function *CGOpenMPSIMDRuntime::emitThreadPrivateVarDefinition(
8808 const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit,
8809 CodeGenFunction *CGF) {
8810 llvm_unreachable("Not supported in SIMD-only mode");
8811}
8812
8813Address CGOpenMPSIMDRuntime::getAddrOfArtificialThreadPrivate(
8814 CodeGenFunction &CGF, QualType VarType, StringRef Name) {
8815 llvm_unreachable("Not supported in SIMD-only mode");
8816}
8817
8818void CGOpenMPSIMDRuntime::emitFlush(CodeGenFunction &CGF,
8819 ArrayRef<const Expr *> Vars,
8820 SourceLocation Loc) {
8821 llvm_unreachable("Not supported in SIMD-only mode");
8822}
8823
8824void CGOpenMPSIMDRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
8825 const OMPExecutableDirective &D,
8826 llvm::Value *TaskFunction,
8827 QualType SharedsTy, Address Shareds,
8828 const Expr *IfCond,
8829 const OMPTaskDataTy &Data) {
8830 llvm_unreachable("Not supported in SIMD-only mode");
8831}
8832
8833void CGOpenMPSIMDRuntime::emitTaskLoopCall(
8834 CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D,
8835 llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
8836 const Expr *IfCond, const OMPTaskDataTy &Data) {
8837 llvm_unreachable("Not supported in SIMD-only mode");
8838}
8839
8840void CGOpenMPSIMDRuntime::emitReduction(
8841 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
8842 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
8843 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
8844 assert(Options.SimpleReduction && "Only simple reduction is expected.");
8845 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
8846 ReductionOps, Options);
8847}
8848
8849llvm::Value *CGOpenMPSIMDRuntime::emitTaskReductionInit(
8850 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
8851 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
8852 llvm_unreachable("Not supported in SIMD-only mode");
8853}
8854
8855void CGOpenMPSIMDRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
8856 SourceLocation Loc,
8857 ReductionCodeGen &RCG,
8858 unsigned N) {
8859 llvm_unreachable("Not supported in SIMD-only mode");
8860}
8861
8862Address CGOpenMPSIMDRuntime::getTaskReductionItem(CodeGenFunction &CGF,
8863 SourceLocation Loc,
8864 llvm::Value *ReductionsPtr,
8865 LValue SharedLVal) {
8866 llvm_unreachable("Not supported in SIMD-only mode");
8867}
8868
8869void CGOpenMPSIMDRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
8870 SourceLocation Loc) {
8871 llvm_unreachable("Not supported in SIMD-only mode");
8872}
8873
8874void CGOpenMPSIMDRuntime::emitCancellationPointCall(
8875 CodeGenFunction &CGF, SourceLocation Loc,
8876 OpenMPDirectiveKind CancelRegion) {
8877 llvm_unreachable("Not supported in SIMD-only mode");
8878}
8879
8880void CGOpenMPSIMDRuntime::emitCancelCall(CodeGenFunction &CGF,
8881 SourceLocation Loc, const Expr *IfCond,
8882 OpenMPDirectiveKind CancelRegion) {
8883 llvm_unreachable("Not supported in SIMD-only mode");
8884}
8885
8886void CGOpenMPSIMDRuntime::emitTargetOutlinedFunction(
8887 const OMPExecutableDirective &D, StringRef ParentName,
8888 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
8889 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
8890 llvm_unreachable("Not supported in SIMD-only mode");
8891}
8892
8893void CGOpenMPSIMDRuntime::emitTargetCall(CodeGenFunction &CGF,
8894 const OMPExecutableDirective &D,
8895 llvm::Value *OutlinedFn,
8896 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00008897 const Expr *IfCond, const Expr *Device) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00008898 llvm_unreachable("Not supported in SIMD-only mode");
8899}
8900
8901bool CGOpenMPSIMDRuntime::emitTargetFunctions(GlobalDecl GD) {
8902 llvm_unreachable("Not supported in SIMD-only mode");
8903}
8904
8905bool CGOpenMPSIMDRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
8906 llvm_unreachable("Not supported in SIMD-only mode");
8907}
8908
8909bool CGOpenMPSIMDRuntime::emitTargetGlobal(GlobalDecl GD) {
8910 return false;
8911}
8912
8913llvm::Function *CGOpenMPSIMDRuntime::emitRegistrationFunction() {
8914 return nullptr;
8915}
8916
8917void CGOpenMPSIMDRuntime::emitTeamsCall(CodeGenFunction &CGF,
8918 const OMPExecutableDirective &D,
8919 SourceLocation Loc,
8920 llvm::Value *OutlinedFn,
8921 ArrayRef<llvm::Value *> CapturedVars) {
8922 llvm_unreachable("Not supported in SIMD-only mode");
8923}
8924
8925void CGOpenMPSIMDRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
8926 const Expr *NumTeams,
8927 const Expr *ThreadLimit,
8928 SourceLocation Loc) {
8929 llvm_unreachable("Not supported in SIMD-only mode");
8930}
8931
8932void CGOpenMPSIMDRuntime::emitTargetDataCalls(
8933 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8934 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
8935 llvm_unreachable("Not supported in SIMD-only mode");
8936}
8937
8938void CGOpenMPSIMDRuntime::emitTargetDataStandAloneCall(
8939 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8940 const Expr *Device) {
8941 llvm_unreachable("Not supported in SIMD-only mode");
8942}
8943
8944void CGOpenMPSIMDRuntime::emitDoacrossInit(CodeGenFunction &CGF,
8945 const OMPLoopDirective &D) {
8946 llvm_unreachable("Not supported in SIMD-only mode");
8947}
8948
8949void CGOpenMPSIMDRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
8950 const OMPDependClause *C) {
8951 llvm_unreachable("Not supported in SIMD-only mode");
8952}
8953
8954const VarDecl *
8955CGOpenMPSIMDRuntime::translateParameter(const FieldDecl *FD,
8956 const VarDecl *NativeParam) const {
8957 llvm_unreachable("Not supported in SIMD-only mode");
8958}
8959
8960Address
8961CGOpenMPSIMDRuntime::getParameterAddress(CodeGenFunction &CGF,
8962 const VarDecl *NativeParam,
8963 const VarDecl *TargetParam) const {
8964 llvm_unreachable("Not supported in SIMD-only mode");
8965}
8966