blob: cade093941a54f57df31188dea27bdc270967980 [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"
Richard Smithbf5bcf22018-06-26 23:20:26 +000022#include "clang/Basic/BitmaskEnum.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000023#include "llvm/ADT/ArrayRef.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 {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000037/// Base class for handling code generation inside OpenMP regions.
Alexey Bataev18095712014-10-10 12:19:54 +000038class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
39public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000040 /// Kinds of OpenMP regions used in codegen.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000041 enum CGOpenMPRegionKind {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000042 /// Region with outlined function for standalone 'parallel'
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000043 /// directive.
44 ParallelOutlinedRegion,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000045 /// Region with outlined function for standalone 'task' directive.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000046 TaskOutlinedRegion,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000047 /// Region for constructs that do not require function outlining,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000048 /// like 'for', 'sections', 'atomic' etc. directives.
49 InlinedRegion,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000050 /// Region with outlined function for standalone 'target' directive.
Samuel Antaobed3c462015-10-02 16:14:20 +000051 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000067 /// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000071 /// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000074 /// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000099/// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000112 /// Get a variable or parameter for storing global thread id
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000113 /// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000116 /// 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:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000126 /// A variable or parameter storing global thread id for OpenMP
Alexey Bataev18095712014-10-10 12:19:54 +0000127 /// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000132/// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000193 /// Get a variable or parameter for storing global thread id
Alexey Bataev62b63b12015-03-10 07:28:44 +0000194 /// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000197 /// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000200 /// Get the name of the capture helper.
Alexey Bataev62b63b12015-03-10 07:28:44 +0000201 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:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000214 /// A variable or parameter storing global thread id for OpenMP
Alexey Bataev62b63b12015-03-10 07:28:44 +0000215 /// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000221/// API for inlined captured statement code generation in OpenMP
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000222/// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000232 // 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000247 /// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000262 /// Get a variable or parameter for storing global thread id
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000263 /// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000270 /// Get an LValue for the current ThreadID variable.
Alexey Bataev311a9282017-10-12 13:51:32 +0000271 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override {
272 if (OuterRegionInfo)
273 return OuterRegionInfo->getThreadIDVariableLValue(CGF);
274 llvm_unreachable("No LValue for inlined OpenMP construct");
275 }
276
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000277 /// 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:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000299 /// CodeGen info about outer OpenMP region.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000300 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
301 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000302};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000303
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000304/// API for captured statement code generation in OpenMP target
Samuel Antaobed3c462015-10-02 16:14:20 +0000305/// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000317 /// This is unused for target regions because each starts executing
Samuel Antaobed3c462015-10-02 16:14:20 +0000318 /// with a single thread.
319 const VarDecl *getThreadIDVariable() const override { return nullptr; }
320
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000321 /// 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}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000336/// API for generation of expressions captured in a innermost OpenMP
Samuel Antaob68e2db2016-03-03 16:20:23 +0000337/// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000366 /// Lookup the captured field decl for a variable.
Samuel Antaob68e2db2016-03-03 16:20:23 +0000367 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000373 /// Emit the captured statement body.
Samuel Antaob68e2db2016-03-03 16:20:23 +0000374 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
375 llvm_unreachable("No body for expressions");
376 }
377
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000378 /// Get a variable or parameter for storing global thread id
Samuel Antaob68e2db2016-03-03 16:20:23 +0000379 /// inside OpenMP construct.
380 const VarDecl *getThreadIDVariable() const override {
381 llvm_unreachable("No thread id for expressions");
382 }
383
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000384 /// Get the name of the capture helper.
Samuel Antaob68e2db2016-03-03 16:20:23 +0000385 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000396/// RAII for emitting code of OpenMP constructs.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000397class 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:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000404 /// Constructs region for combined constructs.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000405 /// \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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000433/// Values for bit flags used in the ident_t to describe the fields.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000434/// 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 {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000437 /// Use trampoline for internal microtask.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000438 OMP_IDENT_IMD = 0x01,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000439 /// Use c-style ident structure.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000440 OMP_IDENT_KMPC = 0x02,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000441 /// Atomic reduction option for kmpc_reduce.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000442 OMP_ATOMIC_REDUCE = 0x10,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000443 /// Explicit 'barrier' directive.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000444 OMP_IDENT_BARRIER_EXPL = 0x20,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000445 /// Implicit barrier in code.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000446 OMP_IDENT_BARRIER_IMPL = 0x40,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000447 /// Implicit barrier in 'for' directive.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000448 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000449 /// Implicit barrier in 'sections' directive.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000450 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000451 /// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000462/// Describes ident structure that describes a source location.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000463/// 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 {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000489 /// might be used in Fortran
Alexey Bataev50b3c952016-02-19 10:38:26 +0000490 IdentField_Reserved_1,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000491 /// OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000492 IdentField_Flags,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000493 /// Not really used in Fortran any more
Alexey Bataev50b3c952016-02-19 10:38:26 +0000494 IdentField_Reserved_2,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000495 /// Source[4] in Fortran, do not use for C++
Alexey Bataev50b3c952016-02-19 10:38:26 +0000496 IdentField_Reserved_3,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000497 /// String describing the source location. The string is composed of
Alexey Bataev50b3c952016-02-19 10:38:26 +0000498 /// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000503/// Schedule types for 'omp for' loops (these enumerators are taken from
Alexey Bataev50b3c952016-02-19 10:38:26 +0000504/// the enum sched_type in kmp.h).
505enum OpenMPSchedType {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000506 /// Lower bound for default (unordered) versions.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000507 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,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000516 /// Lower bound for 'ordered' versions.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000517 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,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000525 /// dist_schedule types
Carlo Bertollifc35ad22016-03-07 16:04:49 +0000526 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 {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000536 /// Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000537 /// kmpc_micro microtask, ...);
538 OMPRTL__kmpc_fork_call,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000539 /// Call to void *__kmpc_threadprivate_cached(ident_t *loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000540 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
541 OMPRTL__kmpc_threadprivate_cached,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000542 /// Call to void __kmpc_threadprivate_register( ident_t *,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000543 /// 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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000811/// Emit initialization of arrays of complex types.
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000812/// \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
900LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000901 return CGF.EmitOMPSharedLValue(E);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000902}
903
904LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
905 const Expr *E) {
906 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
907 return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
908 return LValue();
909}
910
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000911void ReductionCodeGen::emitAggregateInitialization(
912 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
913 const OMPDeclareReductionDecl *DRD) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000914 // Emit VarDecl with copy init for arrays.
915 // Get the address of the original variable captured in current
916 // captured region.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000917 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000918 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva7b19152017-10-12 20:03:39 +0000919 bool EmitDeclareReductionInit =
920 DRD && (DRD->getInitializer() || !PrivateVD->hasInit());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000921 EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
Alexey Bataeva7b19152017-10-12 20:03:39 +0000922 EmitDeclareReductionInit,
923 EmitDeclareReductionInit ? ClausesData[N].ReductionOp
924 : PrivateVD->getInit(),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000925 DRD, SharedLVal.getAddress());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000926}
927
928ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
929 ArrayRef<const Expr *> Privates,
930 ArrayRef<const Expr *> ReductionOps) {
931 ClausesData.reserve(Shareds.size());
932 SharedAddresses.reserve(Shareds.size());
933 Sizes.reserve(Shareds.size());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000934 BaseDecls.reserve(Shareds.size());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000935 auto IPriv = Privates.begin();
936 auto IRed = ReductionOps.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000937 for (const Expr *Ref : Shareds) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000938 ClausesData.emplace_back(Ref, *IPriv, *IRed);
939 std::advance(IPriv, 1);
940 std::advance(IRed, 1);
941 }
942}
943
944void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
945 assert(SharedAddresses.size() == N &&
946 "Number of generated lvalues must be exactly N.");
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000947 LValue First = emitSharedLValue(CGF, ClausesData[N].Ref);
948 LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Ref);
949 SharedAddresses.emplace_back(First, Second);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000950}
951
952void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000953 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000954 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
955 QualType PrivateType = PrivateVD->getType();
956 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000957 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000958 Sizes.emplace_back(
959 CGF.getTypeSize(
960 SharedAddresses[N].first.getType().getNonReferenceType()),
961 nullptr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000962 return;
963 }
964 llvm::Value *Size;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000965 llvm::Value *SizeInChars;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000966 auto *ElemType =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000967 cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
968 ->getElementType();
969 auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000970 if (AsArraySection) {
971 Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
972 SharedAddresses[N].first.getPointer());
973 Size = CGF.Builder.CreateNUWAdd(
974 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000975 SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000976 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000977 SizeInChars = CGF.getTypeSize(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000978 SharedAddresses[N].first.getType().getNonReferenceType());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000979 Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000980 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000981 Sizes.emplace_back(SizeInChars, Size);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000982 CodeGenFunction::OpaqueValueMapping OpaqueMap(
983 CGF,
984 cast<OpaqueValueExpr>(
985 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
986 RValue::get(Size));
987 CGF.EmitVariablyModifiedType(PrivateType);
988}
989
990void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
991 llvm::Value *Size) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000992 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000993 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
994 QualType PrivateType = PrivateVD->getType();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000995 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000996 assert(!Size && !Sizes[N].second &&
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000997 "Size should be nullptr for non-variably modified reduction "
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000998 "items.");
999 return;
1000 }
1001 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1002 CGF,
1003 cast<OpaqueValueExpr>(
1004 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
1005 RValue::get(Size));
1006 CGF.EmitVariablyModifiedType(PrivateType);
1007}
1008
1009void ReductionCodeGen::emitInitialization(
1010 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
1011 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
1012 assert(SharedAddresses.size() > N && "No variable was generated");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001013 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001014 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001015 const OMPDeclareReductionDecl *DRD =
1016 getReductionInit(ClausesData[N].ReductionOp);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001017 QualType PrivateType = PrivateVD->getType();
1018 PrivateAddr = CGF.Builder.CreateElementBitCast(
1019 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1020 QualType SharedType = SharedAddresses[N].first.getType();
1021 SharedLVal = CGF.MakeAddrLValue(
1022 CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
1023 CGF.ConvertTypeForMem(SharedType)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001024 SharedType, SharedAddresses[N].first.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001025 CGF.CGM.getTBAAInfoForSubobject(SharedAddresses[N].first, SharedType));
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001026 if (CGF.getContext().getAsArrayType(PrivateVD->getType())) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001027 emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001028 } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
1029 emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
1030 PrivateAddr, SharedLVal.getAddress(),
1031 SharedLVal.getType());
1032 } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
1033 !CGF.isTrivialInitializer(PrivateVD->getInit())) {
1034 CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
1035 PrivateVD->getType().getQualifiers(),
1036 /*IsInitializer=*/false);
1037 }
1038}
1039
1040bool ReductionCodeGen::needCleanups(unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001041 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001042 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1043 QualType PrivateType = PrivateVD->getType();
1044 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1045 return DTorKind != QualType::DK_none;
1046}
1047
1048void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
1049 Address PrivateAddr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001050 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001051 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1052 QualType PrivateType = PrivateVD->getType();
1053 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1054 if (needCleanups(N)) {
1055 PrivateAddr = CGF.Builder.CreateElementBitCast(
1056 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1057 CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
1058 }
1059}
1060
1061static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1062 LValue BaseLV) {
1063 BaseTy = BaseTy.getNonReferenceType();
1064 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1065 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001066 if (const auto *PtrTy = BaseTy->getAs<PointerType>()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001067 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001068 } else {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00001069 LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(), BaseTy);
1070 BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001071 }
1072 BaseTy = BaseTy->getPointeeType();
1073 }
1074 return CGF.MakeAddrLValue(
1075 CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
1076 CGF.ConvertTypeForMem(ElTy)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001077 BaseLV.getType(), BaseLV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001078 CGF.CGM.getTBAAInfoForSubobject(BaseLV, BaseLV.getType()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001079}
1080
1081static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1082 llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
1083 llvm::Value *Addr) {
1084 Address Tmp = Address::invalid();
1085 Address TopTmp = Address::invalid();
1086 Address MostTopTmp = Address::invalid();
1087 BaseTy = BaseTy.getNonReferenceType();
1088 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1089 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1090 Tmp = CGF.CreateMemTemp(BaseTy);
1091 if (TopTmp.isValid())
1092 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
1093 else
1094 MostTopTmp = Tmp;
1095 TopTmp = Tmp;
1096 BaseTy = BaseTy->getPointeeType();
1097 }
1098 llvm::Type *Ty = BaseLVType;
1099 if (Tmp.isValid())
1100 Ty = Tmp.getElementType();
1101 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
1102 if (Tmp.isValid()) {
1103 CGF.Builder.CreateStore(Addr, Tmp);
1104 return MostTopTmp;
1105 }
1106 return Address(Addr, BaseLVAlignment);
1107}
1108
Alexey Bataev1c44e152018-03-06 18:59:43 +00001109static const VarDecl *getBaseDecl(const Expr *Ref, const DeclRefExpr *&DE) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001110 const VarDecl *OrigVD = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001111 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(Ref)) {
1112 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
1113 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001114 Base = TempOASE->getBase()->IgnoreParenImpCasts();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001115 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001116 Base = TempASE->getBase()->IgnoreParenImpCasts();
1117 DE = cast<DeclRefExpr>(Base);
1118 OrigVD = cast<VarDecl>(DE->getDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001119 } else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Ref)) {
1120 const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
1121 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001122 Base = TempASE->getBase()->IgnoreParenImpCasts();
1123 DE = cast<DeclRefExpr>(Base);
1124 OrigVD = cast<VarDecl>(DE->getDecl());
1125 }
Alexey Bataev1c44e152018-03-06 18:59:43 +00001126 return OrigVD;
1127}
1128
1129Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
1130 Address PrivateAddr) {
1131 const DeclRefExpr *DE;
1132 if (const VarDecl *OrigVD = ::getBaseDecl(ClausesData[N].Ref, DE)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001133 BaseDecls.emplace_back(OrigVD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001134 LValue OriginalBaseLValue = CGF.EmitLValue(DE);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001135 LValue BaseLValue =
1136 loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1137 OriginalBaseLValue);
1138 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1139 BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001140 llvm::Value *PrivatePointer =
1141 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1142 PrivateAddr.getPointer(),
1143 SharedAddresses[N].first.getAddress().getType());
1144 llvm::Value *Ptr = CGF.Builder.CreateGEP(PrivatePointer, Adjustment);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001145 return castToBase(CGF, OrigVD->getType(),
1146 SharedAddresses[N].first.getType(),
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001147 OriginalBaseLValue.getAddress().getType(),
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001148 OriginalBaseLValue.getAlignment(), Ptr);
1149 }
1150 BaseDecls.emplace_back(
1151 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1152 return PrivateAddr;
1153}
1154
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001155bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001156 const OMPDeclareReductionDecl *DRD =
1157 getReductionInit(ClausesData[N].ReductionOp);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001158 return DRD && DRD->getInitializer();
1159}
1160
Alexey Bataev18095712014-10-10 12:19:54 +00001161LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00001162 return CGF.EmitLoadOfPointerLValue(
1163 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1164 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +00001165}
1166
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001167void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001168 if (!CGF.HaveInsertPoint())
1169 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001170 // 1.2.2 OpenMP Language Terminology
1171 // Structured block - An executable statement with a single entry at the
1172 // top and a single exit at the bottom.
1173 // The point of exit cannot be a branch out of the structured block.
1174 // longjmp() and throw() must not violate the entry/exit criteria.
1175 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001176 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001177 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001178}
1179
Alexey Bataev62b63b12015-03-10 07:28:44 +00001180LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1181 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001182 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1183 getThreadIDVariable()->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00001184 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001185}
1186
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001187static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
1188 QualType FieldTy) {
1189 auto *Field = FieldDecl::Create(
1190 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
1191 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
1192 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
1193 Field->setAccess(AS_public);
1194 DC->addDecl(Field);
1195 return Field;
1196}
1197
Alexey Bataev18fa2322018-05-02 14:20:50 +00001198CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM, StringRef FirstSeparator,
1199 StringRef Separator)
1200 : CGM(CGM), FirstSeparator(FirstSeparator), Separator(Separator),
1201 OffloadEntriesInfoManager(CGM) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001202 ASTContext &C = CGM.getContext();
1203 RecordDecl *RD = C.buildImplicitRecord("ident_t");
1204 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1205 RD->startDefinition();
1206 // reserved_1
1207 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1208 // flags
1209 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1210 // reserved_2
1211 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1212 // reserved_3
1213 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1214 // psource
1215 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
1216 RD->completeDefinition();
1217 IdentQTy = C.getRecordType(RD);
1218 IdentTy = CGM.getTypes().ConvertRecordDeclType(RD);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001219 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +00001220
1221 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +00001222}
1223
Alexey Bataev91797552015-03-18 04:13:55 +00001224void CGOpenMPRuntime::clear() {
1225 InternalVars.clear();
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00001226 // Clean non-target variable declarations possibly used only in debug info.
1227 for (const auto &Data : EmittedNonTargetVariables) {
1228 if (!Data.getValue().pointsToAliveValue())
1229 continue;
1230 auto *GV = dyn_cast<llvm::GlobalVariable>(Data.getValue());
1231 if (!GV)
1232 continue;
1233 if (!GV->isDeclaration() || GV->getNumUses() > 0)
1234 continue;
1235 GV->eraseFromParent();
1236 }
Alexey Bataev91797552015-03-18 04:13:55 +00001237}
1238
Alexey Bataev18fa2322018-05-02 14:20:50 +00001239std::string CGOpenMPRuntime::getName(ArrayRef<StringRef> Parts) const {
1240 SmallString<128> Buffer;
1241 llvm::raw_svector_ostream OS(Buffer);
1242 StringRef Sep = FirstSeparator;
1243 for (StringRef Part : Parts) {
1244 OS << Sep << Part;
1245 Sep = Separator;
1246 }
1247 return OS.str();
1248}
1249
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001250static llvm::Function *
1251emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1252 const Expr *CombinerInitializer, const VarDecl *In,
1253 const VarDecl *Out, bool IsCombiner) {
1254 // void .omp_combiner.(Ty *in, Ty *out);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001255 ASTContext &C = CGM.getContext();
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001256 QualType PtrTy = C.getPointerType(Ty).withRestrict();
1257 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001258 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001259 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001260 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001261 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001262 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001263 Args.push_back(&OmpInParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001264 const CGFunctionInfo &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001265 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001266 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00001267 std::string Name = CGM.getOpenMPRuntime().getName(
1268 {IsCombiner ? "omp_combiner" : "omp_initializer", ""});
1269 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
1270 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001271 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001272 Fn->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001273 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001274 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001275 CodeGenFunction CGF(CGM);
1276 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1277 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001278 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, In->getLocation(),
1279 Out->getLocation());
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001280 CodeGenFunction::OMPPrivateScope Scope(CGF);
1281 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001282 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001283 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1284 .getAddress();
1285 });
1286 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001287 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001288 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1289 .getAddress();
1290 });
1291 (void)Scope.Privatize();
Alexey Bataev070f43a2017-09-06 14:49:58 +00001292 if (!IsCombiner && Out->hasInit() &&
1293 !CGF.isTrivialInitializer(Out->getInit())) {
1294 CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
1295 Out->getType().getQualifiers(),
1296 /*IsInitializer=*/true);
1297 }
1298 if (CombinerInitializer)
1299 CGF.EmitIgnoredExpr(CombinerInitializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001300 Scope.ForceCleanup();
1301 CGF.FinishFunction();
1302 return Fn;
1303}
1304
1305void CGOpenMPRuntime::emitUserDefinedReduction(
1306 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1307 if (UDRMap.count(D) > 0)
1308 return;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001309 llvm::Function *Combiner = emitCombinerOrInitializer(
Alexey Bataeve6aa4692018-09-13 16:54:05 +00001310 CGM, D->getType(), D->getCombiner(),
1311 cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerIn())->getDecl()),
1312 cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerOut())->getDecl()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001313 /*IsCombiner=*/true);
1314 llvm::Function *Initializer = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001315 if (const Expr *Init = D->getInitializer()) {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001316 Initializer = emitCombinerOrInitializer(
Alexey Bataev070f43a2017-09-06 14:49:58 +00001317 CGM, D->getType(),
1318 D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init
1319 : nullptr,
Alexey Bataeve6aa4692018-09-13 16:54:05 +00001320 cast<VarDecl>(cast<DeclRefExpr>(D->getInitOrig())->getDecl()),
1321 cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001322 /*IsCombiner=*/false);
1323 }
Alexey Bataev43a919f2018-04-13 17:48:43 +00001324 UDRMap.try_emplace(D, Combiner, Initializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001325 if (CGF) {
1326 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1327 Decls.second.push_back(D);
1328 }
1329}
1330
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001331std::pair<llvm::Function *, llvm::Function *>
1332CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1333 auto I = UDRMap.find(D);
1334 if (I != UDRMap.end())
1335 return I->second;
1336 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1337 return UDRMap.lookup(D);
1338}
1339
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001340static llvm::Value *emitParallelOrTeamsOutlinedFunction(
1341 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1342 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1343 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001344 assert(ThreadIDVar->getType()->isPointerType() &&
1345 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +00001346 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00001347 bool HasCancel = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001348 if (const auto *OPD = dyn_cast<OMPParallelDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001349 HasCancel = OPD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001350 else if (const auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001351 HasCancel = OPSD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001352 else if (const auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001353 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001354 else if (const auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D))
Alexey Bataev2139ed62017-11-16 18:20:21 +00001355 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001356 else if (const auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&D))
Alexey Bataev10a54312017-11-27 16:54:08 +00001357 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001358 else if (const auto *OPFD =
1359 dyn_cast<OMPTeamsDistributeParallelForDirective>(&D))
Alexey Bataev10a54312017-11-27 16:54:08 +00001360 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001361 else if (const auto *OPFD =
Alexey Bataev10a54312017-11-27 16:54:08 +00001362 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D))
1363 HasCancel = OPFD->hasCancel();
Alexey Bataev25e5b442015-09-15 12:52:43 +00001364 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001365 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +00001366 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001367 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +00001368}
1369
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001370llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
1371 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1372 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1373 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1374 return emitParallelOrTeamsOutlinedFunction(
1375 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1376}
1377
1378llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1379 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1380 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1381 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1382 return emitParallelOrTeamsOutlinedFunction(
1383 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1384}
1385
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001386llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
1387 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +00001388 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1389 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1390 bool Tied, unsigned &NumberOfParts) {
1391 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1392 PrePostActionTy &) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001393 llvm::Value *ThreadID = getThreadID(CGF, D.getBeginLoc());
1394 llvm::Value *UpLoc = emitUpdateLocation(CGF, D.getBeginLoc());
Alexey Bataev48591dd2016-04-20 04:01:36 +00001395 llvm::Value *TaskArgs[] = {
1396 UpLoc, ThreadID,
1397 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1398 TaskTVar->getType()->castAs<PointerType>())
1399 .getPointer()};
1400 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1401 };
1402 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1403 UntiedCodeGen);
1404 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001405 assert(!ThreadIDVar->getType()->isPointerType() &&
1406 "thread id variable must be of type kmp_int32 for tasks");
Alexey Bataev475a7442018-01-12 19:39:11 +00001407 const OpenMPDirectiveKind Region =
1408 isOpenMPTaskLoopDirective(D.getDirectiveKind()) ? OMPD_taskloop
1409 : OMPD_task;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001410 const CapturedStmt *CS = D.getCapturedStmt(Region);
1411 const auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001412 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +00001413 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1414 InnermostKind,
1415 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +00001416 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001417 llvm::Value *Res = CGF.GenerateCapturedStmtFunction(*CS);
Alexey Bataev48591dd2016-04-20 04:01:36 +00001418 if (!Tied)
1419 NumberOfParts = Action.getNumberOfParts();
1420 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001421}
1422
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001423static void buildStructValue(ConstantStructBuilder &Fields, CodeGenModule &CGM,
1424 const RecordDecl *RD, const CGRecordLayout &RL,
1425 ArrayRef<llvm::Constant *> Data) {
1426 llvm::StructType *StructTy = RL.getLLVMType();
1427 unsigned PrevIdx = 0;
1428 ConstantInitBuilder CIBuilder(CGM);
1429 auto DI = Data.begin();
1430 for (const FieldDecl *FD : RD->fields()) {
1431 unsigned Idx = RL.getLLVMFieldNo(FD);
1432 // Fill the alignment.
1433 for (unsigned I = PrevIdx; I < Idx; ++I)
1434 Fields.add(llvm::Constant::getNullValue(StructTy->getElementType(I)));
1435 PrevIdx = Idx + 1;
1436 Fields.add(*DI);
1437 ++DI;
1438 }
1439}
1440
1441template <class... As>
1442static llvm::GlobalVariable *
Mike Ricee1ca7b62018-08-29 15:45:11 +00001443createGlobalStruct(CodeGenModule &CGM, QualType Ty, bool IsConstant,
1444 ArrayRef<llvm::Constant *> Data, const Twine &Name,
1445 As &&... Args) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001446 const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1447 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1448 ConstantInitBuilder CIBuilder(CGM);
1449 ConstantStructBuilder Fields = CIBuilder.beginStruct(RL.getLLVMType());
1450 buildStructValue(Fields, CGM, RD, RL, Data);
1451 return Fields.finishAndCreateGlobal(
Mike Ricee1ca7b62018-08-29 15:45:11 +00001452 Name, CGM.getContext().getAlignOfGlobalVarInChars(Ty), IsConstant,
1453 std::forward<As>(Args)...);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001454}
1455
1456template <typename T>
Benjamin Kramer651d0bf2018-05-15 21:26:47 +00001457static void
1458createConstantGlobalStructAndAddToParent(CodeGenModule &CGM, QualType Ty,
1459 ArrayRef<llvm::Constant *> Data,
1460 T &Parent) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001461 const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1462 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1463 ConstantStructBuilder Fields = Parent.beginStruct(RL.getLLVMType());
1464 buildStructValue(Fields, CGM, RD, RL, Data);
1465 Fields.finishAndAddTo(Parent);
1466}
1467
Alexey Bataev50b3c952016-02-19 10:38:26 +00001468Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001469 CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
Alexey Bataevceeaa482018-11-21 21:04:34 +00001470 unsigned Reserved2Flags = getDefaultLocationReserved2Flags();
1471 FlagsTy FlagsKey(Flags, Reserved2Flags);
1472 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(FlagsKey);
Alexey Bataev9959db52014-05-06 10:08:46 +00001473 if (!Entry) {
1474 if (!DefaultOpenMPPSource) {
1475 // Initialize default location for psource field of ident_t structure of
1476 // all ident_t objects. Format is ";file;function;line;column;;".
1477 // Taken from
1478 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1479 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +00001480 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001481 DefaultOpenMPPSource =
1482 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1483 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001484
Alexey Bataevceeaa482018-11-21 21:04:34 +00001485 llvm::Constant *Data[] = {
1486 llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1487 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
1488 llvm::ConstantInt::get(CGM.Int32Ty, Reserved2Flags),
1489 llvm::ConstantInt::getNullValue(CGM.Int32Ty), DefaultOpenMPPSource};
Mike Ricee1ca7b62018-08-29 15:45:11 +00001490 llvm::GlobalValue *DefaultOpenMPLocation =
Alexey Bataevceeaa482018-11-21 21:04:34 +00001491 createGlobalStruct(CGM, IdentQTy, isDefaultLocationConstant(), Data, "",
Mike Ricee1ca7b62018-08-29 15:45:11 +00001492 llvm::GlobalValue::PrivateLinkage);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001493 DefaultOpenMPLocation->setUnnamedAddr(
1494 llvm::GlobalValue::UnnamedAddr::Global);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001495
Alexey Bataevceeaa482018-11-21 21:04:34 +00001496 OpenMPDefaultLocMap[FlagsKey] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +00001497 }
John McCall7f416cc2015-09-08 08:05:57 +00001498 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +00001499}
1500
Alexey Bataevfd006c42018-10-05 15:08:53 +00001501void CGOpenMPRuntime::setLocThreadIdInsertPt(CodeGenFunction &CGF,
1502 bool AtCurrentPoint) {
1503 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1504 assert(!Elem.second.ServiceInsertPt && "Insert point is set already.");
1505
1506 llvm::Value *Undef = llvm::UndefValue::get(CGF.Int32Ty);
1507 if (AtCurrentPoint) {
1508 Elem.second.ServiceInsertPt = new llvm::BitCastInst(
1509 Undef, CGF.Int32Ty, "svcpt", CGF.Builder.GetInsertBlock());
1510 } else {
1511 Elem.second.ServiceInsertPt =
1512 new llvm::BitCastInst(Undef, CGF.Int32Ty, "svcpt");
1513 Elem.second.ServiceInsertPt->insertAfter(CGF.AllocaInsertPt);
1514 }
1515}
1516
1517void CGOpenMPRuntime::clearLocThreadIdInsertPt(CodeGenFunction &CGF) {
1518 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1519 if (Elem.second.ServiceInsertPt) {
1520 llvm::Instruction *Ptr = Elem.second.ServiceInsertPt;
1521 Elem.second.ServiceInsertPt = nullptr;
1522 Ptr->eraseFromParent();
1523 }
1524}
1525
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001526llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1527 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001528 unsigned Flags) {
1529 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +00001530 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001531 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +00001532 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +00001533 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001534
1535 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1536
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001537 CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
John McCall7f416cc2015-09-08 08:05:57 +00001538 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001539 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1540 if (I != OpenMPLocThreadIDMap.end())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001541 LocValue = Address(I->second.DebugLoc, Align);
John McCall7f416cc2015-09-08 08:05:57 +00001542
Alexander Musmanc6388682014-12-15 07:07:06 +00001543 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1544 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +00001545 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +00001546 // Generate "ident_t .kmpc_loc.addr;"
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001547 Address AI = CGF.CreateMemTemp(IdentQTy, ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +00001548 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +00001549 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001550 LocValue = AI;
1551
Alexey Bataevfd006c42018-10-05 15:08:53 +00001552 if (!Elem.second.ServiceInsertPt)
1553 setLocThreadIdInsertPt(CGF);
Alexey Bataev9959db52014-05-06 10:08:46 +00001554 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001555 CGF.Builder.SetInsertPoint(Elem.second.ServiceInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001556 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001557 CGF.getTypeSize(IdentQTy));
Alexey Bataev9959db52014-05-06 10:08:46 +00001558 }
1559
1560 // char **psource = &.kmpc_loc_<flags>.addr.psource;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001561 LValue Base = CGF.MakeAddrLValue(LocValue, IdentQTy);
1562 auto Fields = cast<RecordDecl>(IdentQTy->getAsTagDecl())->field_begin();
1563 LValue PSource =
1564 CGF.EmitLValueForField(Base, *std::next(Fields, IdentField_PSource));
Alexey Bataev9959db52014-05-06 10:08:46 +00001565
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001566 llvm::Value *OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
Alexey Bataevf002aca2014-05-30 05:48:40 +00001567 if (OMPDebugLoc == nullptr) {
1568 SmallString<128> Buffer2;
1569 llvm::raw_svector_ostream OS2(Buffer2);
1570 // Build debug location
1571 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1572 OS2 << ";" << PLoc.getFilename() << ";";
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001573 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl))
Alexey Bataevf002aca2014-05-30 05:48:40 +00001574 OS2 << FD->getQualifiedNameAsString();
Alexey Bataevf002aca2014-05-30 05:48:40 +00001575 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1576 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1577 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +00001578 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001579 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001580 CGF.EmitStoreOfScalar(OMPDebugLoc, PSource);
Alexey Bataevf002aca2014-05-30 05:48:40 +00001581
John McCall7f416cc2015-09-08 08:05:57 +00001582 // Our callers always pass this to a runtime function, so for
1583 // convenience, go ahead and return a naked pointer.
1584 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001585}
1586
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001587llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1588 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001589 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1590
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001591 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001592 // Check whether we've already cached a load of the thread id in this
1593 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001594 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001595 if (I != OpenMPLocThreadIDMap.end()) {
1596 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001597 if (ThreadID != nullptr)
1598 return ThreadID;
1599 }
Alexey Bataevaee18552017-08-16 14:01:00 +00001600 // If exceptions are enabled, do not use parameter to avoid possible crash.
Alexey Bataev5d2c9a42017-11-02 18:55:05 +00001601 if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions ||
1602 !CGF.getLangOpts().CXXExceptions ||
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001603 CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
Alexey Bataevaee18552017-08-16 14:01:00 +00001604 if (auto *OMPRegionInfo =
1605 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1606 if (OMPRegionInfo->getThreadIDVariable()) {
1607 // Check if this an outlined function with thread id passed as argument.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001608 LValue LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev1e491372018-01-23 18:44:14 +00001609 ThreadID = CGF.EmitLoadOfScalar(LVal, Loc);
Alexey Bataevaee18552017-08-16 14:01:00 +00001610 // If value loaded in entry block, cache it and use it everywhere in
1611 // function.
1612 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1613 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1614 Elem.second.ThreadID = ThreadID;
1615 }
1616 return ThreadID;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001617 }
Alexey Bataevd6c57552014-07-25 07:55:17 +00001618 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001619 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001620
1621 // This is not an outlined function region - need to call __kmpc_int32
1622 // kmpc_global_thread_num(ident_t *loc).
1623 // Generate thread id value and cache this value for use across the
1624 // function.
Alexey Bataevfd006c42018-10-05 15:08:53 +00001625 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1626 if (!Elem.second.ServiceInsertPt)
1627 setLocThreadIdInsertPt(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001628 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001629 CGF.Builder.SetInsertPoint(Elem.second.ServiceInsertPt);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001630 llvm::CallInst *Call = CGF.Builder.CreateCall(
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001631 createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1632 emitUpdateLocation(CGF, Loc));
1633 Call->setCallingConv(CGF.getRuntimeCC());
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001634 Elem.second.ThreadID = Call;
1635 return Call;
Alexey Bataev9959db52014-05-06 10:08:46 +00001636}
1637
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001638void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001639 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataevfd006c42018-10-05 15:08:53 +00001640 if (OpenMPLocThreadIDMap.count(CGF.CurFn)) {
1641 clearLocThreadIdInsertPt(CGF);
Alexey Bataev03b340a2014-10-21 03:16:40 +00001642 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001643 }
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001644 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001645 for(auto *D : FunctionUDRMap[CGF.CurFn])
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001646 UDRMap.erase(D);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001647 FunctionUDRMap.erase(CGF.CurFn);
1648 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001649}
1650
1651llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001652 return IdentTy->getPointerTo();
Alexey Bataev9959db52014-05-06 10:08:46 +00001653}
1654
1655llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001656 if (!Kmpc_MicroTy) {
1657 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1658 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1659 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1660 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1661 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001662 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1663}
1664
1665llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001666CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001667 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001668 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001669 case OMPRTL__kmpc_fork_call: {
1670 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1671 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001672 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1673 getKmpc_MicroPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001674 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001675 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001676 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1677 break;
1678 }
1679 case OMPRTL__kmpc_global_thread_num: {
1680 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001681 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001682 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001683 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001684 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1685 break;
1686 }
Alexey Bataev97720002014-11-11 04:05:39 +00001687 case OMPRTL__kmpc_threadprivate_cached: {
1688 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1689 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1690 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1691 CGM.VoidPtrTy, CGM.SizeTy,
1692 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001693 auto *FnTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001694 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1695 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1696 break;
1697 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001698 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001699 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1700 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001701 llvm::Type *TypeParams[] = {
1702 getIdentTyPointerTy(), CGM.Int32Ty,
1703 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001704 auto *FnTy =
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001705 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1706 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1707 break;
1708 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001709 case OMPRTL__kmpc_critical_with_hint: {
1710 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1711 // kmp_critical_name *crit, uintptr_t hint);
1712 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1713 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1714 CGM.IntPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001715 auto *FnTy =
Alexey Bataevfc57d162015-12-15 10:55:09 +00001716 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1717 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1718 break;
1719 }
Alexey Bataev97720002014-11-11 04:05:39 +00001720 case OMPRTL__kmpc_threadprivate_register: {
1721 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1722 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1723 // typedef void *(*kmpc_ctor)(void *);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001724 auto *KmpcCtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001725 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1726 /*isVarArg*/ false)->getPointerTo();
1727 // typedef void *(*kmpc_cctor)(void *, void *);
1728 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001729 auto *KmpcCopyCtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001730 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001731 /*isVarArg*/ false)
1732 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00001733 // typedef void (*kmpc_dtor)(void *);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001734 auto *KmpcDtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001735 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1736 ->getPointerTo();
1737 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1738 KmpcCopyCtorTy, KmpcDtorTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001739 auto *FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
Alexey Bataev97720002014-11-11 04:05:39 +00001740 /*isVarArg*/ false);
1741 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1742 break;
1743 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001744 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001745 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1746 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001747 llvm::Type *TypeParams[] = {
1748 getIdentTyPointerTy(), CGM.Int32Ty,
1749 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001750 auto *FnTy =
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001751 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1752 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1753 break;
1754 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001755 case OMPRTL__kmpc_cancel_barrier: {
1756 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1757 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001758 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001759 auto *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001760 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1761 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001762 break;
1763 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001764 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001765 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001766 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001767 auto *FnTy =
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001768 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1769 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1770 break;
1771 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001772 case OMPRTL__kmpc_for_static_fini: {
1773 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1774 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001775 auto *FnTy =
Alexander Musmanc6388682014-12-15 07:07:06 +00001776 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1777 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1778 break;
1779 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001780 case OMPRTL__kmpc_push_num_threads: {
1781 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1782 // kmp_int32 num_threads)
1783 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1784 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001785 auto *FnTy =
Alexey Bataevb2059782014-10-13 08:23:51 +00001786 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1787 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1788 break;
1789 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001790 case OMPRTL__kmpc_serialized_parallel: {
1791 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1792 // global_tid);
1793 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001794 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001795 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1796 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1797 break;
1798 }
1799 case OMPRTL__kmpc_end_serialized_parallel: {
1800 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1801 // global_tid);
1802 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001803 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001804 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1805 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1806 break;
1807 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001808 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001809 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001810 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001811 auto *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001812 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001813 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1814 break;
1815 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001816 case OMPRTL__kmpc_master: {
1817 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1818 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001819 auto *FnTy =
Alexey Bataev8d690652014-12-04 07:23:53 +00001820 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1821 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1822 break;
1823 }
1824 case OMPRTL__kmpc_end_master: {
1825 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1826 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001827 auto *FnTy =
Alexey Bataev8d690652014-12-04 07:23:53 +00001828 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1829 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1830 break;
1831 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001832 case OMPRTL__kmpc_omp_taskyield: {
1833 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1834 // int end_part);
1835 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001836 auto *FnTy =
Alexey Bataev9f797f32015-02-05 05:57:51 +00001837 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1838 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1839 break;
1840 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001841 case OMPRTL__kmpc_single: {
1842 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1843 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001844 auto *FnTy =
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001845 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1846 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1847 break;
1848 }
1849 case OMPRTL__kmpc_end_single: {
1850 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1851 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001852 auto *FnTy =
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001853 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1854 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1855 break;
1856 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001857 case OMPRTL__kmpc_omp_task_alloc: {
1858 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1859 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1860 // kmp_routine_entry_t *task_entry);
1861 assert(KmpRoutineEntryPtrTy != nullptr &&
1862 "Type kmp_routine_entry_t must be created.");
1863 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1864 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1865 // Return void * and then cast to particular kmp_task_t type.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001866 auto *FnTy =
Alexey Bataev62b63b12015-03-10 07:28:44 +00001867 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1868 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1869 break;
1870 }
1871 case OMPRTL__kmpc_omp_task: {
1872 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1873 // *new_task);
1874 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1875 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001876 auto *FnTy =
Alexey Bataev62b63b12015-03-10 07:28:44 +00001877 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1878 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1879 break;
1880 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001881 case OMPRTL__kmpc_copyprivate: {
1882 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001883 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001884 // kmp_int32 didit);
1885 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1886 auto *CpyFnTy =
1887 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001888 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001889 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1890 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001891 auto *FnTy =
Alexey Bataeva63048e2015-03-23 06:18:07 +00001892 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1893 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1894 break;
1895 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001896 case OMPRTL__kmpc_reduce: {
1897 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1898 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1899 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1900 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1901 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1902 /*isVarArg=*/false);
1903 llvm::Type *TypeParams[] = {
1904 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1905 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1906 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001907 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001908 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1909 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1910 break;
1911 }
1912 case OMPRTL__kmpc_reduce_nowait: {
1913 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1914 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1915 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1916 // *lck);
1917 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1918 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1919 /*isVarArg=*/false);
1920 llvm::Type *TypeParams[] = {
1921 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1922 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1923 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001924 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001925 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1926 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1927 break;
1928 }
1929 case OMPRTL__kmpc_end_reduce: {
1930 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1931 // kmp_critical_name *lck);
1932 llvm::Type *TypeParams[] = {
1933 getIdentTyPointerTy(), CGM.Int32Ty,
1934 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001935 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001936 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1937 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1938 break;
1939 }
1940 case OMPRTL__kmpc_end_reduce_nowait: {
1941 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1942 // kmp_critical_name *lck);
1943 llvm::Type *TypeParams[] = {
1944 getIdentTyPointerTy(), CGM.Int32Ty,
1945 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001946 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001947 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1948 RTLFn =
1949 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1950 break;
1951 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001952 case OMPRTL__kmpc_omp_task_begin_if0: {
1953 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1954 // *new_task);
1955 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1956 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001957 auto *FnTy =
Alexey Bataev1d677132015-04-22 13:57:31 +00001958 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1959 RTLFn =
1960 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1961 break;
1962 }
1963 case OMPRTL__kmpc_omp_task_complete_if0: {
1964 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1965 // *new_task);
1966 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1967 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001968 auto *FnTy =
Alexey Bataev1d677132015-04-22 13:57:31 +00001969 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1970 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1971 /*Name=*/"__kmpc_omp_task_complete_if0");
1972 break;
1973 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001974 case OMPRTL__kmpc_ordered: {
1975 // Build void __kmpc_ordered(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 Bataev98eb6e32015-04-22 11:15:40 +00001978 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1979 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1980 break;
1981 }
1982 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001983 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001984 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001985 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001986 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1987 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1988 break;
1989 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001990 case OMPRTL__kmpc_omp_taskwait: {
1991 // Build kmp_int32 __kmpc_omp_taskwait(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 Bataev8b8e2022015-04-27 05:22:09 +00001994 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1995 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1996 break;
1997 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001998 case OMPRTL__kmpc_taskgroup: {
1999 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
2000 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002001 auto *FnTy =
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002002 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2003 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
2004 break;
2005 }
2006 case OMPRTL__kmpc_end_taskgroup: {
2007 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
2008 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002009 auto *FnTy =
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002010 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2011 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
2012 break;
2013 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00002014 case OMPRTL__kmpc_push_proc_bind: {
2015 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
2016 // int proc_bind)
2017 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002018 auto *FnTy =
Alexey Bataev7f210c62015-06-18 13:40:03 +00002019 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2020 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
2021 break;
2022 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002023 case OMPRTL__kmpc_omp_task_with_deps: {
2024 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
2025 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
2026 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
2027 llvm::Type *TypeParams[] = {
2028 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
2029 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002030 auto *FnTy =
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002031 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
2032 RTLFn =
2033 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
2034 break;
2035 }
2036 case OMPRTL__kmpc_omp_wait_deps: {
2037 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
2038 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
2039 // kmp_depend_info_t *noalias_dep_list);
2040 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2041 CGM.Int32Ty, CGM.VoidPtrTy,
2042 CGM.Int32Ty, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002043 auto *FnTy =
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002044 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2045 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
2046 break;
2047 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00002048 case OMPRTL__kmpc_cancellationpoint: {
2049 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
2050 // global_tid, kmp_int32 cncl_kind)
2051 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002052 auto *FnTy =
Alexey Bataev0f34da12015-07-02 04:17:07 +00002053 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2054 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
2055 break;
2056 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002057 case OMPRTL__kmpc_cancel: {
2058 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
2059 // kmp_int32 cncl_kind)
2060 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002061 auto *FnTy =
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002062 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2063 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
2064 break;
2065 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002066 case OMPRTL__kmpc_push_num_teams: {
2067 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
2068 // kmp_int32 num_teams, kmp_int32 num_threads)
2069 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
2070 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002071 auto *FnTy =
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002072 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2073 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
2074 break;
2075 }
2076 case OMPRTL__kmpc_fork_teams: {
2077 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
2078 // microtask, ...);
2079 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2080 getKmpc_MicroPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002081 auto *FnTy =
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002082 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
2083 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
2084 break;
2085 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002086 case OMPRTL__kmpc_taskloop: {
2087 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
2088 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
2089 // sched, kmp_uint64 grainsize, void *task_dup);
2090 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2091 CGM.IntTy,
2092 CGM.VoidPtrTy,
2093 CGM.IntTy,
2094 CGM.Int64Ty->getPointerTo(),
2095 CGM.Int64Ty->getPointerTo(),
2096 CGM.Int64Ty,
2097 CGM.IntTy,
2098 CGM.IntTy,
2099 CGM.Int64Ty,
2100 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002101 auto *FnTy =
Alexey Bataev7292c292016-04-25 12:22:29 +00002102 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2103 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
2104 break;
2105 }
Alexey Bataev8b427062016-05-25 12:36:08 +00002106 case OMPRTL__kmpc_doacross_init: {
2107 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
2108 // num_dims, struct kmp_dim *dims);
2109 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2110 CGM.Int32Ty,
2111 CGM.Int32Ty,
2112 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002113 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002114 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2115 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
2116 break;
2117 }
2118 case OMPRTL__kmpc_doacross_fini: {
2119 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
2120 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002121 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002122 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2123 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
2124 break;
2125 }
2126 case OMPRTL__kmpc_doacross_post: {
2127 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
2128 // *vec);
2129 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2130 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002131 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002132 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2133 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
2134 break;
2135 }
2136 case OMPRTL__kmpc_doacross_wait: {
2137 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
2138 // *vec);
2139 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2140 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002141 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002142 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2143 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
2144 break;
2145 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002146 case OMPRTL__kmpc_task_reduction_init: {
2147 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
2148 // *data);
2149 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002150 auto *FnTy =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002151 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2152 RTLFn =
2153 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
2154 break;
2155 }
2156 case OMPRTL__kmpc_task_reduction_get_th_data: {
2157 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
2158 // *d);
2159 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002160 auto *FnTy =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002161 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2162 RTLFn = CGM.CreateRuntimeFunction(
2163 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2164 break;
2165 }
Samuel Antaobed3c462015-10-02 16:14:20 +00002166 case OMPRTL__tgt_target: {
George Rokos63bc9d62017-11-21 18:25:12 +00002167 // Build int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
2168 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Samuel Antaobed3c462015-10-02 16:14:20 +00002169 // *arg_types);
George Rokos63bc9d62017-11-21 18:25:12 +00002170 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaobed3c462015-10-02 16:14:20 +00002171 CGM.VoidPtrTy,
2172 CGM.Int32Ty,
2173 CGM.VoidPtrPtrTy,
2174 CGM.VoidPtrPtrTy,
2175 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002176 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002177 auto *FnTy =
Samuel Antaobed3c462015-10-02 16:14:20 +00002178 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2179 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2180 break;
2181 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002182 case OMPRTL__tgt_target_nowait: {
2183 // Build int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
2184 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2185 // int64_t *arg_types);
2186 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2187 CGM.VoidPtrTy,
2188 CGM.Int32Ty,
2189 CGM.VoidPtrPtrTy,
2190 CGM.VoidPtrPtrTy,
2191 CGM.SizeTy->getPointerTo(),
2192 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002193 auto *FnTy =
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002194 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2195 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_nowait");
2196 break;
2197 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00002198 case OMPRTL__tgt_target_teams: {
George Rokos63bc9d62017-11-21 18:25:12 +00002199 // Build int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002200 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
George Rokos63bc9d62017-11-21 18:25:12 +00002201 // int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2202 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002203 CGM.VoidPtrTy,
2204 CGM.Int32Ty,
2205 CGM.VoidPtrPtrTy,
2206 CGM.VoidPtrPtrTy,
2207 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002208 CGM.Int64Ty->getPointerTo(),
Samuel Antaob68e2db2016-03-03 16:20:23 +00002209 CGM.Int32Ty,
2210 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002211 auto *FnTy =
Samuel Antaob68e2db2016-03-03 16:20:23 +00002212 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2213 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2214 break;
2215 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002216 case OMPRTL__tgt_target_teams_nowait: {
2217 // Build int32_t __tgt_target_teams_nowait(int64_t device_id, void
2218 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
2219 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2220 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2221 CGM.VoidPtrTy,
2222 CGM.Int32Ty,
2223 CGM.VoidPtrPtrTy,
2224 CGM.VoidPtrPtrTy,
2225 CGM.SizeTy->getPointerTo(),
2226 CGM.Int64Ty->getPointerTo(),
2227 CGM.Int32Ty,
2228 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002229 auto *FnTy =
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002230 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2231 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams_nowait");
2232 break;
2233 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002234 case OMPRTL__tgt_register_lib: {
2235 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2236 QualType ParamTy =
2237 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2238 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002239 auto *FnTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002240 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2241 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2242 break;
2243 }
2244 case OMPRTL__tgt_unregister_lib: {
2245 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2246 QualType ParamTy =
2247 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2248 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002249 auto *FnTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002250 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2251 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2252 break;
2253 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002254 case OMPRTL__tgt_target_data_begin: {
George Rokos63bc9d62017-11-21 18:25:12 +00002255 // Build void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
2256 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2257 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002258 CGM.Int32Ty,
2259 CGM.VoidPtrPtrTy,
2260 CGM.VoidPtrPtrTy,
2261 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002262 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002263 auto *FnTy =
Samuel Antaodf158d52016-04-27 22:58:19 +00002264 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2265 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2266 break;
2267 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002268 case OMPRTL__tgt_target_data_begin_nowait: {
2269 // Build void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
2270 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2271 // *arg_types);
2272 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2273 CGM.Int32Ty,
2274 CGM.VoidPtrPtrTy,
2275 CGM.VoidPtrPtrTy,
2276 CGM.SizeTy->getPointerTo(),
2277 CGM.Int64Ty->getPointerTo()};
2278 auto *FnTy =
2279 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2280 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin_nowait");
2281 break;
2282 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002283 case OMPRTL__tgt_target_data_end: {
George Rokos63bc9d62017-11-21 18:25:12 +00002284 // Build void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
2285 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2286 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002287 CGM.Int32Ty,
2288 CGM.VoidPtrPtrTy,
2289 CGM.VoidPtrPtrTy,
2290 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002291 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002292 auto *FnTy =
Samuel Antaodf158d52016-04-27 22:58:19 +00002293 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2294 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2295 break;
2296 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002297 case OMPRTL__tgt_target_data_end_nowait: {
2298 // Build void __tgt_target_data_end_nowait(int64_t device_id, int32_t
2299 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2300 // *arg_types);
2301 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2302 CGM.Int32Ty,
2303 CGM.VoidPtrPtrTy,
2304 CGM.VoidPtrPtrTy,
2305 CGM.SizeTy->getPointerTo(),
2306 CGM.Int64Ty->getPointerTo()};
2307 auto *FnTy =
2308 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2309 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end_nowait");
2310 break;
2311 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002312 case OMPRTL__tgt_target_data_update: {
George Rokos63bc9d62017-11-21 18:25:12 +00002313 // Build void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
2314 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2315 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antao8d2d7302016-05-26 18:30:22 +00002316 CGM.Int32Ty,
2317 CGM.VoidPtrPtrTy,
2318 CGM.VoidPtrPtrTy,
2319 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002320 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002321 auto *FnTy =
Samuel Antao8d2d7302016-05-26 18:30:22 +00002322 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2323 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2324 break;
2325 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002326 case OMPRTL__tgt_target_data_update_nowait: {
2327 // Build void __tgt_target_data_update_nowait(int64_t device_id, int32_t
2328 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2329 // *arg_types);
2330 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2331 CGM.Int32Ty,
2332 CGM.VoidPtrPtrTy,
2333 CGM.VoidPtrPtrTy,
2334 CGM.SizeTy->getPointerTo(),
2335 CGM.Int64Ty->getPointerTo()};
2336 auto *FnTy =
2337 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2338 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update_nowait");
2339 break;
2340 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002341 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002342 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002343 return RTLFn;
2344}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002345
Alexander Musman21212e42015-03-13 10:38:23 +00002346llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2347 bool IVSigned) {
2348 assert((IVSize == 32 || IVSize == 64) &&
2349 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002350 StringRef Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2351 : "__kmpc_for_static_init_4u")
2352 : (IVSigned ? "__kmpc_for_static_init_8"
2353 : "__kmpc_for_static_init_8u");
2354 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2355 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
Alexander Musman21212e42015-03-13 10:38:23 +00002356 llvm::Type *TypeParams[] = {
2357 getIdentTyPointerTy(), // loc
2358 CGM.Int32Ty, // tid
2359 CGM.Int32Ty, // schedtype
2360 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2361 PtrTy, // p_lower
2362 PtrTy, // p_upper
2363 PtrTy, // p_stride
2364 ITy, // incr
2365 ITy // chunk
2366 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002367 auto *FnTy =
Alexander Musman21212e42015-03-13 10:38:23 +00002368 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2369 return CGM.CreateRuntimeFunction(FnTy, Name);
2370}
2371
Alexander Musman92bdaab2015-03-12 13:37:50 +00002372llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2373 bool IVSigned) {
2374 assert((IVSize == 32 || IVSize == 64) &&
2375 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002376 StringRef Name =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002377 IVSize == 32
2378 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2379 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002380 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
Alexander Musman92bdaab2015-03-12 13:37:50 +00002381 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2382 CGM.Int32Ty, // tid
2383 CGM.Int32Ty, // schedtype
2384 ITy, // lower
2385 ITy, // upper
2386 ITy, // stride
2387 ITy // chunk
2388 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002389 auto *FnTy =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002390 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2391 return CGM.CreateRuntimeFunction(FnTy, Name);
2392}
2393
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002394llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2395 bool IVSigned) {
2396 assert((IVSize == 32 || IVSize == 64) &&
2397 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002398 StringRef Name =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002399 IVSize == 32
2400 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2401 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2402 llvm::Type *TypeParams[] = {
2403 getIdentTyPointerTy(), // loc
2404 CGM.Int32Ty, // tid
2405 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002406 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002407 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2408 return CGM.CreateRuntimeFunction(FnTy, Name);
2409}
2410
Alexander Musman92bdaab2015-03-12 13:37:50 +00002411llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2412 bool IVSigned) {
2413 assert((IVSize == 32 || IVSize == 64) &&
2414 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002415 StringRef Name =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002416 IVSize == 32
2417 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2418 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002419 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2420 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002421 llvm::Type *TypeParams[] = {
2422 getIdentTyPointerTy(), // loc
2423 CGM.Int32Ty, // tid
2424 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2425 PtrTy, // p_lower
2426 PtrTy, // p_upper
2427 PtrTy // p_stride
2428 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002429 auto *FnTy =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002430 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2431 return CGM.CreateRuntimeFunction(FnTy, Name);
2432}
2433
Alexey Bataev03f270c2018-03-30 18:31:07 +00002434Address CGOpenMPRuntime::getAddrOfDeclareTargetLink(const VarDecl *VD) {
2435 if (CGM.getLangOpts().OpenMPSimd)
2436 return Address::invalid();
Alexey Bataev92327c52018-03-26 16:40:55 +00002437 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002438 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00002439 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2440 SmallString<64> PtrName;
2441 {
2442 llvm::raw_svector_ostream OS(PtrName);
2443 OS << CGM.getMangledName(GlobalDecl(VD)) << "_decl_tgt_link_ptr";
2444 }
2445 llvm::Value *Ptr = CGM.getModule().getNamedValue(PtrName);
2446 if (!Ptr) {
2447 QualType PtrTy = CGM.getContext().getPointerType(VD->getType());
2448 Ptr = getOrCreateInternalVariable(CGM.getTypes().ConvertTypeForMem(PtrTy),
2449 PtrName);
Alexey Bataev03f270c2018-03-30 18:31:07 +00002450 if (!CGM.getLangOpts().OpenMPIsDevice) {
2451 auto *GV = cast<llvm::GlobalVariable>(Ptr);
2452 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2453 GV->setInitializer(CGM.GetAddrOfGlobal(VD));
2454 }
2455 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ptr));
2456 registerTargetGlobalVariable(VD, cast<llvm::Constant>(Ptr));
Alexey Bataev92327c52018-03-26 16:40:55 +00002457 }
2458 return Address(Ptr, CGM.getContext().getDeclAlign(VD));
2459 }
2460 return Address::invalid();
2461}
2462
Alexey Bataev97720002014-11-11 04:05:39 +00002463llvm::Constant *
2464CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002465 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2466 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002467 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev18fa2322018-05-02 14:20:50 +00002468 std::string Suffix = getName({"cache", ""});
2469 return getOrCreateInternalVariable(
2470 CGM.Int8PtrPtrTy, Twine(CGM.getMangledName(VD)).concat(Suffix));
Alexey Bataev97720002014-11-11 04:05:39 +00002471}
2472
John McCall7f416cc2015-09-08 08:05:57 +00002473Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2474 const VarDecl *VD,
2475 Address VDAddr,
2476 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002477 if (CGM.getLangOpts().OpenMPUseTLS &&
2478 CGM.getContext().getTargetInfo().isTLSSupported())
2479 return VDAddr;
2480
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002481 llvm::Type *VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002482 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002483 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2484 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002485 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2486 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002487 return Address(CGF.EmitRuntimeCall(
2488 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2489 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002490}
2491
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002492void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002493 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002494 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2495 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2496 // library.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002497 llvm::Value *OMPLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002498 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002499 OMPLoc);
2500 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2501 // to register constructor/destructor for variable.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002502 llvm::Value *Args[] = {
2503 OMPLoc, CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.VoidPtrTy),
2504 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002505 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002506 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002507}
2508
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002509llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002510 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002511 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002512 if (CGM.getLangOpts().OpenMPUseTLS &&
2513 CGM.getContext().getTargetInfo().isTLSSupported())
2514 return nullptr;
2515
Alexey Bataev97720002014-11-11 04:05:39 +00002516 VD = VD->getDefinition(CGM.getContext());
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00002517 if (VD && ThreadPrivateWithDefinition.insert(CGM.getMangledName(VD)).second) {
Alexey Bataev97720002014-11-11 04:05:39 +00002518 QualType ASTTy = VD->getType();
2519
2520 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002521 const Expr *Init = VD->getAnyInitializer();
Alexey Bataev97720002014-11-11 04:05:39 +00002522 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2523 // Generate function that re-emits the declaration's initializer into the
2524 // threadprivate copy of the variable VD
2525 CodeGenFunction CtorCGF(CGM);
2526 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002527 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2528 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002529 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002530 Args.push_back(&Dst);
2531
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002532 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
John McCallc56a8b32016-03-11 04:30:31 +00002533 CGM.getContext().VoidPtrTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002534 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002535 std::string Name = getName({"__kmpc_global_ctor_", ""});
2536 llvm::Function *Fn =
2537 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002538 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002539 Args, Loc, Loc);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002540 llvm::Value *ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002541 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002542 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002543 Address Arg = Address(ArgVal, VDAddr.getAlignment());
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002544 Arg = CtorCGF.Builder.CreateElementBitCast(
2545 Arg, CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002546 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2547 /*IsInitializer=*/true);
2548 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002549 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002550 CGM.getContext().VoidPtrTy, Dst.getLocation());
2551 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2552 CtorCGF.FinishFunction();
2553 Ctor = Fn;
2554 }
2555 if (VD->getType().isDestructedType() != QualType::DK_none) {
2556 // Generate function that emits destructor call for the threadprivate copy
2557 // of the variable VD
2558 CodeGenFunction DtorCGF(CGM);
2559 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002560 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2561 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002562 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002563 Args.push_back(&Dst);
2564
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002565 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
John McCallc56a8b32016-03-11 04:30:31 +00002566 CGM.getContext().VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002567 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002568 std::string Name = getName({"__kmpc_global_dtor_", ""});
2569 llvm::Function *Fn =
2570 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002571 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002572 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002573 Loc, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002574 // Create a scope with an artificial location for the body of this function.
2575 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002576 llvm::Value *ArgVal = DtorCGF.EmitLoadOfScalar(
Alexey Bataev97720002014-11-11 04:05:39 +00002577 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002578 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2579 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002580 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2581 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2582 DtorCGF.FinishFunction();
2583 Dtor = Fn;
2584 }
2585 // Do not emit init function if it is not required.
2586 if (!Ctor && !Dtor)
2587 return nullptr;
2588
2589 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002590 auto *CopyCtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2591 /*isVarArg=*/false)
2592 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002593 // Copying constructor for the threadprivate variable.
2594 // Must be NULL - reserved by runtime, but currently it requires that this
2595 // parameter is always NULL. Otherwise it fires assertion.
2596 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2597 if (Ctor == nullptr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002598 auto *CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2599 /*isVarArg=*/false)
2600 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002601 Ctor = llvm::Constant::getNullValue(CtorTy);
2602 }
2603 if (Dtor == nullptr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002604 auto *DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2605 /*isVarArg=*/false)
2606 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002607 Dtor = llvm::Constant::getNullValue(DtorTy);
2608 }
2609 if (!CGF) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002610 auto *InitFunctionTy =
Alexey Bataev97720002014-11-11 04:05:39 +00002611 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002612 std::string Name = getName({"__omp_threadprivate_init_", ""});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002613 llvm::Function *InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Alexey Bataev18fa2322018-05-02 14:20:50 +00002614 InitFunctionTy, Name, CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002615 CodeGenFunction InitCGF(CGM);
2616 FunctionArgList ArgList;
2617 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2618 CGM.getTypes().arrangeNullaryFunction(), ArgList,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002619 Loc, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002620 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002621 InitCGF.FinishFunction();
2622 return InitFunction;
2623 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002624 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002625 }
2626 return nullptr;
2627}
2628
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002629/// Obtain information that uniquely identifies a target entry. This
Alexey Bataev34f8a702018-03-28 14:28:54 +00002630/// consists of the file and device IDs as well as line number associated with
2631/// the relevant entry source location.
2632static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
2633 unsigned &DeviceID, unsigned &FileID,
2634 unsigned &LineNum) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002635 SourceManager &SM = C.getSourceManager();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002636
2637 // The loc should be always valid and have a file ID (the user cannot use
2638 // #pragma directives in macros)
2639
2640 assert(Loc.isValid() && "Source location is expected to be always valid.");
Alexey Bataev34f8a702018-03-28 14:28:54 +00002641
2642 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
2643 assert(PLoc.isValid() && "Source location is expected to be always valid.");
2644
2645 llvm::sys::fs::UniqueID ID;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00002646 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
2647 SM.getDiagnostics().Report(diag::err_cannot_open_file)
2648 << PLoc.getFilename() << EC.message();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002649
2650 DeviceID = ID.getDevice();
2651 FileID = ID.getFile();
2652 LineNum = PLoc.getLine();
2653}
2654
2655bool CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD,
2656 llvm::GlobalVariable *Addr,
2657 bool PerformInit) {
2658 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002659 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002660 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link)
Alexey Bataevd01b7492018-08-15 19:45:12 +00002661 return CGM.getLangOpts().OpenMPIsDevice;
Alexey Bataev34f8a702018-03-28 14:28:54 +00002662 VD = VD->getDefinition(CGM.getContext());
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00002663 if (VD && !DeclareTargetWithDefinition.insert(CGM.getMangledName(VD)).second)
Alexey Bataev34f8a702018-03-28 14:28:54 +00002664 return CGM.getLangOpts().OpenMPIsDevice;
2665
2666 QualType ASTTy = VD->getType();
2667
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002668 SourceLocation Loc = VD->getCanonicalDecl()->getBeginLoc();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002669 // Produce the unique prefix to identify the new target regions. We use
2670 // the source location of the variable declaration which we know to not
2671 // conflict with any target region.
2672 unsigned DeviceID;
2673 unsigned FileID;
2674 unsigned Line;
2675 getTargetEntryUniqueInfo(CGM.getContext(), Loc, DeviceID, FileID, Line);
2676 SmallString<128> Buffer, Out;
2677 {
2678 llvm::raw_svector_ostream OS(Buffer);
2679 OS << "__omp_offloading_" << llvm::format("_%x", DeviceID)
2680 << llvm::format("_%x_", FileID) << VD->getName() << "_l" << Line;
2681 }
2682
2683 const Expr *Init = VD->getAnyInitializer();
2684 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2685 llvm::Constant *Ctor;
2686 llvm::Constant *ID;
2687 if (CGM.getLangOpts().OpenMPIsDevice) {
2688 // Generate function that re-emits the declaration's initializer into
2689 // the threadprivate copy of the variable VD
2690 CodeGenFunction CtorCGF(CGM);
2691
2692 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2693 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2694 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2695 FTy, Twine(Buffer, "_ctor"), FI, Loc);
2696 auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF);
2697 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2698 FunctionArgList(), Loc, Loc);
2699 auto AL = ApplyDebugLocation::CreateArtificial(CtorCGF);
2700 CtorCGF.EmitAnyExprToMem(Init,
2701 Address(Addr, CGM.getContext().getDeclAlign(VD)),
2702 Init->getType().getQualifiers(),
2703 /*IsInitializer=*/true);
2704 CtorCGF.FinishFunction();
2705 Ctor = Fn;
2706 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
Alexey Bataeve253f2f2018-05-09 14:15:18 +00002707 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ctor));
Alexey Bataev34f8a702018-03-28 14:28:54 +00002708 } else {
2709 Ctor = new llvm::GlobalVariable(
2710 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2711 llvm::GlobalValue::PrivateLinkage,
2712 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_ctor"));
2713 ID = Ctor;
2714 }
2715
2716 // Register the information for the entry associated with the constructor.
2717 Out.clear();
2718 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2719 DeviceID, FileID, Twine(Buffer, "_ctor").toStringRef(Out), Line, Ctor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002720 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryCtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002721 }
2722 if (VD->getType().isDestructedType() != QualType::DK_none) {
2723 llvm::Constant *Dtor;
2724 llvm::Constant *ID;
2725 if (CGM.getLangOpts().OpenMPIsDevice) {
2726 // Generate function that emits destructor call for the threadprivate
2727 // copy of the variable VD
2728 CodeGenFunction DtorCGF(CGM);
2729
2730 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2731 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2732 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2733 FTy, Twine(Buffer, "_dtor"), FI, Loc);
2734 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
2735 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2736 FunctionArgList(), Loc, Loc);
2737 // Create a scope with an artificial location for the body of this
2738 // function.
2739 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
2740 DtorCGF.emitDestroy(Address(Addr, CGM.getContext().getDeclAlign(VD)),
2741 ASTTy, DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2742 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2743 DtorCGF.FinishFunction();
2744 Dtor = Fn;
2745 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
Alexey Bataeve253f2f2018-05-09 14:15:18 +00002746 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Dtor));
Alexey Bataev34f8a702018-03-28 14:28:54 +00002747 } else {
2748 Dtor = new llvm::GlobalVariable(
2749 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2750 llvm::GlobalValue::PrivateLinkage,
2751 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_dtor"));
2752 ID = Dtor;
2753 }
2754 // Register the information for the entry associated with the destructor.
2755 Out.clear();
2756 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2757 DeviceID, FileID, Twine(Buffer, "_dtor").toStringRef(Out), Line, Dtor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002758 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryDtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002759 }
2760 return CGM.getLangOpts().OpenMPIsDevice;
2761}
2762
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002763Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2764 QualType VarType,
2765 StringRef Name) {
Alexey Bataev18fa2322018-05-02 14:20:50 +00002766 std::string Suffix = getName({"artificial", ""});
2767 std::string CacheSuffix = getName({"cache", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002768 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002769 llvm::Value *GAddr =
2770 getOrCreateInternalVariable(VarLVType, Twine(Name).concat(Suffix));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002771 llvm::Value *Args[] = {
2772 emitUpdateLocation(CGF, SourceLocation()),
2773 getThreadID(CGF, SourceLocation()),
2774 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2775 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2776 /*IsSigned=*/false),
Alexey Bataev18fa2322018-05-02 14:20:50 +00002777 getOrCreateInternalVariable(
2778 CGM.VoidPtrPtrTy, Twine(Name).concat(Suffix).concat(CacheSuffix))};
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002779 return Address(
2780 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2781 CGF.EmitRuntimeCall(
2782 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2783 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2784 CGM.getPointerAlign());
2785}
2786
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002787void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2788 const RegionCodeGenTy &ThenGen,
2789 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002790 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2791
2792 // If the condition constant folds and can be elided, try to avoid emitting
2793 // the condition and the dead arm of the if/else.
2794 bool CondConstant;
2795 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002796 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002797 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002798 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002799 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002800 return;
2801 }
2802
2803 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2804 // emit the conditional branch.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002805 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("omp_if.then");
2806 llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else");
2807 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("omp_if.end");
Alexey Bataev1d677132015-04-22 13:57:31 +00002808 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2809
2810 // Emit the 'then' code.
2811 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002812 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002813 CGF.EmitBranch(ContBlock);
2814 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002815 // There is no need to emit line number for unconditional branch.
2816 (void)ApplyDebugLocation::CreateEmpty(CGF);
2817 CGF.EmitBlock(ElseBlock);
2818 ElseGen(CGF);
2819 // There is no need to emit line number for unconditional branch.
2820 (void)ApplyDebugLocation::CreateEmpty(CGF);
2821 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002822 // Emit the continuation block for code after the if.
2823 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002824}
2825
Alexey Bataev1d677132015-04-22 13:57:31 +00002826void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2827 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002828 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002829 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002830 if (!CGF.HaveInsertPoint())
2831 return;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002832 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002833 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2834 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002835 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002836 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002837 llvm::Value *Args[] = {
2838 RTLoc,
2839 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002840 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002841 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2842 RealArgs.append(std::begin(Args), std::end(Args));
2843 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2844
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002845 llvm::Value *RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002846 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2847 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002848 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2849 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002850 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
2851 llvm::Value *ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00002852 // Build calls:
2853 // __kmpc_serialized_parallel(&Loc, GTid);
2854 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002855 CGF.EmitRuntimeCall(
2856 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002857
Alexey Bataev1d677132015-04-22 13:57:31 +00002858 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002859 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2860 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00002861 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00002862 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataev8521ff62018-07-25 20:03:01 +00002863 // ThreadId for serialized parallels is 0.
2864 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
Alexey Bataev2377fe92015-09-10 08:12:02 +00002865 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2866 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002867 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002868
Alexey Bataev1d677132015-04-22 13:57:31 +00002869 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002870 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00002871 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002872 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2873 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002874 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002875 if (IfCond) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002876 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002877 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002878 RegionCodeGenTy ThenRCG(ThenGen);
2879 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002880 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002881}
2882
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002883// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002884// thread-ID variable (it is passed in a first argument of the outlined function
2885// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2886// regular serial code region, get thread ID by calling kmp_int32
2887// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2888// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002889Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2890 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002891 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002892 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002893 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002894 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002895
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002896 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2897 QualType Int32Ty =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002898 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002899 Address ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
Alexey Bataevd74d0602014-10-13 06:02:40 +00002900 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002901 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002902
2903 return ThreadIDTemp;
2904}
2905
Alexey Bataev97720002014-11-11 04:05:39 +00002906llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002907CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002908 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002909 SmallString<256> Buffer;
2910 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002911 Out << Name;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002912 StringRef RuntimeName = Out.str();
Alexey Bataev43a919f2018-04-13 17:48:43 +00002913 auto &Elem = *InternalVars.try_emplace(RuntimeName, nullptr).first;
David Blaikie13156b62014-11-19 03:06:06 +00002914 if (Elem.second) {
2915 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002916 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002917 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002918 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002919
David Blaikie13156b62014-11-19 03:06:06 +00002920 return Elem.second = new llvm::GlobalVariable(
2921 CGM.getModule(), Ty, /*IsConstant*/ false,
2922 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2923 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002924}
2925
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002926llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev18fa2322018-05-02 14:20:50 +00002927 std::string Prefix = Twine("gomp_critical_user_", CriticalName).str();
2928 std::string Name = getName({Prefix, "var"});
2929 return getOrCreateInternalVariable(KmpCriticalNameTy, Name);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002930}
2931
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002932namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002933/// Common pre(post)-action for different OpenMP constructs.
2934class CommonActionTy final : public PrePostActionTy {
2935 llvm::Value *EnterCallee;
2936 ArrayRef<llvm::Value *> EnterArgs;
2937 llvm::Value *ExitCallee;
2938 ArrayRef<llvm::Value *> ExitArgs;
2939 bool Conditional;
2940 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002941
2942public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002943 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2944 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2945 bool Conditional = false)
2946 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2947 ExitArgs(ExitArgs), Conditional(Conditional) {}
2948 void Enter(CodeGenFunction &CGF) override {
2949 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2950 if (Conditional) {
2951 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2952 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2953 ContBlock = CGF.createBasicBlock("omp_if.end");
2954 // Generate the branch (If-stmt)
2955 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2956 CGF.EmitBlock(ThenBlock);
2957 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002958 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002959 void Done(CodeGenFunction &CGF) {
2960 // Emit the rest of blocks/branches
2961 CGF.EmitBranch(ContBlock);
2962 CGF.EmitBlock(ContBlock, true);
2963 }
2964 void Exit(CodeGenFunction &CGF) override {
2965 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002966 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002967};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002968} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002969
2970void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2971 StringRef CriticalName,
2972 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002973 SourceLocation Loc, const Expr *Hint) {
2974 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002975 // CriticalOpGen();
2976 // __kmpc_end_critical(ident_t *, gtid, Lock);
2977 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002978 if (!CGF.HaveInsertPoint())
2979 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002980 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2981 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002982 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2983 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002984 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002985 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2986 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2987 }
2988 CommonActionTy Action(
2989 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2990 : OMPRTL__kmpc_critical),
2991 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2992 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002993 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002994}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002995
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002996void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002997 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002998 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002999 if (!CGF.HaveInsertPoint())
3000 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00003001 // if(__kmpc_master(ident_t *, gtid)) {
3002 // MasterOpGen();
3003 // __kmpc_end_master(ident_t *, gtid);
3004 // }
3005 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00003006 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003007 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
3008 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
3009 /*Conditional=*/true);
3010 MasterOpGen.setAction(Action);
3011 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
3012 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00003013}
3014
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003015void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
3016 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003017 if (!CGF.HaveInsertPoint())
3018 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00003019 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
3020 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003021 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00003022 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003023 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003024 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
3025 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00003026}
3027
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003028void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
3029 const RegionCodeGenTy &TaskgroupOpGen,
3030 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003031 if (!CGF.HaveInsertPoint())
3032 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003033 // __kmpc_taskgroup(ident_t *, gtid);
3034 // TaskgroupOpGen();
3035 // __kmpc_end_taskgroup(ident_t *, gtid);
3036 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003037 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3038 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
3039 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
3040 Args);
3041 TaskgroupOpGen.setAction(Action);
3042 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003043}
3044
John McCall7f416cc2015-09-08 08:05:57 +00003045/// Given an array of pointers to variables, project the address of a
3046/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003047static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
3048 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00003049 // Pull out the pointer to the variable.
3050 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003051 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00003052 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
3053
3054 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003055 Addr = CGF.Builder.CreateElementBitCast(
3056 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00003057 return Addr;
3058}
3059
Alexey Bataeva63048e2015-03-23 06:18:07 +00003060static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00003061 CodeGenModule &CGM, llvm::Type *ArgsType,
3062 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003063 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps,
3064 SourceLocation Loc) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003065 ASTContext &C = CGM.getContext();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003066 // void copy_func(void *LHSArg, void *RHSArg);
3067 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003068 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3069 ImplicitParamDecl::Other);
3070 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3071 ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003072 Args.push_back(&LHSArg);
3073 Args.push_back(&RHSArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003074 const auto &CGFI =
3075 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003076 std::string Name =
3077 CGM.getOpenMPRuntime().getName({"omp", "copyprivate", "copy_func"});
3078 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
3079 llvm::GlobalValue::InternalLinkage, Name,
3080 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003081 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003082 Fn->setDoesNotRecurse();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003083 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003084 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00003085 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003086 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00003087 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3088 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
3089 ArgsType), CGF.getPointerAlign());
3090 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3091 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
3092 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00003093 // *(Type0*)Dst[0] = *(Type0*)Src[0];
3094 // *(Type1*)Dst[1] = *(Type1*)Src[1];
3095 // ...
3096 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00003097 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003098 const auto *DestVar =
3099 cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003100 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
3101
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003102 const auto *SrcVar =
3103 cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003104 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
3105
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003106 const auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003107 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00003108 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003109 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00003110 CGF.FinishFunction();
3111 return Fn;
3112}
3113
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003114void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003115 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00003116 SourceLocation Loc,
3117 ArrayRef<const Expr *> CopyprivateVars,
3118 ArrayRef<const Expr *> SrcExprs,
3119 ArrayRef<const Expr *> DstExprs,
3120 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003121 if (!CGF.HaveInsertPoint())
3122 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00003123 assert(CopyprivateVars.size() == SrcExprs.size() &&
3124 CopyprivateVars.size() == DstExprs.size() &&
3125 CopyprivateVars.size() == AssignmentOps.size());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003126 ASTContext &C = CGM.getContext();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003127 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003128 // if(__kmpc_single(ident_t *, gtid)) {
3129 // SingleOpGen();
3130 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003131 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003132 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00003133 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3134 // <copy_func>, did_it);
3135
John McCall7f416cc2015-09-08 08:05:57 +00003136 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003137 if (!CopyprivateVars.empty()) {
3138 // int32 did_it = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003139 QualType KmpInt32Ty =
3140 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003141 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00003142 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003143 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003144 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00003145 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003146 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
3147 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
3148 /*Conditional=*/true);
3149 SingleOpGen.setAction(Action);
3150 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
3151 if (DidIt.isValid()) {
3152 // did_it = 1;
3153 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
3154 }
3155 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003156 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3157 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00003158 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00003159 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003160 QualType CopyprivateArrayTy =
Alexey Bataeva63048e2015-03-23 06:18:07 +00003161 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3162 /*IndexTypeQuals=*/0);
3163 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00003164 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00003165 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
3166 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00003167 Address Elem = CGF.Builder.CreateConstArrayGEP(
3168 CopyprivateList, I, CGF.getPointerSize());
3169 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00003170 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003171 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
3172 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003173 }
3174 // Build function that copies private values from single region to all other
3175 // threads in the corresponding parallel region.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003176 llvm::Value *CpyFn = emitCopyprivateCopyFunction(
Alexey Bataeva63048e2015-03-23 06:18:07 +00003177 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003178 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps, Loc);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003179 llvm::Value *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00003180 Address CL =
3181 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
3182 CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003183 llvm::Value *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003184 llvm::Value *Args[] = {
3185 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
3186 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00003187 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00003188 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00003189 CpyFn, // void (*) (void *, void *) <copy_func>
3190 DidItVal // i32 did_it
3191 };
3192 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
3193 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003194}
3195
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003196void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
3197 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00003198 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003199 if (!CGF.HaveInsertPoint())
3200 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003201 // __kmpc_ordered(ident_t *, gtid);
3202 // OrderedOpGen();
3203 // __kmpc_end_ordered(ident_t *, gtid);
3204 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00003205 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003206 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003207 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
3208 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
3209 Args);
3210 OrderedOpGen.setAction(Action);
3211 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
3212 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003213 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003214 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003215}
3216
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003217void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00003218 OpenMPDirectiveKind Kind, bool EmitChecks,
3219 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003220 if (!CGF.HaveInsertPoint())
3221 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00003222 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003223 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003224 unsigned Flags;
3225 if (Kind == OMPD_for)
3226 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
3227 else if (Kind == OMPD_sections)
3228 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
3229 else if (Kind == OMPD_single)
3230 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
3231 else if (Kind == OMPD_barrier)
3232 Flags = OMP_IDENT_BARRIER_EXPL;
3233 else
3234 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003235 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
3236 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003237 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
3238 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003239 if (auto *OMPRegionInfo =
3240 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00003241 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003242 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003243 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00003244 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003245 // if (__kmpc_cancel_barrier()) {
3246 // exit from construct;
3247 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003248 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
3249 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
3250 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003251 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
3252 CGF.EmitBlock(ExitBB);
3253 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003254 CodeGenFunction::JumpDest CancelDestination =
Alexey Bataev25e5b442015-09-15 12:52:43 +00003255 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003256 CGF.EmitBranchThroughCleanup(CancelDestination);
3257 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
3258 }
3259 return;
3260 }
3261 }
3262 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00003263}
3264
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003265/// Map the OpenMP loop schedule to the runtime enumeration.
Alexander Musmanc6388682014-12-15 07:07:06 +00003266static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003267 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003268 switch (ScheduleKind) {
3269 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003270 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
3271 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00003272 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003273 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003274 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003275 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003276 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003277 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
3278 case OMPC_SCHEDULE_auto:
3279 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00003280 case OMPC_SCHEDULE_unknown:
3281 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003282 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00003283 }
3284 llvm_unreachable("Unexpected runtime schedule");
3285}
3286
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003287/// Map the OpenMP distribute schedule to the runtime enumeration.
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003288static OpenMPSchedType
3289getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
3290 // only static is allowed for dist_schedule
3291 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
3292}
3293
Alexander Musmanc6388682014-12-15 07:07:06 +00003294bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
3295 bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003296 OpenMPSchedType Schedule =
3297 getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00003298 return Schedule == OMP_sch_static;
3299}
3300
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003301bool CGOpenMPRuntime::isStaticNonchunked(
3302 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003303 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003304 return Schedule == OMP_dist_sch_static;
3305}
3306
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003307bool CGOpenMPRuntime::isStaticChunked(OpenMPScheduleClauseKind ScheduleKind,
3308 bool Chunked) const {
3309 OpenMPSchedType Schedule =
3310 getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
3311 return Schedule == OMP_sch_static_chunked;
3312}
3313
3314bool CGOpenMPRuntime::isStaticChunked(
3315 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
3316 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
3317 return Schedule == OMP_dist_sch_static_chunked;
3318}
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003319
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003320bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003321 OpenMPSchedType Schedule =
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003322 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003323 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
3324 return Schedule != OMP_sch_static;
3325}
3326
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003327static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
3328 OpenMPScheduleClauseModifier M1,
3329 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00003330 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003331 switch (M1) {
3332 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003333 Modifier = OMP_sch_modifier_monotonic;
3334 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003335 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003336 Modifier = OMP_sch_modifier_nonmonotonic;
3337 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003338 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003339 if (Schedule == OMP_sch_static_chunked)
3340 Schedule = OMP_sch_static_balanced_chunked;
3341 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003342 case OMPC_SCHEDULE_MODIFIER_last:
3343 case OMPC_SCHEDULE_MODIFIER_unknown:
3344 break;
3345 }
3346 switch (M2) {
3347 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003348 Modifier = OMP_sch_modifier_monotonic;
3349 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003350 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003351 Modifier = OMP_sch_modifier_nonmonotonic;
3352 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003353 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003354 if (Schedule == OMP_sch_static_chunked)
3355 Schedule = OMP_sch_static_balanced_chunked;
3356 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003357 case OMPC_SCHEDULE_MODIFIER_last:
3358 case OMPC_SCHEDULE_MODIFIER_unknown:
3359 break;
3360 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00003361 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003362}
3363
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003364void CGOpenMPRuntime::emitForDispatchInit(
3365 CodeGenFunction &CGF, SourceLocation Loc,
3366 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
3367 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003368 if (!CGF.HaveInsertPoint())
3369 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003370 OpenMPSchedType Schedule = getRuntimeSchedule(
3371 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00003372 assert(Ordered ||
3373 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00003374 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
3375 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00003376 // Call __kmpc_dispatch_init(
3377 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
3378 // kmp_int[32|64] lower, kmp_int[32|64] upper,
3379 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00003380
John McCall7f416cc2015-09-08 08:05:57 +00003381 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003382 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
3383 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00003384 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003385 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3386 CGF.Builder.getInt32(addMonoNonMonoModifier(
3387 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003388 DispatchValues.LB, // Lower
3389 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003390 CGF.Builder.getIntN(IVSize, 1), // Stride
3391 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00003392 };
3393 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
3394}
3395
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003396static void emitForStaticInitCall(
3397 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
3398 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
3399 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003400 const CGOpenMPRuntime::StaticRTInput &Values) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003401 if (!CGF.HaveInsertPoint())
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003402 return;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003403
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003404 assert(!Values.Ordered);
3405 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
3406 Schedule == OMP_sch_static_balanced_chunked ||
3407 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
3408 Schedule == OMP_dist_sch_static ||
3409 Schedule == OMP_dist_sch_static_chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003410
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003411 // Call __kmpc_for_static_init(
3412 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
3413 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
3414 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
3415 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
3416 llvm::Value *Chunk = Values.Chunk;
3417 if (Chunk == nullptr) {
3418 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
3419 Schedule == OMP_dist_sch_static) &&
3420 "expected static non-chunked schedule");
3421 // If the Chunk was not specified in the clause - use default value 1.
3422 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3423 } else {
3424 assert((Schedule == OMP_sch_static_chunked ||
3425 Schedule == OMP_sch_static_balanced_chunked ||
3426 Schedule == OMP_ord_static_chunked ||
3427 Schedule == OMP_dist_sch_static_chunked) &&
3428 "expected static chunked schedule");
3429 }
3430 llvm::Value *Args[] = {
3431 UpdateLocation,
3432 ThreadId,
3433 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3434 M2)), // Schedule type
3435 Values.IL.getPointer(), // &isLastIter
3436 Values.LB.getPointer(), // &LB
3437 Values.UB.getPointer(), // &UB
3438 Values.ST.getPointer(), // &Stride
3439 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3440 Chunk // Chunk
3441 };
3442 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003443}
3444
John McCall7f416cc2015-09-08 08:05:57 +00003445void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3446 SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003447 OpenMPDirectiveKind DKind,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003448 const OpenMPScheduleTy &ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003449 const StaticRTInput &Values) {
3450 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3451 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3452 assert(isOpenMPWorksharingDirective(DKind) &&
3453 "Expected loop-based or sections-based directive.");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003454 llvm::Value *UpdatedLocation = emitUpdateLocation(CGF, Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003455 isOpenMPLoopDirective(DKind)
3456 ? OMP_IDENT_WORK_LOOP
3457 : OMP_IDENT_WORK_SECTIONS);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003458 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3459 llvm::Constant *StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003460 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003461 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003462 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003463}
John McCall7f416cc2015-09-08 08:05:57 +00003464
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003465void CGOpenMPRuntime::emitDistributeStaticInit(
3466 CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003467 OpenMPDistScheduleClauseKind SchedKind,
3468 const CGOpenMPRuntime::StaticRTInput &Values) {
3469 OpenMPSchedType ScheduleNum =
3470 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003471 llvm::Value *UpdatedLocation =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003472 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003473 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3474 llvm::Constant *StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003475 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003476 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3477 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003478 OMPC_SCHEDULE_MODIFIER_unknown, Values);
Alexander Musmanc6388682014-12-15 07:07:06 +00003479}
3480
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003481void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
Alexey Bataevf43f7142017-09-06 16:17:35 +00003482 SourceLocation Loc,
3483 OpenMPDirectiveKind DKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003484 if (!CGF.HaveInsertPoint())
3485 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003486 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataevf43f7142017-09-06 16:17:35 +00003487 llvm::Value *Args[] = {
3488 emitUpdateLocation(CGF, Loc,
3489 isOpenMPDistributeDirective(DKind)
3490 ? OMP_IDENT_WORK_DISTRIBUTE
3491 : isOpenMPLoopDirective(DKind)
3492 ? OMP_IDENT_WORK_LOOP
3493 : OMP_IDENT_WORK_SECTIONS),
3494 getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003495 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3496 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003497}
3498
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003499void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3500 SourceLocation Loc,
3501 unsigned IVSize,
3502 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003503 if (!CGF.HaveInsertPoint())
3504 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003505 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003506 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003507 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3508}
3509
Alexander Musman92bdaab2015-03-12 13:37:50 +00003510llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3511 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003512 bool IVSigned, Address IL,
3513 Address LB, Address UB,
3514 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003515 // Call __kmpc_dispatch_next(
3516 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3517 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3518 // kmp_int[32|64] *p_stride);
3519 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003520 emitUpdateLocation(CGF, Loc),
3521 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003522 IL.getPointer(), // &isLastIter
3523 LB.getPointer(), // &Lower
3524 UB.getPointer(), // &Upper
3525 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003526 };
3527 llvm::Value *Call =
3528 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3529 return CGF.EmitScalarConversion(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003530 Call, CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/1),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003531 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003532}
3533
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003534void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3535 llvm::Value *NumThreads,
3536 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003537 if (!CGF.HaveInsertPoint())
3538 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003539 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3540 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003541 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003542 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003543 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3544 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003545}
3546
Alexey Bataev7f210c62015-06-18 13:40:03 +00003547void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3548 OpenMPProcBindClauseKind ProcBind,
3549 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003550 if (!CGF.HaveInsertPoint())
3551 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003552 // Constants for proc bind value accepted by the runtime.
3553 enum ProcBindTy {
3554 ProcBindFalse = 0,
3555 ProcBindTrue,
3556 ProcBindMaster,
3557 ProcBindClose,
3558 ProcBindSpread,
3559 ProcBindIntel,
3560 ProcBindDefault
3561 } RuntimeProcBind;
3562 switch (ProcBind) {
3563 case OMPC_PROC_BIND_master:
3564 RuntimeProcBind = ProcBindMaster;
3565 break;
3566 case OMPC_PROC_BIND_close:
3567 RuntimeProcBind = ProcBindClose;
3568 break;
3569 case OMPC_PROC_BIND_spread:
3570 RuntimeProcBind = ProcBindSpread;
3571 break;
3572 case OMPC_PROC_BIND_unknown:
3573 llvm_unreachable("Unsupported proc_bind value.");
3574 }
3575 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3576 llvm::Value *Args[] = {
3577 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3578 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3579 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3580}
3581
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003582void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3583 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003584 if (!CGF.HaveInsertPoint())
3585 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003586 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003587 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3588 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003589}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003590
Alexey Bataev62b63b12015-03-10 07:28:44 +00003591namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003592/// Indexes of fields for type kmp_task_t.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003593enum KmpTaskTFields {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003594 /// List of shared variables.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003595 KmpTaskTShareds,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003596 /// Task routine.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003597 KmpTaskTRoutine,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003598 /// Partition id for the untied tasks.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003599 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003600 /// Function with call of destructors for private variables.
3601 Data1,
3602 /// Task priority.
3603 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003604 /// (Taskloops only) Lower bound.
3605 KmpTaskTLowerBound,
3606 /// (Taskloops only) Upper bound.
3607 KmpTaskTUpperBound,
3608 /// (Taskloops only) Stride.
3609 KmpTaskTStride,
3610 /// (Taskloops only) Is last iteration flag.
3611 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003612 /// (Taskloops only) Reduction data.
3613 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003614};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003615} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003616
Samuel Antaoee8fb302016-01-06 13:42:12 +00003617bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003618 return OffloadEntriesTargetRegion.empty() &&
3619 OffloadEntriesDeviceGlobalVar.empty();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003620}
3621
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003622/// Initialize target region entry.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003623void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3624 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3625 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003626 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003627 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3628 "only required for the device "
3629 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003630 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003631 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003632 OMPTargetRegionEntryTargetRegion);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003633 ++OffloadingEntriesNum;
3634}
3635
3636void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3637 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3638 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003639 llvm::Constant *Addr, llvm::Constant *ID,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003640 OMPTargetRegionEntryKind Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003641 // If we are emitting code for a target, the entry is already initialized,
3642 // only has to be registered.
3643 if (CGM.getLangOpts().OpenMPIsDevice) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00003644 if (!hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum)) {
3645 unsigned DiagID = CGM.getDiags().getCustomDiagID(
3646 DiagnosticsEngine::Error,
3647 "Unable to find target region on line '%0' in the device code.");
3648 CGM.getDiags().Report(DiagID) << LineNum;
3649 return;
3650 }
Samuel Antao2de62b02016-02-13 23:35:10 +00003651 auto &Entry =
3652 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003653 assert(Entry.isValid() && "Entry not initialized!");
3654 Entry.setAddress(Addr);
3655 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003656 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003657 } else {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003658 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003659 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00003660 ++OffloadingEntriesNum;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003661 }
3662}
3663
3664bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003665 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3666 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003667 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3668 if (PerDevice == OffloadEntriesTargetRegion.end())
3669 return false;
3670 auto PerFile = PerDevice->second.find(FileID);
3671 if (PerFile == PerDevice->second.end())
3672 return false;
3673 auto PerParentName = PerFile->second.find(ParentName);
3674 if (PerParentName == PerFile->second.end())
3675 return false;
3676 auto PerLine = PerParentName->second.find(LineNum);
3677 if (PerLine == PerParentName->second.end())
3678 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003679 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003680 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003681 return false;
3682 return true;
3683}
3684
3685void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3686 const OffloadTargetRegionEntryInfoActTy &Action) {
3687 // Scan all target region entries and perform the provided action.
Alexey Bataev03f270c2018-03-30 18:31:07 +00003688 for (const auto &D : OffloadEntriesTargetRegion)
3689 for (const auto &F : D.second)
3690 for (const auto &P : F.second)
3691 for (const auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003692 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003693}
3694
Alexey Bataev03f270c2018-03-30 18:31:07 +00003695void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3696 initializeDeviceGlobalVarEntryInfo(StringRef Name,
3697 OMPTargetGlobalVarEntryKind Flags,
3698 unsigned Order) {
3699 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3700 "only required for the device "
3701 "code generation.");
3702 OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags);
3703 ++OffloadingEntriesNum;
3704}
Samuel Antaoee8fb302016-01-06 13:42:12 +00003705
Alexey Bataev03f270c2018-03-30 18:31:07 +00003706void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3707 registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr,
3708 CharUnits VarSize,
3709 OMPTargetGlobalVarEntryKind Flags,
3710 llvm::GlobalValue::LinkageTypes Linkage) {
3711 if (CGM.getLangOpts().OpenMPIsDevice) {
3712 auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
3713 assert(Entry.isValid() && Entry.getFlags() == Flags &&
3714 "Entry not initialized!");
3715 assert((!Entry.getAddress() || Entry.getAddress() == Addr) &&
3716 "Resetting with the new address.");
3717 if (Entry.getAddress() && hasDeviceGlobalVarEntryInfo(VarName))
3718 return;
3719 Entry.setAddress(Addr);
3720 Entry.setVarSize(VarSize);
3721 Entry.setLinkage(Linkage);
3722 } else {
3723 if (hasDeviceGlobalVarEntryInfo(VarName))
3724 return;
3725 OffloadEntriesDeviceGlobalVar.try_emplace(
3726 VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage);
3727 ++OffloadingEntriesNum;
3728 }
3729}
3730
3731void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3732 actOnDeviceGlobalVarEntriesInfo(
3733 const OffloadDeviceGlobalVarEntryInfoActTy &Action) {
3734 // Scan all target region entries and perform the provided action.
3735 for (const auto &E : OffloadEntriesDeviceGlobalVar)
3736 Action(E.getKey(), E.getValue());
Samuel Antaoee8fb302016-01-06 13:42:12 +00003737}
3738
3739llvm::Function *
3740CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003741 // If we don't have entries or if we are emitting code for the device, we
3742 // don't need to do anything.
3743 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3744 return nullptr;
3745
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003746 llvm::Module &M = CGM.getModule();
3747 ASTContext &C = CGM.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003748
3749 // Get list of devices we care about
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003750 const std::vector<llvm::Triple> &Devices = CGM.getLangOpts().OMPTargetTriples;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003751
3752 // We should be creating an offloading descriptor only if there are devices
3753 // specified.
3754 assert(!Devices.empty() && "No OpenMP offloading devices??");
3755
3756 // Create the external variables that will point to the begin and end of the
3757 // host entries section. These will be defined by the linker.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003758 llvm::Type *OffloadEntryTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00003759 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
Alexey Bataev18fa2322018-05-02 14:20:50 +00003760 std::string EntriesBeginName = getName({"omp_offloading", "entries_begin"});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003761 auto *HostEntriesBegin = new llvm::GlobalVariable(
Samuel Antaoee8fb302016-01-06 13:42:12 +00003762 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003763 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003764 EntriesBeginName);
3765 std::string EntriesEndName = getName({"omp_offloading", "entries_end"});
3766 auto *HostEntriesEnd =
3767 new llvm::GlobalVariable(M, OffloadEntryTy, /*isConstant=*/true,
3768 llvm::GlobalValue::ExternalLinkage,
3769 /*Initializer=*/nullptr, EntriesEndName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003770
3771 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003772 auto *DeviceImageTy = cast<llvm::StructType>(
3773 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003774 ConstantInitBuilder DeviceImagesBuilder(CGM);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003775 ConstantArrayBuilder DeviceImagesEntries =
3776 DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003777
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003778 for (const llvm::Triple &Device : Devices) {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003779 StringRef T = Device.getTriple();
Alexey Bataev18fa2322018-05-02 14:20:50 +00003780 std::string BeginName = getName({"omp_offloading", "img_start", ""});
Samuel Antaoee8fb302016-01-06 13:42:12 +00003781 auto *ImgBegin = new llvm::GlobalVariable(
Alexey Bataev62a4cb02018-07-31 18:27:42 +00003782 M, CGM.Int8Ty, /*isConstant=*/true,
3783 llvm::GlobalValue::ExternalWeakLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003784 /*Initializer=*/nullptr, Twine(BeginName).concat(T));
3785 std::string EndName = getName({"omp_offloading", "img_end", ""});
Samuel Antaoee8fb302016-01-06 13:42:12 +00003786 auto *ImgEnd = new llvm::GlobalVariable(
Alexey Bataev62a4cb02018-07-31 18:27:42 +00003787 M, CGM.Int8Ty, /*isConstant=*/true,
3788 llvm::GlobalValue::ExternalWeakLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003789 /*Initializer=*/nullptr, Twine(EndName).concat(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003790
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003791 llvm::Constant *Data[] = {ImgBegin, ImgEnd, HostEntriesBegin,
3792 HostEntriesEnd};
3793 createConstantGlobalStructAndAddToParent(CGM, getTgtDeviceImageQTy(), Data,
3794 DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003795 }
3796
3797 // Create device images global array.
Alexey Bataev18fa2322018-05-02 14:20:50 +00003798 std::string ImagesName = getName({"omp_offloading", "device_images"});
John McCall6c9f1fdb2016-11-19 08:17:24 +00003799 llvm::GlobalVariable *DeviceImages =
Alexey Bataev18fa2322018-05-02 14:20:50 +00003800 DeviceImagesEntries.finishAndCreateGlobal(ImagesName,
3801 CGM.getPointerAlign(),
3802 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003803 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003804
3805 // This is a Zero array to be used in the creation of the constant expressions
3806 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3807 llvm::Constant::getNullValue(CGM.Int32Ty)};
3808
3809 // Create the target region descriptor.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003810 llvm::Constant *Data[] = {
3811 llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
3812 llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3813 DeviceImages, Index),
3814 HostEntriesBegin, HostEntriesEnd};
Alexey Bataev18fa2322018-05-02 14:20:50 +00003815 std::string Descriptor = getName({"omp_offloading", "descriptor"});
Mike Ricee1ca7b62018-08-29 15:45:11 +00003816 llvm::GlobalVariable *Desc = createGlobalStruct(
3817 CGM, getTgtBinaryDescriptorQTy(), /*IsConstant=*/true, Data, Descriptor);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003818
3819 // Emit code to register or unregister the descriptor at execution
3820 // startup or closing, respectively.
3821
Alexey Bataev03f270c2018-03-30 18:31:07 +00003822 llvm::Function *UnRegFn;
3823 {
3824 FunctionArgList Args;
3825 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
3826 Args.push_back(&DummyPtr);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003827
Alexey Bataev03f270c2018-03-30 18:31:07 +00003828 CodeGenFunction CGF(CGM);
3829 // Disable debug info for global (de-)initializer because they are not part
3830 // of some particular construct.
3831 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003832 const auto &FI =
3833 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3834 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003835 std::string UnregName = getName({"omp_offloading", "descriptor_unreg"});
3836 UnRegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, UnregName, FI);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003837 CGF.StartFunction(GlobalDecl(), C.VoidTy, UnRegFn, FI, Args);
3838 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3839 Desc);
3840 CGF.FinishFunction();
3841 }
3842 llvm::Function *RegFn;
3843 {
3844 CodeGenFunction CGF(CGM);
3845 // Disable debug info for global (de-)initializer because they are not part
3846 // of some particular construct.
3847 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003848 const auto &FI = CGM.getTypes().arrangeNullaryFunction();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003849 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Sergey Dmitrievbde9cf92018-08-03 20:19:28 +00003850
3851 // Encode offload target triples into the registration function name. It
3852 // will serve as a comdat key for the registration/unregistration code for
3853 // this particular combination of offloading targets.
3854 SmallVector<StringRef, 4U> RegFnNameParts(Devices.size() + 2U);
3855 RegFnNameParts[0] = "omp_offloading";
3856 RegFnNameParts[1] = "descriptor_reg";
3857 llvm::transform(Devices, std::next(RegFnNameParts.begin(), 2),
3858 [](const llvm::Triple &T) -> const std::string& {
3859 return T.getTriple();
3860 });
3861 llvm::sort(std::next(RegFnNameParts.begin(), 2), RegFnNameParts.end());
3862 std::string Descriptor = getName(RegFnNameParts);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003863 RegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, Descriptor, FI);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003864 CGF.StartFunction(GlobalDecl(), C.VoidTy, RegFn, FI, FunctionArgList());
3865 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib), Desc);
3866 // Create a variable to drive the registration and unregistration of the
3867 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3868 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(),
3869 SourceLocation(), nullptr, C.CharTy,
3870 ImplicitParamDecl::Other);
3871 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3872 CGF.FinishFunction();
3873 }
George Rokos29d0f002017-05-27 03:03:13 +00003874 if (CGM.supportsCOMDAT()) {
3875 // It is sufficient to call registration function only once, so create a
3876 // COMDAT group for registration/unregistration functions and associated
3877 // data. That would reduce startup time and code size. Registration
3878 // function serves as a COMDAT group key.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003879 llvm::Comdat *ComdatKey = M.getOrInsertComdat(RegFn->getName());
George Rokos29d0f002017-05-27 03:03:13 +00003880 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3881 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3882 RegFn->setComdat(ComdatKey);
3883 UnRegFn->setComdat(ComdatKey);
3884 DeviceImages->setComdat(ComdatKey);
3885 Desc->setComdat(ComdatKey);
3886 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003887 return RegFn;
3888}
3889
Alexey Bataev03f270c2018-03-30 18:31:07 +00003890void CGOpenMPRuntime::createOffloadEntry(
3891 llvm::Constant *ID, llvm::Constant *Addr, uint64_t Size, int32_t Flags,
3892 llvm::GlobalValue::LinkageTypes Linkage) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003893 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003894 llvm::Module &M = CGM.getModule();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003895 llvm::LLVMContext &C = M.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003896
3897 // Create constant string with the name.
3898 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3899
Alexey Bataev18fa2322018-05-02 14:20:50 +00003900 std::string StringName = getName({"omp_offloading", "entry_name"});
3901 auto *Str = new llvm::GlobalVariable(
3902 M, StrPtrInit->getType(), /*isConstant=*/true,
3903 llvm::GlobalValue::InternalLinkage, StrPtrInit, StringName);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003904 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003905
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003906 llvm::Constant *Data[] = {llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy),
3907 llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy),
3908 llvm::ConstantInt::get(CGM.SizeTy, Size),
3909 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
3910 llvm::ConstantInt::get(CGM.Int32Ty, 0)};
Alexey Bataev18fa2322018-05-02 14:20:50 +00003911 std::string EntryName = getName({"omp_offloading", "entry", ""});
Mike Ricee1ca7b62018-08-29 15:45:11 +00003912 llvm::GlobalVariable *Entry = createGlobalStruct(
3913 CGM, getTgtOffloadEntryQTy(), /*IsConstant=*/true, Data,
3914 Twine(EntryName).concat(Name), llvm::GlobalValue::WeakAnyLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003915
3916 // The entry has to be created in the section the linker expects it to be.
Alexey Bataev18fa2322018-05-02 14:20:50 +00003917 std::string Section = getName({"omp_offloading", "entries"});
3918 Entry->setSection(Section);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003919}
3920
3921void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3922 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003923 // can easily figure out what to emit. The produced metadata looks like
3924 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003925 //
3926 // !omp_offload.info = !{!1, ...}
3927 //
3928 // Right now we only generate metadata for function that contain target
3929 // regions.
3930
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003931 // If we do not have entries, we don't need to do anything.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003932 if (OffloadEntriesInfoManager.empty())
3933 return;
3934
3935 llvm::Module &M = CGM.getModule();
3936 llvm::LLVMContext &C = M.getContext();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003937 SmallVector<const OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
Samuel Antaoee8fb302016-01-06 13:42:12 +00003938 OrderedEntries(OffloadEntriesInfoManager.size());
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00003939 llvm::SmallVector<StringRef, 16> ParentFunctions(
3940 OffloadEntriesInfoManager.size());
Samuel Antaoee8fb302016-01-06 13:42:12 +00003941
Simon Pilgrim2c518802017-03-30 14:13:19 +00003942 // Auxiliary methods to create metadata values and strings.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003943 auto &&GetMDInt = [this](unsigned V) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003944 return llvm::ConstantAsMetadata::get(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003945 llvm::ConstantInt::get(CGM.Int32Ty, V));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003946 };
3947
Alexey Bataev03f270c2018-03-30 18:31:07 +00003948 auto &&GetMDString = [&C](StringRef V) { return llvm::MDString::get(C, V); };
3949
3950 // Create the offloading info metadata node.
3951 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003952
3953 // Create function that emits metadata for each target region entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00003954 auto &&TargetRegionMetadataEmitter =
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00003955 [&C, MD, &OrderedEntries, &ParentFunctions, &GetMDInt, &GetMDString](
Alexey Bataev03f270c2018-03-30 18:31:07 +00003956 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3957 unsigned Line,
3958 const OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3959 // Generate metadata for target regions. Each entry of this metadata
3960 // contains:
3961 // - Entry 0 -> Kind of this type of metadata (0).
3962 // - Entry 1 -> Device ID of the file where the entry was identified.
3963 // - Entry 2 -> File ID of the file where the entry was identified.
3964 // - Entry 3 -> Mangled name of the function where the entry was
3965 // identified.
3966 // - Entry 4 -> Line in the file where the entry was identified.
3967 // - Entry 5 -> Order the entry was created.
3968 // The first element of the metadata node is the kind.
3969 llvm::Metadata *Ops[] = {GetMDInt(E.getKind()), GetMDInt(DeviceID),
3970 GetMDInt(FileID), GetMDString(ParentName),
3971 GetMDInt(Line), GetMDInt(E.getOrder())};
Samuel Antaoee8fb302016-01-06 13:42:12 +00003972
Alexey Bataev03f270c2018-03-30 18:31:07 +00003973 // Save this entry in the right position of the ordered entries array.
3974 OrderedEntries[E.getOrder()] = &E;
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00003975 ParentFunctions[E.getOrder()] = ParentName;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003976
Alexey Bataev03f270c2018-03-30 18:31:07 +00003977 // Add metadata to the named metadata node.
3978 MD->addOperand(llvm::MDNode::get(C, Ops));
3979 };
Samuel Antaoee8fb302016-01-06 13:42:12 +00003980
3981 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3982 TargetRegionMetadataEmitter);
3983
Alexey Bataev03f270c2018-03-30 18:31:07 +00003984 // Create function that emits metadata for each device global variable entry;
3985 auto &&DeviceGlobalVarMetadataEmitter =
3986 [&C, &OrderedEntries, &GetMDInt, &GetMDString,
3987 MD](StringRef MangledName,
3988 const OffloadEntriesInfoManagerTy::OffloadEntryInfoDeviceGlobalVar
3989 &E) {
3990 // Generate metadata for global variables. Each entry of this metadata
3991 // contains:
3992 // - Entry 0 -> Kind of this type of metadata (1).
3993 // - Entry 1 -> Mangled name of the variable.
3994 // - Entry 2 -> Declare target kind.
3995 // - Entry 3 -> Order the entry was created.
3996 // The first element of the metadata node is the kind.
3997 llvm::Metadata *Ops[] = {
3998 GetMDInt(E.getKind()), GetMDString(MangledName),
3999 GetMDInt(E.getFlags()), GetMDInt(E.getOrder())};
4000
4001 // Save this entry in the right position of the ordered entries array.
4002 OrderedEntries[E.getOrder()] = &E;
4003
4004 // Add metadata to the named metadata node.
4005 MD->addOperand(llvm::MDNode::get(C, Ops));
4006 };
4007
4008 OffloadEntriesInfoManager.actOnDeviceGlobalVarEntriesInfo(
4009 DeviceGlobalVarMetadataEmitter);
4010
4011 for (const auto *E : OrderedEntries) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004012 assert(E && "All ordered entries must exist!");
Alexey Bataev03f270c2018-03-30 18:31:07 +00004013 if (const auto *CE =
Samuel Antaoee8fb302016-01-06 13:42:12 +00004014 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
4015 E)) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004016 if (!CE->getID() || !CE->getAddress()) {
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00004017 // Do not blame the entry if the parent funtion is not emitted.
4018 StringRef FnName = ParentFunctions[CE->getOrder()];
4019 if (!CGM.GetGlobalValue(FnName))
4020 continue;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004021 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4022 DiagnosticsEngine::Error,
Alexey Bataev7f01d202018-07-16 18:12:18 +00004023 "Offloading entry for target region is incorrect: either the "
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004024 "address or the ID is invalid.");
4025 CGM.getDiags().Report(DiagID);
4026 continue;
4027 }
Alexey Bataev34f8a702018-03-28 14:28:54 +00004028 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0,
Alexey Bataev03f270c2018-03-30 18:31:07 +00004029 CE->getFlags(), llvm::GlobalValue::WeakAnyLinkage);
4030 } else if (const auto *CE =
4031 dyn_cast<OffloadEntriesInfoManagerTy::
4032 OffloadEntryInfoDeviceGlobalVar>(E)) {
Alexey Bataevc52f01d2018-07-16 20:05:25 +00004033 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags =
4034 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
4035 CE->getFlags());
4036 switch (Flags) {
4037 case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo: {
4038 if (!CE->getAddress()) {
4039 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4040 DiagnosticsEngine::Error,
4041 "Offloading entry for declare target variable is incorrect: the "
4042 "address is invalid.");
4043 CGM.getDiags().Report(DiagID);
4044 continue;
4045 }
Alexey Bataevb4dd6d22018-08-29 20:41:37 +00004046 // The vaiable has no definition - no need to add the entry.
4047 if (CE->getVarSize().isZero())
4048 continue;
Alexey Bataevc52f01d2018-07-16 20:05:25 +00004049 break;
4050 }
4051 case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink:
4052 assert(((CGM.getLangOpts().OpenMPIsDevice && !CE->getAddress()) ||
4053 (!CGM.getLangOpts().OpenMPIsDevice && CE->getAddress())) &&
4054 "Declaret target link address is set.");
4055 if (CGM.getLangOpts().OpenMPIsDevice)
4056 continue;
4057 if (!CE->getAddress()) {
4058 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4059 DiagnosticsEngine::Error,
4060 "Offloading entry for declare target variable is incorrect: the "
4061 "address is invalid.");
4062 CGM.getDiags().Report(DiagID);
4063 continue;
4064 }
4065 break;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004066 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00004067 createOffloadEntry(CE->getAddress(), CE->getAddress(),
Alexey Bataevc52f01d2018-07-16 20:05:25 +00004068 CE->getVarSize().getQuantity(), Flags,
Alexey Bataev03f270c2018-03-30 18:31:07 +00004069 CE->getLinkage());
4070 } else {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004071 llvm_unreachable("Unsupported entry kind.");
Alexey Bataev03f270c2018-03-30 18:31:07 +00004072 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004073 }
4074}
4075
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004076/// Loads all the offload entries information from the host IR
Samuel Antaoee8fb302016-01-06 13:42:12 +00004077/// metadata.
4078void CGOpenMPRuntime::loadOffloadInfoMetadata() {
4079 // If we are in target mode, load the metadata from the host IR. This code has
4080 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
4081
4082 if (!CGM.getLangOpts().OpenMPIsDevice)
4083 return;
4084
4085 if (CGM.getLangOpts().OMPHostIRFile.empty())
4086 return;
4087
4088 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004089 if (auto EC = Buf.getError()) {
4090 CGM.getDiags().Report(diag::err_cannot_open_file)
4091 << CGM.getLangOpts().OMPHostIRFile << EC.message();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004092 return;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004093 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004094
4095 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00004096 auto ME = expectedToErrorOrAndEmitErrors(
4097 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004098
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004099 if (auto EC = ME.getError()) {
4100 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4101 DiagnosticsEngine::Error, "Unable to parse host IR file '%0':'%1'");
4102 CGM.getDiags().Report(DiagID)
4103 << CGM.getLangOpts().OMPHostIRFile << EC.message();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004104 return;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004105 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004106
4107 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
4108 if (!MD)
4109 return;
4110
George Burgess IV00f70bd2018-03-01 05:43:23 +00004111 for (llvm::MDNode *MN : MD->operands()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004112 auto &&GetMDInt = [MN](unsigned Idx) {
4113 auto *V = cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004114 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
4115 };
4116
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004117 auto &&GetMDString = [MN](unsigned Idx) {
4118 auto *V = cast<llvm::MDString>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004119 return V->getString();
4120 };
4121
Alexey Bataev03f270c2018-03-30 18:31:07 +00004122 switch (GetMDInt(0)) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004123 default:
4124 llvm_unreachable("Unexpected metadata!");
4125 break;
4126 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
Alexey Bataev34f8a702018-03-28 14:28:54 +00004127 OffloadingEntryInfoTargetRegion:
Samuel Antaoee8fb302016-01-06 13:42:12 +00004128 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
Alexey Bataev03f270c2018-03-30 18:31:07 +00004129 /*DeviceID=*/GetMDInt(1), /*FileID=*/GetMDInt(2),
4130 /*ParentName=*/GetMDString(3), /*Line=*/GetMDInt(4),
4131 /*Order=*/GetMDInt(5));
4132 break;
4133 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
4134 OffloadingEntryInfoDeviceGlobalVar:
4135 OffloadEntriesInfoManager.initializeDeviceGlobalVarEntryInfo(
4136 /*MangledName=*/GetMDString(1),
4137 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
4138 /*Flags=*/GetMDInt(2)),
4139 /*Order=*/GetMDInt(3));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004140 break;
4141 }
4142 }
4143}
4144
Alexey Bataev62b63b12015-03-10 07:28:44 +00004145void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
4146 if (!KmpRoutineEntryPtrTy) {
4147 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004148 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004149 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
4150 FunctionProtoType::ExtProtoInfo EPI;
4151 KmpRoutineEntryPtrQTy = C.getPointerType(
4152 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
4153 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
4154 }
4155}
4156
Samuel Antaoee8fb302016-01-06 13:42:12 +00004157QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004158 // Make sure the type of the entry is already created. This is the type we
4159 // have to create:
4160 // struct __tgt_offload_entry{
4161 // void *addr; // Pointer to the offload entry info.
4162 // // (function or global)
4163 // char *name; // Name of the function or global.
4164 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00004165 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
4166 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004167 // };
4168 if (TgtOffloadEntryQTy.isNull()) {
4169 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004170 RecordDecl *RD = C.buildImplicitRecord("__tgt_offload_entry");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004171 RD->startDefinition();
4172 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4173 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
4174 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00004175 addFieldToRecordDecl(
4176 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4177 addFieldToRecordDecl(
4178 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004179 RD->completeDefinition();
Jonas Hahnfeld5e4df282018-01-18 15:38:03 +00004180 RD->addAttr(PackedAttr::CreateImplicit(C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004181 TgtOffloadEntryQTy = C.getRecordType(RD);
4182 }
4183 return TgtOffloadEntryQTy;
4184}
4185
4186QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
4187 // These are the types we need to build:
4188 // struct __tgt_device_image{
4189 // void *ImageStart; // Pointer to the target code start.
4190 // void *ImageEnd; // Pointer to the target code end.
4191 // // We also add the host entries to the device image, as it may be useful
4192 // // for the target runtime to have access to that information.
4193 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
4194 // // the entries.
4195 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4196 // // entries (non inclusive).
4197 // };
4198 if (TgtDeviceImageQTy.isNull()) {
4199 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004200 RecordDecl *RD = C.buildImplicitRecord("__tgt_device_image");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004201 RD->startDefinition();
4202 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4203 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4204 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4205 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4206 RD->completeDefinition();
4207 TgtDeviceImageQTy = C.getRecordType(RD);
4208 }
4209 return TgtDeviceImageQTy;
4210}
4211
4212QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
4213 // struct __tgt_bin_desc{
4214 // int32_t NumDevices; // Number of devices supported.
4215 // __tgt_device_image *DeviceImages; // Arrays of device images
4216 // // (one per device).
4217 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
4218 // // entries.
4219 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4220 // // entries (non inclusive).
4221 // };
4222 if (TgtBinaryDescriptorQTy.isNull()) {
4223 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004224 RecordDecl *RD = C.buildImplicitRecord("__tgt_bin_desc");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004225 RD->startDefinition();
4226 addFieldToRecordDecl(
4227 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4228 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
4229 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4230 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4231 RD->completeDefinition();
4232 TgtBinaryDescriptorQTy = C.getRecordType(RD);
4233 }
4234 return TgtBinaryDescriptorQTy;
4235}
4236
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004237namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00004238struct PrivateHelpersTy {
4239 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
4240 const VarDecl *PrivateElemInit)
4241 : Original(Original), PrivateCopy(PrivateCopy),
4242 PrivateElemInit(PrivateElemInit) {}
4243 const VarDecl *Original;
4244 const VarDecl *PrivateCopy;
4245 const VarDecl *PrivateElemInit;
4246};
4247typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00004248} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004249
Alexey Bataev9e034042015-05-05 04:05:12 +00004250static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00004251createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004252 if (!Privates.empty()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004253 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004254 // Build struct .kmp_privates_t. {
4255 // /* private vars */
4256 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004257 RecordDecl *RD = C.buildImplicitRecord(".kmp_privates.t");
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004258 RD->startDefinition();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004259 for (const auto &Pair : Privates) {
4260 const VarDecl *VD = Pair.second.Original;
4261 QualType Type = VD->getType().getNonReferenceType();
4262 FieldDecl *FD = addFieldToRecordDecl(C, RD, Type);
Alexey Bataevc71a4092015-09-11 10:29:41 +00004263 if (VD->hasAttrs()) {
4264 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
4265 E(VD->getAttrs().end());
4266 I != E; ++I)
4267 FD->addAttr(*I);
4268 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004269 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004270 RD->completeDefinition();
4271 return RD;
4272 }
4273 return nullptr;
4274}
4275
Alexey Bataev9e034042015-05-05 04:05:12 +00004276static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00004277createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
4278 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004279 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004280 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004281 // Build struct kmp_task_t {
4282 // void * shareds;
4283 // kmp_routine_entry_t routine;
4284 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00004285 // kmp_cmplrdata_t data1;
4286 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00004287 // For taskloops additional fields:
4288 // kmp_uint64 lb;
4289 // kmp_uint64 ub;
4290 // kmp_int64 st;
4291 // kmp_int32 liter;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004292 // void * reductions;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004293 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004294 RecordDecl *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004295 UD->startDefinition();
4296 addFieldToRecordDecl(C, UD, KmpInt32Ty);
4297 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
4298 UD->completeDefinition();
4299 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004300 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t");
Alexey Bataev62b63b12015-03-10 07:28:44 +00004301 RD->startDefinition();
4302 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4303 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
4304 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004305 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
4306 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004307 if (isOpenMPTaskLoopDirective(Kind)) {
4308 QualType KmpUInt64Ty =
4309 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4310 QualType KmpInt64Ty =
4311 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4312 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4313 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4314 addFieldToRecordDecl(C, RD, KmpInt64Ty);
4315 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004316 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004317 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004318 RD->completeDefinition();
4319 return RD;
4320}
4321
4322static RecordDecl *
4323createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004324 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004325 ASTContext &C = CGM.getContext();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004326 // Build struct kmp_task_t_with_privates {
4327 // kmp_task_t task_data;
4328 // .kmp_privates_t. privates;
4329 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004330 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004331 RD->startDefinition();
4332 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004333 if (const RecordDecl *PrivateRD = createPrivatesRecordDecl(CGM, Privates))
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004334 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004335 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004336 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004337}
4338
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004339/// Emit a proxy function which accepts kmp_task_t as the second
Alexey Bataev62b63b12015-03-10 07:28:44 +00004340/// argument.
4341/// \code
4342/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004343/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00004344/// For taskloops:
4345/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004346/// tt->reductions, tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004347/// return 0;
4348/// }
4349/// \endcode
4350static llvm::Value *
4351emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00004352 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
4353 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004354 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004355 QualType SharedsPtrTy, llvm::Value *TaskFunction,
4356 llvm::Value *TaskPrivatesMap) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004357 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004358 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004359 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4360 ImplicitParamDecl::Other);
4361 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4362 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4363 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004364 Args.push_back(&GtidArg);
4365 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004366 const auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004367 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004368 llvm::FunctionType *TaskEntryTy =
4369 CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004370 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_entry", ""});
4371 auto *TaskEntry = llvm::Function::Create(
4372 TaskEntryTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004373 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskEntry, TaskEntryFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004374 TaskEntry->setDoesNotRecurse();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004375 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004376 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args,
4377 Loc, Loc);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004378
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004379 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00004380 // tt,
4381 // For taskloops:
4382 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
4383 // tt->task_data.shareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004384 llvm::Value *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00004385 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00004386 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4387 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4388 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004389 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004390 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004391 LValue Base =
4392 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004393 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004394 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004395 LValue PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
4396 llvm::Value *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004397
4398 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004399 LValue SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
4400 llvm::Value *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev1e491372018-01-23 18:44:14 +00004401 CGF.EmitLoadOfScalar(SharedsLVal, Loc),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004402 CGF.ConvertTypeForMem(SharedsPtrTy));
4403
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004404 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4405 llvm::Value *PrivatesParam;
4406 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004407 LValue PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004408 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004409 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004410 } else {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004411 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004412 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004413
Alexey Bataev7292c292016-04-25 12:22:29 +00004414 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
4415 TaskPrivatesMap,
4416 CGF.Builder
4417 .CreatePointerBitCastOrAddrSpaceCast(
4418 TDBase.getAddress(), CGF.VoidPtrTy)
4419 .getPointer()};
4420 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
4421 std::end(CommonArgs));
4422 if (isOpenMPTaskLoopDirective(Kind)) {
4423 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004424 LValue LBLVal = CGF.EmitLValueForField(Base, *LBFI);
4425 llvm::Value *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004426 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004427 LValue UBLVal = CGF.EmitLValueForField(Base, *UBFI);
4428 llvm::Value *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004429 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004430 LValue StLVal = CGF.EmitLValueForField(Base, *StFI);
4431 llvm::Value *StParam = CGF.EmitLoadOfScalar(StLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004432 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004433 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4434 llvm::Value *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004435 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004436 LValue RLVal = CGF.EmitLValueForField(Base, *RFI);
4437 llvm::Value *RParam = CGF.EmitLoadOfScalar(RLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004438 CallArgs.push_back(LBParam);
4439 CallArgs.push_back(UBParam);
4440 CallArgs.push_back(StParam);
4441 CallArgs.push_back(LIParam);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004442 CallArgs.push_back(RParam);
Alexey Bataev7292c292016-04-25 12:22:29 +00004443 }
4444 CallArgs.push_back(SharedsParam);
4445
Alexey Bataev3c595a62017-08-14 15:01:03 +00004446 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
4447 CallArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004448 CGF.EmitStoreThroughLValue(RValue::get(CGF.Builder.getInt32(/*C=*/0)),
4449 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004450 CGF.FinishFunction();
4451 return TaskEntry;
4452}
4453
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004454static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
4455 SourceLocation Loc,
4456 QualType KmpInt32Ty,
4457 QualType KmpTaskTWithPrivatesPtrQTy,
4458 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004459 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004460 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004461 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4462 ImplicitParamDecl::Other);
4463 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4464 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4465 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004466 Args.push_back(&GtidArg);
4467 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004468 const auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004469 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004470 llvm::FunctionType *DestructorFnTy =
4471 CGM.getTypes().GetFunctionType(DestructorFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004472 std::string Name =
4473 CGM.getOpenMPRuntime().getName({"omp_task_destructor", ""});
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004474 auto *DestructorFn =
4475 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00004476 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004477 CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004478 DestructorFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004479 DestructorFn->setDoesNotRecurse();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004480 CodeGenFunction CGF(CGM);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004481 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004482 Args, Loc, Loc);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004483
Alexey Bataev31300ed2016-02-04 11:27:03 +00004484 LValue Base = CGF.EmitLoadOfPointerLValue(
4485 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4486 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004487 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004488 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
4489 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004490 Base = CGF.EmitLValueForField(Base, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004491 for (const auto *Field :
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004492 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004493 if (QualType::DestructionKind DtorKind =
4494 Field->getType().isDestructedType()) {
4495 LValue FieldLValue = CGF.EmitLValueForField(Base, Field);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004496 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
4497 }
4498 }
4499 CGF.FinishFunction();
4500 return DestructorFn;
4501}
4502
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004503/// Emit a privates mapping function for correct handling of private and
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004504/// firstprivate variables.
4505/// \code
4506/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
4507/// **noalias priv1,..., <tyn> **noalias privn) {
4508/// *priv1 = &.privates.priv1;
4509/// ...;
4510/// *privn = &.privates.privn;
4511/// }
4512/// \endcode
4513static llvm::Value *
4514emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00004515 ArrayRef<const Expr *> PrivateVars,
4516 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004517 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004518 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004519 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004520 ASTContext &C = CGM.getContext();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004521 FunctionArgList Args;
4522 ImplicitParamDecl TaskPrivatesArg(
4523 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00004524 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
4525 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004526 Args.push_back(&TaskPrivatesArg);
4527 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
4528 unsigned Counter = 1;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004529 for (const Expr *E : PrivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004530 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004531 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4532 C.getPointerType(C.getPointerType(E->getType()))
4533 .withConst()
4534 .withRestrict(),
4535 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004536 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004537 PrivateVarsPos[VD] = Counter;
4538 ++Counter;
4539 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004540 for (const Expr *E : FirstprivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004541 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004542 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4543 C.getPointerType(C.getPointerType(E->getType()))
4544 .withConst()
4545 .withRestrict(),
4546 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004547 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004548 PrivateVarsPos[VD] = Counter;
4549 ++Counter;
4550 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004551 for (const Expr *E : LastprivateVars) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004552 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004553 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4554 C.getPointerType(C.getPointerType(E->getType()))
4555 .withConst()
4556 .withRestrict(),
4557 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004558 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004559 PrivateVarsPos[VD] = Counter;
4560 ++Counter;
4561 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004562 const auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004563 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004564 llvm::FunctionType *TaskPrivatesMapTy =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004565 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004566 std::string Name =
4567 CGM.getOpenMPRuntime().getName({"omp_task_privates_map", ""});
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004568 auto *TaskPrivatesMap = llvm::Function::Create(
Alexey Bataev18fa2322018-05-02 14:20:50 +00004569 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage, Name,
4570 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004571 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004572 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00004573 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00004574 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00004575 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004576 CodeGenFunction CGF(CGM);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004577 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004578 TaskPrivatesMapFnInfo, Args, Loc, Loc);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004579
4580 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00004581 LValue Base = CGF.EmitLoadOfPointerLValue(
4582 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4583 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004584 const auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004585 Counter = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004586 for (const FieldDecl *Field : PrivatesQTyRD->fields()) {
4587 LValue FieldLVal = CGF.EmitLValueForField(Base, Field);
4588 const VarDecl *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
4589 LValue RefLVal =
4590 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
4591 LValue RefLoadLVal = CGF.EmitLoadOfPointerLValue(
Alexey Bataev31300ed2016-02-04 11:27:03 +00004592 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00004593 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004594 ++Counter;
4595 }
4596 CGF.FinishFunction();
4597 return TaskPrivatesMap;
4598}
4599
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004600static bool stable_sort_comparator(const PrivateDataTy P1,
4601 const PrivateDataTy P2) {
4602 return P1.first > P2.first;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004603}
4604
Alexey Bataevf93095a2016-05-05 08:46:22 +00004605/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00004606static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004607 const OMPExecutableDirective &D,
4608 Address KmpTaskSharedsPtr, LValue TDBase,
4609 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4610 QualType SharedsTy, QualType SharedsPtrTy,
4611 const OMPTaskDataTy &Data,
4612 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004613 ASTContext &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004614 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4615 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004616 OpenMPDirectiveKind Kind = isOpenMPTaskLoopDirective(D.getDirectiveKind())
4617 ? OMPD_taskloop
4618 : OMPD_task;
4619 const CapturedStmt &CS = *D.getCapturedStmt(Kind);
4620 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004621 LValue SrcBase;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004622 bool IsTargetTask =
4623 isOpenMPTargetDataManagementDirective(D.getDirectiveKind()) ||
4624 isOpenMPTargetExecutionDirective(D.getDirectiveKind());
4625 // For target-based directives skip 3 firstprivate arrays BasePointersArray,
4626 // PointersArray and SizesArray. The original variables for these arrays are
4627 // not captured and we get their addresses explicitly.
4628 if ((!IsTargetTask && !Data.FirstprivateVars.empty()) ||
Alexey Bataev8451efa2018-01-15 19:06:12 +00004629 (IsTargetTask && KmpTaskSharedsPtr.isValid())) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004630 SrcBase = CGF.MakeAddrLValue(
4631 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4632 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4633 SharedsTy);
4634 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004635 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004636 for (const PrivateDataTy &Pair : Privates) {
4637 const VarDecl *VD = Pair.second.PrivateCopy;
4638 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004639 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4640 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004641 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004642 if (const VarDecl *Elem = Pair.second.PrivateElemInit) {
4643 const VarDecl *OriginalVD = Pair.second.Original;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004644 // Check if the variable is the target-based BasePointersArray,
4645 // PointersArray or SizesArray.
4646 LValue SharedRefLValue;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004647 QualType Type = OriginalVD->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004648 const FieldDecl *SharedField = CapturesInfo.lookup(OriginalVD);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004649 if (IsTargetTask && !SharedField) {
4650 assert(isa<ImplicitParamDecl>(OriginalVD) &&
4651 isa<CapturedDecl>(OriginalVD->getDeclContext()) &&
4652 cast<CapturedDecl>(OriginalVD->getDeclContext())
4653 ->getNumParams() == 0 &&
4654 isa<TranslationUnitDecl>(
4655 cast<CapturedDecl>(OriginalVD->getDeclContext())
4656 ->getDeclContext()) &&
4657 "Expected artificial target data variable.");
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004658 SharedRefLValue =
4659 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type);
4660 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004661 SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4662 SharedRefLValue = CGF.MakeAddrLValue(
4663 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
4664 SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl),
4665 SharedRefLValue.getTBAAInfo());
4666 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004667 if (Type->isArrayType()) {
4668 // Initialize firstprivate array.
4669 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4670 // Perform simple memcpy.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004671 CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004672 } else {
4673 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00004674 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00004675 CGF.EmitOMPAggregateAssign(
4676 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4677 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4678 Address SrcElement) {
4679 // Clean up any temporaries needed by the initialization.
4680 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4681 InitScope.addPrivate(
4682 Elem, [SrcElement]() -> Address { return SrcElement; });
4683 (void)InitScope.Privatize();
4684 // Emit initialization for single element.
4685 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4686 CGF, &CapturesInfo);
4687 CGF.EmitAnyExprToMem(Init, DestElement,
4688 Init->getType().getQualifiers(),
4689 /*IsInitializer=*/false);
4690 });
4691 }
4692 } else {
4693 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4694 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4695 return SharedRefLValue.getAddress();
4696 });
4697 (void)InitScope.Privatize();
4698 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4699 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4700 /*capturedByInit=*/false);
4701 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004702 } else {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004703 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004704 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004705 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004706 ++FI;
4707 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004708}
4709
4710/// Check if duplication function is required for taskloops.
4711static bool checkInitIsRequired(CodeGenFunction &CGF,
4712 ArrayRef<PrivateDataTy> Privates) {
4713 bool InitRequired = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004714 for (const PrivateDataTy &Pair : Privates) {
4715 const VarDecl *VD = Pair.second.PrivateCopy;
4716 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004717 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4718 !CGF.isTrivialInitializer(Init));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004719 if (InitRequired)
4720 break;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004721 }
4722 return InitRequired;
4723}
4724
4725
4726/// Emit task_dup function (for initialization of
4727/// private/firstprivate/lastprivate vars and last_iter flag)
4728/// \code
4729/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4730/// lastpriv) {
4731/// // setup lastprivate flag
4732/// task_dst->last = lastpriv;
4733/// // could be constructor calls here...
4734/// }
4735/// \endcode
4736static llvm::Value *
4737emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4738 const OMPExecutableDirective &D,
4739 QualType KmpTaskTWithPrivatesPtrQTy,
4740 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4741 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4742 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4743 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004744 ASTContext &C = CGM.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004745 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004746 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4747 KmpTaskTWithPrivatesPtrQTy,
4748 ImplicitParamDecl::Other);
4749 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4750 KmpTaskTWithPrivatesPtrQTy,
4751 ImplicitParamDecl::Other);
4752 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4753 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004754 Args.push_back(&DstArg);
4755 Args.push_back(&SrcArg);
4756 Args.push_back(&LastprivArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004757 const auto &TaskDupFnInfo =
Alexey Bataevf93095a2016-05-05 08:46:22 +00004758 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004759 llvm::FunctionType *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004760 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_dup", ""});
4761 auto *TaskDup = llvm::Function::Create(
4762 TaskDupTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004763 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskDup, TaskDupFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004764 TaskDup->setDoesNotRecurse();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004765 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004766 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args, Loc,
4767 Loc);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004768
4769 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4770 CGF.GetAddrOfLocalVar(&DstArg),
4771 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4772 // task_dst->liter = lastpriv;
4773 if (WithLastIter) {
4774 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4775 LValue Base = CGF.EmitLValueForField(
4776 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4777 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4778 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4779 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4780 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4781 }
4782
4783 // Emit initial values for private copies (if any).
4784 assert(!Privates.empty());
4785 Address KmpTaskSharedsPtr = Address::invalid();
4786 if (!Data.FirstprivateVars.empty()) {
4787 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4788 CGF.GetAddrOfLocalVar(&SrcArg),
4789 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4790 LValue Base = CGF.EmitLValueForField(
4791 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4792 KmpTaskSharedsPtr = Address(
4793 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4794 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4795 KmpTaskTShareds)),
4796 Loc),
4797 CGF.getNaturalTypeAlignment(SharedsTy));
4798 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004799 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4800 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004801 CGF.FinishFunction();
4802 return TaskDup;
4803}
4804
Alexey Bataev8a831592016-05-10 10:36:51 +00004805/// Checks if destructor function is required to be generated.
4806/// \return true if cleanups are required, false otherwise.
4807static bool
4808checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4809 bool NeedsCleanup = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004810 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4811 const auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4812 for (const FieldDecl *FD : PrivateRD->fields()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004813 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4814 if (NeedsCleanup)
4815 break;
4816 }
4817 return NeedsCleanup;
4818}
4819
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004820CGOpenMPRuntime::TaskResultTy
4821CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4822 const OMPExecutableDirective &D,
4823 llvm::Value *TaskFunction, QualType SharedsTy,
4824 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004825 ASTContext &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004826 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004827 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004828 auto I = Data.PrivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004829 for (const Expr *E : Data.PrivateVars) {
4830 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004831 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004832 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004833 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004834 /*PrivateElemInit=*/nullptr));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004835 ++I;
4836 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004837 I = Data.FirstprivateCopies.begin();
4838 auto IElemInitRef = Data.FirstprivateInits.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004839 for (const Expr *E : Data.FirstprivateVars) {
4840 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004841 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004842 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004843 PrivateHelpersTy(
4844 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004845 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl())));
Richard Trieucc3949d2016-02-18 22:34:54 +00004846 ++I;
4847 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004848 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004849 I = Data.LastprivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004850 for (const Expr *E : Data.LastprivateVars) {
4851 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004852 Privates.emplace_back(
Alexey Bataevf93095a2016-05-05 08:46:22 +00004853 C.getDeclAlign(VD),
4854 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004855 /*PrivateElemInit=*/nullptr));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004856 ++I;
4857 }
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004858 std::stable_sort(Privates.begin(), Privates.end(), stable_sort_comparator);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004859 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004860 // Build type kmp_routine_entry_t (if not built yet).
4861 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004862 // Build type kmp_task_t (if not built yet).
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004863 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
4864 if (SavedKmpTaskloopTQTy.isNull()) {
4865 SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4866 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4867 }
4868 KmpTaskTQTy = SavedKmpTaskloopTQTy;
Alexey Bataev3a03a7f2017-10-11 15:56:38 +00004869 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004870 assert((D.getDirectiveKind() == OMPD_task ||
4871 isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||
4872 isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) &&
4873 "Expected taskloop, task or target directive");
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004874 if (SavedKmpTaskTQTy.isNull()) {
4875 SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4876 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4877 }
4878 KmpTaskTQTy = SavedKmpTaskTQTy;
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004879 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004880 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004881 // Build particular struct kmp_task_t for the given task.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004882 const RecordDecl *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004883 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004884 QualType KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004885 QualType KmpTaskTWithPrivatesPtrQTy =
4886 C.getPointerType(KmpTaskTWithPrivatesQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004887 llvm::Type *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4888 llvm::Type *KmpTaskTWithPrivatesPtrTy =
4889 KmpTaskTWithPrivatesTy->getPointerTo();
4890 llvm::Value *KmpTaskTWithPrivatesTySize =
4891 CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004892 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4893
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004894 // Emit initial values for private copies (if any).
4895 llvm::Value *TaskPrivatesMap = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004896 llvm::Type *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00004897 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004898 if (!Privates.empty()) {
4899 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004900 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4901 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4902 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004903 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4904 TaskPrivatesMap, TaskPrivatesMapTy);
4905 } else {
4906 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4907 cast<llvm::PointerType>(TaskPrivatesMapTy));
4908 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004909 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4910 // kmp_task_t *tt);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004911 llvm::Value *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004912 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4913 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4914 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004915
4916 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4917 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4918 // kmp_routine_entry_t *task_entry);
4919 // Task flags. Format is taken from
4920 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4921 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004922 enum {
4923 TiedFlag = 0x1,
4924 FinalFlag = 0x2,
4925 DestructorsFlag = 0x8,
4926 PriorityFlag = 0x20
4927 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004928 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004929 bool NeedsCleanup = false;
4930 if (!Privates.empty()) {
4931 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4932 if (NeedsCleanup)
4933 Flags = Flags | DestructorsFlag;
4934 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004935 if (Data.Priority.getInt())
4936 Flags = Flags | PriorityFlag;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004937 llvm::Value *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004938 Data.Final.getPointer()
4939 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00004940 CGF.Builder.getInt32(FinalFlag),
4941 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004942 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004943 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004944 llvm::Value *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004945 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4946 getThreadID(CGF, Loc), TaskFlags,
4947 KmpTaskTWithPrivatesTySize, SharedsSize,
4948 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4949 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004950 llvm::Value *NewTask = CGF.EmitRuntimeCall(
Alexey Bataev62b63b12015-03-10 07:28:44 +00004951 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004952 llvm::Value *NewTaskNewTaskTTy =
4953 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4954 NewTask, KmpTaskTWithPrivatesPtrTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004955 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4956 KmpTaskTWithPrivatesQTy);
4957 LValue TDBase =
4958 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004959 // Fill the data in the resulting kmp_task_t record.
4960 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00004961 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004962 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00004963 KmpTaskSharedsPtr =
4964 Address(CGF.EmitLoadOfScalar(
4965 CGF.EmitLValueForField(
4966 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4967 KmpTaskTShareds)),
4968 Loc),
4969 CGF.getNaturalTypeAlignment(SharedsTy));
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004970 LValue Dest = CGF.MakeAddrLValue(KmpTaskSharedsPtr, SharedsTy);
4971 LValue Src = CGF.MakeAddrLValue(Shareds, SharedsTy);
Richard Smithe78fac52018-04-05 20:52:58 +00004972 CGF.EmitAggregateCopy(Dest, Src, SharedsTy, AggValueSlot::DoesNotOverlap);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004973 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004974 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00004975 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004976 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004977 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4978 SharedsTy, SharedsPtrTy, Data, Privates,
4979 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004980 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4981 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4982 Result.TaskDupFn = emitTaskDupFunction(
4983 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4984 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4985 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004986 }
4987 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00004988 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4989 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00004990 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00004991 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004992 const RecordDecl *KmpCmplrdataUD =
4993 (*FI)->getType()->getAsUnionType()->getDecl();
Alexey Bataevad537bb2016-05-30 09:06:50 +00004994 if (NeedsCleanup) {
4995 llvm::Value *DestructorFn = emitDestructorsFunction(
4996 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4997 KmpTaskTWithPrivatesQTy);
4998 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4999 LValue DestructorsLV = CGF.EmitLValueForField(
5000 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
5001 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5002 DestructorFn, KmpRoutineEntryPtrTy),
5003 DestructorsLV);
5004 }
5005 // Set priority.
5006 if (Data.Priority.getInt()) {
5007 LValue Data2LV = CGF.EmitLValueForField(
5008 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
5009 LValue PriorityLV = CGF.EmitLValueForField(
5010 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
5011 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
5012 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005013 Result.NewTask = NewTask;
5014 Result.TaskEntry = TaskEntry;
5015 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
5016 Result.TDBase = TDBase;
5017 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
5018 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00005019}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005020
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005021void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
5022 const OMPExecutableDirective &D,
5023 llvm::Value *TaskFunction,
5024 QualType SharedsTy, Address Shareds,
5025 const Expr *IfCond,
5026 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005027 if (!CGF.HaveInsertPoint())
5028 return;
5029
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005030 TaskResultTy Result =
5031 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
5032 llvm::Value *NewTask = Result.NewTask;
5033 llvm::Value *TaskEntry = Result.TaskEntry;
5034 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
5035 LValue TDBase = Result.TDBase;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005036 const RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
5037 ASTContext &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005038 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00005039 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005040 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00005041 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005042 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00005043 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005044 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
5045 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005046 QualType FlagsTy =
5047 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005048 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
5049 if (KmpDependInfoTy.isNull()) {
5050 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
5051 KmpDependInfoRD->startDefinition();
5052 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
5053 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
5054 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
5055 KmpDependInfoRD->completeDefinition();
5056 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005057 } else {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005058 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005059 }
John McCall7f416cc2015-09-08 08:05:57 +00005060 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005061 // Define type kmp_depend_info[<Dependences.size()>];
5062 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00005063 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005064 ArrayType::Normal, /*IndexTypeQuals=*/0);
5065 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00005066 DependenciesArray =
5067 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005068 for (unsigned I = 0; I < NumDependencies; ++I) {
5069 const Expr *E = Data.Dependences[I].second;
5070 LValue Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005071 llvm::Value *Size;
5072 QualType Ty = E->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005073 if (const auto *ASE =
5074 dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005075 LValue UpAddrLVal =
5076 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
5077 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00005078 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005079 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00005080 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005081 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
5082 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005083 } else {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005084 Size = CGF.getTypeSize(Ty);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005085 }
5086 LValue Base = CGF.MakeAddrLValue(
5087 CGF.Builder.CreateConstArrayGEP(DependenciesArray, I, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005088 KmpDependInfoTy);
5089 // deps[i].base_addr = &<Dependences[i].second>;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005090 LValue BaseAddrLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005091 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00005092 CGF.EmitStoreOfScalar(
5093 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
5094 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005095 // deps[i].len = sizeof(<Dependences[i].second>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005096 LValue LenLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005097 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
5098 CGF.EmitStoreOfScalar(Size, LenLVal);
5099 // deps[i].flags = <Dependences[i].first>;
5100 RTLDependenceKindTy DepKind;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005101 switch (Data.Dependences[I].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005102 case OMPC_DEPEND_in:
5103 DepKind = DepIn;
5104 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00005105 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005106 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005107 case OMPC_DEPEND_inout:
5108 DepKind = DepInOut;
5109 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00005110 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005111 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005112 case OMPC_DEPEND_unknown:
5113 llvm_unreachable("Unknown task dependence type");
5114 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005115 LValue FlagsLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005116 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
5117 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
5118 FlagsLVal);
5119 }
John McCall7f416cc2015-09-08 08:05:57 +00005120 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5121 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005122 CGF.VoidPtrTy);
5123 }
5124
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005125 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev62b63b12015-03-10 07:28:44 +00005126 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005127 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
5128 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
5129 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
5130 // list is not empty
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005131 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5132 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00005133 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
5134 llvm::Value *DepTaskArgs[7];
5135 if (NumDependencies) {
5136 DepTaskArgs[0] = UpLoc;
5137 DepTaskArgs[1] = ThreadID;
5138 DepTaskArgs[2] = NewTask;
5139 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
5140 DepTaskArgs[4] = DependenciesArray.getPointer();
5141 DepTaskArgs[5] = CGF.Builder.getInt32(0);
5142 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5143 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005144 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
5145 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005146 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005147 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005148 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005149 LValue PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005150 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
5151 }
John McCall7f416cc2015-09-08 08:05:57 +00005152 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005153 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00005154 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00005155 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005156 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00005157 TaskArgs);
5158 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00005159 // Check if parent region is untied and build return for untied task;
5160 if (auto *Region =
5161 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5162 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00005163 };
John McCall7f416cc2015-09-08 08:05:57 +00005164
5165 llvm::Value *DepWaitTaskArgs[6];
5166 if (NumDependencies) {
5167 DepWaitTaskArgs[0] = UpLoc;
5168 DepWaitTaskArgs[1] = ThreadID;
5169 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
5170 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
5171 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
5172 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5173 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005174 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00005175 NumDependencies, &DepWaitTaskArgs,
5176 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005177 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005178 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
5179 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
5180 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
5181 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
5182 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00005183 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005184 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005185 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005186 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00005187 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
5188 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005189 Action.Enter(CGF);
5190 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00005191 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00005192 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005193 };
5194
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005195 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
5196 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005197 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
5198 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005199 RegionCodeGenTy RCG(CodeGen);
5200 CommonActionTy Action(
5201 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
5202 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
5203 RCG.setAction(Action);
5204 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005205 };
John McCall7f416cc2015-09-08 08:05:57 +00005206
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005207 if (IfCond) {
Alexey Bataev1d677132015-04-22 13:57:31 +00005208 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005209 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005210 RegionCodeGenTy ThenRCG(ThenCodeGen);
5211 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00005212 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00005213}
5214
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005215void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
5216 const OMPLoopDirective &D,
5217 llvm::Value *TaskFunction,
5218 QualType SharedsTy, Address Shareds,
5219 const Expr *IfCond,
5220 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005221 if (!CGF.HaveInsertPoint())
5222 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005223 TaskResultTy Result =
5224 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005225 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev7292c292016-04-25 12:22:29 +00005226 // libcall.
5227 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
5228 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
5229 // sched, kmp_uint64 grainsize, void *task_dup);
5230 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5231 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
5232 llvm::Value *IfVal;
5233 if (IfCond) {
5234 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
5235 /*isSigned=*/true);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005236 } else {
Alexey Bataev7292c292016-04-25 12:22:29 +00005237 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005238 }
Alexey Bataev7292c292016-04-25 12:22:29 +00005239
5240 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005241 Result.TDBase,
5242 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005243 const auto *LBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005244 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
5245 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
5246 /*IsInitializer=*/true);
5247 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005248 Result.TDBase,
5249 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005250 const auto *UBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005251 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
5252 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
5253 /*IsInitializer=*/true);
5254 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005255 Result.TDBase,
5256 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005257 const auto *StVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005258 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
5259 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
5260 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005261 // Store reductions address.
5262 LValue RedLVal = CGF.EmitLValueForField(
5263 Result.TDBase,
5264 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005265 if (Data.Reductions) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005266 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005267 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005268 CGF.EmitNullInitialization(RedLVal.getAddress(),
5269 CGF.getContext().VoidPtrTy);
5270 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005271 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00005272 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00005273 UpLoc,
5274 ThreadID,
5275 Result.NewTask,
5276 IfVal,
5277 LBLVal.getPointer(),
5278 UBLVal.getPointer(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005279 CGF.EmitLoadOfScalar(StLVal, Loc),
Alexey Bataevac6e4de2018-10-24 19:06:37 +00005280 llvm::ConstantInt::getSigned(
5281 CGF.IntTy, 1), // Always 1 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005282 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005283 CGF.IntTy, Data.Schedule.getPointer()
5284 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005285 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005286 Data.Schedule.getPointer()
5287 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005288 /*isSigned=*/false)
5289 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00005290 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5291 Result.TaskDupFn, CGF.VoidPtrTy)
5292 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00005293 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
5294}
5295
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005296/// Emit reduction operation for each element of array (required for
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005297/// array sections) LHS op = RHS.
5298/// \param Type Type of array.
5299/// \param LHSVar Variable on the left side of the reduction operation
5300/// (references element of array in original variable).
5301/// \param RHSVar Variable on the right side of the reduction operation
5302/// (references element of array in original variable).
5303/// \param RedOpGen Generator of reduction operation with use of LHSVar and
5304/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00005305static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005306 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
5307 const VarDecl *RHSVar,
5308 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
5309 const Expr *, const Expr *)> &RedOpGen,
5310 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
5311 const Expr *UpExpr = nullptr) {
5312 // Perform element-by-element initialization.
5313 QualType ElementTy;
5314 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
5315 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
5316
5317 // Drill down to the base element type on both arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005318 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
5319 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005320
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005321 llvm::Value *RHSBegin = RHSAddr.getPointer();
5322 llvm::Value *LHSBegin = LHSAddr.getPointer();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005323 // Cast from pointer to array type to pointer to single element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005324 llvm::Value *LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005325 // The basic structure here is a while-do loop.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005326 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
5327 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
5328 llvm::Value *IsEmpty =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005329 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
5330 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
5331
5332 // Enter the loop body, making that address the current address.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005333 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005334 CGF.EmitBlock(BodyBB);
5335
5336 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
5337
5338 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
5339 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
5340 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
5341 Address RHSElementCurrent =
5342 Address(RHSElementPHI,
5343 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5344
5345 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
5346 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
5347 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
5348 Address LHSElementCurrent =
5349 Address(LHSElementPHI,
5350 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5351
5352 // Emit copy.
5353 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005354 Scope.addPrivate(LHSVar, [=]() { return LHSElementCurrent; });
5355 Scope.addPrivate(RHSVar, [=]() { return RHSElementCurrent; });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005356 Scope.Privatize();
5357 RedOpGen(CGF, XExpr, EExpr, UpExpr);
5358 Scope.ForceCleanup();
5359
5360 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005361 llvm::Value *LHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005362 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005363 llvm::Value *RHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005364 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
5365 // Check whether we've reached the end.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005366 llvm::Value *Done =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005367 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
5368 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
5369 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
5370 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
5371
5372 // Done.
5373 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
5374}
5375
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005376/// Emit reduction combiner. If the combiner is a simple expression emit it as
5377/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
5378/// UDR combiner function.
5379static void emitReductionCombiner(CodeGenFunction &CGF,
5380 const Expr *ReductionOp) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005381 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
5382 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
5383 if (const auto *DRE =
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005384 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005385 if (const auto *DRD =
5386 dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005387 std::pair<llvm::Function *, llvm::Function *> Reduction =
5388 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
5389 RValue Func = RValue::get(Reduction.first);
5390 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
5391 CGF.EmitIgnoredExpr(ReductionOp);
5392 return;
5393 }
5394 CGF.EmitIgnoredExpr(ReductionOp);
5395}
5396
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005397llvm::Value *CGOpenMPRuntime::emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005398 CodeGenModule &CGM, SourceLocation Loc, llvm::Type *ArgsType,
5399 ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs,
5400 ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005401 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005402
5403 // void reduction_func(void *LHSArg, void *RHSArg);
5404 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005405 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5406 ImplicitParamDecl::Other);
5407 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5408 ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005409 Args.push_back(&LHSArg);
5410 Args.push_back(&RHSArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005411 const auto &CGFI =
5412 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005413 std::string Name = getName({"omp", "reduction", "reduction_func"});
5414 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
5415 llvm::GlobalValue::InternalLinkage, Name,
5416 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005417 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005418 Fn->setDoesNotRecurse();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005419 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005420 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005421
5422 // Dst = (void*[n])(LHSArg);
5423 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00005424 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5425 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
5426 ArgsType), CGF.getPointerAlign());
5427 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5428 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
5429 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005430
5431 // ...
5432 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
5433 // ...
5434 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005435 auto IPriv = Privates.begin();
5436 unsigned Idx = 0;
5437 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005438 const auto *RHSVar =
5439 cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
5440 Scope.addPrivate(RHSVar, [&CGF, RHS, Idx, RHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005441 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005442 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005443 const auto *LHSVar =
5444 cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
5445 Scope.addPrivate(LHSVar, [&CGF, LHS, Idx, LHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005446 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005447 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005448 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00005449 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005450 // Get array size and emit VLA type.
5451 ++Idx;
5452 Address Elem =
5453 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
5454 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005455 const VariableArrayType *VLA =
5456 CGF.getContext().getAsVariableArrayType(PrivTy);
5457 const auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005458 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00005459 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005460 CGF.EmitVariablyModifiedType(PrivTy);
5461 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005462 }
5463 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005464 IPriv = Privates.begin();
5465 auto ILHS = LHSExprs.begin();
5466 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005467 for (const Expr *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005468 if ((*IPriv)->getType()->isArrayType()) {
5469 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005470 const auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5471 const auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005472 EmitOMPAggregateReduction(
5473 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5474 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5475 emitReductionCombiner(CGF, E);
5476 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005477 } else {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005478 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005479 emitReductionCombiner(CGF, E);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005480 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005481 ++IPriv;
5482 ++ILHS;
5483 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005484 }
5485 Scope.ForceCleanup();
5486 CGF.FinishFunction();
5487 return Fn;
5488}
5489
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005490void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
5491 const Expr *ReductionOp,
5492 const Expr *PrivateRef,
5493 const DeclRefExpr *LHS,
5494 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005495 if (PrivateRef->getType()->isArrayType()) {
5496 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005497 const auto *LHSVar = cast<VarDecl>(LHS->getDecl());
5498 const auto *RHSVar = cast<VarDecl>(RHS->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005499 EmitOMPAggregateReduction(
5500 CGF, PrivateRef->getType(), LHSVar, RHSVar,
5501 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5502 emitReductionCombiner(CGF, ReductionOp);
5503 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005504 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005505 // Emit reduction for array subscript or single variable.
5506 emitReductionCombiner(CGF, ReductionOp);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005507 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005508}
5509
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005510void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005511 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005512 ArrayRef<const Expr *> LHSExprs,
5513 ArrayRef<const Expr *> RHSExprs,
5514 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005515 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005516 if (!CGF.HaveInsertPoint())
5517 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005518
5519 bool WithNowait = Options.WithNowait;
5520 bool SimpleReduction = Options.SimpleReduction;
5521
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005522 // Next code should be emitted for reduction:
5523 //
5524 // static kmp_critical_name lock = { 0 };
5525 //
5526 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
5527 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
5528 // ...
5529 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
5530 // *(Type<n>-1*)rhs[<n>-1]);
5531 // }
5532 //
5533 // ...
5534 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
5535 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5536 // RedList, reduce_func, &<lock>)) {
5537 // case 1:
5538 // ...
5539 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5540 // ...
5541 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5542 // break;
5543 // case 2:
5544 // ...
5545 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5546 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00005547 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005548 // break;
5549 // default:;
5550 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005551 //
5552 // if SimpleReduction is true, only the next code is generated:
5553 // ...
5554 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5555 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005556
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005557 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005558
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005559 if (SimpleReduction) {
5560 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005561 auto IPriv = Privates.begin();
5562 auto ILHS = LHSExprs.begin();
5563 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005564 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005565 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5566 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005567 ++IPriv;
5568 ++ILHS;
5569 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005570 }
5571 return;
5572 }
5573
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005574 // 1. Build a list of reduction variables.
5575 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005576 auto Size = RHSExprs.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005577 for (const Expr *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005578 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005579 // Reserve place for array size.
5580 ++Size;
5581 }
5582 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005583 QualType ReductionArrayTy =
5584 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
5585 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00005586 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005587 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005588 auto IPriv = Privates.begin();
5589 unsigned Idx = 0;
5590 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00005591 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005592 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00005593 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005594 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00005595 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
5596 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005597 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005598 // Store array size.
5599 ++Idx;
5600 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
5601 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00005602 llvm::Value *Size = CGF.Builder.CreateIntCast(
5603 CGF.getVLASize(
5604 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
Sander de Smalen891af03a2018-02-03 13:55:59 +00005605 .NumElts,
Alexey Bataev1189bd02016-01-26 12:20:39 +00005606 CGF.SizeTy, /*isSigned=*/false);
5607 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
5608 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005609 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005610 }
5611
5612 // 2. Emit reduce_func().
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005613 llvm::Value *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005614 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
5615 Privates, LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005616
5617 // 3. Create static kmp_critical_name lock = { 0 };
Alexey Bataev18fa2322018-05-02 14:20:50 +00005618 std::string Name = getName({"reduction"});
5619 llvm::Value *Lock = getCriticalRegionLock(Name);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005620
5621 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5622 // RedList, reduce_func, &<lock>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005623 llvm::Value *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
5624 llvm::Value *ThreadId = getThreadID(CGF, Loc);
5625 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
5626 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Samuel Antao4c8035b2016-12-12 18:00:20 +00005627 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005628 llvm::Value *Args[] = {
5629 IdentTLoc, // ident_t *<loc>
5630 ThreadId, // i32 <gtid>
5631 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5632 ReductionArrayTySize, // size_type sizeof(RedList)
5633 RL, // void *RedList
5634 ReductionFn, // void (*) (void *, void *) <reduce_func>
5635 Lock // kmp_critical_name *&<lock>
5636 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005637 llvm::Value *Res = CGF.EmitRuntimeCall(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005638 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5639 : OMPRTL__kmpc_reduce),
5640 Args);
5641
5642 // 5. Build switch(res)
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005643 llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5644 llvm::SwitchInst *SwInst =
5645 CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005646
5647 // 6. Build case 1:
5648 // ...
5649 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5650 // ...
5651 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5652 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005653 llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005654 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5655 CGF.EmitBlock(Case1BB);
5656
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005657 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5658 llvm::Value *EndArgs[] = {
5659 IdentTLoc, // ident_t *<loc>
5660 ThreadId, // i32 <gtid>
5661 Lock // kmp_critical_name *&<lock>
5662 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005663 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps](
5664 CodeGenFunction &CGF, PrePostActionTy &Action) {
5665 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005666 auto IPriv = Privates.begin();
5667 auto ILHS = LHSExprs.begin();
5668 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005669 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005670 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5671 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005672 ++IPriv;
5673 ++ILHS;
5674 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005675 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005676 };
5677 RegionCodeGenTy RCG(CodeGen);
5678 CommonActionTy Action(
5679 nullptr, llvm::None,
5680 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5681 : OMPRTL__kmpc_end_reduce),
5682 EndArgs);
5683 RCG.setAction(Action);
5684 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005685
5686 CGF.EmitBranch(DefaultBB);
5687
5688 // 7. Build case 2:
5689 // ...
5690 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5691 // ...
5692 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005693 llvm::BasicBlock *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005694 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5695 CGF.EmitBlock(Case2BB);
5696
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005697 auto &&AtomicCodeGen = [Loc, Privates, LHSExprs, RHSExprs, ReductionOps](
5698 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005699 auto ILHS = LHSExprs.begin();
5700 auto IRHS = RHSExprs.begin();
5701 auto IPriv = Privates.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005702 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005703 const Expr *XExpr = nullptr;
5704 const Expr *EExpr = nullptr;
5705 const Expr *UpExpr = nullptr;
5706 BinaryOperatorKind BO = BO_Comma;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005707 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005708 if (BO->getOpcode() == BO_Assign) {
5709 XExpr = BO->getLHS();
5710 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005711 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005712 }
5713 // Try to emit update expression as a simple atomic.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005714 const Expr *RHSExpr = UpExpr;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005715 if (RHSExpr) {
5716 // Analyze RHS part of the whole expression.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005717 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005718 RHSExpr->IgnoreParenImpCasts())) {
5719 // If this is a conditional operator, analyze its condition for
5720 // min/max reduction operator.
5721 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005722 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005723 if (const auto *BORHS =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005724 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5725 EExpr = BORHS->getRHS();
5726 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005727 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005728 }
5729 if (XExpr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005730 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005731 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005732 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5733 const Expr *EExpr, const Expr *UpExpr) {
5734 LValue X = CGF.EmitLValue(XExpr);
5735 RValue E;
5736 if (EExpr)
5737 E = CGF.EmitAnyExpr(EExpr);
5738 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005739 X, E, BO, /*IsXLHSInRHSPart=*/true,
5740 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005741 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005742 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5743 PrivateScope.addPrivate(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005744 VD, [&CGF, VD, XRValue, Loc]() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005745 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5746 CGF.emitOMPSimpleStore(
5747 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5748 VD->getType().getNonReferenceType(), Loc);
5749 return LHSTemp;
5750 });
5751 (void)PrivateScope.Privatize();
5752 return CGF.EmitAnyExpr(UpExpr);
5753 });
5754 };
5755 if ((*IPriv)->getType()->isArrayType()) {
5756 // Emit atomic reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005757 const auto *RHSVar =
5758 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005759 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5760 AtomicRedGen, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005761 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005762 // Emit atomic reduction for array subscript or single variable.
5763 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005764 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005765 } else {
5766 // Emit as a critical region.
5767 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005768 const Expr *, const Expr *) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005769 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005770 std::string Name = RT.getName({"atomic_reduction"});
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005771 RT.emitCriticalRegion(
Alexey Bataev18fa2322018-05-02 14:20:50 +00005772 CGF, Name,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005773 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5774 Action.Enter(CGF);
5775 emitReductionCombiner(CGF, E);
5776 },
5777 Loc);
5778 };
5779 if ((*IPriv)->getType()->isArrayType()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005780 const auto *LHSVar =
5781 cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5782 const auto *RHSVar =
5783 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005784 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5785 CritRedGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005786 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005787 CritRedGen(CGF, nullptr, nullptr, nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005788 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005789 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005790 ++ILHS;
5791 ++IRHS;
5792 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005793 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005794 };
5795 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5796 if (!WithNowait) {
5797 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5798 llvm::Value *EndArgs[] = {
5799 IdentTLoc, // ident_t *<loc>
5800 ThreadId, // i32 <gtid>
5801 Lock // kmp_critical_name *&<lock>
5802 };
5803 CommonActionTy Action(nullptr, llvm::None,
5804 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5805 EndArgs);
5806 AtomicRCG.setAction(Action);
5807 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005808 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005809 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005810 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005811
5812 CGF.EmitBranch(DefaultBB);
5813 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5814}
5815
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005816/// Generates unique name for artificial threadprivate variables.
Alexey Bataev1c44e152018-03-06 18:59:43 +00005817/// Format is: <Prefix> "." <Decl_mangled_name> "_" "<Decl_start_loc_raw_enc>"
5818static std::string generateUniqueName(CodeGenModule &CGM, StringRef Prefix,
5819 const Expr *Ref) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005820 SmallString<256> Buffer;
5821 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev1c44e152018-03-06 18:59:43 +00005822 const clang::DeclRefExpr *DE;
5823 const VarDecl *D = ::getBaseDecl(Ref, DE);
5824 if (!D)
5825 D = cast<VarDecl>(cast<DeclRefExpr>(Ref)->getDecl());
5826 D = D->getCanonicalDecl();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005827 std::string Name = CGM.getOpenMPRuntime().getName(
5828 {D->isLocalVarDeclOrParm() ? D->getName() : CGM.getMangledName(D)});
5829 Out << Prefix << Name << "_"
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005830 << D->getCanonicalDecl()->getBeginLoc().getRawEncoding();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005831 return Out.str();
5832}
5833
5834/// Emits reduction initializer function:
5835/// \code
5836/// void @.red_init(void* %arg) {
5837/// %0 = bitcast void* %arg to <type>*
5838/// store <type> <init>, <type>* %0
5839/// ret void
5840/// }
5841/// \endcode
5842static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5843 SourceLocation Loc,
5844 ReductionCodeGen &RCG, unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005845 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005846 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005847 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5848 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005849 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005850 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005851 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005852 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005853 std::string Name = CGM.getOpenMPRuntime().getName({"red_init", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005854 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005855 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005856 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005857 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005858 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005859 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005860 Address PrivateAddr = CGF.EmitLoadOfPointer(
5861 CGF.GetAddrOfLocalVar(&Param),
5862 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5863 llvm::Value *Size = nullptr;
5864 // If the size of the reduction item is non-constant, load it from global
5865 // threadprivate variable.
5866 if (RCG.getSizes(N).second) {
5867 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5868 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005869 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005870 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5871 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005872 }
5873 RCG.emitAggregateType(CGF, N, Size);
5874 LValue SharedLVal;
5875 // If initializer uses initializer from declare reduction construct, emit a
5876 // pointer to the address of the original reduction item (reuired by reduction
5877 // initializer)
5878 if (RCG.usesReductionInitializer(N)) {
5879 Address SharedAddr =
5880 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5881 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00005882 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataev21dab122018-03-09 15:20:30 +00005883 SharedAddr = CGF.EmitLoadOfPointer(
5884 SharedAddr,
5885 CGM.getContext().VoidPtrTy.castAs<PointerType>()->getTypePtr());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005886 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5887 } else {
5888 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5889 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5890 CGM.getContext().VoidPtrTy);
5891 }
5892 // Emit the initializer:
5893 // %0 = bitcast void* %arg to <type>*
5894 // store <type> <init>, <type>* %0
5895 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5896 [](CodeGenFunction &) { return false; });
5897 CGF.FinishFunction();
5898 return Fn;
5899}
5900
5901/// Emits reduction combiner function:
5902/// \code
5903/// void @.red_comb(void* %arg0, void* %arg1) {
5904/// %lhs = bitcast void* %arg0 to <type>*
5905/// %rhs = bitcast void* %arg1 to <type>*
5906/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5907/// store <type> %2, <type>* %lhs
5908/// ret void
5909/// }
5910/// \endcode
5911static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5912 SourceLocation Loc,
5913 ReductionCodeGen &RCG, unsigned N,
5914 const Expr *ReductionOp,
5915 const Expr *LHS, const Expr *RHS,
5916 const Expr *PrivateRef) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005917 ASTContext &C = CGM.getContext();
5918 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5919 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005920 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005921 ImplicitParamDecl ParamInOut(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
5922 C.VoidPtrTy, ImplicitParamDecl::Other);
5923 ImplicitParamDecl ParamIn(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5924 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005925 Args.emplace_back(&ParamInOut);
5926 Args.emplace_back(&ParamIn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005927 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005928 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005929 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005930 std::string Name = CGM.getOpenMPRuntime().getName({"red_comb", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005931 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005932 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005933 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005934 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005935 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005936 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005937 llvm::Value *Size = nullptr;
5938 // If the size of the reduction item is non-constant, load it from global
5939 // threadprivate variable.
5940 if (RCG.getSizes(N).second) {
5941 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5942 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005943 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005944 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5945 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005946 }
5947 RCG.emitAggregateType(CGF, N, Size);
5948 // Remap lhs and rhs variables to the addresses of the function arguments.
5949 // %lhs = bitcast void* %arg0 to <type>*
5950 // %rhs = bitcast void* %arg1 to <type>*
5951 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005952 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005953 // Pull out the pointer to the variable.
5954 Address PtrAddr = CGF.EmitLoadOfPointer(
5955 CGF.GetAddrOfLocalVar(&ParamInOut),
5956 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5957 return CGF.Builder.CreateElementBitCast(
5958 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
5959 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005960 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005961 // Pull out the pointer to the variable.
5962 Address PtrAddr = CGF.EmitLoadOfPointer(
5963 CGF.GetAddrOfLocalVar(&ParamIn),
5964 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5965 return CGF.Builder.CreateElementBitCast(
5966 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
5967 });
5968 PrivateScope.Privatize();
5969 // Emit the combiner body:
5970 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
5971 // store <type> %2, <type>* %lhs
5972 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
5973 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
5974 cast<DeclRefExpr>(RHS));
5975 CGF.FinishFunction();
5976 return Fn;
5977}
5978
5979/// Emits reduction finalizer function:
5980/// \code
5981/// void @.red_fini(void* %arg) {
5982/// %0 = bitcast void* %arg to <type>*
5983/// <destroy>(<type>* %0)
5984/// ret void
5985/// }
5986/// \endcode
5987static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
5988 SourceLocation Loc,
5989 ReductionCodeGen &RCG, unsigned N) {
5990 if (!RCG.needCleanups(N))
5991 return nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005992 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005993 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005994 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5995 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005996 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005997 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005998 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005999 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00006000 std::string Name = CGM.getOpenMPRuntime().getName({"red_fini", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006001 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00006002 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00006003 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00006004 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006005 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00006006 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006007 Address PrivateAddr = CGF.EmitLoadOfPointer(
6008 CGF.GetAddrOfLocalVar(&Param),
6009 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
6010 llvm::Value *Size = nullptr;
6011 // If the size of the reduction item is non-constant, load it from global
6012 // threadprivate variable.
6013 if (RCG.getSizes(N).second) {
6014 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
6015 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00006016 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00006017 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
6018 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006019 }
6020 RCG.emitAggregateType(CGF, N, Size);
6021 // Emit the finalizer body:
6022 // <destroy>(<type>* %0)
6023 RCG.emitCleanups(CGF, N, PrivateAddr);
6024 CGF.FinishFunction();
6025 return Fn;
6026}
6027
6028llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
6029 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
6030 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
6031 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
6032 return nullptr;
6033
6034 // Build typedef struct:
6035 // kmp_task_red_input {
6036 // void *reduce_shar; // shared reduction item
6037 // size_t reduce_size; // size of data item
6038 // void *reduce_init; // data initialization routine
6039 // void *reduce_fini; // data finalization routine
6040 // void *reduce_comb; // data combiner routine
6041 // kmp_task_red_flags_t flags; // flags for additional info from compiler
6042 // } kmp_task_red_input_t;
6043 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006044 RecordDecl *RD = C.buildImplicitRecord("kmp_task_red_input_t");
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006045 RD->startDefinition();
6046 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6047 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
6048 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6049 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6050 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6051 const FieldDecl *FlagsFD = addFieldToRecordDecl(
6052 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
6053 RD->completeDefinition();
6054 QualType RDType = C.getRecordType(RD);
6055 unsigned Size = Data.ReductionVars.size();
6056 llvm::APInt ArraySize(/*numBits=*/64, Size);
6057 QualType ArrayRDType = C.getConstantArrayType(
6058 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
6059 // kmp_task_red_input_t .rd_input.[Size];
6060 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
6061 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
6062 Data.ReductionOps);
6063 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
6064 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
6065 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
6066 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
6067 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
6068 TaskRedInput.getPointer(), Idxs,
6069 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
6070 ".rd_input.gep.");
6071 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
6072 // ElemLVal.reduce_shar = &Shareds[Cnt];
6073 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
6074 RCG.emitSharedLValue(CGF, Cnt);
6075 llvm::Value *CastedShared =
6076 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
6077 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
6078 RCG.emitAggregateType(CGF, Cnt);
6079 llvm::Value *SizeValInChars;
6080 llvm::Value *SizeVal;
6081 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
6082 // We use delayed creation/initialization for VLAs, array sections and
6083 // custom reduction initializations. It is required because runtime does not
6084 // provide the way to pass the sizes of VLAs/array sections to
6085 // initializer/combiner/finalizer functions and does not pass the pointer to
6086 // original reduction item to the initializer. Instead threadprivate global
6087 // variables are used to store these values and use them in the functions.
6088 bool DelayedCreation = !!SizeVal;
6089 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
6090 /*isSigned=*/false);
6091 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
6092 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
6093 // ElemLVal.reduce_init = init;
6094 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
6095 llvm::Value *InitAddr =
6096 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
6097 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
6098 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
6099 // ElemLVal.reduce_fini = fini;
6100 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
6101 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
6102 llvm::Value *FiniAddr = Fini
6103 ? CGF.EmitCastToVoidPtr(Fini)
6104 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
6105 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
6106 // ElemLVal.reduce_comb = comb;
6107 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
6108 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
6109 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
6110 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
6111 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
6112 // ElemLVal.flags = 0;
6113 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
6114 if (DelayedCreation) {
6115 CGF.EmitStoreOfScalar(
6116 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
6117 FlagsLVal);
6118 } else
6119 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
6120 }
6121 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
6122 // *data);
6123 llvm::Value *Args[] = {
6124 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6125 /*isSigned=*/true),
6126 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
6127 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
6128 CGM.VoidPtrTy)};
6129 return CGF.EmitRuntimeCall(
6130 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
6131}
6132
6133void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
6134 SourceLocation Loc,
6135 ReductionCodeGen &RCG,
6136 unsigned N) {
6137 auto Sizes = RCG.getSizes(N);
6138 // Emit threadprivate global variable if the type is non-constant
6139 // (Sizes.second = nullptr).
6140 if (Sizes.second) {
6141 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
6142 /*isSigned=*/false);
6143 Address SizeAddr = getAddrOfArtificialThreadPrivate(
6144 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00006145 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006146 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
6147 }
6148 // Store address of the original reduction item if custom initializer is used.
6149 if (RCG.usesReductionInitializer(N)) {
6150 Address SharedAddr = getAddrOfArtificialThreadPrivate(
6151 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00006152 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006153 CGF.Builder.CreateStore(
6154 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6155 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
6156 SharedAddr, /*IsVolatile=*/false);
6157 }
6158}
6159
6160Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
6161 SourceLocation Loc,
6162 llvm::Value *ReductionsPtr,
6163 LValue SharedLVal) {
6164 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
6165 // *d);
6166 llvm::Value *Args[] = {
6167 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6168 /*isSigned=*/true),
6169 ReductionsPtr,
6170 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
6171 CGM.VoidPtrTy)};
6172 return Address(
6173 CGF.EmitRuntimeCall(
6174 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
6175 SharedLVal.getAlignment());
6176}
6177
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006178void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
6179 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006180 if (!CGF.HaveInsertPoint())
6181 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006182 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
6183 // global_tid);
6184 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
6185 // Ignore return result until untied tasks are supported.
6186 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00006187 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
6188 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006189}
6190
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006191void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006192 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006193 const RegionCodeGenTy &CodeGen,
6194 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006195 if (!CGF.HaveInsertPoint())
6196 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00006197 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006198 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00006199}
6200
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006201namespace {
6202enum RTCancelKind {
6203 CancelNoreq = 0,
6204 CancelParallel = 1,
6205 CancelLoop = 2,
6206 CancelSections = 3,
6207 CancelTaskgroup = 4
6208};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00006209} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006210
6211static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
6212 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00006213 if (CancelRegion == OMPD_parallel)
6214 CancelKind = CancelParallel;
6215 else if (CancelRegion == OMPD_for)
6216 CancelKind = CancelLoop;
6217 else if (CancelRegion == OMPD_sections)
6218 CancelKind = CancelSections;
6219 else {
6220 assert(CancelRegion == OMPD_taskgroup);
6221 CancelKind = CancelTaskgroup;
6222 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006223 return CancelKind;
6224}
6225
6226void CGOpenMPRuntime::emitCancellationPointCall(
6227 CodeGenFunction &CGF, SourceLocation Loc,
6228 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006229 if (!CGF.HaveInsertPoint())
6230 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006231 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
6232 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006233 if (auto *OMPRegionInfo =
6234 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00006235 // For 'cancellation point taskgroup', the task region info may not have a
6236 // cancel. This may instead happen in another adjacent task.
6237 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006238 llvm::Value *Args[] = {
6239 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
6240 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006241 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006242 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006243 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
6244 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006245 // exit from construct;
6246 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006247 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6248 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6249 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006250 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6251 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006252 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006253 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev25e5b442015-09-15 12:52:43 +00006254 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006255 CGF.EmitBranchThroughCleanup(CancelDest);
6256 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6257 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006258 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006259}
6260
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006261void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00006262 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006263 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006264 if (!CGF.HaveInsertPoint())
6265 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006266 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
6267 // kmp_int32 cncl_kind);
6268 if (auto *OMPRegionInfo =
6269 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006270 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
6271 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006272 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00006273 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006274 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00006275 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
6276 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006277 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006278 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00006279 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00006280 // exit from construct;
6281 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006282 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6283 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6284 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev87933c72015-09-18 08:07:34 +00006285 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6286 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00006287 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006288 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev87933c72015-09-18 08:07:34 +00006289 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
6290 CGF.EmitBranchThroughCleanup(CancelDest);
6291 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6292 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006293 if (IfCond) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006294 emitOMPIfClause(CGF, IfCond, ThenGen,
6295 [](CodeGenFunction &, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006296 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006297 RegionCodeGenTy ThenRCG(ThenGen);
6298 ThenRCG(CGF);
6299 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006300 }
6301}
Samuel Antaobed3c462015-10-02 16:14:20 +00006302
Samuel Antaoee8fb302016-01-06 13:42:12 +00006303void CGOpenMPRuntime::emitTargetOutlinedFunction(
6304 const OMPExecutableDirective &D, StringRef ParentName,
6305 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006306 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00006307 assert(!ParentName.empty() && "Invalid target region parent name!");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006308 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
6309 IsOffloadEntry, CodeGen);
6310}
6311
6312void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
6313 const OMPExecutableDirective &D, StringRef ParentName,
6314 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
6315 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00006316 // Create a unique name for the entry function using the source location
6317 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00006318 //
Samuel Antao2de62b02016-02-13 23:35:10 +00006319 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00006320 //
6321 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00006322 // mangled name of the function that encloses the target region and BB is the
6323 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00006324
6325 unsigned DeviceID;
6326 unsigned FileID;
6327 unsigned Line;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006328 getTargetEntryUniqueInfo(CGM.getContext(), D.getBeginLoc(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00006329 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006330 SmallString<64> EntryFnName;
6331 {
6332 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00006333 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
6334 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00006335 }
6336
Alexey Bataev475a7442018-01-12 19:39:11 +00006337 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006338
Samuel Antaobed3c462015-10-02 16:14:20 +00006339 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006340 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00006341 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006342
Samuel Antao6d004262016-06-16 18:39:34 +00006343 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006344
6345 // If this target outline function is not an offload entry, we don't need to
6346 // register it.
6347 if (!IsOffloadEntry)
6348 return;
6349
6350 // The target region ID is used by the runtime library to identify the current
6351 // target region, so it only has to be unique and not necessarily point to
6352 // anything. It could be the pointer to the outlined function that implements
6353 // the target region, but we aren't using that so that the compiler doesn't
6354 // need to keep that, and could therefore inline the host function if proven
6355 // worthwhile during optimization. In the other hand, if emitting code for the
6356 // device, the ID has to be the function address so that it can retrieved from
6357 // the offloading entry and launched by the runtime library. We also mark the
6358 // outlined function to have external linkage in case we are emitting code for
6359 // the device, because these functions will be entry points to the device.
6360
6361 if (CGM.getLangOpts().OpenMPIsDevice) {
6362 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
Alexey Bataev9a700172018-05-08 14:16:57 +00006363 OutlinedFn->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Rafael Espindolacbca4872018-01-11 22:15:12 +00006364 OutlinedFn->setDSOLocal(false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006365 } else {
Alexey Bataevc15ea702018-05-09 18:02:37 +00006366 std::string Name = getName({EntryFnName, "region_id"});
Samuel Antaoee8fb302016-01-06 13:42:12 +00006367 OutlinedFnID = new llvm::GlobalVariable(
6368 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
Alexey Bataev9a700172018-05-08 14:16:57 +00006369 llvm::GlobalValue::WeakAnyLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00006370 llvm::Constant::getNullValue(CGM.Int8Ty), Name);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006371 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00006372
6373 // Register the information for the entry associated with this target region.
6374 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00006375 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
Alexey Bataev03f270c2018-03-30 18:31:07 +00006376 OffloadEntriesInfoManagerTy::OMPTargetRegionEntryTargetRegion);
Samuel Antaobed3c462015-10-02 16:14:20 +00006377}
6378
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006379/// discard all CompoundStmts intervening between two constructs
6380static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006381 while (const auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006382 Body = CS->body_front();
6383
6384 return Body;
6385}
6386
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006387/// Emit the number of teams for a target directive. Inspect the num_teams
6388/// clause associated with a teams construct combined or closely nested
6389/// with the target directive.
6390///
6391/// Emit a team of size one for directives such as 'target parallel' that
6392/// have no associated teams construct.
6393///
6394/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006395static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006396emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6397 CodeGenFunction &CGF,
6398 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006399 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6400 "teams directive expected to be "
6401 "emitted only for the host!");
6402
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006403 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006404
6405 // If the target directive is combined with a teams directive:
6406 // Return the value in the num_teams clause, if any.
6407 // Otherwise, return 0 to denote the runtime default.
6408 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
6409 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
6410 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006411 llvm::Value *NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
6412 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006413 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6414 /*IsSigned=*/true);
6415 }
6416
6417 // The default value is 0.
6418 return Bld.getInt32(0);
6419 }
6420
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006421 // If the target directive is combined with a parallel directive but not a
6422 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006423 if (isOpenMPParallelDirective(D.getDirectiveKind()))
6424 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006425
6426 // If the current target region has a teams region enclosed, we need to get
6427 // the number of teams to pass to the runtime function call. This is done
6428 // by generating the expression in a inlined region. This is required because
6429 // the expression is captured in the enclosing target environment when the
6430 // teams directive is not combined with target.
6431
Alexey Bataev475a7442018-01-12 19:39:11 +00006432 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006433
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006434 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006435 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006436 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006437 if (const auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006438 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6439 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6440 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
6441 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6442 /*IsSigned=*/true);
6443 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006444
Alexey Bataev50a1c782017-12-01 21:31:08 +00006445 // If we have an enclosed teams directive but no num_teams clause we use
6446 // the default value 0.
6447 return Bld.getInt32(0);
6448 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006449 }
6450
6451 // No teams associated with the directive.
6452 return nullptr;
6453}
6454
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006455/// Emit the number of threads for a target directive. Inspect the
6456/// thread_limit clause associated with a teams construct combined or closely
6457/// nested with the target directive.
6458///
6459/// Emit the num_threads clause for directives such as 'target parallel' that
6460/// have no associated teams construct.
6461///
6462/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006463static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006464emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6465 CodeGenFunction &CGF,
6466 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006467 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6468 "teams directive expected to be "
6469 "emitted only for the host!");
6470
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006471 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006472
6473 //
6474 // If the target directive is combined with a teams directive:
6475 // Return the value in the thread_limit clause, if any.
6476 //
6477 // If the target directive is combined with a parallel directive:
6478 // Return the value in the num_threads clause, if any.
6479 //
6480 // If both clauses are set, select the minimum of the two.
6481 //
6482 // If neither teams or parallel combined directives set the number of threads
6483 // in a team, return 0 to denote the runtime default.
6484 //
6485 // If this is not a teams directive return nullptr.
6486
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006487 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
6488 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006489 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
6490 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006491 llvm::Value *ThreadLimitVal = nullptr;
6492
6493 if (const auto *ThreadLimitClause =
6494 D.getSingleClause<OMPThreadLimitClause>()) {
6495 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006496 llvm::Value *ThreadLimit =
6497 CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
6498 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006499 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6500 /*IsSigned=*/true);
6501 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006502
6503 if (const auto *NumThreadsClause =
6504 D.getSingleClause<OMPNumThreadsClause>()) {
6505 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
6506 llvm::Value *NumThreads =
6507 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
6508 /*IgnoreResultAssign*/ true);
6509 NumThreadsVal =
6510 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
6511 }
6512
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006513 // Select the lesser of thread_limit and num_threads.
6514 if (NumThreadsVal)
6515 ThreadLimitVal = ThreadLimitVal
6516 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
6517 ThreadLimitVal),
6518 NumThreadsVal, ThreadLimitVal)
6519 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00006520
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006521 // Set default value passed to the runtime if either teams or a target
6522 // parallel type directive is found but no clause is specified.
6523 if (!ThreadLimitVal)
6524 ThreadLimitVal = DefaultThreadLimitVal;
6525
6526 return ThreadLimitVal;
6527 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00006528
Samuel Antaob68e2db2016-03-03 16:20:23 +00006529 // If the current target region has a teams region enclosed, we need to get
6530 // the thread limit to pass to the runtime function call. This is done
6531 // by generating the expression in a inlined region. This is required because
6532 // the expression is captured in the enclosing target environment when the
6533 // teams directive is not combined with target.
6534
Alexey Bataev475a7442018-01-12 19:39:11 +00006535 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006536
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006537 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006538 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006539 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006540 if (const auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006541 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6542 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6543 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
6544 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6545 /*IsSigned=*/true);
6546 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006547
Alexey Bataev50a1c782017-12-01 21:31:08 +00006548 // If we have an enclosed teams directive but no thread_limit clause we
6549 // use the default value 0.
6550 return CGF.Builder.getInt32(0);
6551 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006552 }
6553
6554 // No teams associated with the directive.
6555 return nullptr;
6556}
6557
Samuel Antao86ace552016-04-27 22:40:57 +00006558namespace {
Alexey Bataevb3638132018-07-19 16:34:13 +00006559LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
6560
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006561// Utility to handle information from clauses associated with a given
Samuel Antao86ace552016-04-27 22:40:57 +00006562// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
6563// It provides a convenient interface to obtain the information and generate
6564// code for that information.
6565class MappableExprsHandler {
6566public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006567 /// Values for bit flags used to specify the mapping type for
Samuel Antao86ace552016-04-27 22:40:57 +00006568 /// offloading.
Alexey Bataevb3638132018-07-19 16:34:13 +00006569 enum OpenMPOffloadMappingFlags : uint64_t {
6570 /// No flags
6571 OMP_MAP_NONE = 0x0,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006572 /// Allocate memory on the device and move data from host to device.
Samuel Antao86ace552016-04-27 22:40:57 +00006573 OMP_MAP_TO = 0x01,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006574 /// Allocate memory on the device and move data from device to host.
Samuel Antao86ace552016-04-27 22:40:57 +00006575 OMP_MAP_FROM = 0x02,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006576 /// Always perform the requested mapping action on the element, even
Samuel Antao86ace552016-04-27 22:40:57 +00006577 /// if it was already mapped before.
6578 OMP_MAP_ALWAYS = 0x04,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006579 /// Delete the element from the device environment, ignoring the
Samuel Antao86ace552016-04-27 22:40:57 +00006580 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00006581 OMP_MAP_DELETE = 0x08,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006582 /// The element being mapped is a pointer-pointee pair; both the
George Rokos065755d2017-11-07 18:27:04 +00006583 /// pointer and the pointee should be mapped.
6584 OMP_MAP_PTR_AND_OBJ = 0x10,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006585 /// This flags signals that the base address of an entry should be
George Rokos065755d2017-11-07 18:27:04 +00006586 /// passed to the target kernel as an argument.
6587 OMP_MAP_TARGET_PARAM = 0x20,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006588 /// Signal that the runtime library has to return the device pointer
George Rokos065755d2017-11-07 18:27:04 +00006589 /// in the current position for the data being mapped. Used when we have the
6590 /// use_device_ptr clause.
6591 OMP_MAP_RETURN_PARAM = 0x40,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006592 /// This flag signals that the reference being passed is a pointer to
Samuel Antaod486f842016-05-26 16:53:38 +00006593 /// private data.
George Rokos065755d2017-11-07 18:27:04 +00006594 OMP_MAP_PRIVATE = 0x80,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006595 /// Pass the element to the device by value.
George Rokos065755d2017-11-07 18:27:04 +00006596 OMP_MAP_LITERAL = 0x100,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006597 /// Implicit map
6598 OMP_MAP_IMPLICIT = 0x200,
Alexey Bataevb3638132018-07-19 16:34:13 +00006599 /// The 16 MSBs of the flags indicate whether the entry is member of some
6600 /// struct/class.
6601 OMP_MAP_MEMBER_OF = 0xffff000000000000,
6602 LLVM_MARK_AS_BITMASK_ENUM(/* LargestFlag = */ OMP_MAP_MEMBER_OF),
Samuel Antao86ace552016-04-27 22:40:57 +00006603 };
6604
Samuel Antaocc10b852016-07-28 14:23:26 +00006605 /// Class that associates information with a base pointer to be passed to the
6606 /// runtime library.
6607 class BasePointerInfo {
6608 /// The base pointer.
6609 llvm::Value *Ptr = nullptr;
6610 /// The base declaration that refers to this device pointer, or null if
6611 /// there is none.
6612 const ValueDecl *DevPtrDecl = nullptr;
6613
6614 public:
6615 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
6616 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
6617 llvm::Value *operator*() const { return Ptr; }
6618 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
6619 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
6620 };
6621
Alexey Bataevb3638132018-07-19 16:34:13 +00006622 using MapBaseValuesArrayTy = SmallVector<BasePointerInfo, 4>;
6623 using MapValuesArrayTy = SmallVector<llvm::Value *, 4>;
6624 using MapFlagsArrayTy = SmallVector<OpenMPOffloadMappingFlags, 4>;
6625
6626 /// Map between a struct and the its lowest & highest elements which have been
6627 /// mapped.
6628 /// [ValueDecl *] --> {LE(FieldIndex, Pointer),
6629 /// HE(FieldIndex, Pointer)}
6630 struct StructRangeInfoTy {
6631 std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> LowestElem = {
6632 0, Address::invalid()};
6633 std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> HighestElem = {
6634 0, Address::invalid()};
6635 Address Base = Address::invalid();
6636 };
Samuel Antao86ace552016-04-27 22:40:57 +00006637
6638private:
Alexey Bataevb3638132018-07-19 16:34:13 +00006639 /// Kind that defines how a device pointer has to be returned.
6640 struct MapInfo {
6641 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
6642 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
6643 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
6644 bool ReturnDevicePointer = false;
6645 bool IsImplicit = false;
6646
6647 MapInfo() = default;
6648 MapInfo(
6649 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
6650 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6651 bool ReturnDevicePointer, bool IsImplicit)
6652 : Components(Components), MapType(MapType),
6653 MapTypeModifier(MapTypeModifier),
6654 ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
6655 };
6656
6657 /// If use_device_ptr is used on a pointer which is a struct member and there
6658 /// is no map information about it, then emission of that entry is deferred
6659 /// until the whole struct has been processed.
6660 struct DeferredDevicePtrEntryTy {
6661 const Expr *IE = nullptr;
6662 const ValueDecl *VD = nullptr;
6663
6664 DeferredDevicePtrEntryTy(const Expr *IE, const ValueDecl *VD)
6665 : IE(IE), VD(VD) {}
6666 };
6667
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006668 /// Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00006669 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00006670
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006671 /// Function the directive is being generated for.
Samuel Antao86ace552016-04-27 22:40:57 +00006672 CodeGenFunction &CGF;
6673
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006674 /// Set of all first private variables in the current directive.
Samuel Antaod486f842016-05-26 16:53:38 +00006675 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
6676
Samuel Antao6890b092016-07-28 14:25:09 +00006677 /// Map between device pointer declarations and their expression components.
6678 /// The key value for declarations in 'this' is null.
6679 llvm::DenseMap<
6680 const ValueDecl *,
6681 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6682 DevPointersMap;
6683
Samuel Antao86ace552016-04-27 22:40:57 +00006684 llvm::Value *getExprTypeSize(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006685 QualType ExprTy = E->getType().getCanonicalType();
Samuel Antao86ace552016-04-27 22:40:57 +00006686
6687 // Reference types are ignored for mapping purposes.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006688 if (const auto *RefTy = ExprTy->getAs<ReferenceType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006689 ExprTy = RefTy->getPointeeType().getCanonicalType();
6690
6691 // Given that an array section is considered a built-in type, we need to
6692 // do the calculation based on the length of the section instead of relying
6693 // on CGF.getTypeSize(E->getType()).
6694 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6695 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6696 OAE->getBase()->IgnoreParenImpCasts())
6697 .getCanonicalType();
6698
6699 // If there is no length associated with the expression, that means we
6700 // are using the whole length of the base.
6701 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6702 return CGF.getTypeSize(BaseTy);
6703
6704 llvm::Value *ElemSize;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006705 if (const auto *PTy = BaseTy->getAs<PointerType>()) {
Samuel Antao86ace552016-04-27 22:40:57 +00006706 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006707 } else {
6708 const auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
Samuel Antao86ace552016-04-27 22:40:57 +00006709 assert(ATy && "Expecting array type if not a pointer type.");
6710 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6711 }
6712
6713 // If we don't have a length at this point, that is because we have an
6714 // array section with a single element.
6715 if (!OAE->getLength())
6716 return ElemSize;
6717
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006718 llvm::Value *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
Samuel Antao86ace552016-04-27 22:40:57 +00006719 LengthVal =
6720 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6721 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6722 }
6723 return CGF.getTypeSize(ExprTy);
6724 }
6725
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006726 /// Return the corresponding bits for a given map clause modifier. Add
Samuel Antao86ace552016-04-27 22:40:57 +00006727 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006728 /// map as the first one of a series of maps that relate to the same map
6729 /// expression.
Alexey Bataevb3638132018-07-19 16:34:13 +00006730 OpenMPOffloadMappingFlags getMapTypeBits(OpenMPMapClauseKind MapType,
6731 OpenMPMapClauseKind MapTypeModifier,
6732 bool IsImplicit, bool AddPtrFlag,
6733 bool AddIsTargetParamFlag) const {
6734 OpenMPOffloadMappingFlags Bits =
6735 IsImplicit ? OMP_MAP_IMPLICIT : OMP_MAP_NONE;
Samuel Antao86ace552016-04-27 22:40:57 +00006736 switch (MapType) {
6737 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006738 case OMPC_MAP_release:
6739 // alloc and release is the default behavior in the runtime library, i.e.
6740 // if we don't pass any bits alloc/release that is what the runtime is
6741 // going to do. Therefore, we don't need to signal anything for these two
6742 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006743 break;
6744 case OMPC_MAP_to:
Alexey Bataevb3638132018-07-19 16:34:13 +00006745 Bits |= OMP_MAP_TO;
Samuel Antao86ace552016-04-27 22:40:57 +00006746 break;
6747 case OMPC_MAP_from:
Alexey Bataevb3638132018-07-19 16:34:13 +00006748 Bits |= OMP_MAP_FROM;
Samuel Antao86ace552016-04-27 22:40:57 +00006749 break;
6750 case OMPC_MAP_tofrom:
Alexey Bataevb3638132018-07-19 16:34:13 +00006751 Bits |= OMP_MAP_TO | OMP_MAP_FROM;
Samuel Antao86ace552016-04-27 22:40:57 +00006752 break;
6753 case OMPC_MAP_delete:
Alexey Bataevb3638132018-07-19 16:34:13 +00006754 Bits |= OMP_MAP_DELETE;
Samuel Antao86ace552016-04-27 22:40:57 +00006755 break;
Alexey Bataevb3638132018-07-19 16:34:13 +00006756 case OMPC_MAP_always:
6757 case OMPC_MAP_unknown:
Samuel Antao86ace552016-04-27 22:40:57 +00006758 llvm_unreachable("Unexpected map type!");
Samuel Antao86ace552016-04-27 22:40:57 +00006759 }
6760 if (AddPtrFlag)
George Rokos065755d2017-11-07 18:27:04 +00006761 Bits |= OMP_MAP_PTR_AND_OBJ;
6762 if (AddIsTargetParamFlag)
6763 Bits |= OMP_MAP_TARGET_PARAM;
Samuel Antao86ace552016-04-27 22:40:57 +00006764 if (MapTypeModifier == OMPC_MAP_always)
6765 Bits |= OMP_MAP_ALWAYS;
6766 return Bits;
6767 }
6768
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006769 /// Return true if the provided expression is a final array section. A
Samuel Antao86ace552016-04-27 22:40:57 +00006770 /// final array section, is one whose length can't be proved to be one.
6771 bool isFinalArraySectionExpression(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006772 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antao86ace552016-04-27 22:40:57 +00006773
6774 // It is not an array section and therefore not a unity-size one.
6775 if (!OASE)
6776 return false;
6777
6778 // An array section with no colon always refer to a single element.
6779 if (OASE->getColonLoc().isInvalid())
6780 return false;
6781
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006782 const Expr *Length = OASE->getLength();
Samuel Antao86ace552016-04-27 22:40:57 +00006783
6784 // If we don't have a length we have to check if the array has size 1
6785 // for this dimension. Also, we should always expect a length if the
6786 // base type is pointer.
6787 if (!Length) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006788 QualType BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6789 OASE->getBase()->IgnoreParenImpCasts())
6790 .getCanonicalType();
6791 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antao86ace552016-04-27 22:40:57 +00006792 return ATy->getSize().getSExtValue() != 1;
6793 // If we don't have a constant dimension length, we have to consider
6794 // the current section as having any size, so it is not necessarily
6795 // unitary. If it happen to be unity size, that's user fault.
6796 return true;
6797 }
6798
6799 // Check if the length evaluates to 1.
Bill Wendling6ff17512018-11-21 20:44:18 +00006800 Expr::EvalResult Result;
6801 if (!Length->EvaluateAsInt(Result, CGF.getContext()))
Samuel Antao86ace552016-04-27 22:40:57 +00006802 return true; // Can have more that size 1.
6803
Bill Wendling6ff17512018-11-21 20:44:18 +00006804 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antao86ace552016-04-27 22:40:57 +00006805 return ConstLength.getSExtValue() != 1;
6806 }
6807
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006808 /// Generate the base pointers, section pointers, sizes and map type
Samuel Antao86ace552016-04-27 22:40:57 +00006809 /// bits for the provided map type, map modifier, and expression components.
6810 /// \a IsFirstComponent should be set to true if the provided set of
6811 /// components is the first associated with a capture.
6812 void generateInfoForComponentList(
6813 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6814 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006815 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006816 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
Alexey Bataevb3638132018-07-19 16:34:13 +00006817 StructRangeInfoTy &PartialStruct, bool IsFirstComponentList,
Alexey Bataeve82445f2018-09-20 13:54:02 +00006818 bool IsImplicit,
6819 ArrayRef<OMPClauseMappableExprCommon::MappableExprComponentListRef>
6820 OverlappedElements = llvm::None) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006821 // The following summarizes what has to be generated for each map and the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006822 // types below. The generated information is expressed in this order:
Samuel Antao86ace552016-04-27 22:40:57 +00006823 // base pointer, section pointer, size, flags
6824 // (to add to the ones that come from the map type and modifier).
6825 //
6826 // double d;
6827 // int i[100];
6828 // float *p;
6829 //
6830 // struct S1 {
6831 // int i;
6832 // float f[50];
6833 // }
6834 // struct S2 {
6835 // int i;
6836 // float f[50];
6837 // S1 s;
6838 // double *p;
6839 // struct S2 *ps;
6840 // }
6841 // S2 s;
6842 // S2 *ps;
6843 //
6844 // map(d)
Alexey Bataevb3638132018-07-19 16:34:13 +00006845 // &d, &d, sizeof(double), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006846 //
6847 // map(i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006848 // &i, &i, 100*sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006849 //
6850 // map(i[1:23])
Alexey Bataevb3638132018-07-19 16:34:13 +00006851 // &i(=&i[0]), &i[1], 23*sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006852 //
6853 // map(p)
Alexey Bataevb3638132018-07-19 16:34:13 +00006854 // &p, &p, sizeof(float*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006855 //
6856 // map(p[1:24])
Alexey Bataevb3638132018-07-19 16:34:13 +00006857 // p, &p[1], 24*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006858 //
6859 // map(s)
Alexey Bataevb3638132018-07-19 16:34:13 +00006860 // &s, &s, sizeof(S2), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006861 //
6862 // map(s.i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006863 // &s, &(s.i), sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006864 //
6865 // map(s.s.f)
Alexey Bataevb3638132018-07-19 16:34:13 +00006866 // &s, &(s.s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006867 //
6868 // map(s.p)
Alexey Bataevb3638132018-07-19 16:34:13 +00006869 // &s, &(s.p), sizeof(double*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006870 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006871 // map(to: s.p[:22])
6872 // &s, &(s.p), sizeof(double*), TARGET_PARAM (*)
6873 // &s, &(s.p), sizeof(double*), MEMBER_OF(1) (**)
6874 // &(s.p), &(s.p[0]), 22*sizeof(double),
6875 // MEMBER_OF(1) | PTR_AND_OBJ | TO (***)
6876 // (*) alloc space for struct members, only this is a target parameter
6877 // (**) map the pointer (nothing to be mapped in this example) (the compiler
6878 // optimizes this entry out, same in the examples below)
6879 // (***) map the pointee (map: to)
Samuel Antao86ace552016-04-27 22:40:57 +00006880 //
6881 // map(s.ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006882 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006883 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006884 // map(from: s.ps->s.i)
6885 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6886 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6887 // &(s.ps), &(s.ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006888 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006889 // map(to: s.ps->ps)
6890 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6891 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6892 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006893 //
6894 // map(s.ps->ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006895 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6896 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6897 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6898 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006899 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006900 // map(to: s.ps->ps->s.f[:22])
6901 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6902 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6903 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6904 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006905 //
6906 // map(ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006907 // &ps, &ps, sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006908 //
6909 // map(ps->i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006910 // ps, &(ps->i), sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006911 //
6912 // map(ps->s.f)
Alexey Bataevb3638132018-07-19 16:34:13 +00006913 // ps, &(ps->s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006914 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006915 // map(from: ps->p)
6916 // ps, &(ps->p), sizeof(double*), TARGET_PARAM | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006917 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006918 // map(to: ps->p[:22])
6919 // ps, &(ps->p), sizeof(double*), TARGET_PARAM
6920 // ps, &(ps->p), sizeof(double*), MEMBER_OF(1)
6921 // &(ps->p), &(ps->p[0]), 22*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006922 //
6923 // map(ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006924 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006925 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006926 // map(from: ps->ps->s.i)
6927 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6928 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6929 // &(ps->ps), &(ps->ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006930 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006931 // map(from: ps->ps->ps)
6932 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6933 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6934 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006935 //
6936 // map(ps->ps->ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006937 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6938 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6939 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6940 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006941 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006942 // map(to: ps->ps->ps->s.f[:22])
6943 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6944 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6945 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6946 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO
6947 //
6948 // map(to: s.f[:22]) map(from: s.p[:33])
6949 // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1) +
6950 // sizeof(double*) (**), TARGET_PARAM
6951 // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | TO
6952 // &s, &(s.p), sizeof(double*), MEMBER_OF(1)
6953 // &(s.p), &(s.p[0]), 33*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | FROM
6954 // (*) allocate contiguous space needed to fit all mapped members even if
6955 // we allocate space for members not mapped (in this example,
6956 // s.f[22..49] and s.s are not mapped, yet we must allocate space for
6957 // them as well because they fall between &s.f[0] and &s.p)
6958 //
6959 // map(from: s.f[:22]) map(to: ps->p[:33])
6960 // &s, &(s.f[0]), 22*sizeof(float), TARGET_PARAM | FROM
6961 // ps, &(ps->p), sizeof(S2*), TARGET_PARAM
6962 // ps, &(ps->p), sizeof(double*), MEMBER_OF(2) (*)
6963 // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(2) | PTR_AND_OBJ | TO
6964 // (*) the struct this entry pertains to is the 2nd element in the list of
6965 // arguments, hence MEMBER_OF(2)
6966 //
6967 // map(from: s.f[:22], s.s) map(to: ps->p[:33])
6968 // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1), TARGET_PARAM
6969 // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | FROM
6970 // &s, &(s.s), sizeof(struct S1), MEMBER_OF(1) | FROM
6971 // ps, &(ps->p), sizeof(S2*), TARGET_PARAM
6972 // ps, &(ps->p), sizeof(double*), MEMBER_OF(4) (*)
6973 // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(4) | PTR_AND_OBJ | TO
6974 // (*) the struct this entry pertains to is the 4th element in the list
6975 // of arguments, hence MEMBER_OF(4)
Samuel Antao86ace552016-04-27 22:40:57 +00006976
6977 // Track if the map information being generated is the first for a capture.
6978 bool IsCaptureFirstInfo = IsFirstComponentList;
Alexey Bataev92327c52018-03-26 16:40:55 +00006979 bool IsLink = false; // Is this variable a "declare target link"?
Samuel Antao86ace552016-04-27 22:40:57 +00006980
6981 // Scan the components from the base to the complete expression.
6982 auto CI = Components.rbegin();
6983 auto CE = Components.rend();
6984 auto I = CI;
6985
6986 // Track if the map information being generated is the first for a list of
6987 // components.
6988 bool IsExpressionFirstInfo = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00006989 Address BP = Address::invalid();
Samuel Antao86ace552016-04-27 22:40:57 +00006990
Erich Keanee69755a2018-07-19 17:19:16 +00006991 if (isa<MemberExpr>(I->getAssociatedExpression())) {
Samuel Antao86ace552016-04-27 22:40:57 +00006992 // The base is the 'this' pointer. The content of the pointer is going
6993 // to be the base of the field being mapped.
Alexey Bataevb3638132018-07-19 16:34:13 +00006994 BP = CGF.LoadCXXThisAddress();
Samuel Antao86ace552016-04-27 22:40:57 +00006995 } else {
6996 // The base is the reference to the variable.
6997 // BP = &Var.
Alexey Bataevb3638132018-07-19 16:34:13 +00006998 BP = CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getAddress();
Alexey Bataev92327c52018-03-26 16:40:55 +00006999 if (const auto *VD =
7000 dyn_cast_or_null<VarDecl>(I->getAssociatedDeclaration())) {
7001 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00007002 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataev2c1dffe2018-04-16 20:34:41 +00007003 if (*Res == OMPDeclareTargetDeclAttr::MT_Link) {
7004 IsLink = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00007005 BP = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
Alexey Bataev2c1dffe2018-04-16 20:34:41 +00007006 }
Alexey Bataev92327c52018-03-26 16:40:55 +00007007 }
Samuel Antao86ace552016-04-27 22:40:57 +00007008
7009 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00007010 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00007011 // reference. References are ignored for mapping purposes.
7012 QualType Ty =
7013 I->getAssociatedDeclaration()->getType().getNonReferenceType();
7014 if (Ty->isAnyPointerType() && std::next(I) != CE) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007015 BP = CGF.EmitLoadOfPointer(BP, Ty->castAs<PointerType>());
Samuel Antao86ace552016-04-27 22:40:57 +00007016
7017 // We do not need to generate individual map information for the
7018 // pointer, it can be associated with the combined storage.
7019 ++I;
7020 }
7021 }
7022
Alexey Bataevb3638132018-07-19 16:34:13 +00007023 // Track whether a component of the list should be marked as MEMBER_OF some
7024 // combined entry (for partial structs). Only the first PTR_AND_OBJ entry
7025 // in a component list should be marked as MEMBER_OF, all subsequent entries
7026 // do not belong to the base struct. E.g.
7027 // struct S2 s;
7028 // s.ps->ps->ps->f[:]
7029 // (1) (2) (3) (4)
7030 // ps(1) is a member pointer, ps(2) is a pointee of ps(1), so it is a
7031 // PTR_AND_OBJ entry; the PTR is ps(1), so MEMBER_OF the base struct. ps(3)
7032 // is the pointee of ps(2) which is not member of struct s, so it should not
7033 // be marked as such (it is still PTR_AND_OBJ).
7034 // The variable is initialized to false so that PTR_AND_OBJ entries which
7035 // are not struct members are not considered (e.g. array of pointers to
7036 // data).
7037 bool ShouldBeMemberOf = false;
7038
7039 // Variable keeping track of whether or not we have encountered a component
7040 // in the component list which is a member expression. Useful when we have a
7041 // pointer or a final array section, in which case it is the previous
7042 // component in the list which tells us whether we have a member expression.
7043 // E.g. X.f[:]
7044 // While processing the final array section "[:]" it is "f" which tells us
7045 // whether we are dealing with a member of a declared struct.
7046 const MemberExpr *EncounteredME = nullptr;
7047
Samuel Antao86ace552016-04-27 22:40:57 +00007048 for (; I != CE; ++I) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007049 // If the current component is member of a struct (parent struct) mark it.
7050 if (!EncounteredME) {
7051 EncounteredME = dyn_cast<MemberExpr>(I->getAssociatedExpression());
7052 // If we encounter a PTR_AND_OBJ entry from now on it should be marked
7053 // as MEMBER_OF the parent struct.
7054 if (EncounteredME)
7055 ShouldBeMemberOf = true;
7056 }
7057
Samuel Antao86ace552016-04-27 22:40:57 +00007058 auto Next = std::next(I);
7059
7060 // We need to generate the addresses and sizes if this is the last
7061 // component, if the component is a pointer or if it is an array section
7062 // whose length can't be proved to be one. If this is a pointer, it
7063 // becomes the base address for the following components.
7064
7065 // A final array section, is one whose length can't be proved to be one.
7066 bool IsFinalArraySection =
7067 isFinalArraySectionExpression(I->getAssociatedExpression());
7068
7069 // Get information on whether the element is a pointer. Have to do a
7070 // special treatment for array sections given that they are built-in
7071 // types.
7072 const auto *OASE =
7073 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
7074 bool IsPointer =
Alexey Bataevb3638132018-07-19 16:34:13 +00007075 (OASE && OMPArraySectionExpr::getBaseOriginalType(OASE)
7076 .getCanonicalType()
7077 ->isAnyPointerType()) ||
Samuel Antao86ace552016-04-27 22:40:57 +00007078 I->getAssociatedExpression()->getType()->isAnyPointerType();
7079
7080 if (Next == CE || IsPointer || IsFinalArraySection) {
Samuel Antao86ace552016-04-27 22:40:57 +00007081 // If this is not the last component, we expect the pointer to be
7082 // associated with an array expression or member expression.
7083 assert((Next == CE ||
7084 isa<MemberExpr>(Next->getAssociatedExpression()) ||
7085 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
7086 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
7087 "Unexpected expression");
7088
Alexey Bataevb3638132018-07-19 16:34:13 +00007089 Address LB =
7090 CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getAddress();
Samuel Antao86ace552016-04-27 22:40:57 +00007091
Alexey Bataevb3638132018-07-19 16:34:13 +00007092 // If this component is a pointer inside the base struct then we don't
7093 // need to create any entry for it - it will be combined with the object
7094 // it is pointing to into a single PTR_AND_OBJ entry.
7095 bool IsMemberPointer =
7096 IsPointer && EncounteredME &&
7097 (dyn_cast<MemberExpr>(I->getAssociatedExpression()) ==
7098 EncounteredME);
Alexey Bataeve82445f2018-09-20 13:54:02 +00007099 if (!OverlappedElements.empty()) {
7100 // Handle base element with the info for overlapped elements.
7101 assert(!PartialStruct.Base.isValid() && "The base element is set.");
7102 assert(Next == CE &&
7103 "Expected last element for the overlapped elements.");
7104 assert(!IsPointer &&
7105 "Unexpected base element with the pointer type.");
7106 // Mark the whole struct as the struct that requires allocation on the
7107 // device.
7108 PartialStruct.LowestElem = {0, LB};
7109 CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(
7110 I->getAssociatedExpression()->getType());
7111 Address HB = CGF.Builder.CreateConstGEP(
7112 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(LB,
7113 CGF.VoidPtrTy),
7114 TypeSize.getQuantity() - 1, CharUnits::One());
7115 PartialStruct.HighestElem = {
7116 std::numeric_limits<decltype(
7117 PartialStruct.HighestElem.first)>::max(),
7118 HB};
7119 PartialStruct.Base = BP;
7120 // Emit data for non-overlapped data.
7121 OpenMPOffloadMappingFlags Flags =
7122 OMP_MAP_MEMBER_OF |
7123 getMapTypeBits(MapType, MapTypeModifier, IsImplicit,
7124 /*AddPtrFlag=*/false,
7125 /*AddIsTargetParamFlag=*/false);
7126 LB = BP;
7127 llvm::Value *Size = nullptr;
7128 // Do bitcopy of all non-overlapped structure elements.
7129 for (OMPClauseMappableExprCommon::MappableExprComponentListRef
7130 Component : OverlappedElements) {
7131 Address ComponentLB = Address::invalid();
7132 for (const OMPClauseMappableExprCommon::MappableComponent &MC :
7133 Component) {
7134 if (MC.getAssociatedDeclaration()) {
7135 ComponentLB =
7136 CGF.EmitOMPSharedLValue(MC.getAssociatedExpression())
7137 .getAddress();
7138 Size = CGF.Builder.CreatePtrDiff(
7139 CGF.EmitCastToVoidPtr(ComponentLB.getPointer()),
7140 CGF.EmitCastToVoidPtr(LB.getPointer()));
7141 break;
7142 }
7143 }
7144 BasePointers.push_back(BP.getPointer());
7145 Pointers.push_back(LB.getPointer());
7146 Sizes.push_back(Size);
7147 Types.push_back(Flags);
7148 LB = CGF.Builder.CreateConstGEP(ComponentLB, 1,
7149 CGF.getPointerSize());
7150 }
7151 BasePointers.push_back(BP.getPointer());
7152 Pointers.push_back(LB.getPointer());
7153 Size = CGF.Builder.CreatePtrDiff(
7154 CGF.EmitCastToVoidPtr(
7155 CGF.Builder.CreateConstGEP(HB, 1, CharUnits::One())
7156 .getPointer()),
7157 CGF.EmitCastToVoidPtr(LB.getPointer()));
7158 Sizes.push_back(Size);
7159 Types.push_back(Flags);
7160 break;
7161 }
7162 llvm::Value *Size = getExprTypeSize(I->getAssociatedExpression());
Alexey Bataevb3638132018-07-19 16:34:13 +00007163 if (!IsMemberPointer) {
7164 BasePointers.push_back(BP.getPointer());
7165 Pointers.push_back(LB.getPointer());
7166 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00007167
Alexey Bataevb3638132018-07-19 16:34:13 +00007168 // We need to add a pointer flag for each map that comes from the
7169 // same expression except for the first one. We also need to signal
7170 // this map is the first one that relates with the current capture
7171 // (there is a set of entries for each capture).
7172 OpenMPOffloadMappingFlags Flags = getMapTypeBits(
7173 MapType, MapTypeModifier, IsImplicit,
7174 !IsExpressionFirstInfo || IsLink, IsCaptureFirstInfo && !IsLink);
7175
7176 if (!IsExpressionFirstInfo) {
7177 // If we have a PTR_AND_OBJ pair where the OBJ is a pointer as well,
7178 // then we reset the TO/FROM/ALWAYS/DELETE flags.
7179 if (IsPointer)
7180 Flags &= ~(OMP_MAP_TO | OMP_MAP_FROM | OMP_MAP_ALWAYS |
7181 OMP_MAP_DELETE);
7182
7183 if (ShouldBeMemberOf) {
7184 // Set placeholder value MEMBER_OF=FFFF to indicate that the flag
7185 // should be later updated with the correct value of MEMBER_OF.
7186 Flags |= OMP_MAP_MEMBER_OF;
7187 // From now on, all subsequent PTR_AND_OBJ entries should not be
7188 // marked as MEMBER_OF.
7189 ShouldBeMemberOf = false;
7190 }
7191 }
7192
7193 Types.push_back(Flags);
Samuel Antao03a3cec2016-07-27 22:52:16 +00007194 }
7195
Alexey Bataevb3638132018-07-19 16:34:13 +00007196 // If we have encountered a member expression so far, keep track of the
7197 // mapped member. If the parent is "*this", then the value declaration
7198 // is nullptr.
7199 if (EncounteredME) {
7200 const auto *FD = dyn_cast<FieldDecl>(EncounteredME->getMemberDecl());
7201 unsigned FieldIndex = FD->getFieldIndex();
Samuel Antao03a3cec2016-07-27 22:52:16 +00007202
Alexey Bataevb3638132018-07-19 16:34:13 +00007203 // Update info about the lowest and highest elements for this struct
7204 if (!PartialStruct.Base.isValid()) {
7205 PartialStruct.LowestElem = {FieldIndex, LB};
7206 PartialStruct.HighestElem = {FieldIndex, LB};
7207 PartialStruct.Base = BP;
7208 } else if (FieldIndex < PartialStruct.LowestElem.first) {
7209 PartialStruct.LowestElem = {FieldIndex, LB};
7210 } else if (FieldIndex > PartialStruct.HighestElem.first) {
7211 PartialStruct.HighestElem = {FieldIndex, LB};
7212 }
7213 }
Samuel Antao86ace552016-04-27 22:40:57 +00007214
7215 // If we have a final array section, we are done with this expression.
7216 if (IsFinalArraySection)
7217 break;
7218
7219 // The pointer becomes the base for the next element.
7220 if (Next != CE)
7221 BP = LB;
7222
7223 IsExpressionFirstInfo = false;
7224 IsCaptureFirstInfo = false;
Samuel Antao86ace552016-04-27 22:40:57 +00007225 }
7226 }
7227 }
7228
Alexey Bataevb3638132018-07-19 16:34:13 +00007229 /// Return the adjusted map modifiers if the declaration a capture refers to
7230 /// appears in a first-private clause. This is expected to be used only with
7231 /// directives that start with 'target'.
7232 MappableExprsHandler::OpenMPOffloadMappingFlags
7233 getMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap) const {
7234 assert(Cap.capturesVariable() && "Expected capture by reference only!");
7235
7236 // A first private variable captured by reference will use only the
7237 // 'private ptr' and 'map to' flag. Return the right flags if the captured
7238 // declaration is known as first-private in this handler.
7239 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
7240 return MappableExprsHandler::OMP_MAP_PRIVATE |
7241 MappableExprsHandler::OMP_MAP_TO;
7242 return MappableExprsHandler::OMP_MAP_TO |
7243 MappableExprsHandler::OMP_MAP_FROM;
7244 }
7245
7246 static OpenMPOffloadMappingFlags getMemberOfFlag(unsigned Position) {
7247 // Member of is given by the 16 MSB of the flag, so rotate by 48 bits.
7248 return static_cast<OpenMPOffloadMappingFlags>(((uint64_t)Position + 1)
7249 << 48);
7250 }
7251
7252 static void setCorrectMemberOfFlag(OpenMPOffloadMappingFlags &Flags,
7253 OpenMPOffloadMappingFlags MemberOfFlag) {
7254 // If the entry is PTR_AND_OBJ but has not been marked with the special
7255 // placeholder value 0xFFFF in the MEMBER_OF field, then it should not be
7256 // marked as MEMBER_OF.
7257 if ((Flags & OMP_MAP_PTR_AND_OBJ) &&
7258 ((Flags & OMP_MAP_MEMBER_OF) != OMP_MAP_MEMBER_OF))
7259 return;
7260
7261 // Reset the placeholder value to prepare the flag for the assignment of the
7262 // proper MEMBER_OF value.
7263 Flags &= ~OMP_MAP_MEMBER_OF;
7264 Flags |= MemberOfFlag;
7265 }
7266
Alexey Bataeve82445f2018-09-20 13:54:02 +00007267 void getPlainLayout(const CXXRecordDecl *RD,
7268 llvm::SmallVectorImpl<const FieldDecl *> &Layout,
7269 bool AsBase) const {
7270 const CGRecordLayout &RL = CGF.getTypes().getCGRecordLayout(RD);
7271
7272 llvm::StructType *St =
7273 AsBase ? RL.getBaseSubobjectLLVMType() : RL.getLLVMType();
7274
7275 unsigned NumElements = St->getNumElements();
7276 llvm::SmallVector<
7277 llvm::PointerUnion<const CXXRecordDecl *, const FieldDecl *>, 4>
7278 RecordLayout(NumElements);
7279
7280 // Fill bases.
7281 for (const auto &I : RD->bases()) {
7282 if (I.isVirtual())
7283 continue;
7284 const auto *Base = I.getType()->getAsCXXRecordDecl();
7285 // Ignore empty bases.
7286 if (Base->isEmpty() || CGF.getContext()
7287 .getASTRecordLayout(Base)
7288 .getNonVirtualSize()
7289 .isZero())
7290 continue;
7291
7292 unsigned FieldIndex = RL.getNonVirtualBaseLLVMFieldNo(Base);
7293 RecordLayout[FieldIndex] = Base;
7294 }
7295 // Fill in virtual bases.
7296 for (const auto &I : RD->vbases()) {
7297 const auto *Base = I.getType()->getAsCXXRecordDecl();
7298 // Ignore empty bases.
7299 if (Base->isEmpty())
7300 continue;
7301 unsigned FieldIndex = RL.getVirtualBaseIndex(Base);
7302 if (RecordLayout[FieldIndex])
7303 continue;
7304 RecordLayout[FieldIndex] = Base;
7305 }
7306 // Fill in all the fields.
7307 assert(!RD->isUnion() && "Unexpected union.");
7308 for (const auto *Field : RD->fields()) {
7309 // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
7310 // will fill in later.)
7311 if (!Field->isBitField()) {
7312 unsigned FieldIndex = RL.getLLVMFieldNo(Field);
7313 RecordLayout[FieldIndex] = Field;
7314 }
7315 }
7316 for (const llvm::PointerUnion<const CXXRecordDecl *, const FieldDecl *>
7317 &Data : RecordLayout) {
7318 if (Data.isNull())
7319 continue;
7320 if (const auto *Base = Data.dyn_cast<const CXXRecordDecl *>())
7321 getPlainLayout(Base, Layout, /*AsBase=*/true);
7322 else
7323 Layout.push_back(Data.get<const FieldDecl *>());
7324 }
7325 }
7326
Alexey Bataevb3638132018-07-19 16:34:13 +00007327public:
7328 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
7329 : CurDir(Dir), CGF(CGF) {
7330 // Extract firstprivate clause information.
7331 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
7332 for (const auto *D : C->varlists())
7333 FirstPrivateDecls.insert(
7334 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
7335 // Extract device pointer clause information.
7336 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
7337 for (auto L : C->component_lists())
7338 DevPointersMap[L.first].push_back(L.second);
7339 }
7340
7341 /// Generate code for the combined entry if we have a partially mapped struct
7342 /// and take care of the mapping flags of the arguments corresponding to
7343 /// individual struct members.
7344 void emitCombinedEntry(MapBaseValuesArrayTy &BasePointers,
7345 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7346 MapFlagsArrayTy &Types, MapFlagsArrayTy &CurTypes,
7347 const StructRangeInfoTy &PartialStruct) const {
7348 // Base is the base of the struct
7349 BasePointers.push_back(PartialStruct.Base.getPointer());
7350 // Pointer is the address of the lowest element
7351 llvm::Value *LB = PartialStruct.LowestElem.second.getPointer();
7352 Pointers.push_back(LB);
7353 // Size is (addr of {highest+1} element) - (addr of lowest element)
7354 llvm::Value *HB = PartialStruct.HighestElem.second.getPointer();
7355 llvm::Value *HAddr = CGF.Builder.CreateConstGEP1_32(HB, /*Idx0=*/1);
7356 llvm::Value *CLAddr = CGF.Builder.CreatePointerCast(LB, CGF.VoidPtrTy);
7357 llvm::Value *CHAddr = CGF.Builder.CreatePointerCast(HAddr, CGF.VoidPtrTy);
7358 llvm::Value *Diff = CGF.Builder.CreatePtrDiff(CHAddr, CLAddr);
7359 llvm::Value *Size = CGF.Builder.CreateIntCast(Diff, CGF.SizeTy,
7360 /*isSinged=*/false);
7361 Sizes.push_back(Size);
7362 // Map type is always TARGET_PARAM
7363 Types.push_back(OMP_MAP_TARGET_PARAM);
7364 // Remove TARGET_PARAM flag from the first element
7365 (*CurTypes.begin()) &= ~OMP_MAP_TARGET_PARAM;
7366
7367 // All other current entries will be MEMBER_OF the combined entry
7368 // (except for PTR_AND_OBJ entries which do not have a placeholder value
7369 // 0xFFFF in the MEMBER_OF field).
7370 OpenMPOffloadMappingFlags MemberOfFlag =
7371 getMemberOfFlag(BasePointers.size() - 1);
7372 for (auto &M : CurTypes)
7373 setCorrectMemberOfFlag(M, MemberOfFlag);
7374 }
7375
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007376 /// Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00007377 /// types for the extracted mappable expressions. Also, for each item that
7378 /// relates with a device pointer, a pair of the relevant declaration and
7379 /// index where it occurs is appended to the device pointers info array.
7380 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007381 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7382 MapFlagsArrayTy &Types) const {
Samuel Antao86ace552016-04-27 22:40:57 +00007383 // We have to process the component lists that relate with the same
7384 // declaration in a single chunk so that we can generate the map flags
7385 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00007386 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00007387
7388 // Helper function to fill the information map for the different supported
7389 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00007390 auto &&InfoGen = [&Info](
7391 const ValueDecl *D,
7392 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
7393 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Alexey Bataevb3638132018-07-19 16:34:13 +00007394 bool ReturnDevicePointer, bool IsImplicit) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007395 const ValueDecl *VD =
7396 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007397 Info[VD].emplace_back(L, MapType, MapModifier, ReturnDevicePointer,
7398 IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007399 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00007400
Paul Robinson78fb1322016-08-01 22:12:46 +00007401 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007402 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
7403 for (const auto &L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00007404 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
Alexey Bataevb3638132018-07-19 16:34:13 +00007405 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007406 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007407 for (const auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
7408 for (const auto &L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00007409 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
Alexey Bataevb3638132018-07-19 16:34:13 +00007410 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007411 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007412 for (const auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
7413 for (const auto &L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00007414 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
Alexey Bataevb3638132018-07-19 16:34:13 +00007415 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007416 }
Samuel Antao86ace552016-04-27 22:40:57 +00007417
Samuel Antaocc10b852016-07-28 14:23:26 +00007418 // Look at the use_device_ptr clause information and mark the existing map
7419 // entries as such. If there is no map information for an entry in the
7420 // use_device_ptr list, we create one with map type 'alloc' and zero size
Alexey Bataevb3638132018-07-19 16:34:13 +00007421 // section. It is the user fault if that was not mapped before. If there is
7422 // no map information and the pointer is a struct member, then we defer the
7423 // emission of that entry until the whole struct has been processed.
7424 llvm::MapVector<const ValueDecl *, SmallVector<DeferredDevicePtrEntryTy, 4>>
7425 DeferredInfo;
7426
Paul Robinson78fb1322016-08-01 22:12:46 +00007427 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataevb3638132018-07-19 16:34:13 +00007428 for (const auto *C :
7429 this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007430 for (const auto &L : C->component_lists()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007431 assert(!L.second.empty() && "Not expecting empty list of components!");
7432 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
7433 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007434 const Expr *IE = L.second.back().getAssociatedExpression();
Samuel Antaocc10b852016-07-28 14:23:26 +00007435 // If the first component is a member expression, we have to look into
7436 // 'this', which maps to null in the map of map information. Otherwise
7437 // look directly for the information.
7438 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
7439
7440 // We potentially have map information for this declaration already.
7441 // Look for the first set of components that refer to it.
7442 if (It != Info.end()) {
7443 auto CI = std::find_if(
7444 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
7445 return MI.Components.back().getAssociatedDeclaration() == VD;
7446 });
7447 // If we found a map entry, signal that the pointer has to be returned
7448 // and move on to the next declaration.
7449 if (CI != It->second.end()) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007450 CI->ReturnDevicePointer = true;
Samuel Antaocc10b852016-07-28 14:23:26 +00007451 continue;
7452 }
7453 }
7454
7455 // We didn't find any match in our map information - generate a zero
Alexey Bataevb3638132018-07-19 16:34:13 +00007456 // size array section - if the pointer is a struct member we defer this
7457 // action until the whole struct has been processed.
Paul Robinson78fb1322016-08-01 22:12:46 +00007458 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Alexey Bataevb3638132018-07-19 16:34:13 +00007459 if (isa<MemberExpr>(IE)) {
7460 // Insert the pointer into Info to be processed by
7461 // generateInfoForComponentList. Because it is a member pointer
7462 // without a pointee, no entry will be generated for it, therefore
7463 // we need to generate one after the whole struct has been processed.
7464 // Nonetheless, generateInfoForComponentList must be called to take
7465 // the pointer into account for the calculation of the range of the
7466 // partial struct.
7467 InfoGen(nullptr, L.second, OMPC_MAP_unknown, OMPC_MAP_unknown,
7468 /*ReturnDevicePointer=*/false, C->isImplicit());
7469 DeferredInfo[nullptr].emplace_back(IE, VD);
7470 } else {
7471 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(
7472 this->CGF.EmitLValue(IE), IE->getExprLoc());
7473 BasePointers.emplace_back(Ptr, VD);
7474 Pointers.push_back(Ptr);
7475 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
7476 Types.push_back(OMP_MAP_RETURN_PARAM | OMP_MAP_TARGET_PARAM);
7477 }
Samuel Antaocc10b852016-07-28 14:23:26 +00007478 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007479 }
Samuel Antaocc10b852016-07-28 14:23:26 +00007480
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007481 for (const auto &M : Info) {
Samuel Antao86ace552016-04-27 22:40:57 +00007482 // We need to know when we generate information for the first component
7483 // associated with a capture, because the mapping flags depend on it.
7484 bool IsFirstComponentList = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00007485
7486 // Temporary versions of arrays
7487 MapBaseValuesArrayTy CurBasePointers;
7488 MapValuesArrayTy CurPointers;
7489 MapValuesArrayTy CurSizes;
7490 MapFlagsArrayTy CurTypes;
7491 StructRangeInfoTy PartialStruct;
7492
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007493 for (const MapInfo &L : M.second) {
Samuel Antao86ace552016-04-27 22:40:57 +00007494 assert(!L.Components.empty() &&
7495 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00007496
7497 // Remember the current base pointer index.
Alexey Bataevb3638132018-07-19 16:34:13 +00007498 unsigned CurrentBasePointersIdx = CurBasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00007499 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007500 this->generateInfoForComponentList(
Alexey Bataevb3638132018-07-19 16:34:13 +00007501 L.MapType, L.MapTypeModifier, L.Components, CurBasePointers,
7502 CurPointers, CurSizes, CurTypes, PartialStruct,
7503 IsFirstComponentList, L.IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007504
7505 // If this entry relates with a device pointer, set the relevant
7506 // declaration and add the 'return pointer' flag.
Alexey Bataevb3638132018-07-19 16:34:13 +00007507 if (L.ReturnDevicePointer) {
7508 assert(CurBasePointers.size() > CurrentBasePointersIdx &&
Samuel Antaocc10b852016-07-28 14:23:26 +00007509 "Unexpected number of mapped base pointers.");
7510
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007511 const ValueDecl *RelevantVD =
7512 L.Components.back().getAssociatedDeclaration();
Samuel Antaocc10b852016-07-28 14:23:26 +00007513 assert(RelevantVD &&
7514 "No relevant declaration related with device pointer??");
7515
Alexey Bataevb3638132018-07-19 16:34:13 +00007516 CurBasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
7517 CurTypes[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PARAM;
Samuel Antaocc10b852016-07-28 14:23:26 +00007518 }
Samuel Antao86ace552016-04-27 22:40:57 +00007519 IsFirstComponentList = false;
7520 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007521
7522 // Append any pending zero-length pointers which are struct members and
7523 // used with use_device_ptr.
7524 auto CI = DeferredInfo.find(M.first);
7525 if (CI != DeferredInfo.end()) {
7526 for (const DeferredDevicePtrEntryTy &L : CI->second) {
7527 llvm::Value *BasePtr = this->CGF.EmitLValue(L.IE).getPointer();
7528 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(
7529 this->CGF.EmitLValue(L.IE), L.IE->getExprLoc());
7530 CurBasePointers.emplace_back(BasePtr, L.VD);
7531 CurPointers.push_back(Ptr);
7532 CurSizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
7533 // Entry is PTR_AND_OBJ and RETURN_PARAM. Also, set the placeholder
7534 // value MEMBER_OF=FFFF so that the entry is later updated with the
7535 // correct value of MEMBER_OF.
7536 CurTypes.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_RETURN_PARAM |
7537 OMP_MAP_MEMBER_OF);
7538 }
7539 }
7540
7541 // If there is an entry in PartialStruct it means we have a struct with
7542 // individual members mapped. Emit an extra combined entry.
7543 if (PartialStruct.Base.isValid())
7544 emitCombinedEntry(BasePointers, Pointers, Sizes, Types, CurTypes,
7545 PartialStruct);
7546
7547 // We need to append the results of this capture to what we already have.
7548 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
7549 Pointers.append(CurPointers.begin(), CurPointers.end());
7550 Sizes.append(CurSizes.begin(), CurSizes.end());
7551 Types.append(CurTypes.begin(), CurTypes.end());
Samuel Antao86ace552016-04-27 22:40:57 +00007552 }
7553 }
7554
Alexey Bataev60705422018-10-30 15:50:12 +00007555 /// Emit capture info for lambdas for variables captured by reference.
Alexey Bataev969dbc02018-11-08 15:47:39 +00007556 void generateInfoForLambdaCaptures(
7557 const ValueDecl *VD, llvm::Value *Arg, MapBaseValuesArrayTy &BasePointers,
7558 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7559 MapFlagsArrayTy &Types,
7560 llvm::DenseMap<llvm::Value *, llvm::Value *> &LambdaPointers) const {
Alexey Bataev60705422018-10-30 15:50:12 +00007561 const auto *RD = VD->getType()
7562 .getCanonicalType()
7563 .getNonReferenceType()
7564 ->getAsCXXRecordDecl();
7565 if (!RD || !RD->isLambda())
7566 return;
7567 Address VDAddr = Address(Arg, CGF.getContext().getDeclAlign(VD));
7568 LValue VDLVal = CGF.MakeAddrLValue(
7569 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
7570 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
7571 FieldDecl *ThisCapture = nullptr;
7572 RD->getCaptureFields(Captures, ThisCapture);
7573 if (ThisCapture) {
7574 LValue ThisLVal =
7575 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
Alexey Bataev969dbc02018-11-08 15:47:39 +00007576 LValue ThisLValVal = CGF.EmitLValueForField(VDLVal, ThisCapture);
7577 LambdaPointers.try_emplace(ThisLVal.getPointer(), VDLVal.getPointer());
7578 BasePointers.push_back(ThisLVal.getPointer());
7579 Pointers.push_back(ThisLValVal.getPointer());
Alexey Bataev60705422018-10-30 15:50:12 +00007580 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
Alexey Bataev2dc07d02018-11-02 15:25:06 +00007581 Types.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
Alexey Bataev60705422018-10-30 15:50:12 +00007582 OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT);
7583 }
7584 for (const LambdaCapture &LC : RD->captures()) {
7585 if (LC.getCaptureKind() != LCK_ByRef)
7586 continue;
7587 const VarDecl *VD = LC.getCapturedVar();
7588 auto It = Captures.find(VD);
7589 assert(It != Captures.end() && "Found lambda capture without field.");
7590 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
Alexey Bataev969dbc02018-11-08 15:47:39 +00007591 LValue VarLValVal = CGF.EmitLValueForField(VDLVal, It->second);
7592 LambdaPointers.try_emplace(VarLVal.getPointer(), VDLVal.getPointer());
7593 BasePointers.push_back(VarLVal.getPointer());
7594 Pointers.push_back(VarLValVal.getPointer());
Alexey Bataev60705422018-10-30 15:50:12 +00007595 Sizes.push_back(CGF.getTypeSize(
7596 VD->getType().getCanonicalType().getNonReferenceType()));
Alexey Bataev2dc07d02018-11-02 15:25:06 +00007597 Types.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
Alexey Bataev60705422018-10-30 15:50:12 +00007598 OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT);
7599 }
7600 }
7601
7602 /// Set correct indices for lambdas captures.
Alexey Bataev969dbc02018-11-08 15:47:39 +00007603 void adjustMemberOfForLambdaCaptures(
7604 const llvm::DenseMap<llvm::Value *, llvm::Value *> &LambdaPointers,
7605 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
7606 MapFlagsArrayTy &Types) const {
Alexey Bataev60705422018-10-30 15:50:12 +00007607 for (unsigned I = 0, E = Types.size(); I < E; ++I) {
7608 // Set correct member_of idx for all implicit lambda captures.
Alexey Bataev2dc07d02018-11-02 15:25:06 +00007609 if (Types[I] != (OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
Alexey Bataev60705422018-10-30 15:50:12 +00007610 OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT))
7611 continue;
Alexey Bataev969dbc02018-11-08 15:47:39 +00007612 llvm::Value *BasePtr = LambdaPointers.lookup(*BasePointers[I]);
7613 assert(BasePtr && "Unable to find base lambda address.");
Alexey Bataev60705422018-10-30 15:50:12 +00007614 int TgtIdx = -1;
7615 for (unsigned J = I; J > 0; --J) {
7616 unsigned Idx = J - 1;
7617 if (Pointers[Idx] != BasePtr)
7618 continue;
7619 TgtIdx = Idx;
7620 break;
7621 }
7622 assert(TgtIdx != -1 && "Unable to find parent lambda.");
7623 // All other current entries will be MEMBER_OF the combined entry
7624 // (except for PTR_AND_OBJ entries which do not have a placeholder value
7625 // 0xFFFF in the MEMBER_OF field).
7626 OpenMPOffloadMappingFlags MemberOfFlag = getMemberOfFlag(TgtIdx);
7627 setCorrectMemberOfFlag(Types[I], MemberOfFlag);
7628 }
7629 }
7630
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007631 /// Generate the base pointers, section pointers, sizes and map types
Samuel Antao86ace552016-04-27 22:40:57 +00007632 /// associated to a given capture.
7633 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00007634 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007635 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007636 MapValuesArrayTy &Pointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007637 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
7638 StructRangeInfoTy &PartialStruct) const {
Samuel Antao86ace552016-04-27 22:40:57 +00007639 assert(!Cap->capturesVariableArrayType() &&
7640 "Not expecting to generate map info for a variable array type!");
7641
Samuel Antao6890b092016-07-28 14:25:09 +00007642 // We need to know when we generating information for the first component
Alexey Bataevb3638132018-07-19 16:34:13 +00007643 const ValueDecl *VD = Cap->capturesThis()
7644 ? nullptr
7645 : Cap->getCapturedVar()->getCanonicalDecl();
Samuel Antao86ace552016-04-27 22:40:57 +00007646
Samuel Antao6890b092016-07-28 14:25:09 +00007647 // If this declaration appears in a is_device_ptr clause we just have to
7648 // pass the pointer by value. If it is a reference to a declaration, we just
Alexey Bataevb3638132018-07-19 16:34:13 +00007649 // pass its value.
7650 if (DevPointersMap.count(VD)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007651 BasePointers.emplace_back(Arg, VD);
Samuel Antao6890b092016-07-28 14:25:09 +00007652 Pointers.push_back(Arg);
7653 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
George Rokos065755d2017-11-07 18:27:04 +00007654 Types.push_back(OMP_MAP_LITERAL | OMP_MAP_TARGET_PARAM);
Samuel Antao6890b092016-07-28 14:25:09 +00007655 return;
7656 }
7657
Alexey Bataeve82445f2018-09-20 13:54:02 +00007658 using MapData =
7659 std::tuple<OMPClauseMappableExprCommon::MappableExprComponentListRef,
7660 OpenMPMapClauseKind, OpenMPMapClauseKind, bool>;
7661 SmallVector<MapData, 4> DeclComponentLists;
Paul Robinson78fb1322016-08-01 22:12:46 +00007662 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeve82445f2018-09-20 13:54:02 +00007663 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007664 for (const auto &L : C->decl_component_lists(VD)) {
Samuel Antao86ace552016-04-27 22:40:57 +00007665 assert(L.first == VD &&
7666 "We got information for the wrong declaration??");
7667 assert(!L.second.empty() &&
7668 "Not expecting declaration with no component lists.");
Alexey Bataeve82445f2018-09-20 13:54:02 +00007669 DeclComponentLists.emplace_back(L.second, C->getMapType(),
7670 C->getMapTypeModifier(),
7671 C->isImplicit());
Samuel Antao86ace552016-04-27 22:40:57 +00007672 }
Alexey Bataeve82445f2018-09-20 13:54:02 +00007673 }
7674
7675 // Find overlapping elements (including the offset from the base element).
7676 llvm::SmallDenseMap<
7677 const MapData *,
7678 llvm::SmallVector<
7679 OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>,
7680 4>
7681 OverlappedData;
7682 size_t Count = 0;
7683 for (const MapData &L : DeclComponentLists) {
7684 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7685 OpenMPMapClauseKind MapType;
7686 OpenMPMapClauseKind MapTypeModifier;
7687 bool IsImplicit;
7688 std::tie(Components, MapType, MapTypeModifier, IsImplicit) = L;
7689 ++Count;
7690 for (const MapData &L1 : makeArrayRef(DeclComponentLists).slice(Count)) {
7691 OMPClauseMappableExprCommon::MappableExprComponentListRef Components1;
7692 std::tie(Components1, MapType, MapTypeModifier, IsImplicit) = L1;
7693 auto CI = Components.rbegin();
7694 auto CE = Components.rend();
7695 auto SI = Components1.rbegin();
7696 auto SE = Components1.rend();
7697 for (; CI != CE && SI != SE; ++CI, ++SI) {
7698 if (CI->getAssociatedExpression()->getStmtClass() !=
7699 SI->getAssociatedExpression()->getStmtClass())
7700 break;
7701 // Are we dealing with different variables/fields?
7702 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
7703 break;
7704 }
7705 // Found overlapping if, at least for one component, reached the head of
7706 // the components list.
7707 if (CI == CE || SI == SE) {
7708 assert((CI != CE || SI != SE) &&
7709 "Unexpected full match of the mapping components.");
7710 const MapData &BaseData = CI == CE ? L : L1;
7711 OMPClauseMappableExprCommon::MappableExprComponentListRef SubData =
7712 SI == SE ? Components : Components1;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007713 auto &OverlappedElements = OverlappedData.FindAndConstruct(&BaseData);
7714 OverlappedElements.getSecond().push_back(SubData);
7715 }
7716 }
7717 }
7718 // Sort the overlapped elements for each item.
7719 llvm::SmallVector<const FieldDecl *, 4> Layout;
7720 if (!OverlappedData.empty()) {
7721 if (const auto *CRD =
7722 VD->getType().getCanonicalType()->getAsCXXRecordDecl())
7723 getPlainLayout(CRD, Layout, /*AsBase=*/false);
7724 else {
7725 const auto *RD = VD->getType().getCanonicalType()->getAsRecordDecl();
7726 Layout.append(RD->field_begin(), RD->field_end());
7727 }
7728 }
7729 for (auto &Pair : OverlappedData) {
7730 llvm::sort(
7731 Pair.getSecond(),
7732 [&Layout](
7733 OMPClauseMappableExprCommon::MappableExprComponentListRef First,
7734 OMPClauseMappableExprCommon::MappableExprComponentListRef
7735 Second) {
7736 auto CI = First.rbegin();
7737 auto CE = First.rend();
7738 auto SI = Second.rbegin();
7739 auto SE = Second.rend();
7740 for (; CI != CE && SI != SE; ++CI, ++SI) {
7741 if (CI->getAssociatedExpression()->getStmtClass() !=
7742 SI->getAssociatedExpression()->getStmtClass())
7743 break;
7744 // Are we dealing with different variables/fields?
7745 if (CI->getAssociatedDeclaration() !=
7746 SI->getAssociatedDeclaration())
7747 break;
7748 }
Richard Trieu5061e832018-09-21 21:20:33 +00007749
7750 // Lists contain the same elements.
7751 if (CI == CE && SI == SE)
7752 return false;
7753
7754 // List with less elements is less than list with more elements.
7755 if (CI == CE || SI == SE)
7756 return CI == CE;
7757
Alexey Bataeve82445f2018-09-20 13:54:02 +00007758 const auto *FD1 = cast<FieldDecl>(CI->getAssociatedDeclaration());
7759 const auto *FD2 = cast<FieldDecl>(SI->getAssociatedDeclaration());
7760 if (FD1->getParent() == FD2->getParent())
7761 return FD1->getFieldIndex() < FD2->getFieldIndex();
7762 const auto It =
7763 llvm::find_if(Layout, [FD1, FD2](const FieldDecl *FD) {
7764 return FD == FD1 || FD == FD2;
7765 });
7766 return *It == FD1;
7767 });
7768 }
7769
7770 // Associated with a capture, because the mapping flags depend on it.
7771 // Go through all of the elements with the overlapped elements.
7772 for (const auto &Pair : OverlappedData) {
7773 const MapData &L = *Pair.getFirst();
7774 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7775 OpenMPMapClauseKind MapType;
7776 OpenMPMapClauseKind MapTypeModifier;
7777 bool IsImplicit;
7778 std::tie(Components, MapType, MapTypeModifier, IsImplicit) = L;
7779 ArrayRef<OMPClauseMappableExprCommon::MappableExprComponentListRef>
7780 OverlappedComponents = Pair.getSecond();
7781 bool IsFirstComponentList = true;
7782 generateInfoForComponentList(MapType, MapTypeModifier, Components,
7783 BasePointers, Pointers, Sizes, Types,
7784 PartialStruct, IsFirstComponentList,
7785 IsImplicit, OverlappedComponents);
7786 }
7787 // Go through other elements without overlapped elements.
7788 bool IsFirstComponentList = OverlappedData.empty();
7789 for (const MapData &L : DeclComponentLists) {
7790 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7791 OpenMPMapClauseKind MapType;
7792 OpenMPMapClauseKind MapTypeModifier;
7793 bool IsImplicit;
7794 std::tie(Components, MapType, MapTypeModifier, IsImplicit) = L;
7795 auto It = OverlappedData.find(&L);
7796 if (It == OverlappedData.end())
7797 generateInfoForComponentList(MapType, MapTypeModifier, Components,
7798 BasePointers, Pointers, Sizes, Types,
7799 PartialStruct, IsFirstComponentList,
7800 IsImplicit);
7801 IsFirstComponentList = false;
7802 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007803 }
Samuel Antao86ace552016-04-27 22:40:57 +00007804
Alexey Bataevb3638132018-07-19 16:34:13 +00007805 /// Generate the base pointers, section pointers, sizes and map types
7806 /// associated with the declare target link variables.
7807 void generateInfoForDeclareTargetLink(MapBaseValuesArrayTy &BasePointers,
7808 MapValuesArrayTy &Pointers,
7809 MapValuesArrayTy &Sizes,
7810 MapFlagsArrayTy &Types) const {
7811 // Map other list items in the map clause which are not captured variables
7812 // but "declare target link" global variables.,
7813 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) {
7814 for (const auto &L : C->component_lists()) {
7815 if (!L.first)
7816 continue;
7817 const auto *VD = dyn_cast<VarDecl>(L.first);
7818 if (!VD)
7819 continue;
7820 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00007821 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataevb3638132018-07-19 16:34:13 +00007822 if (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link)
7823 continue;
7824 StructRangeInfoTy PartialStruct;
7825 generateInfoForComponentList(
7826 C->getMapType(), C->getMapTypeModifier(), L.second, BasePointers,
7827 Pointers, Sizes, Types, PartialStruct,
7828 /*IsFirstComponentList=*/true, C->isImplicit());
7829 assert(!PartialStruct.Base.isValid() &&
7830 "No partial structs for declare target link expected.");
7831 }
7832 }
Samuel Antao86ace552016-04-27 22:40:57 +00007833 }
Samuel Antaod486f842016-05-26 16:53:38 +00007834
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007835 /// Generate the default map information for a given capture \a CI,
Samuel Antaod486f842016-05-26 16:53:38 +00007836 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00007837 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
7838 const FieldDecl &RI, llvm::Value *CV,
7839 MapBaseValuesArrayTy &CurBasePointers,
7840 MapValuesArrayTy &CurPointers,
7841 MapValuesArrayTy &CurSizes,
Alexey Bataevb3638132018-07-19 16:34:13 +00007842 MapFlagsArrayTy &CurMapTypes) const {
Samuel Antaod486f842016-05-26 16:53:38 +00007843 // Do the default mapping.
7844 if (CI.capturesThis()) {
7845 CurBasePointers.push_back(CV);
7846 CurPointers.push_back(CV);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007847 const auto *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007848 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
7849 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00007850 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00007851 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007852 CurBasePointers.push_back(CV);
7853 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00007854 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007855 // We have to signal to the runtime captures passed by value that are
7856 // not pointers.
George Rokos065755d2017-11-07 18:27:04 +00007857 CurMapTypes.push_back(OMP_MAP_LITERAL);
Samuel Antaod486f842016-05-26 16:53:38 +00007858 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
7859 } else {
7860 // Pointers are implicitly mapped with a zero size and no flags
7861 // (other than first map that is added for all implicit maps).
Alexey Bataevb3638132018-07-19 16:34:13 +00007862 CurMapTypes.push_back(OMP_MAP_NONE);
Samuel Antaod486f842016-05-26 16:53:38 +00007863 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
7864 }
7865 } else {
7866 assert(CI.capturesVariable() && "Expected captured reference.");
7867 CurBasePointers.push_back(CV);
7868 CurPointers.push_back(CV);
7869
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007870 const auto *PtrTy = cast<ReferenceType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007871 QualType ElementType = PtrTy->getPointeeType();
7872 CurSizes.push_back(CGF.getTypeSize(ElementType));
7873 // The default map type for a scalar/complex type is 'to' because by
7874 // default the value doesn't have to be retrieved. For an aggregate
7875 // type, the default is 'tofrom'.
Alexey Bataevb3638132018-07-19 16:34:13 +00007876 CurMapTypes.push_back(getMapModifiersForPrivateClauses(CI));
Samuel Antaod486f842016-05-26 16:53:38 +00007877 }
George Rokos065755d2017-11-07 18:27:04 +00007878 // Every default map produces a single argument which is a target parameter.
7879 CurMapTypes.back() |= OMP_MAP_TARGET_PARAM;
Alexey Bataevb3638132018-07-19 16:34:13 +00007880
7881 // Add flag stating this is an implicit map.
7882 CurMapTypes.back() |= OMP_MAP_IMPLICIT;
Samuel Antaod486f842016-05-26 16:53:38 +00007883 }
Samuel Antao86ace552016-04-27 22:40:57 +00007884};
Samuel Antaodf158d52016-04-27 22:58:19 +00007885
7886enum OpenMPOffloadingReservedDeviceIDs {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007887 /// Device ID if the device was not defined, runtime should get it
Samuel Antaodf158d52016-04-27 22:58:19 +00007888 /// from environment variables in the spec.
7889 OMP_DEVICEID_UNDEF = -1,
7890};
7891} // anonymous namespace
7892
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007893/// Emit the arrays used to pass the captures and map information to the
Samuel Antaodf158d52016-04-27 22:58:19 +00007894/// offloading runtime library. If there is no map or capture information,
7895/// return nullptr by reference.
7896static void
Samuel Antaocc10b852016-07-28 14:23:26 +00007897emitOffloadingArrays(CodeGenFunction &CGF,
7898 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00007899 MappableExprsHandler::MapValuesArrayTy &Pointers,
7900 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00007901 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
7902 CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007903 CodeGenModule &CGM = CGF.CGM;
7904 ASTContext &Ctx = CGF.getContext();
Samuel Antaodf158d52016-04-27 22:58:19 +00007905
Samuel Antaocc10b852016-07-28 14:23:26 +00007906 // Reset the array information.
7907 Info.clearArrayInfo();
7908 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00007909
Samuel Antaocc10b852016-07-28 14:23:26 +00007910 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007911 // Detect if we have any capture size requiring runtime evaluation of the
7912 // size so that a constant array could be eventually used.
7913 bool hasRuntimeEvaluationCaptureSize = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007914 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00007915 if (!isa<llvm::Constant>(S)) {
7916 hasRuntimeEvaluationCaptureSize = true;
7917 break;
7918 }
7919
Samuel Antaocc10b852016-07-28 14:23:26 +00007920 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00007921 QualType PointerArrayType =
7922 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
7923 /*IndexTypeQuals=*/0);
7924
Samuel Antaocc10b852016-07-28 14:23:26 +00007925 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007926 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00007927 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007928 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
7929
7930 // If we don't have any VLA types or other types that require runtime
7931 // evaluation, we can use a constant array for the map sizes, otherwise we
7932 // need to fill up the arrays as we do for the pointers.
7933 if (hasRuntimeEvaluationCaptureSize) {
7934 QualType SizeArrayType = Ctx.getConstantArrayType(
7935 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
7936 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00007937 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007938 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
7939 } else {
7940 // We expect all the sizes to be constant, so we collect them to create
7941 // a constant array.
7942 SmallVector<llvm::Constant *, 16> ConstSizes;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007943 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00007944 ConstSizes.push_back(cast<llvm::Constant>(S));
7945
7946 auto *SizesArrayInit = llvm::ConstantArray::get(
7947 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
Alexey Bataev18fa2322018-05-02 14:20:50 +00007948 std::string Name = CGM.getOpenMPRuntime().getName({"offload_sizes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00007949 auto *SizesArrayGbl = new llvm::GlobalVariable(
7950 CGM.getModule(), SizesArrayInit->getType(),
7951 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00007952 SizesArrayInit, Name);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00007953 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00007954 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00007955 }
7956
7957 // The map types are always constant so we don't need to generate code to
7958 // fill arrays. Instead, we create an array constant.
Alexey Bataevb3638132018-07-19 16:34:13 +00007959 SmallVector<uint64_t, 4> Mapping(MapTypes.size(), 0);
7960 llvm::copy(MapTypes, Mapping.begin());
Samuel Antaodf158d52016-04-27 22:58:19 +00007961 llvm::Constant *MapTypesArrayInit =
Alexey Bataevb3638132018-07-19 16:34:13 +00007962 llvm::ConstantDataArray::get(CGF.Builder.getContext(), Mapping);
Alexey Bataev18fa2322018-05-02 14:20:50 +00007963 std::string MaptypesName =
7964 CGM.getOpenMPRuntime().getName({"offload_maptypes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00007965 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
7966 CGM.getModule(), MapTypesArrayInit->getType(),
7967 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00007968 MapTypesArrayInit, MaptypesName);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00007969 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00007970 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00007971
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007972 for (unsigned I = 0; I < Info.NumberOfPtrs; ++I) {
7973 llvm::Value *BPVal = *BasePointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00007974 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007975 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007976 Info.BasePointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00007977 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7978 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00007979 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
7980 CGF.Builder.CreateStore(BPVal, BPAddr);
7981
Samuel Antaocc10b852016-07-28 14:23:26 +00007982 if (Info.requiresDevicePointerInfo())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007983 if (const ValueDecl *DevVD = BasePointers[I].getDevicePtrDecl())
Alexey Bataev43a919f2018-04-13 17:48:43 +00007984 Info.CaptureDeviceAddrMap.try_emplace(DevVD, BPAddr);
Samuel Antaocc10b852016-07-28 14:23:26 +00007985
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007986 llvm::Value *PVal = Pointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00007987 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007988 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007989 Info.PointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00007990 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7991 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00007992 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
7993 CGF.Builder.CreateStore(PVal, PAddr);
7994
7995 if (hasRuntimeEvaluationCaptureSize) {
7996 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007997 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
7998 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007999 /*Idx0=*/0,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008000 /*Idx1=*/I);
Samuel Antaodf158d52016-04-27 22:58:19 +00008001 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
8002 CGF.Builder.CreateStore(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008003 CGF.Builder.CreateIntCast(Sizes[I], CGM.SizeTy, /*isSigned=*/true),
Samuel Antaodf158d52016-04-27 22:58:19 +00008004 SAddr);
8005 }
8006 }
8007 }
8008}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008009/// Emit the arguments to be passed to the runtime library based on the
Samuel Antaodf158d52016-04-27 22:58:19 +00008010/// arrays of pointers, sizes and map types.
8011static void emitOffloadingArraysArgument(
8012 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
8013 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008014 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008015 CodeGenModule &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00008016 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008017 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008018 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
8019 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008020 /*Idx0=*/0, /*Idx1=*/0);
8021 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008022 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
8023 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008024 /*Idx0=*/0,
8025 /*Idx1=*/0);
8026 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008027 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008028 /*Idx0=*/0, /*Idx1=*/0);
8029 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
George Rokos63bc9d62017-11-21 18:25:12 +00008030 llvm::ArrayType::get(CGM.Int64Ty, Info.NumberOfPtrs),
Samuel Antaocc10b852016-07-28 14:23:26 +00008031 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008032 /*Idx0=*/0,
8033 /*Idx1=*/0);
8034 } else {
8035 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
8036 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
8037 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
8038 MapTypesArrayArg =
George Rokos63bc9d62017-11-21 18:25:12 +00008039 llvm::ConstantPointerNull::get(CGM.Int64Ty->getPointerTo());
Samuel Antaodf158d52016-04-27 22:58:19 +00008040 }
Samuel Antao86ace552016-04-27 22:40:57 +00008041}
8042
Samuel Antaobed3c462015-10-02 16:14:20 +00008043void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
8044 const OMPExecutableDirective &D,
8045 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00008046 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00008047 const Expr *IfCond, const Expr *Device) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00008048 if (!CGF.HaveInsertPoint())
8049 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00008050
Samuel Antaoee8fb302016-01-06 13:42:12 +00008051 assert(OutlinedFn && "Invalid outlined function!");
8052
Alexey Bataev8451efa2018-01-15 19:06:12 +00008053 const bool RequiresOuterTask = D.hasClausesOfKind<OMPDependClause>();
8054 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Alexey Bataev475a7442018-01-12 19:39:11 +00008055 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008056 auto &&ArgsCodegen = [&CS, &CapturedVars](CodeGenFunction &CGF,
8057 PrePostActionTy &) {
8058 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
8059 };
8060 emitInlinedDirective(CGF, OMPD_unknown, ArgsCodegen);
Samuel Antao86ace552016-04-27 22:40:57 +00008061
Alexey Bataev8451efa2018-01-15 19:06:12 +00008062 CodeGenFunction::OMPTargetDataInfo InputInfo;
8063 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00008064 // Fill up the pointer arrays and transfer execution to the device.
Alexey Bataev8451efa2018-01-15 19:06:12 +00008065 auto &&ThenGen = [this, Device, OutlinedFn, OutlinedFnID, &D, &InputInfo,
8066 &MapTypesArray, &CS, RequiresOuterTask,
8067 &CapturedVars](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobed3c462015-10-02 16:14:20 +00008068 // On top of the arrays that were filled up, the target offloading call
8069 // takes as arguments the device id as well as the host pointer. The host
8070 // pointer is used by the runtime library to identify the current target
8071 // region, so it only has to be unique and not necessarily point to
8072 // anything. It could be the pointer to the outlined function that
8073 // implements the target region, but we aren't using that so that the
8074 // compiler doesn't need to keep that, and could therefore inline the host
8075 // function if proven worthwhile during optimization.
8076
Samuel Antaoee8fb302016-01-06 13:42:12 +00008077 // From this point on, we need to have an ID of the target region defined.
8078 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00008079
8080 // Emit device ID if any.
8081 llvm::Value *DeviceID;
George Rokos63bc9d62017-11-21 18:25:12 +00008082 if (Device) {
Samuel Antaobed3c462015-10-02 16:14:20 +00008083 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008084 CGF.Int64Ty, /*isSigned=*/true);
8085 } else {
8086 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8087 }
Samuel Antaobed3c462015-10-02 16:14:20 +00008088
Samuel Antaodf158d52016-04-27 22:58:19 +00008089 // Emit the number of elements in the offloading arrays.
Alexey Bataev8451efa2018-01-15 19:06:12 +00008090 llvm::Value *PointerNum =
8091 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaodf158d52016-04-27 22:58:19 +00008092
Samuel Antaob68e2db2016-03-03 16:20:23 +00008093 // Return value of the runtime offloading call.
8094 llvm::Value *Return;
8095
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008096 llvm::Value *NumTeams = emitNumTeamsForTargetDirective(*this, CGF, D);
8097 llvm::Value *NumThreads = emitNumThreadsForTargetDirective(*this, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00008098
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008099 bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008100 // The target region is an outlined function launched by the runtime
8101 // via calls __tgt_target() or __tgt_target_teams().
8102 //
8103 // __tgt_target() launches a target region with one team and one thread,
8104 // executing a serial region. This master thread may in turn launch
8105 // more threads within its team upon encountering a parallel region,
8106 // however, no additional teams can be launched on the device.
8107 //
8108 // __tgt_target_teams() launches a target region with one or more teams,
8109 // each with one or more threads. This call is required for target
8110 // constructs such as:
8111 // 'target teams'
8112 // 'target' / 'teams'
8113 // 'target teams distribute parallel for'
8114 // 'target parallel'
8115 // and so on.
8116 //
8117 // Note that on the host and CPU targets, the runtime implementation of
8118 // these calls simply call the outlined function without forking threads.
8119 // The outlined functions themselves have runtime calls to
8120 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
8121 // the compiler in emitTeamsCall() and emitParallelCall().
8122 //
8123 // In contrast, on the NVPTX target, the implementation of
8124 // __tgt_target_teams() launches a GPU kernel with the requested number
8125 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00008126 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008127 // If we have NumTeams defined this means that we have an enclosed teams
8128 // region. Therefore we also expect to have NumThreads defined. These two
8129 // values should be defined in the presence of a teams directive,
8130 // regardless of having any clauses associated. If the user is using teams
8131 // but no clauses, these two values will be the default that should be
8132 // passed to the runtime library - a 32-bit integer with the value zero.
8133 assert(NumThreads && "Thread limit expression should be available along "
8134 "with number of teams.");
Alexey Bataev8451efa2018-01-15 19:06:12 +00008135 llvm::Value *OffloadingArgs[] = {DeviceID,
8136 OutlinedFnID,
8137 PointerNum,
8138 InputInfo.BasePointersArray.getPointer(),
8139 InputInfo.PointersArray.getPointer(),
8140 InputInfo.SizesArray.getPointer(),
8141 MapTypesArray,
8142 NumTeams,
8143 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00008144 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00008145 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_teams_nowait
8146 : OMPRTL__tgt_target_teams),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008147 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00008148 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00008149 llvm::Value *OffloadingArgs[] = {DeviceID,
8150 OutlinedFnID,
8151 PointerNum,
8152 InputInfo.BasePointersArray.getPointer(),
8153 InputInfo.PointersArray.getPointer(),
8154 InputInfo.SizesArray.getPointer(),
8155 MapTypesArray};
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008156 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00008157 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_nowait
8158 : OMPRTL__tgt_target),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008159 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00008160 }
Samuel Antaobed3c462015-10-02 16:14:20 +00008161
Alexey Bataev2a007e02017-10-02 14:20:58 +00008162 // Check the error code and execute the host version if required.
8163 llvm::BasicBlock *OffloadFailedBlock =
8164 CGF.createBasicBlock("omp_offload.failed");
8165 llvm::BasicBlock *OffloadContBlock =
8166 CGF.createBasicBlock("omp_offload.cont");
8167 llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
8168 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
8169
8170 CGF.EmitBlock(OffloadFailedBlock);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008171 if (RequiresOuterTask) {
8172 CapturedVars.clear();
8173 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
8174 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008175 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars);
Alexey Bataev2a007e02017-10-02 14:20:58 +00008176 CGF.EmitBranch(OffloadContBlock);
8177
8178 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00008179 };
8180
Samuel Antaoee8fb302016-01-06 13:42:12 +00008181 // Notify that the host version must be executed.
Alexey Bataev8451efa2018-01-15 19:06:12 +00008182 auto &&ElseGen = [this, &D, OutlinedFn, &CS, &CapturedVars,
8183 RequiresOuterTask](CodeGenFunction &CGF,
8184 PrePostActionTy &) {
8185 if (RequiresOuterTask) {
8186 CapturedVars.clear();
8187 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
8188 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008189 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008190 };
8191
8192 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray,
8193 &CapturedVars, RequiresOuterTask,
8194 &CS](CodeGenFunction &CGF, PrePostActionTy &) {
8195 // Fill up the arrays with all the captured variables.
8196 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
8197 MappableExprsHandler::MapValuesArrayTy Pointers;
8198 MappableExprsHandler::MapValuesArrayTy Sizes;
8199 MappableExprsHandler::MapFlagsArrayTy MapTypes;
8200
Alexey Bataev8451efa2018-01-15 19:06:12 +00008201 // Get mappable expression information.
8202 MappableExprsHandler MEHandler(D, CGF);
Alexey Bataev969dbc02018-11-08 15:47:39 +00008203 llvm::DenseMap<llvm::Value *, llvm::Value *> LambdaPointers;
Alexey Bataev8451efa2018-01-15 19:06:12 +00008204
8205 auto RI = CS.getCapturedRecordDecl()->field_begin();
8206 auto CV = CapturedVars.begin();
8207 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
8208 CE = CS.capture_end();
8209 CI != CE; ++CI, ++RI, ++CV) {
Alexey Bataevb3638132018-07-19 16:34:13 +00008210 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
8211 MappableExprsHandler::MapValuesArrayTy CurPointers;
8212 MappableExprsHandler::MapValuesArrayTy CurSizes;
8213 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
8214 MappableExprsHandler::StructRangeInfoTy PartialStruct;
Alexey Bataev8451efa2018-01-15 19:06:12 +00008215
8216 // VLA sizes are passed to the outlined region by copy and do not have map
8217 // information associated.
8218 if (CI->capturesVariableArrayType()) {
8219 CurBasePointers.push_back(*CV);
8220 CurPointers.push_back(*CV);
8221 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
8222 // Copy to the device as an argument. No need to retrieve it.
8223 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_LITERAL |
8224 MappableExprsHandler::OMP_MAP_TARGET_PARAM);
8225 } else {
8226 // If we have any information in the map clause, we use it, otherwise we
8227 // just do a default mapping.
8228 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00008229 CurSizes, CurMapTypes, PartialStruct);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008230 if (CurBasePointers.empty())
8231 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
8232 CurPointers, CurSizes, CurMapTypes);
Alexey Bataev60705422018-10-30 15:50:12 +00008233 // Generate correct mapping for variables captured by reference in
8234 // lambdas.
8235 if (CI->capturesVariable())
Alexey Bataev969dbc02018-11-08 15:47:39 +00008236 MEHandler.generateInfoForLambdaCaptures(
8237 CI->getCapturedVar(), *CV, CurBasePointers, CurPointers, CurSizes,
8238 CurMapTypes, LambdaPointers);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008239 }
8240 // We expect to have at least an element of information for this capture.
8241 assert(!CurBasePointers.empty() &&
8242 "Non-existing map pointer for capture!");
8243 assert(CurBasePointers.size() == CurPointers.size() &&
8244 CurBasePointers.size() == CurSizes.size() &&
8245 CurBasePointers.size() == CurMapTypes.size() &&
8246 "Inconsistent map information sizes!");
8247
Alexey Bataevb3638132018-07-19 16:34:13 +00008248 // If there is an entry in PartialStruct it means we have a struct with
8249 // individual members mapped. Emit an extra combined entry.
8250 if (PartialStruct.Base.isValid())
8251 MEHandler.emitCombinedEntry(BasePointers, Pointers, Sizes, MapTypes,
8252 CurMapTypes, PartialStruct);
8253
Alexey Bataev8451efa2018-01-15 19:06:12 +00008254 // We need to append the results of this capture to what we already have.
8255 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
8256 Pointers.append(CurPointers.begin(), CurPointers.end());
8257 Sizes.append(CurSizes.begin(), CurSizes.end());
8258 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
8259 }
Alexey Bataev60705422018-10-30 15:50:12 +00008260 // Adjust MEMBER_OF flags for the lambdas captures.
Alexey Bataev969dbc02018-11-08 15:47:39 +00008261 MEHandler.adjustMemberOfForLambdaCaptures(LambdaPointers, BasePointers,
8262 Pointers, MapTypes);
Alexey Bataev92327c52018-03-26 16:40:55 +00008263 // Map other list items in the map clause which are not captured variables
8264 // but "declare target link" global variables.
Alexey Bataevb3638132018-07-19 16:34:13 +00008265 MEHandler.generateInfoForDeclareTargetLink(BasePointers, Pointers, Sizes,
8266 MapTypes);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008267
8268 TargetDataInfo Info;
8269 // Fill up the arrays and create the arguments.
8270 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
8271 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
8272 Info.PointersArray, Info.SizesArray,
8273 Info.MapTypesArray, Info);
8274 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
8275 InputInfo.BasePointersArray =
8276 Address(Info.BasePointersArray, CGM.getPointerAlign());
8277 InputInfo.PointersArray =
8278 Address(Info.PointersArray, CGM.getPointerAlign());
8279 InputInfo.SizesArray = Address(Info.SizesArray, CGM.getPointerAlign());
8280 MapTypesArray = Info.MapTypesArray;
8281 if (RequiresOuterTask)
8282 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
8283 else
8284 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
8285 };
8286
8287 auto &&TargetElseGen = [this, &ElseGen, &D, RequiresOuterTask](
8288 CodeGenFunction &CGF, PrePostActionTy &) {
8289 if (RequiresOuterTask) {
8290 CodeGenFunction::OMPTargetDataInfo InputInfo;
8291 CGF.EmitOMPTargetTaskBasedDirective(D, ElseGen, InputInfo);
8292 } else {
8293 emitInlinedDirective(CGF, D.getDirectiveKind(), ElseGen);
8294 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00008295 };
8296
8297 // If we have a target function ID it means that we need to support
8298 // offloading, otherwise, just execute on the host. We need to execute on host
8299 // regardless of the conditional in the if clause if, e.g., the user do not
8300 // specify target triples.
8301 if (OutlinedFnID) {
Alexey Bataev8451efa2018-01-15 19:06:12 +00008302 if (IfCond) {
8303 emitOMPIfClause(CGF, IfCond, TargetThenGen, TargetElseGen);
8304 } else {
8305 RegionCodeGenTy ThenRCG(TargetThenGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00008306 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00008307 }
8308 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00008309 RegionCodeGenTy ElseRCG(TargetElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00008310 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00008311 }
Samuel Antaobed3c462015-10-02 16:14:20 +00008312}
Samuel Antaoee8fb302016-01-06 13:42:12 +00008313
8314void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
8315 StringRef ParentName) {
8316 if (!S)
8317 return;
8318
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008319 // Codegen OMP target directives that offload compute to the device.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008320 bool RequiresDeviceCodegen =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008321 isa<OMPExecutableDirective>(S) &&
8322 isOpenMPTargetExecutionDirective(
8323 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00008324
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008325 if (RequiresDeviceCodegen) {
8326 const auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008327 unsigned DeviceID;
8328 unsigned FileID;
8329 unsigned Line;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008330 getTargetEntryUniqueInfo(CGM.getContext(), E.getBeginLoc(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00008331 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008332
8333 // Is this a target region that should not be emitted as an entry point? If
8334 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00008335 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
8336 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008337 return;
8338
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008339 switch (E.getDirectiveKind()) {
8340 case OMPD_target:
8341 CodeGenFunction::EmitOMPTargetDeviceFunction(CGM, ParentName,
8342 cast<OMPTargetDirective>(E));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008343 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008344 case OMPD_target_parallel:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00008345 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008346 CGM, ParentName, cast<OMPTargetParallelDirective>(E));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00008347 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008348 case OMPD_target_teams:
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00008349 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008350 CGM, ParentName, cast<OMPTargetTeamsDirective>(E));
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00008351 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008352 case OMPD_target_teams_distribute:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008353 CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008354 CGM, ParentName, cast<OMPTargetTeamsDistributeDirective>(E));
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008355 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008356 case OMPD_target_teams_distribute_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008357 CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008358 CGM, ParentName, cast<OMPTargetTeamsDistributeSimdDirective>(E));
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008359 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008360 case OMPD_target_parallel_for:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008361 CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008362 CGM, ParentName, cast<OMPTargetParallelForDirective>(E));
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008363 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008364 case OMPD_target_parallel_for_simd:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008365 CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008366 CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(E));
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008367 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008368 case OMPD_target_simd:
Alexey Bataevf8365372017-11-17 17:57:25 +00008369 CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008370 CGM, ParentName, cast<OMPTargetSimdDirective>(E));
Alexey Bataevf8365372017-11-17 17:57:25 +00008371 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008372 case OMPD_target_teams_distribute_parallel_for:
Carlo Bertolli52978c32018-01-03 21:12:44 +00008373 CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
8374 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008375 cast<OMPTargetTeamsDistributeParallelForDirective>(E));
Carlo Bertolli52978c32018-01-03 21:12:44 +00008376 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008377 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00008378 CodeGenFunction::
8379 EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
8380 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008381 cast<OMPTargetTeamsDistributeParallelForSimdDirective>(E));
Alexey Bataev647dd842018-01-15 20:59:40 +00008382 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008383 case OMPD_parallel:
8384 case OMPD_for:
8385 case OMPD_parallel_for:
8386 case OMPD_parallel_sections:
8387 case OMPD_for_simd:
8388 case OMPD_parallel_for_simd:
8389 case OMPD_cancel:
8390 case OMPD_cancellation_point:
8391 case OMPD_ordered:
8392 case OMPD_threadprivate:
8393 case OMPD_task:
8394 case OMPD_simd:
8395 case OMPD_sections:
8396 case OMPD_section:
8397 case OMPD_single:
8398 case OMPD_master:
8399 case OMPD_critical:
8400 case OMPD_taskyield:
8401 case OMPD_barrier:
8402 case OMPD_taskwait:
8403 case OMPD_taskgroup:
8404 case OMPD_atomic:
8405 case OMPD_flush:
8406 case OMPD_teams:
8407 case OMPD_target_data:
8408 case OMPD_target_exit_data:
8409 case OMPD_target_enter_data:
8410 case OMPD_distribute:
8411 case OMPD_distribute_simd:
8412 case OMPD_distribute_parallel_for:
8413 case OMPD_distribute_parallel_for_simd:
8414 case OMPD_teams_distribute:
8415 case OMPD_teams_distribute_simd:
8416 case OMPD_teams_distribute_parallel_for:
8417 case OMPD_teams_distribute_parallel_for_simd:
8418 case OMPD_target_update:
8419 case OMPD_declare_simd:
8420 case OMPD_declare_target:
8421 case OMPD_end_declare_target:
8422 case OMPD_declare_reduction:
8423 case OMPD_taskloop:
8424 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008425 case OMPD_requires:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008426 case OMPD_unknown:
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008427 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
8428 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00008429 return;
8430 }
8431
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008432 if (const auto *E = dyn_cast<OMPExecutableDirective>(S)) {
Alexey Bataev475a7442018-01-12 19:39:11 +00008433 if (!E->hasAssociatedStmt() || !E->getAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00008434 return;
8435
8436 scanForTargetRegionsFunctions(
Alexey Bataev475a7442018-01-12 19:39:11 +00008437 E->getInnermostCapturedStmt()->getCapturedStmt(), ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008438 return;
8439 }
8440
8441 // If this is a lambda function, look into its body.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008442 if (const auto *L = dyn_cast<LambdaExpr>(S))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008443 S = L->getBody();
8444
8445 // Keep looking for target regions recursively.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008446 for (const Stmt *II : S->children())
Samuel Antaoee8fb302016-01-06 13:42:12 +00008447 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008448}
8449
8450bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008451 // If emitting code for the host, we do not process FD here. Instead we do
8452 // the normal code generation.
8453 if (!CGM.getLangOpts().OpenMPIsDevice)
8454 return false;
8455
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008456 const ValueDecl *VD = cast<ValueDecl>(GD.getDecl());
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008457 StringRef Name = CGM.getMangledName(GD);
8458 // Try to detect target regions in the function.
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008459 if (const auto *FD = dyn_cast<FunctionDecl>(VD))
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008460 scanForTargetRegionsFunctions(FD->getBody(), Name);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008461
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008462 // Do not to emit function if it is not marked as declare target.
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008463 return !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008464 AlreadyEmittedTargetFunctions.count(Name) == 0;
Samuel Antaoee8fb302016-01-06 13:42:12 +00008465}
8466
8467bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
8468 if (!CGM.getLangOpts().OpenMPIsDevice)
8469 return false;
8470
8471 // Check if there are Ctors/Dtors in this declaration and look for target
8472 // regions in it. We use the complete variant to produce the kernel name
8473 // mangling.
8474 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008475 if (const auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
8476 for (const CXXConstructorDecl *Ctor : RD->ctors()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008477 StringRef ParentName =
8478 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
8479 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
8480 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008481 if (const CXXDestructorDecl *Dtor = RD->getDestructor()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008482 StringRef ParentName =
8483 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
8484 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
8485 }
8486 }
8487
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008488 // Do not to emit variable if it is not marked as declare target.
Alexey Bataev92327c52018-03-26 16:40:55 +00008489 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00008490 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
8491 cast<VarDecl>(GD.getDecl()));
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008492 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Alexey Bataevd01b7492018-08-15 19:45:12 +00008493 DeferredGlobalVariables.insert(cast<VarDecl>(GD.getDecl()));
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008494 return true;
8495 }
8496 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00008497}
8498
Alexey Bataev03f270c2018-03-30 18:31:07 +00008499void CGOpenMPRuntime::registerTargetGlobalVariable(const VarDecl *VD,
8500 llvm::Constant *Addr) {
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008501 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
8502 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
8503 if (!Res) {
8504 if (CGM.getLangOpts().OpenMPIsDevice) {
8505 // Register non-target variables being emitted in device code (debug info
8506 // may cause this).
8507 StringRef VarName = CGM.getMangledName(VD);
8508 EmittedNonTargetVariables.try_emplace(VarName, Addr);
Alexey Bataev03f270c2018-03-30 18:31:07 +00008509 }
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008510 return;
Alexey Bataev03f270c2018-03-30 18:31:07 +00008511 }
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008512 // Register declare target variables.
8513 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags;
8514 StringRef VarName;
8515 CharUnits VarSize;
8516 llvm::GlobalValue::LinkageTypes Linkage;
8517 switch (*Res) {
8518 case OMPDeclareTargetDeclAttr::MT_To:
8519 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo;
8520 VarName = CGM.getMangledName(VD);
8521 if (VD->hasDefinition(CGM.getContext()) != VarDecl::DeclarationOnly) {
8522 VarSize = CGM.getContext().getTypeSizeInChars(VD->getType());
8523 assert(!VarSize.isZero() && "Expected non-zero size of the variable");
8524 } else {
8525 VarSize = CharUnits::Zero();
8526 }
8527 Linkage = CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false);
8528 // Temp solution to prevent optimizations of the internal variables.
8529 if (CGM.getLangOpts().OpenMPIsDevice && !VD->isExternallyVisible()) {
8530 std::string RefName = getName({VarName, "ref"});
8531 if (!CGM.GetGlobalValue(RefName)) {
8532 llvm::Constant *AddrRef =
8533 getOrCreateInternalVariable(Addr->getType(), RefName);
8534 auto *GVAddrRef = cast<llvm::GlobalVariable>(AddrRef);
8535 GVAddrRef->setConstant(/*Val=*/true);
8536 GVAddrRef->setLinkage(llvm::GlobalValue::InternalLinkage);
8537 GVAddrRef->setInitializer(Addr);
8538 CGM.addCompilerUsedGlobal(GVAddrRef);
8539 }
8540 }
8541 break;
8542 case OMPDeclareTargetDeclAttr::MT_Link:
8543 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink;
8544 if (CGM.getLangOpts().OpenMPIsDevice) {
8545 VarName = Addr->getName();
8546 Addr = nullptr;
8547 } else {
8548 VarName = getAddrOfDeclareTargetLink(VD).getName();
8549 Addr = cast<llvm::Constant>(getAddrOfDeclareTargetLink(VD).getPointer());
8550 }
8551 VarSize = CGM.getPointerSize();
8552 Linkage = llvm::GlobalValue::WeakAnyLinkage;
8553 break;
8554 }
8555 OffloadEntriesInfoManager.registerDeviceGlobalVarEntryInfo(
8556 VarName, Addr, VarSize, Flags, Linkage);
Alexey Bataev03f270c2018-03-30 18:31:07 +00008557}
8558
Samuel Antaoee8fb302016-01-06 13:42:12 +00008559bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008560 if (isa<FunctionDecl>(GD.getDecl()) ||
8561 isa<OMPDeclareReductionDecl>(GD.getDecl()))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008562 return emitTargetFunctions(GD);
8563
8564 return emitTargetGlobalVariable(GD);
8565}
8566
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008567void CGOpenMPRuntime::emitDeferredTargetDecls() const {
8568 for (const VarDecl *VD : DeferredGlobalVariables) {
8569 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00008570 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataevd01b7492018-08-15 19:45:12 +00008571 if (!Res)
8572 continue;
8573 if (*Res == OMPDeclareTargetDeclAttr::MT_To) {
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008574 CGM.EmitGlobal(VD);
Alexey Bataevd01b7492018-08-15 19:45:12 +00008575 } else {
8576 assert(*Res == OMPDeclareTargetDeclAttr::MT_Link &&
8577 "Expected to or link clauses.");
8578 (void)CGM.getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008579 }
8580 }
8581}
8582
Alexey Bataev60705422018-10-30 15:50:12 +00008583void CGOpenMPRuntime::adjustTargetSpecificDataForLambdas(
8584 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
8585 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
8586 " Expected target-based directive.");
8587}
8588
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008589CGOpenMPRuntime::DisableAutoDeclareTargetRAII::DisableAutoDeclareTargetRAII(
8590 CodeGenModule &CGM)
8591 : CGM(CGM) {
8592 if (CGM.getLangOpts().OpenMPIsDevice) {
8593 SavedShouldMarkAsGlobal = CGM.getOpenMPRuntime().ShouldMarkAsGlobal;
8594 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = false;
8595 }
8596}
8597
8598CGOpenMPRuntime::DisableAutoDeclareTargetRAII::~DisableAutoDeclareTargetRAII() {
8599 if (CGM.getLangOpts().OpenMPIsDevice)
8600 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = SavedShouldMarkAsGlobal;
8601}
8602
Alexey Bataev6d944102018-05-02 15:45:28 +00008603bool CGOpenMPRuntime::markAsGlobalTarget(GlobalDecl GD) {
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008604 if (!CGM.getLangOpts().OpenMPIsDevice || !ShouldMarkAsGlobal)
8605 return true;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008606
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008607 StringRef Name = CGM.getMangledName(GD);
Alexey Bataev6d944102018-05-02 15:45:28 +00008608 const auto *D = cast<FunctionDecl>(GD.getDecl());
Alexey Bataev34f8a702018-03-28 14:28:54 +00008609 // Do not to emit function if it is marked as declare target as it was already
8610 // emitted.
Alexey Bataev97b72212018-08-14 18:31:20 +00008611 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(D)) {
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008612 if (D->hasBody() && AlreadyEmittedTargetFunctions.count(Name) == 0) {
8613 if (auto *F = dyn_cast_or_null<llvm::Function>(CGM.GetGlobalValue(Name)))
Alexey Bataev34f8a702018-03-28 14:28:54 +00008614 return !F->isDeclaration();
8615 return false;
8616 }
8617 return true;
8618 }
8619
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008620 return !AlreadyEmittedTargetFunctions.insert(Name).second;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008621}
8622
Samuel Antaoee8fb302016-01-06 13:42:12 +00008623llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
8624 // If we have offloading in the current module, we need to emit the entries
8625 // now and register the offloading descriptor.
8626 createOffloadEntriesAndInfoMetadata();
8627
8628 // Create and register the offloading binary descriptors. This is the main
8629 // entity that captures all the information about offloading in the current
8630 // compilation unit.
8631 return createOffloadingBinaryDescriptorRegistration();
8632}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008633
8634void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
8635 const OMPExecutableDirective &D,
8636 SourceLocation Loc,
8637 llvm::Value *OutlinedFn,
8638 ArrayRef<llvm::Value *> CapturedVars) {
8639 if (!CGF.HaveInsertPoint())
8640 return;
8641
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008642 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008643 CodeGenFunction::RunCleanupsScope Scope(CGF);
8644
8645 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
8646 llvm::Value *Args[] = {
8647 RTLoc,
8648 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
8649 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
8650 llvm::SmallVector<llvm::Value *, 16> RealArgs;
8651 RealArgs.append(std::begin(Args), std::end(Args));
8652 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
8653
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008654 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008655 CGF.EmitRuntimeCall(RTLFn, RealArgs);
8656}
8657
8658void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00008659 const Expr *NumTeams,
8660 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008661 SourceLocation Loc) {
8662 if (!CGF.HaveInsertPoint())
8663 return;
8664
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008665 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008666
Carlo Bertollic6872252016-04-04 15:55:02 +00008667 llvm::Value *NumTeamsVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008668 NumTeams
Carlo Bertollic6872252016-04-04 15:55:02 +00008669 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
8670 CGF.CGM.Int32Ty, /* isSigned = */ true)
8671 : CGF.Builder.getInt32(0);
8672
8673 llvm::Value *ThreadLimitVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008674 ThreadLimit
Carlo Bertollic6872252016-04-04 15:55:02 +00008675 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
8676 CGF.CGM.Int32Ty, /* isSigned = */ true)
8677 : CGF.Builder.getInt32(0);
8678
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008679 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00008680 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
8681 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008682 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
8683 PushNumTeamsArgs);
8684}
Samuel Antaodf158d52016-04-27 22:58:19 +00008685
Samuel Antaocc10b852016-07-28 14:23:26 +00008686void CGOpenMPRuntime::emitTargetDataCalls(
8687 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8688 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008689 if (!CGF.HaveInsertPoint())
8690 return;
8691
Samuel Antaocc10b852016-07-28 14:23:26 +00008692 // Action used to replace the default codegen action and turn privatization
8693 // off.
8694 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00008695
8696 // Generate the code for the opening of the data environment. Capture all the
8697 // arguments of the runtime call by reference because they are used in the
8698 // closing of the region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008699 auto &&BeginThenGen = [this, &D, Device, &Info,
8700 &CodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008701 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00008702 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00008703 MappableExprsHandler::MapValuesArrayTy Pointers;
8704 MappableExprsHandler::MapValuesArrayTy Sizes;
8705 MappableExprsHandler::MapFlagsArrayTy MapTypes;
8706
8707 // Get map clause information.
8708 MappableExprsHandler MCHandler(D, CGF);
8709 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00008710
8711 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00008712 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008713
8714 llvm::Value *BasePointersArrayArg = nullptr;
8715 llvm::Value *PointersArrayArg = nullptr;
8716 llvm::Value *SizesArrayArg = nullptr;
8717 llvm::Value *MapTypesArrayArg = nullptr;
8718 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008719 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008720
8721 // Emit device ID if any.
8722 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008723 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008724 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008725 CGF.Int64Ty, /*isSigned=*/true);
8726 } else {
8727 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8728 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008729
8730 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008731 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00008732
8733 llvm::Value *OffloadingArgs[] = {
8734 DeviceID, PointerNum, BasePointersArrayArg,
8735 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008736 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_begin),
Samuel Antaodf158d52016-04-27 22:58:19 +00008737 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00008738
8739 // If device pointer privatization is required, emit the body of the region
8740 // here. It will have to be duplicated: with and without privatization.
8741 if (!Info.CaptureDeviceAddrMap.empty())
8742 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008743 };
8744
8745 // Generate code for the closing of the data region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008746 auto &&EndThenGen = [this, Device, &Info](CodeGenFunction &CGF,
8747 PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008748 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00008749
8750 llvm::Value *BasePointersArrayArg = nullptr;
8751 llvm::Value *PointersArrayArg = nullptr;
8752 llvm::Value *SizesArrayArg = nullptr;
8753 llvm::Value *MapTypesArrayArg = nullptr;
8754 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008755 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008756
8757 // Emit device ID if any.
8758 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008759 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008760 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008761 CGF.Int64Ty, /*isSigned=*/true);
8762 } else {
8763 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8764 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008765
8766 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008767 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00008768
8769 llvm::Value *OffloadingArgs[] = {
8770 DeviceID, PointerNum, BasePointersArrayArg,
8771 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008772 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_end),
Samuel Antaodf158d52016-04-27 22:58:19 +00008773 OffloadingArgs);
8774 };
8775
Samuel Antaocc10b852016-07-28 14:23:26 +00008776 // If we need device pointer privatization, we need to emit the body of the
8777 // region with no privatization in the 'else' branch of the conditional.
8778 // Otherwise, we don't have to do anything.
8779 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
8780 PrePostActionTy &) {
8781 if (!Info.CaptureDeviceAddrMap.empty()) {
8782 CodeGen.setAction(NoPrivAction);
8783 CodeGen(CGF);
8784 }
8785 };
8786
8787 // We don't have to do anything to close the region if the if clause evaluates
8788 // to false.
8789 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00008790
8791 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008792 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00008793 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00008794 RegionCodeGenTy RCG(BeginThenGen);
8795 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008796 }
8797
Samuel Antaocc10b852016-07-28 14:23:26 +00008798 // If we don't require privatization of device pointers, we emit the body in
8799 // between the runtime calls. This avoids duplicating the body code.
8800 if (Info.CaptureDeviceAddrMap.empty()) {
8801 CodeGen.setAction(NoPrivAction);
8802 CodeGen(CGF);
8803 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008804
8805 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008806 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00008807 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00008808 RegionCodeGenTy RCG(EndThenGen);
8809 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008810 }
8811}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008812
Samuel Antao8d2d7302016-05-26 18:30:22 +00008813void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00008814 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8815 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008816 if (!CGF.HaveInsertPoint())
8817 return;
8818
Samuel Antao8dd66282016-04-27 23:14:30 +00008819 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00008820 isa<OMPTargetExitDataDirective>(D) ||
8821 isa<OMPTargetUpdateDirective>(D)) &&
8822 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00008823
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008824 CodeGenFunction::OMPTargetDataInfo InputInfo;
8825 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008826 // Generate the code for the opening of the data environment.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008827 auto &&ThenGen = [this, &D, Device, &InputInfo,
8828 &MapTypesArray](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008829 // Emit device ID if any.
8830 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008831 if (Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008832 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008833 CGF.Int64Ty, /*isSigned=*/true);
8834 } else {
8835 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8836 }
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008837
8838 // Emit the number of elements in the offloading arrays.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008839 llvm::Constant *PointerNum =
8840 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008841
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008842 llvm::Value *OffloadingArgs[] = {DeviceID,
8843 PointerNum,
8844 InputInfo.BasePointersArray.getPointer(),
8845 InputInfo.PointersArray.getPointer(),
8846 InputInfo.SizesArray.getPointer(),
8847 MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00008848
Samuel Antao8d2d7302016-05-26 18:30:22 +00008849 // Select the right runtime function call for each expected standalone
8850 // directive.
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008851 const bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Samuel Antao8d2d7302016-05-26 18:30:22 +00008852 OpenMPRTLFunction RTLFn;
8853 switch (D.getDirectiveKind()) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00008854 case OMPD_target_enter_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008855 RTLFn = HasNowait ? OMPRTL__tgt_target_data_begin_nowait
8856 : OMPRTL__tgt_target_data_begin;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008857 break;
8858 case OMPD_target_exit_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008859 RTLFn = HasNowait ? OMPRTL__tgt_target_data_end_nowait
8860 : OMPRTL__tgt_target_data_end;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008861 break;
8862 case OMPD_target_update:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008863 RTLFn = HasNowait ? OMPRTL__tgt_target_data_update_nowait
8864 : OMPRTL__tgt_target_data_update;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008865 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008866 case OMPD_parallel:
8867 case OMPD_for:
8868 case OMPD_parallel_for:
8869 case OMPD_parallel_sections:
8870 case OMPD_for_simd:
8871 case OMPD_parallel_for_simd:
8872 case OMPD_cancel:
8873 case OMPD_cancellation_point:
8874 case OMPD_ordered:
8875 case OMPD_threadprivate:
8876 case OMPD_task:
8877 case OMPD_simd:
8878 case OMPD_sections:
8879 case OMPD_section:
8880 case OMPD_single:
8881 case OMPD_master:
8882 case OMPD_critical:
8883 case OMPD_taskyield:
8884 case OMPD_barrier:
8885 case OMPD_taskwait:
8886 case OMPD_taskgroup:
8887 case OMPD_atomic:
8888 case OMPD_flush:
8889 case OMPD_teams:
8890 case OMPD_target_data:
8891 case OMPD_distribute:
8892 case OMPD_distribute_simd:
8893 case OMPD_distribute_parallel_for:
8894 case OMPD_distribute_parallel_for_simd:
8895 case OMPD_teams_distribute:
8896 case OMPD_teams_distribute_simd:
8897 case OMPD_teams_distribute_parallel_for:
8898 case OMPD_teams_distribute_parallel_for_simd:
8899 case OMPD_declare_simd:
8900 case OMPD_declare_target:
8901 case OMPD_end_declare_target:
8902 case OMPD_declare_reduction:
8903 case OMPD_taskloop:
8904 case OMPD_taskloop_simd:
8905 case OMPD_target:
8906 case OMPD_target_simd:
8907 case OMPD_target_teams_distribute:
8908 case OMPD_target_teams_distribute_simd:
8909 case OMPD_target_teams_distribute_parallel_for:
8910 case OMPD_target_teams_distribute_parallel_for_simd:
8911 case OMPD_target_teams:
8912 case OMPD_target_parallel:
8913 case OMPD_target_parallel_for:
8914 case OMPD_target_parallel_for_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008915 case OMPD_requires:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008916 case OMPD_unknown:
8917 llvm_unreachable("Unexpected standalone target data directive.");
8918 break;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008919 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008920 CGF.EmitRuntimeCall(createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008921 };
8922
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008923 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray](
8924 CodeGenFunction &CGF, PrePostActionTy &) {
8925 // Fill up the arrays with all the mapped variables.
8926 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
8927 MappableExprsHandler::MapValuesArrayTy Pointers;
8928 MappableExprsHandler::MapValuesArrayTy Sizes;
8929 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008930
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008931 // Get map clause information.
8932 MappableExprsHandler MEHandler(D, CGF);
8933 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
8934
8935 TargetDataInfo Info;
8936 // Fill up the arrays and create the arguments.
8937 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
8938 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
8939 Info.PointersArray, Info.SizesArray,
8940 Info.MapTypesArray, Info);
8941 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
8942 InputInfo.BasePointersArray =
8943 Address(Info.BasePointersArray, CGM.getPointerAlign());
8944 InputInfo.PointersArray =
8945 Address(Info.PointersArray, CGM.getPointerAlign());
8946 InputInfo.SizesArray =
8947 Address(Info.SizesArray, CGM.getPointerAlign());
8948 MapTypesArray = Info.MapTypesArray;
8949 if (D.hasClausesOfKind<OMPDependClause>())
8950 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
8951 else
Alexey Bataev768f1f22018-01-09 19:59:25 +00008952 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008953 };
8954
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008955 if (IfCond) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008956 emitOMPIfClause(CGF, IfCond, TargetThenGen,
8957 [](CodeGenFunction &CGF, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008958 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008959 RegionCodeGenTy ThenRCG(TargetThenGen);
8960 ThenRCG(CGF);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008961 }
8962}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008963
8964namespace {
8965 /// Kind of parameter in a function with 'declare simd' directive.
8966 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
8967 /// Attribute set of the parameter.
8968 struct ParamAttrTy {
8969 ParamKindTy Kind = Vector;
8970 llvm::APSInt StrideOrArg;
8971 llvm::APSInt Alignment;
8972 };
8973} // namespace
8974
8975static unsigned evaluateCDTSize(const FunctionDecl *FD,
8976 ArrayRef<ParamAttrTy> ParamAttrs) {
8977 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
8978 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
8979 // of that clause. The VLEN value must be power of 2.
8980 // In other case the notion of the function`s "characteristic data type" (CDT)
8981 // is used to compute the vector length.
8982 // CDT is defined in the following order:
8983 // a) For non-void function, the CDT is the return type.
8984 // b) If the function has any non-uniform, non-linear parameters, then the
8985 // CDT is the type of the first such parameter.
8986 // c) If the CDT determined by a) or b) above is struct, union, or class
8987 // type which is pass-by-value (except for the type that maps to the
8988 // built-in complex data type), the characteristic data type is int.
8989 // d) If none of the above three cases is applicable, the CDT is int.
8990 // The VLEN is then determined based on the CDT and the size of vector
8991 // register of that ISA for which current vector version is generated. The
8992 // VLEN is computed using the formula below:
8993 // VLEN = sizeof(vector_register) / sizeof(CDT),
8994 // where vector register size specified in section 3.2.1 Registers and the
8995 // Stack Frame of original AMD64 ABI document.
8996 QualType RetType = FD->getReturnType();
8997 if (RetType.isNull())
8998 return 0;
8999 ASTContext &C = FD->getASTContext();
9000 QualType CDT;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009001 if (!RetType.isNull() && !RetType->isVoidType()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009002 CDT = RetType;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009003 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009004 unsigned Offset = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009005 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009006 if (ParamAttrs[Offset].Kind == Vector)
9007 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
9008 ++Offset;
9009 }
9010 if (CDT.isNull()) {
9011 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
9012 if (ParamAttrs[I + Offset].Kind == Vector) {
9013 CDT = FD->getParamDecl(I)->getType();
9014 break;
9015 }
9016 }
9017 }
9018 }
9019 if (CDT.isNull())
9020 CDT = C.IntTy;
9021 CDT = CDT->getCanonicalTypeUnqualified();
9022 if (CDT->isRecordType() || CDT->isUnionType())
9023 CDT = C.IntTy;
9024 return C.getTypeSize(CDT);
9025}
9026
9027static void
9028emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00009029 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009030 ArrayRef<ParamAttrTy> ParamAttrs,
9031 OMPDeclareSimdDeclAttr::BranchStateTy State) {
9032 struct ISADataTy {
9033 char ISA;
9034 unsigned VecRegSize;
9035 };
9036 ISADataTy ISAData[] = {
9037 {
9038 'b', 128
9039 }, // SSE
9040 {
9041 'c', 256
9042 }, // AVX
9043 {
9044 'd', 256
9045 }, // AVX2
9046 {
9047 'e', 512
9048 }, // AVX512
9049 };
9050 llvm::SmallVector<char, 2> Masked;
9051 switch (State) {
9052 case OMPDeclareSimdDeclAttr::BS_Undefined:
9053 Masked.push_back('N');
9054 Masked.push_back('M');
9055 break;
9056 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
9057 Masked.push_back('N');
9058 break;
9059 case OMPDeclareSimdDeclAttr::BS_Inbranch:
9060 Masked.push_back('M');
9061 break;
9062 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009063 for (char Mask : Masked) {
9064 for (const ISADataTy &Data : ISAData) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009065 SmallString<256> Buffer;
9066 llvm::raw_svector_ostream Out(Buffer);
9067 Out << "_ZGV" << Data.ISA << Mask;
9068 if (!VLENVal) {
9069 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
9070 evaluateCDTSize(FD, ParamAttrs));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009071 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009072 Out << VLENVal;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009073 }
9074 for (const ParamAttrTy &ParamAttr : ParamAttrs) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009075 switch (ParamAttr.Kind){
9076 case LinearWithVarStride:
9077 Out << 's' << ParamAttr.StrideOrArg;
9078 break;
9079 case Linear:
9080 Out << 'l';
9081 if (!!ParamAttr.StrideOrArg)
9082 Out << ParamAttr.StrideOrArg;
9083 break;
9084 case Uniform:
9085 Out << 'u';
9086 break;
9087 case Vector:
9088 Out << 'v';
9089 break;
9090 }
9091 if (!!ParamAttr.Alignment)
9092 Out << 'a' << ParamAttr.Alignment;
9093 }
9094 Out << '_' << Fn->getName();
9095 Fn->addFnAttr(Out.str());
9096 }
9097 }
9098}
9099
9100void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
9101 llvm::Function *Fn) {
9102 ASTContext &C = CGM.getContext();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009103 FD = FD->getMostRecentDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009104 // Map params to their positions in function decl.
9105 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
9106 if (isa<CXXMethodDecl>(FD))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009107 ParamPositions.try_emplace(FD, 0);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009108 unsigned ParamPos = ParamPositions.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009109 for (const ParmVarDecl *P : FD->parameters()) {
9110 ParamPositions.try_emplace(P->getCanonicalDecl(), ParamPos);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009111 ++ParamPos;
9112 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009113 while (FD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009114 for (const auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009115 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
9116 // Mark uniform parameters.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009117 for (const Expr *E : Attr->uniforms()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009118 E = E->IgnoreParenImpCasts();
9119 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009120 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009121 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009122 } else {
9123 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
9124 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009125 Pos = ParamPositions[PVD];
9126 }
9127 ParamAttrs[Pos].Kind = Uniform;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009128 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009129 // Get alignment info.
9130 auto NI = Attr->alignments_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009131 for (const Expr *E : Attr->aligneds()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009132 E = E->IgnoreParenImpCasts();
9133 unsigned Pos;
9134 QualType ParmTy;
9135 if (isa<CXXThisExpr>(E)) {
9136 Pos = ParamPositions[FD];
9137 ParmTy = E->getType();
9138 } else {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009139 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
9140 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009141 Pos = ParamPositions[PVD];
9142 ParmTy = PVD->getType();
9143 }
9144 ParamAttrs[Pos].Alignment =
9145 (*NI)
9146 ? (*NI)->EvaluateKnownConstInt(C)
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009147 : llvm::APSInt::getUnsigned(
9148 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
9149 .getQuantity());
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009150 ++NI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009151 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009152 // Mark linear parameters.
9153 auto SI = Attr->steps_begin();
9154 auto MI = Attr->modifiers_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009155 for (const Expr *E : Attr->linears()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009156 E = E->IgnoreParenImpCasts();
9157 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009158 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009159 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009160 } else {
9161 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
9162 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009163 Pos = ParamPositions[PVD];
9164 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009165 ParamAttrTy &ParamAttr = ParamAttrs[Pos];
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009166 ParamAttr.Kind = Linear;
9167 if (*SI) {
Bill Wendling6ff17512018-11-21 20:44:18 +00009168 Expr::EvalResult Result;
9169 if (!(*SI)->EvaluateAsInt(Result, C, Expr::SE_AllowSideEffects)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009170 if (const auto *DRE =
9171 cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
9172 if (const auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009173 ParamAttr.Kind = LinearWithVarStride;
9174 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
9175 ParamPositions[StridePVD->getCanonicalDecl()]);
9176 }
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009177 }
Bill Wendling6ff17512018-11-21 20:44:18 +00009178 } else {
9179 ParamAttr.StrideOrArg = Result.Val.getInt();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009180 }
9181 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009182 ++SI;
9183 ++MI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009184 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009185 llvm::APSInt VLENVal;
9186 if (const Expr *VLEN = Attr->getSimdlen())
9187 VLENVal = VLEN->EvaluateKnownConstInt(C);
9188 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
9189 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
9190 CGM.getTriple().getArch() == llvm::Triple::x86_64)
9191 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009192 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009193 FD = FD->getPreviousDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009194 }
9195}
Alexey Bataev8b427062016-05-25 12:36:08 +00009196
9197namespace {
9198/// Cleanup action for doacross support.
9199class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
9200public:
9201 static const int DoacrossFinArgs = 2;
9202
9203private:
9204 llvm::Value *RTLFn;
9205 llvm::Value *Args[DoacrossFinArgs];
9206
9207public:
9208 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
9209 : RTLFn(RTLFn) {
9210 assert(CallArgs.size() == DoacrossFinArgs);
9211 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
9212 }
9213 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
9214 if (!CGF.HaveInsertPoint())
9215 return;
9216 CGF.EmitRuntimeCall(RTLFn, Args);
9217 }
9218};
9219} // namespace
9220
9221void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
Alexey Bataevf138fda2018-08-13 19:04:24 +00009222 const OMPLoopDirective &D,
9223 ArrayRef<Expr *> NumIterations) {
Alexey Bataev8b427062016-05-25 12:36:08 +00009224 if (!CGF.HaveInsertPoint())
9225 return;
9226
9227 ASTContext &C = CGM.getContext();
9228 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
9229 RecordDecl *RD;
9230 if (KmpDimTy.isNull()) {
9231 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
9232 // kmp_int64 lo; // lower
9233 // kmp_int64 up; // upper
9234 // kmp_int64 st; // stride
9235 // };
9236 RD = C.buildImplicitRecord("kmp_dim");
9237 RD->startDefinition();
9238 addFieldToRecordDecl(C, RD, Int64Ty);
9239 addFieldToRecordDecl(C, RD, Int64Ty);
9240 addFieldToRecordDecl(C, RD, Int64Ty);
9241 RD->completeDefinition();
9242 KmpDimTy = C.getRecordType(RD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009243 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00009244 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009245 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00009246 llvm::APInt Size(/*numBits=*/32, NumIterations.size());
9247 QualType ArrayTy =
9248 C.getConstantArrayType(KmpDimTy, Size, ArrayType::Normal, 0);
Alexey Bataev8b427062016-05-25 12:36:08 +00009249
Alexey Bataevf138fda2018-08-13 19:04:24 +00009250 Address DimsAddr = CGF.CreateMemTemp(ArrayTy, "dims");
9251 CGF.EmitNullInitialization(DimsAddr, ArrayTy);
Alexey Bataev8b427062016-05-25 12:36:08 +00009252 enum { LowerFD = 0, UpperFD, StrideFD };
9253 // Fill dims with data.
Alexey Bataevf138fda2018-08-13 19:04:24 +00009254 for (unsigned I = 0, E = NumIterations.size(); I < E; ++I) {
9255 LValue DimsLVal =
9256 CGF.MakeAddrLValue(CGF.Builder.CreateConstArrayGEP(
9257 DimsAddr, I, C.getTypeSizeInChars(KmpDimTy)),
9258 KmpDimTy);
9259 // dims.upper = num_iterations;
9260 LValue UpperLVal = CGF.EmitLValueForField(
9261 DimsLVal, *std::next(RD->field_begin(), UpperFD));
9262 llvm::Value *NumIterVal =
9263 CGF.EmitScalarConversion(CGF.EmitScalarExpr(NumIterations[I]),
9264 D.getNumIterations()->getType(), Int64Ty,
9265 D.getNumIterations()->getExprLoc());
9266 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
9267 // dims.stride = 1;
9268 LValue StrideLVal = CGF.EmitLValueForField(
9269 DimsLVal, *std::next(RD->field_begin(), StrideFD));
9270 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
9271 StrideLVal);
9272 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009273
9274 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
9275 // kmp_int32 num_dims, struct kmp_dim * dims);
Alexey Bataevf138fda2018-08-13 19:04:24 +00009276 llvm::Value *Args[] = {
9277 emitUpdateLocation(CGF, D.getBeginLoc()),
9278 getThreadID(CGF, D.getBeginLoc()),
9279 llvm::ConstantInt::getSigned(CGM.Int32Ty, NumIterations.size()),
9280 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
9281 CGF.Builder
9282 .CreateConstArrayGEP(DimsAddr, 0, C.getTypeSizeInChars(KmpDimTy))
9283 .getPointer(),
9284 CGM.VoidPtrTy)};
Alexey Bataev8b427062016-05-25 12:36:08 +00009285
9286 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
9287 CGF.EmitRuntimeCall(RTLFn, Args);
9288 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009289 emitUpdateLocation(CGF, D.getEndLoc()), getThreadID(CGF, D.getEndLoc())};
Alexey Bataev8b427062016-05-25 12:36:08 +00009290 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
9291 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
9292 llvm::makeArrayRef(FiniArgs));
9293}
9294
9295void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
9296 const OMPDependClause *C) {
9297 QualType Int64Ty =
9298 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
Alexey Bataevf138fda2018-08-13 19:04:24 +00009299 llvm::APInt Size(/*numBits=*/32, C->getNumLoops());
9300 QualType ArrayTy = CGM.getContext().getConstantArrayType(
9301 Int64Ty, Size, ArrayType::Normal, 0);
9302 Address CntAddr = CGF.CreateMemTemp(ArrayTy, ".cnt.addr");
9303 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I) {
9304 const Expr *CounterVal = C->getLoopData(I);
9305 assert(CounterVal);
9306 llvm::Value *CntVal = CGF.EmitScalarConversion(
9307 CGF.EmitScalarExpr(CounterVal), CounterVal->getType(), Int64Ty,
9308 CounterVal->getExprLoc());
9309 CGF.EmitStoreOfScalar(
9310 CntVal,
9311 CGF.Builder.CreateConstArrayGEP(
9312 CntAddr, I, CGM.getContext().getTypeSizeInChars(Int64Ty)),
9313 /*Volatile=*/false, Int64Ty);
9314 }
9315 llvm::Value *Args[] = {
9316 emitUpdateLocation(CGF, C->getBeginLoc()),
9317 getThreadID(CGF, C->getBeginLoc()),
9318 CGF.Builder
9319 .CreateConstArrayGEP(CntAddr, 0,
9320 CGM.getContext().getTypeSizeInChars(Int64Ty))
9321 .getPointer()};
Alexey Bataev8b427062016-05-25 12:36:08 +00009322 llvm::Value *RTLFn;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009323 if (C->getDependencyKind() == OMPC_DEPEND_source) {
Alexey Bataev8b427062016-05-25 12:36:08 +00009324 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009325 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00009326 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
9327 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
9328 }
9329 CGF.EmitRuntimeCall(RTLFn, Args);
9330}
9331
Alexey Bataev7ef47a62018-02-22 18:33:31 +00009332void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, SourceLocation Loc,
9333 llvm::Value *Callee,
9334 ArrayRef<llvm::Value *> Args) const {
9335 assert(Loc.isValid() && "Outlined function call location must be valid.");
Alexey Bataev3c595a62017-08-14 15:01:03 +00009336 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
9337
9338 if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00009339 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00009340 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00009341 return;
9342 }
9343 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00009344 CGF.EmitRuntimeCall(Callee, Args);
9345}
9346
9347void CGOpenMPRuntime::emitOutlinedFunctionCall(
9348 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
9349 ArrayRef<llvm::Value *> Args) const {
Alexey Bataev7ef47a62018-02-22 18:33:31 +00009350 emitCall(CGF, Loc, OutlinedFn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00009351}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00009352
9353Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
9354 const VarDecl *NativeParam,
9355 const VarDecl *TargetParam) const {
9356 return CGF.GetAddrOfLocalVar(NativeParam);
9357}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009358
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00009359Address CGOpenMPRuntime::getAddressOfLocalVariable(CodeGenFunction &CGF,
9360 const VarDecl *VD) {
9361 return Address::invalid();
9362}
9363
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009364llvm::Value *CGOpenMPSIMDRuntime::emitParallelOutlinedFunction(
9365 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
9366 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
9367 llvm_unreachable("Not supported in SIMD-only mode");
9368}
9369
9370llvm::Value *CGOpenMPSIMDRuntime::emitTeamsOutlinedFunction(
9371 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
9372 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
9373 llvm_unreachable("Not supported in SIMD-only mode");
9374}
9375
9376llvm::Value *CGOpenMPSIMDRuntime::emitTaskOutlinedFunction(
9377 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
9378 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
9379 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
9380 bool Tied, unsigned &NumberOfParts) {
9381 llvm_unreachable("Not supported in SIMD-only mode");
9382}
9383
9384void CGOpenMPSIMDRuntime::emitParallelCall(CodeGenFunction &CGF,
9385 SourceLocation Loc,
9386 llvm::Value *OutlinedFn,
9387 ArrayRef<llvm::Value *> CapturedVars,
9388 const Expr *IfCond) {
9389 llvm_unreachable("Not supported in SIMD-only mode");
9390}
9391
9392void CGOpenMPSIMDRuntime::emitCriticalRegion(
9393 CodeGenFunction &CGF, StringRef CriticalName,
9394 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
9395 const Expr *Hint) {
9396 llvm_unreachable("Not supported in SIMD-only mode");
9397}
9398
9399void CGOpenMPSIMDRuntime::emitMasterRegion(CodeGenFunction &CGF,
9400 const RegionCodeGenTy &MasterOpGen,
9401 SourceLocation Loc) {
9402 llvm_unreachable("Not supported in SIMD-only mode");
9403}
9404
9405void CGOpenMPSIMDRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
9406 SourceLocation Loc) {
9407 llvm_unreachable("Not supported in SIMD-only mode");
9408}
9409
9410void CGOpenMPSIMDRuntime::emitTaskgroupRegion(
9411 CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen,
9412 SourceLocation Loc) {
9413 llvm_unreachable("Not supported in SIMD-only mode");
9414}
9415
9416void CGOpenMPSIMDRuntime::emitSingleRegion(
9417 CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen,
9418 SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars,
9419 ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs,
9420 ArrayRef<const Expr *> AssignmentOps) {
9421 llvm_unreachable("Not supported in SIMD-only mode");
9422}
9423
9424void CGOpenMPSIMDRuntime::emitOrderedRegion(CodeGenFunction &CGF,
9425 const RegionCodeGenTy &OrderedOpGen,
9426 SourceLocation Loc,
9427 bool IsThreads) {
9428 llvm_unreachable("Not supported in SIMD-only mode");
9429}
9430
9431void CGOpenMPSIMDRuntime::emitBarrierCall(CodeGenFunction &CGF,
9432 SourceLocation Loc,
9433 OpenMPDirectiveKind Kind,
9434 bool EmitChecks,
9435 bool ForceSimpleCall) {
9436 llvm_unreachable("Not supported in SIMD-only mode");
9437}
9438
9439void CGOpenMPSIMDRuntime::emitForDispatchInit(
9440 CodeGenFunction &CGF, SourceLocation Loc,
9441 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
9442 bool Ordered, const DispatchRTInput &DispatchValues) {
9443 llvm_unreachable("Not supported in SIMD-only mode");
9444}
9445
9446void CGOpenMPSIMDRuntime::emitForStaticInit(
9447 CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind,
9448 const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values) {
9449 llvm_unreachable("Not supported in SIMD-only mode");
9450}
9451
9452void CGOpenMPSIMDRuntime::emitDistributeStaticInit(
9453 CodeGenFunction &CGF, SourceLocation Loc,
9454 OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values) {
9455 llvm_unreachable("Not supported in SIMD-only mode");
9456}
9457
9458void CGOpenMPSIMDRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
9459 SourceLocation Loc,
9460 unsigned IVSize,
9461 bool IVSigned) {
9462 llvm_unreachable("Not supported in SIMD-only mode");
9463}
9464
9465void CGOpenMPSIMDRuntime::emitForStaticFinish(CodeGenFunction &CGF,
9466 SourceLocation Loc,
9467 OpenMPDirectiveKind DKind) {
9468 llvm_unreachable("Not supported in SIMD-only mode");
9469}
9470
9471llvm::Value *CGOpenMPSIMDRuntime::emitForNext(CodeGenFunction &CGF,
9472 SourceLocation Loc,
9473 unsigned IVSize, bool IVSigned,
9474 Address IL, Address LB,
9475 Address UB, Address ST) {
9476 llvm_unreachable("Not supported in SIMD-only mode");
9477}
9478
9479void CGOpenMPSIMDRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
9480 llvm::Value *NumThreads,
9481 SourceLocation Loc) {
9482 llvm_unreachable("Not supported in SIMD-only mode");
9483}
9484
9485void CGOpenMPSIMDRuntime::emitProcBindClause(CodeGenFunction &CGF,
9486 OpenMPProcBindClauseKind ProcBind,
9487 SourceLocation Loc) {
9488 llvm_unreachable("Not supported in SIMD-only mode");
9489}
9490
9491Address CGOpenMPSIMDRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
9492 const VarDecl *VD,
9493 Address VDAddr,
9494 SourceLocation Loc) {
9495 llvm_unreachable("Not supported in SIMD-only mode");
9496}
9497
9498llvm::Function *CGOpenMPSIMDRuntime::emitThreadPrivateVarDefinition(
9499 const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit,
9500 CodeGenFunction *CGF) {
9501 llvm_unreachable("Not supported in SIMD-only mode");
9502}
9503
9504Address CGOpenMPSIMDRuntime::getAddrOfArtificialThreadPrivate(
9505 CodeGenFunction &CGF, QualType VarType, StringRef Name) {
9506 llvm_unreachable("Not supported in SIMD-only mode");
9507}
9508
9509void CGOpenMPSIMDRuntime::emitFlush(CodeGenFunction &CGF,
9510 ArrayRef<const Expr *> Vars,
9511 SourceLocation Loc) {
9512 llvm_unreachable("Not supported in SIMD-only mode");
9513}
9514
9515void CGOpenMPSIMDRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
9516 const OMPExecutableDirective &D,
9517 llvm::Value *TaskFunction,
9518 QualType SharedsTy, Address Shareds,
9519 const Expr *IfCond,
9520 const OMPTaskDataTy &Data) {
9521 llvm_unreachable("Not supported in SIMD-only mode");
9522}
9523
9524void CGOpenMPSIMDRuntime::emitTaskLoopCall(
9525 CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D,
9526 llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
9527 const Expr *IfCond, const OMPTaskDataTy &Data) {
9528 llvm_unreachable("Not supported in SIMD-only mode");
9529}
9530
9531void CGOpenMPSIMDRuntime::emitReduction(
9532 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
9533 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
9534 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
9535 assert(Options.SimpleReduction && "Only simple reduction is expected.");
9536 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
9537 ReductionOps, Options);
9538}
9539
9540llvm::Value *CGOpenMPSIMDRuntime::emitTaskReductionInit(
9541 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
9542 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
9543 llvm_unreachable("Not supported in SIMD-only mode");
9544}
9545
9546void CGOpenMPSIMDRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
9547 SourceLocation Loc,
9548 ReductionCodeGen &RCG,
9549 unsigned N) {
9550 llvm_unreachable("Not supported in SIMD-only mode");
9551}
9552
9553Address CGOpenMPSIMDRuntime::getTaskReductionItem(CodeGenFunction &CGF,
9554 SourceLocation Loc,
9555 llvm::Value *ReductionsPtr,
9556 LValue SharedLVal) {
9557 llvm_unreachable("Not supported in SIMD-only mode");
9558}
9559
9560void CGOpenMPSIMDRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
9561 SourceLocation Loc) {
9562 llvm_unreachable("Not supported in SIMD-only mode");
9563}
9564
9565void CGOpenMPSIMDRuntime::emitCancellationPointCall(
9566 CodeGenFunction &CGF, SourceLocation Loc,
9567 OpenMPDirectiveKind CancelRegion) {
9568 llvm_unreachable("Not supported in SIMD-only mode");
9569}
9570
9571void CGOpenMPSIMDRuntime::emitCancelCall(CodeGenFunction &CGF,
9572 SourceLocation Loc, const Expr *IfCond,
9573 OpenMPDirectiveKind CancelRegion) {
9574 llvm_unreachable("Not supported in SIMD-only mode");
9575}
9576
9577void CGOpenMPSIMDRuntime::emitTargetOutlinedFunction(
9578 const OMPExecutableDirective &D, StringRef ParentName,
9579 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
9580 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
9581 llvm_unreachable("Not supported in SIMD-only mode");
9582}
9583
9584void CGOpenMPSIMDRuntime::emitTargetCall(CodeGenFunction &CGF,
9585 const OMPExecutableDirective &D,
9586 llvm::Value *OutlinedFn,
9587 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00009588 const Expr *IfCond, const Expr *Device) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009589 llvm_unreachable("Not supported in SIMD-only mode");
9590}
9591
9592bool CGOpenMPSIMDRuntime::emitTargetFunctions(GlobalDecl GD) {
9593 llvm_unreachable("Not supported in SIMD-only mode");
9594}
9595
9596bool CGOpenMPSIMDRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
9597 llvm_unreachable("Not supported in SIMD-only mode");
9598}
9599
9600bool CGOpenMPSIMDRuntime::emitTargetGlobal(GlobalDecl GD) {
9601 return false;
9602}
9603
9604llvm::Function *CGOpenMPSIMDRuntime::emitRegistrationFunction() {
9605 return nullptr;
9606}
9607
9608void CGOpenMPSIMDRuntime::emitTeamsCall(CodeGenFunction &CGF,
9609 const OMPExecutableDirective &D,
9610 SourceLocation Loc,
9611 llvm::Value *OutlinedFn,
9612 ArrayRef<llvm::Value *> CapturedVars) {
9613 llvm_unreachable("Not supported in SIMD-only mode");
9614}
9615
9616void CGOpenMPSIMDRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
9617 const Expr *NumTeams,
9618 const Expr *ThreadLimit,
9619 SourceLocation Loc) {
9620 llvm_unreachable("Not supported in SIMD-only mode");
9621}
9622
9623void CGOpenMPSIMDRuntime::emitTargetDataCalls(
9624 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
9625 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
9626 llvm_unreachable("Not supported in SIMD-only mode");
9627}
9628
9629void CGOpenMPSIMDRuntime::emitTargetDataStandAloneCall(
9630 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
9631 const Expr *Device) {
9632 llvm_unreachable("Not supported in SIMD-only mode");
9633}
9634
9635void CGOpenMPSIMDRuntime::emitDoacrossInit(CodeGenFunction &CGF,
Alexey Bataevf138fda2018-08-13 19:04:24 +00009636 const OMPLoopDirective &D,
9637 ArrayRef<Expr *> NumIterations) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009638 llvm_unreachable("Not supported in SIMD-only mode");
9639}
9640
9641void CGOpenMPSIMDRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
9642 const OMPDependClause *C) {
9643 llvm_unreachable("Not supported in SIMD-only mode");
9644}
9645
9646const VarDecl *
9647CGOpenMPSIMDRuntime::translateParameter(const FieldDecl *FD,
9648 const VarDecl *NativeParam) const {
9649 llvm_unreachable("Not supported in SIMD-only mode");
9650}
9651
9652Address
9653CGOpenMPSIMDRuntime::getParameterAddress(CodeGenFunction &CGF,
9654 const VarDecl *NativeParam,
9655 const VarDecl *TargetParam) const {
9656 llvm_unreachable("Not supported in SIMD-only mode");
9657}
9658