blob: 81760938406b4cb727b621a37af7a1de6c608f26 [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
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000356 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(VD),
Samuel Antaob68e2db2016-03-03 16:20:23 +0000357 /*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 Bataevc3028ca2018-12-04 15:03:25 +00003217unsigned CGOpenMPRuntime::getDefaultFlagsForBarriers(OpenMPDirectiveKind Kind) {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003218 unsigned Flags;
3219 if (Kind == OMPD_for)
3220 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
3221 else if (Kind == OMPD_sections)
3222 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
3223 else if (Kind == OMPD_single)
3224 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
3225 else if (Kind == OMPD_barrier)
3226 Flags = OMP_IDENT_BARRIER_EXPL;
3227 else
3228 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataevc3028ca2018-12-04 15:03:25 +00003229 return Flags;
3230}
3231
3232void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
3233 OpenMPDirectiveKind Kind, bool EmitChecks,
3234 bool ForceSimpleCall) {
3235 if (!CGF.HaveInsertPoint())
3236 return;
3237 // Build call __kmpc_cancel_barrier(loc, thread_id);
3238 // Build call __kmpc_barrier(loc, thread_id);
3239 unsigned Flags = getDefaultFlagsForBarriers(Kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003240 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
3241 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003242 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
3243 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003244 if (auto *OMPRegionInfo =
3245 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00003246 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003247 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003248 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00003249 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003250 // if (__kmpc_cancel_barrier()) {
3251 // exit from construct;
3252 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003253 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
3254 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
3255 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003256 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
3257 CGF.EmitBlock(ExitBB);
3258 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003259 CodeGenFunction::JumpDest CancelDestination =
Alexey Bataev25e5b442015-09-15 12:52:43 +00003260 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003261 CGF.EmitBranchThroughCleanup(CancelDestination);
3262 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
3263 }
3264 return;
3265 }
3266 }
3267 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00003268}
3269
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003270/// Map the OpenMP loop schedule to the runtime enumeration.
Alexander Musmanc6388682014-12-15 07:07:06 +00003271static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003272 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003273 switch (ScheduleKind) {
3274 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003275 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
3276 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00003277 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003278 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003279 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003280 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003281 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003282 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
3283 case OMPC_SCHEDULE_auto:
3284 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00003285 case OMPC_SCHEDULE_unknown:
3286 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003287 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00003288 }
3289 llvm_unreachable("Unexpected runtime schedule");
3290}
3291
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003292/// Map the OpenMP distribute schedule to the runtime enumeration.
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003293static OpenMPSchedType
3294getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
3295 // only static is allowed for dist_schedule
3296 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
3297}
3298
Alexander Musmanc6388682014-12-15 07:07:06 +00003299bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
3300 bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003301 OpenMPSchedType Schedule =
3302 getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00003303 return Schedule == OMP_sch_static;
3304}
3305
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003306bool CGOpenMPRuntime::isStaticNonchunked(
3307 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003308 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003309 return Schedule == OMP_dist_sch_static;
3310}
3311
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003312bool CGOpenMPRuntime::isStaticChunked(OpenMPScheduleClauseKind ScheduleKind,
3313 bool Chunked) const {
3314 OpenMPSchedType Schedule =
3315 getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
3316 return Schedule == OMP_sch_static_chunked;
3317}
3318
3319bool CGOpenMPRuntime::isStaticChunked(
3320 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
3321 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
3322 return Schedule == OMP_dist_sch_static_chunked;
3323}
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003324
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003325bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003326 OpenMPSchedType Schedule =
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003327 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003328 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
3329 return Schedule != OMP_sch_static;
3330}
3331
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003332static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
3333 OpenMPScheduleClauseModifier M1,
3334 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00003335 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003336 switch (M1) {
3337 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003338 Modifier = OMP_sch_modifier_monotonic;
3339 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003340 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003341 Modifier = OMP_sch_modifier_nonmonotonic;
3342 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003343 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003344 if (Schedule == OMP_sch_static_chunked)
3345 Schedule = OMP_sch_static_balanced_chunked;
3346 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003347 case OMPC_SCHEDULE_MODIFIER_last:
3348 case OMPC_SCHEDULE_MODIFIER_unknown:
3349 break;
3350 }
3351 switch (M2) {
3352 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003353 Modifier = OMP_sch_modifier_monotonic;
3354 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003355 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003356 Modifier = OMP_sch_modifier_nonmonotonic;
3357 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003358 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003359 if (Schedule == OMP_sch_static_chunked)
3360 Schedule = OMP_sch_static_balanced_chunked;
3361 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003362 case OMPC_SCHEDULE_MODIFIER_last:
3363 case OMPC_SCHEDULE_MODIFIER_unknown:
3364 break;
3365 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00003366 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003367}
3368
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003369void CGOpenMPRuntime::emitForDispatchInit(
3370 CodeGenFunction &CGF, SourceLocation Loc,
3371 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
3372 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003373 if (!CGF.HaveInsertPoint())
3374 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003375 OpenMPSchedType Schedule = getRuntimeSchedule(
3376 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00003377 assert(Ordered ||
3378 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00003379 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
3380 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00003381 // Call __kmpc_dispatch_init(
3382 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
3383 // kmp_int[32|64] lower, kmp_int[32|64] upper,
3384 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00003385
John McCall7f416cc2015-09-08 08:05:57 +00003386 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003387 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
3388 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00003389 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003390 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3391 CGF.Builder.getInt32(addMonoNonMonoModifier(
3392 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003393 DispatchValues.LB, // Lower
3394 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003395 CGF.Builder.getIntN(IVSize, 1), // Stride
3396 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00003397 };
3398 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
3399}
3400
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003401static void emitForStaticInitCall(
3402 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
3403 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
3404 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003405 const CGOpenMPRuntime::StaticRTInput &Values) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003406 if (!CGF.HaveInsertPoint())
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003407 return;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003408
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003409 assert(!Values.Ordered);
3410 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
3411 Schedule == OMP_sch_static_balanced_chunked ||
3412 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
3413 Schedule == OMP_dist_sch_static ||
3414 Schedule == OMP_dist_sch_static_chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003415
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003416 // Call __kmpc_for_static_init(
3417 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
3418 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
3419 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
3420 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
3421 llvm::Value *Chunk = Values.Chunk;
3422 if (Chunk == nullptr) {
3423 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
3424 Schedule == OMP_dist_sch_static) &&
3425 "expected static non-chunked schedule");
3426 // If the Chunk was not specified in the clause - use default value 1.
3427 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3428 } else {
3429 assert((Schedule == OMP_sch_static_chunked ||
3430 Schedule == OMP_sch_static_balanced_chunked ||
3431 Schedule == OMP_ord_static_chunked ||
3432 Schedule == OMP_dist_sch_static_chunked) &&
3433 "expected static chunked schedule");
3434 }
3435 llvm::Value *Args[] = {
3436 UpdateLocation,
3437 ThreadId,
3438 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3439 M2)), // Schedule type
3440 Values.IL.getPointer(), // &isLastIter
3441 Values.LB.getPointer(), // &LB
3442 Values.UB.getPointer(), // &UB
3443 Values.ST.getPointer(), // &Stride
3444 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3445 Chunk // Chunk
3446 };
3447 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003448}
3449
John McCall7f416cc2015-09-08 08:05:57 +00003450void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3451 SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003452 OpenMPDirectiveKind DKind,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003453 const OpenMPScheduleTy &ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003454 const StaticRTInput &Values) {
3455 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3456 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3457 assert(isOpenMPWorksharingDirective(DKind) &&
3458 "Expected loop-based or sections-based directive.");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003459 llvm::Value *UpdatedLocation = emitUpdateLocation(CGF, Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003460 isOpenMPLoopDirective(DKind)
3461 ? OMP_IDENT_WORK_LOOP
3462 : OMP_IDENT_WORK_SECTIONS);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003463 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3464 llvm::Constant *StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003465 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003466 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003467 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003468}
John McCall7f416cc2015-09-08 08:05:57 +00003469
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003470void CGOpenMPRuntime::emitDistributeStaticInit(
3471 CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003472 OpenMPDistScheduleClauseKind SchedKind,
3473 const CGOpenMPRuntime::StaticRTInput &Values) {
3474 OpenMPSchedType ScheduleNum =
3475 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003476 llvm::Value *UpdatedLocation =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003477 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003478 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3479 llvm::Constant *StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003480 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003481 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3482 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003483 OMPC_SCHEDULE_MODIFIER_unknown, Values);
Alexander Musmanc6388682014-12-15 07:07:06 +00003484}
3485
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003486void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
Alexey Bataevf43f7142017-09-06 16:17:35 +00003487 SourceLocation Loc,
3488 OpenMPDirectiveKind DKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003489 if (!CGF.HaveInsertPoint())
3490 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003491 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataevf43f7142017-09-06 16:17:35 +00003492 llvm::Value *Args[] = {
3493 emitUpdateLocation(CGF, Loc,
3494 isOpenMPDistributeDirective(DKind)
3495 ? OMP_IDENT_WORK_DISTRIBUTE
3496 : isOpenMPLoopDirective(DKind)
3497 ? OMP_IDENT_WORK_LOOP
3498 : OMP_IDENT_WORK_SECTIONS),
3499 getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003500 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3501 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003502}
3503
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003504void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3505 SourceLocation Loc,
3506 unsigned IVSize,
3507 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003508 if (!CGF.HaveInsertPoint())
3509 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003510 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003511 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003512 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3513}
3514
Alexander Musman92bdaab2015-03-12 13:37:50 +00003515llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3516 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003517 bool IVSigned, Address IL,
3518 Address LB, Address UB,
3519 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003520 // Call __kmpc_dispatch_next(
3521 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3522 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3523 // kmp_int[32|64] *p_stride);
3524 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003525 emitUpdateLocation(CGF, Loc),
3526 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003527 IL.getPointer(), // &isLastIter
3528 LB.getPointer(), // &Lower
3529 UB.getPointer(), // &Upper
3530 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003531 };
3532 llvm::Value *Call =
3533 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3534 return CGF.EmitScalarConversion(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003535 Call, CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/1),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003536 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003537}
3538
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003539void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3540 llvm::Value *NumThreads,
3541 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003542 if (!CGF.HaveInsertPoint())
3543 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003544 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3545 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003546 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003547 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003548 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3549 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003550}
3551
Alexey Bataev7f210c62015-06-18 13:40:03 +00003552void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3553 OpenMPProcBindClauseKind ProcBind,
3554 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003555 if (!CGF.HaveInsertPoint())
3556 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003557 // Constants for proc bind value accepted by the runtime.
3558 enum ProcBindTy {
3559 ProcBindFalse = 0,
3560 ProcBindTrue,
3561 ProcBindMaster,
3562 ProcBindClose,
3563 ProcBindSpread,
3564 ProcBindIntel,
3565 ProcBindDefault
3566 } RuntimeProcBind;
3567 switch (ProcBind) {
3568 case OMPC_PROC_BIND_master:
3569 RuntimeProcBind = ProcBindMaster;
3570 break;
3571 case OMPC_PROC_BIND_close:
3572 RuntimeProcBind = ProcBindClose;
3573 break;
3574 case OMPC_PROC_BIND_spread:
3575 RuntimeProcBind = ProcBindSpread;
3576 break;
3577 case OMPC_PROC_BIND_unknown:
3578 llvm_unreachable("Unsupported proc_bind value.");
3579 }
3580 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3581 llvm::Value *Args[] = {
3582 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3583 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3584 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3585}
3586
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003587void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3588 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003589 if (!CGF.HaveInsertPoint())
3590 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003591 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003592 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3593 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003594}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003595
Alexey Bataev62b63b12015-03-10 07:28:44 +00003596namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003597/// Indexes of fields for type kmp_task_t.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003598enum KmpTaskTFields {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003599 /// List of shared variables.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003600 KmpTaskTShareds,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003601 /// Task routine.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003602 KmpTaskTRoutine,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003603 /// Partition id for the untied tasks.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003604 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003605 /// Function with call of destructors for private variables.
3606 Data1,
3607 /// Task priority.
3608 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003609 /// (Taskloops only) Lower bound.
3610 KmpTaskTLowerBound,
3611 /// (Taskloops only) Upper bound.
3612 KmpTaskTUpperBound,
3613 /// (Taskloops only) Stride.
3614 KmpTaskTStride,
3615 /// (Taskloops only) Is last iteration flag.
3616 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003617 /// (Taskloops only) Reduction data.
3618 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003619};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003620} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003621
Samuel Antaoee8fb302016-01-06 13:42:12 +00003622bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003623 return OffloadEntriesTargetRegion.empty() &&
3624 OffloadEntriesDeviceGlobalVar.empty();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003625}
3626
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003627/// Initialize target region entry.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003628void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3629 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3630 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003631 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003632 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3633 "only required for the device "
3634 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003635 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003636 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003637 OMPTargetRegionEntryTargetRegion);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003638 ++OffloadingEntriesNum;
3639}
3640
3641void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3642 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3643 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003644 llvm::Constant *Addr, llvm::Constant *ID,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003645 OMPTargetRegionEntryKind Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003646 // If we are emitting code for a target, the entry is already initialized,
3647 // only has to be registered.
3648 if (CGM.getLangOpts().OpenMPIsDevice) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00003649 if (!hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum)) {
3650 unsigned DiagID = CGM.getDiags().getCustomDiagID(
3651 DiagnosticsEngine::Error,
3652 "Unable to find target region on line '%0' in the device code.");
3653 CGM.getDiags().Report(DiagID) << LineNum;
3654 return;
3655 }
Samuel Antao2de62b02016-02-13 23:35:10 +00003656 auto &Entry =
3657 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003658 assert(Entry.isValid() && "Entry not initialized!");
3659 Entry.setAddress(Addr);
3660 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003661 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003662 } else {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003663 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003664 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00003665 ++OffloadingEntriesNum;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003666 }
3667}
3668
3669bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003670 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3671 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003672 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3673 if (PerDevice == OffloadEntriesTargetRegion.end())
3674 return false;
3675 auto PerFile = PerDevice->second.find(FileID);
3676 if (PerFile == PerDevice->second.end())
3677 return false;
3678 auto PerParentName = PerFile->second.find(ParentName);
3679 if (PerParentName == PerFile->second.end())
3680 return false;
3681 auto PerLine = PerParentName->second.find(LineNum);
3682 if (PerLine == PerParentName->second.end())
3683 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003684 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003685 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003686 return false;
3687 return true;
3688}
3689
3690void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3691 const OffloadTargetRegionEntryInfoActTy &Action) {
3692 // Scan all target region entries and perform the provided action.
Alexey Bataev03f270c2018-03-30 18:31:07 +00003693 for (const auto &D : OffloadEntriesTargetRegion)
3694 for (const auto &F : D.second)
3695 for (const auto &P : F.second)
3696 for (const auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003697 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003698}
3699
Alexey Bataev03f270c2018-03-30 18:31:07 +00003700void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3701 initializeDeviceGlobalVarEntryInfo(StringRef Name,
3702 OMPTargetGlobalVarEntryKind Flags,
3703 unsigned Order) {
3704 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3705 "only required for the device "
3706 "code generation.");
3707 OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags);
3708 ++OffloadingEntriesNum;
3709}
Samuel Antaoee8fb302016-01-06 13:42:12 +00003710
Alexey Bataev03f270c2018-03-30 18:31:07 +00003711void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3712 registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr,
3713 CharUnits VarSize,
3714 OMPTargetGlobalVarEntryKind Flags,
3715 llvm::GlobalValue::LinkageTypes Linkage) {
3716 if (CGM.getLangOpts().OpenMPIsDevice) {
3717 auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
3718 assert(Entry.isValid() && Entry.getFlags() == Flags &&
3719 "Entry not initialized!");
3720 assert((!Entry.getAddress() || Entry.getAddress() == Addr) &&
3721 "Resetting with the new address.");
3722 if (Entry.getAddress() && hasDeviceGlobalVarEntryInfo(VarName))
3723 return;
3724 Entry.setAddress(Addr);
3725 Entry.setVarSize(VarSize);
3726 Entry.setLinkage(Linkage);
3727 } else {
3728 if (hasDeviceGlobalVarEntryInfo(VarName))
3729 return;
3730 OffloadEntriesDeviceGlobalVar.try_emplace(
3731 VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage);
3732 ++OffloadingEntriesNum;
3733 }
3734}
3735
3736void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3737 actOnDeviceGlobalVarEntriesInfo(
3738 const OffloadDeviceGlobalVarEntryInfoActTy &Action) {
3739 // Scan all target region entries and perform the provided action.
3740 for (const auto &E : OffloadEntriesDeviceGlobalVar)
3741 Action(E.getKey(), E.getValue());
Samuel Antaoee8fb302016-01-06 13:42:12 +00003742}
3743
3744llvm::Function *
3745CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003746 // If we don't have entries or if we are emitting code for the device, we
3747 // don't need to do anything.
3748 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3749 return nullptr;
3750
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003751 llvm::Module &M = CGM.getModule();
3752 ASTContext &C = CGM.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003753
3754 // Get list of devices we care about
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003755 const std::vector<llvm::Triple> &Devices = CGM.getLangOpts().OMPTargetTriples;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003756
3757 // We should be creating an offloading descriptor only if there are devices
3758 // specified.
3759 assert(!Devices.empty() && "No OpenMP offloading devices??");
3760
3761 // Create the external variables that will point to the begin and end of the
3762 // host entries section. These will be defined by the linker.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003763 llvm::Type *OffloadEntryTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00003764 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
Alexey Bataev18fa2322018-05-02 14:20:50 +00003765 std::string EntriesBeginName = getName({"omp_offloading", "entries_begin"});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003766 auto *HostEntriesBegin = new llvm::GlobalVariable(
Samuel Antaoee8fb302016-01-06 13:42:12 +00003767 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003768 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003769 EntriesBeginName);
3770 std::string EntriesEndName = getName({"omp_offloading", "entries_end"});
3771 auto *HostEntriesEnd =
3772 new llvm::GlobalVariable(M, OffloadEntryTy, /*isConstant=*/true,
3773 llvm::GlobalValue::ExternalLinkage,
3774 /*Initializer=*/nullptr, EntriesEndName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003775
3776 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003777 auto *DeviceImageTy = cast<llvm::StructType>(
3778 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003779 ConstantInitBuilder DeviceImagesBuilder(CGM);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003780 ConstantArrayBuilder DeviceImagesEntries =
3781 DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003782
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003783 for (const llvm::Triple &Device : Devices) {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003784 StringRef T = Device.getTriple();
Alexey Bataev18fa2322018-05-02 14:20:50 +00003785 std::string BeginName = getName({"omp_offloading", "img_start", ""});
Samuel Antaoee8fb302016-01-06 13:42:12 +00003786 auto *ImgBegin = 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(BeginName).concat(T));
3790 std::string EndName = getName({"omp_offloading", "img_end", ""});
Samuel Antaoee8fb302016-01-06 13:42:12 +00003791 auto *ImgEnd = new llvm::GlobalVariable(
Alexey Bataev62a4cb02018-07-31 18:27:42 +00003792 M, CGM.Int8Ty, /*isConstant=*/true,
3793 llvm::GlobalValue::ExternalWeakLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003794 /*Initializer=*/nullptr, Twine(EndName).concat(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003795
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003796 llvm::Constant *Data[] = {ImgBegin, ImgEnd, HostEntriesBegin,
3797 HostEntriesEnd};
3798 createConstantGlobalStructAndAddToParent(CGM, getTgtDeviceImageQTy(), Data,
3799 DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003800 }
3801
3802 // Create device images global array.
Alexey Bataev18fa2322018-05-02 14:20:50 +00003803 std::string ImagesName = getName({"omp_offloading", "device_images"});
John McCall6c9f1fdb2016-11-19 08:17:24 +00003804 llvm::GlobalVariable *DeviceImages =
Alexey Bataev18fa2322018-05-02 14:20:50 +00003805 DeviceImagesEntries.finishAndCreateGlobal(ImagesName,
3806 CGM.getPointerAlign(),
3807 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003808 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003809
3810 // This is a Zero array to be used in the creation of the constant expressions
3811 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3812 llvm::Constant::getNullValue(CGM.Int32Ty)};
3813
3814 // Create the target region descriptor.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003815 llvm::Constant *Data[] = {
3816 llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
3817 llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3818 DeviceImages, Index),
3819 HostEntriesBegin, HostEntriesEnd};
Alexey Bataev18fa2322018-05-02 14:20:50 +00003820 std::string Descriptor = getName({"omp_offloading", "descriptor"});
Mike Ricee1ca7b62018-08-29 15:45:11 +00003821 llvm::GlobalVariable *Desc = createGlobalStruct(
3822 CGM, getTgtBinaryDescriptorQTy(), /*IsConstant=*/true, Data, Descriptor);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003823
3824 // Emit code to register or unregister the descriptor at execution
3825 // startup or closing, respectively.
3826
Alexey Bataev03f270c2018-03-30 18:31:07 +00003827 llvm::Function *UnRegFn;
3828 {
3829 FunctionArgList Args;
3830 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
3831 Args.push_back(&DummyPtr);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003832
Alexey Bataev03f270c2018-03-30 18:31:07 +00003833 CodeGenFunction CGF(CGM);
3834 // Disable debug info for global (de-)initializer because they are not part
3835 // of some particular construct.
3836 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003837 const auto &FI =
3838 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3839 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003840 std::string UnregName = getName({"omp_offloading", "descriptor_unreg"});
3841 UnRegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, UnregName, FI);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003842 CGF.StartFunction(GlobalDecl(), C.VoidTy, UnRegFn, FI, Args);
3843 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3844 Desc);
3845 CGF.FinishFunction();
3846 }
3847 llvm::Function *RegFn;
3848 {
3849 CodeGenFunction CGF(CGM);
3850 // Disable debug info for global (de-)initializer because they are not part
3851 // of some particular construct.
3852 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003853 const auto &FI = CGM.getTypes().arrangeNullaryFunction();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003854 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Sergey Dmitrievbde9cf92018-08-03 20:19:28 +00003855
3856 // Encode offload target triples into the registration function name. It
3857 // will serve as a comdat key for the registration/unregistration code for
3858 // this particular combination of offloading targets.
3859 SmallVector<StringRef, 4U> RegFnNameParts(Devices.size() + 2U);
3860 RegFnNameParts[0] = "omp_offloading";
3861 RegFnNameParts[1] = "descriptor_reg";
3862 llvm::transform(Devices, std::next(RegFnNameParts.begin(), 2),
3863 [](const llvm::Triple &T) -> const std::string& {
3864 return T.getTriple();
3865 });
3866 llvm::sort(std::next(RegFnNameParts.begin(), 2), RegFnNameParts.end());
3867 std::string Descriptor = getName(RegFnNameParts);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003868 RegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, Descriptor, FI);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003869 CGF.StartFunction(GlobalDecl(), C.VoidTy, RegFn, FI, FunctionArgList());
3870 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib), Desc);
3871 // Create a variable to drive the registration and unregistration of the
3872 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3873 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(),
3874 SourceLocation(), nullptr, C.CharTy,
3875 ImplicitParamDecl::Other);
3876 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3877 CGF.FinishFunction();
3878 }
George Rokos29d0f002017-05-27 03:03:13 +00003879 if (CGM.supportsCOMDAT()) {
3880 // It is sufficient to call registration function only once, so create a
3881 // COMDAT group for registration/unregistration functions and associated
3882 // data. That would reduce startup time and code size. Registration
3883 // function serves as a COMDAT group key.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003884 llvm::Comdat *ComdatKey = M.getOrInsertComdat(RegFn->getName());
George Rokos29d0f002017-05-27 03:03:13 +00003885 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3886 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3887 RegFn->setComdat(ComdatKey);
3888 UnRegFn->setComdat(ComdatKey);
3889 DeviceImages->setComdat(ComdatKey);
3890 Desc->setComdat(ComdatKey);
3891 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003892 return RegFn;
3893}
3894
Alexey Bataev03f270c2018-03-30 18:31:07 +00003895void CGOpenMPRuntime::createOffloadEntry(
3896 llvm::Constant *ID, llvm::Constant *Addr, uint64_t Size, int32_t Flags,
3897 llvm::GlobalValue::LinkageTypes Linkage) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003898 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003899 llvm::Module &M = CGM.getModule();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003900 llvm::LLVMContext &C = M.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003901
3902 // Create constant string with the name.
3903 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3904
Alexey Bataev18fa2322018-05-02 14:20:50 +00003905 std::string StringName = getName({"omp_offloading", "entry_name"});
3906 auto *Str = new llvm::GlobalVariable(
3907 M, StrPtrInit->getType(), /*isConstant=*/true,
3908 llvm::GlobalValue::InternalLinkage, StrPtrInit, StringName);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003909 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003910
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003911 llvm::Constant *Data[] = {llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy),
3912 llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy),
3913 llvm::ConstantInt::get(CGM.SizeTy, Size),
3914 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
3915 llvm::ConstantInt::get(CGM.Int32Ty, 0)};
Alexey Bataev18fa2322018-05-02 14:20:50 +00003916 std::string EntryName = getName({"omp_offloading", "entry", ""});
Mike Ricee1ca7b62018-08-29 15:45:11 +00003917 llvm::GlobalVariable *Entry = createGlobalStruct(
3918 CGM, getTgtOffloadEntryQTy(), /*IsConstant=*/true, Data,
3919 Twine(EntryName).concat(Name), llvm::GlobalValue::WeakAnyLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003920
3921 // The entry has to be created in the section the linker expects it to be.
Alexey Bataev18fa2322018-05-02 14:20:50 +00003922 std::string Section = getName({"omp_offloading", "entries"});
3923 Entry->setSection(Section);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003924}
3925
3926void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3927 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003928 // can easily figure out what to emit. The produced metadata looks like
3929 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003930 //
3931 // !omp_offload.info = !{!1, ...}
3932 //
3933 // Right now we only generate metadata for function that contain target
3934 // regions.
3935
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003936 // If we do not have entries, we don't need to do anything.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003937 if (OffloadEntriesInfoManager.empty())
3938 return;
3939
3940 llvm::Module &M = CGM.getModule();
3941 llvm::LLVMContext &C = M.getContext();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003942 SmallVector<const OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
Samuel Antaoee8fb302016-01-06 13:42:12 +00003943 OrderedEntries(OffloadEntriesInfoManager.size());
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00003944 llvm::SmallVector<StringRef, 16> ParentFunctions(
3945 OffloadEntriesInfoManager.size());
Samuel Antaoee8fb302016-01-06 13:42:12 +00003946
Simon Pilgrim2c518802017-03-30 14:13:19 +00003947 // Auxiliary methods to create metadata values and strings.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003948 auto &&GetMDInt = [this](unsigned V) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003949 return llvm::ConstantAsMetadata::get(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003950 llvm::ConstantInt::get(CGM.Int32Ty, V));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003951 };
3952
Alexey Bataev03f270c2018-03-30 18:31:07 +00003953 auto &&GetMDString = [&C](StringRef V) { return llvm::MDString::get(C, V); };
3954
3955 // Create the offloading info metadata node.
3956 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003957
3958 // Create function that emits metadata for each target region entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00003959 auto &&TargetRegionMetadataEmitter =
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00003960 [&C, MD, &OrderedEntries, &ParentFunctions, &GetMDInt, &GetMDString](
Alexey Bataev03f270c2018-03-30 18:31:07 +00003961 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3962 unsigned Line,
3963 const OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3964 // Generate metadata for target regions. Each entry of this metadata
3965 // contains:
3966 // - Entry 0 -> Kind of this type of metadata (0).
3967 // - Entry 1 -> Device ID of the file where the entry was identified.
3968 // - Entry 2 -> File ID of the file where the entry was identified.
3969 // - Entry 3 -> Mangled name of the function where the entry was
3970 // identified.
3971 // - Entry 4 -> Line in the file where the entry was identified.
3972 // - Entry 5 -> Order the entry was created.
3973 // The first element of the metadata node is the kind.
3974 llvm::Metadata *Ops[] = {GetMDInt(E.getKind()), GetMDInt(DeviceID),
3975 GetMDInt(FileID), GetMDString(ParentName),
3976 GetMDInt(Line), GetMDInt(E.getOrder())};
Samuel Antaoee8fb302016-01-06 13:42:12 +00003977
Alexey Bataev03f270c2018-03-30 18:31:07 +00003978 // Save this entry in the right position of the ordered entries array.
3979 OrderedEntries[E.getOrder()] = &E;
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00003980 ParentFunctions[E.getOrder()] = ParentName;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003981
Alexey Bataev03f270c2018-03-30 18:31:07 +00003982 // Add metadata to the named metadata node.
3983 MD->addOperand(llvm::MDNode::get(C, Ops));
3984 };
Samuel Antaoee8fb302016-01-06 13:42:12 +00003985
3986 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3987 TargetRegionMetadataEmitter);
3988
Alexey Bataev03f270c2018-03-30 18:31:07 +00003989 // Create function that emits metadata for each device global variable entry;
3990 auto &&DeviceGlobalVarMetadataEmitter =
3991 [&C, &OrderedEntries, &GetMDInt, &GetMDString,
3992 MD](StringRef MangledName,
3993 const OffloadEntriesInfoManagerTy::OffloadEntryInfoDeviceGlobalVar
3994 &E) {
3995 // Generate metadata for global variables. Each entry of this metadata
3996 // contains:
3997 // - Entry 0 -> Kind of this type of metadata (1).
3998 // - Entry 1 -> Mangled name of the variable.
3999 // - Entry 2 -> Declare target kind.
4000 // - Entry 3 -> Order the entry was created.
4001 // The first element of the metadata node is the kind.
4002 llvm::Metadata *Ops[] = {
4003 GetMDInt(E.getKind()), GetMDString(MangledName),
4004 GetMDInt(E.getFlags()), GetMDInt(E.getOrder())};
4005
4006 // Save this entry in the right position of the ordered entries array.
4007 OrderedEntries[E.getOrder()] = &E;
4008
4009 // Add metadata to the named metadata node.
4010 MD->addOperand(llvm::MDNode::get(C, Ops));
4011 };
4012
4013 OffloadEntriesInfoManager.actOnDeviceGlobalVarEntriesInfo(
4014 DeviceGlobalVarMetadataEmitter);
4015
4016 for (const auto *E : OrderedEntries) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004017 assert(E && "All ordered entries must exist!");
Alexey Bataev03f270c2018-03-30 18:31:07 +00004018 if (const auto *CE =
Samuel Antaoee8fb302016-01-06 13:42:12 +00004019 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
4020 E)) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004021 if (!CE->getID() || !CE->getAddress()) {
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00004022 // Do not blame the entry if the parent funtion is not emitted.
4023 StringRef FnName = ParentFunctions[CE->getOrder()];
4024 if (!CGM.GetGlobalValue(FnName))
4025 continue;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004026 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4027 DiagnosticsEngine::Error,
Alexey Bataev7f01d202018-07-16 18:12:18 +00004028 "Offloading entry for target region is incorrect: either the "
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004029 "address or the ID is invalid.");
4030 CGM.getDiags().Report(DiagID);
4031 continue;
4032 }
Alexey Bataev34f8a702018-03-28 14:28:54 +00004033 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0,
Alexey Bataev03f270c2018-03-30 18:31:07 +00004034 CE->getFlags(), llvm::GlobalValue::WeakAnyLinkage);
4035 } else if (const auto *CE =
4036 dyn_cast<OffloadEntriesInfoManagerTy::
4037 OffloadEntryInfoDeviceGlobalVar>(E)) {
Alexey Bataevc52f01d2018-07-16 20:05:25 +00004038 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags =
4039 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
4040 CE->getFlags());
4041 switch (Flags) {
4042 case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo: {
4043 if (!CE->getAddress()) {
4044 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4045 DiagnosticsEngine::Error,
4046 "Offloading entry for declare target variable is incorrect: the "
4047 "address is invalid.");
4048 CGM.getDiags().Report(DiagID);
4049 continue;
4050 }
Alexey Bataevb4dd6d22018-08-29 20:41:37 +00004051 // The vaiable has no definition - no need to add the entry.
4052 if (CE->getVarSize().isZero())
4053 continue;
Alexey Bataevc52f01d2018-07-16 20:05:25 +00004054 break;
4055 }
4056 case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink:
4057 assert(((CGM.getLangOpts().OpenMPIsDevice && !CE->getAddress()) ||
4058 (!CGM.getLangOpts().OpenMPIsDevice && CE->getAddress())) &&
4059 "Declaret target link address is set.");
4060 if (CGM.getLangOpts().OpenMPIsDevice)
4061 continue;
4062 if (!CE->getAddress()) {
4063 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4064 DiagnosticsEngine::Error,
4065 "Offloading entry for declare target variable is incorrect: the "
4066 "address is invalid.");
4067 CGM.getDiags().Report(DiagID);
4068 continue;
4069 }
4070 break;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004071 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00004072 createOffloadEntry(CE->getAddress(), CE->getAddress(),
Alexey Bataevc52f01d2018-07-16 20:05:25 +00004073 CE->getVarSize().getQuantity(), Flags,
Alexey Bataev03f270c2018-03-30 18:31:07 +00004074 CE->getLinkage());
4075 } else {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004076 llvm_unreachable("Unsupported entry kind.");
Alexey Bataev03f270c2018-03-30 18:31:07 +00004077 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004078 }
4079}
4080
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004081/// Loads all the offload entries information from the host IR
Samuel Antaoee8fb302016-01-06 13:42:12 +00004082/// metadata.
4083void CGOpenMPRuntime::loadOffloadInfoMetadata() {
4084 // If we are in target mode, load the metadata from the host IR. This code has
4085 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
4086
4087 if (!CGM.getLangOpts().OpenMPIsDevice)
4088 return;
4089
4090 if (CGM.getLangOpts().OMPHostIRFile.empty())
4091 return;
4092
4093 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004094 if (auto EC = Buf.getError()) {
4095 CGM.getDiags().Report(diag::err_cannot_open_file)
4096 << CGM.getLangOpts().OMPHostIRFile << EC.message();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004097 return;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004098 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004099
4100 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00004101 auto ME = expectedToErrorOrAndEmitErrors(
4102 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004103
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004104 if (auto EC = ME.getError()) {
4105 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4106 DiagnosticsEngine::Error, "Unable to parse host IR file '%0':'%1'");
4107 CGM.getDiags().Report(DiagID)
4108 << CGM.getLangOpts().OMPHostIRFile << EC.message();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004109 return;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004110 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004111
4112 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
4113 if (!MD)
4114 return;
4115
George Burgess IV00f70bd2018-03-01 05:43:23 +00004116 for (llvm::MDNode *MN : MD->operands()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004117 auto &&GetMDInt = [MN](unsigned Idx) {
4118 auto *V = cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004119 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
4120 };
4121
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004122 auto &&GetMDString = [MN](unsigned Idx) {
4123 auto *V = cast<llvm::MDString>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004124 return V->getString();
4125 };
4126
Alexey Bataev03f270c2018-03-30 18:31:07 +00004127 switch (GetMDInt(0)) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004128 default:
4129 llvm_unreachable("Unexpected metadata!");
4130 break;
4131 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
Alexey Bataev34f8a702018-03-28 14:28:54 +00004132 OffloadingEntryInfoTargetRegion:
Samuel Antaoee8fb302016-01-06 13:42:12 +00004133 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
Alexey Bataev03f270c2018-03-30 18:31:07 +00004134 /*DeviceID=*/GetMDInt(1), /*FileID=*/GetMDInt(2),
4135 /*ParentName=*/GetMDString(3), /*Line=*/GetMDInt(4),
4136 /*Order=*/GetMDInt(5));
4137 break;
4138 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
4139 OffloadingEntryInfoDeviceGlobalVar:
4140 OffloadEntriesInfoManager.initializeDeviceGlobalVarEntryInfo(
4141 /*MangledName=*/GetMDString(1),
4142 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
4143 /*Flags=*/GetMDInt(2)),
4144 /*Order=*/GetMDInt(3));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004145 break;
4146 }
4147 }
4148}
4149
Alexey Bataev62b63b12015-03-10 07:28:44 +00004150void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
4151 if (!KmpRoutineEntryPtrTy) {
4152 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004153 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004154 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
4155 FunctionProtoType::ExtProtoInfo EPI;
4156 KmpRoutineEntryPtrQTy = C.getPointerType(
4157 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
4158 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
4159 }
4160}
4161
Samuel Antaoee8fb302016-01-06 13:42:12 +00004162QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004163 // Make sure the type of the entry is already created. This is the type we
4164 // have to create:
4165 // struct __tgt_offload_entry{
4166 // void *addr; // Pointer to the offload entry info.
4167 // // (function or global)
4168 // char *name; // Name of the function or global.
4169 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00004170 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
4171 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004172 // };
4173 if (TgtOffloadEntryQTy.isNull()) {
4174 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004175 RecordDecl *RD = C.buildImplicitRecord("__tgt_offload_entry");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004176 RD->startDefinition();
4177 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4178 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
4179 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00004180 addFieldToRecordDecl(
4181 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4182 addFieldToRecordDecl(
4183 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004184 RD->completeDefinition();
Jonas Hahnfeld5e4df282018-01-18 15:38:03 +00004185 RD->addAttr(PackedAttr::CreateImplicit(C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004186 TgtOffloadEntryQTy = C.getRecordType(RD);
4187 }
4188 return TgtOffloadEntryQTy;
4189}
4190
4191QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
4192 // These are the types we need to build:
4193 // struct __tgt_device_image{
4194 // void *ImageStart; // Pointer to the target code start.
4195 // void *ImageEnd; // Pointer to the target code end.
4196 // // We also add the host entries to the device image, as it may be useful
4197 // // for the target runtime to have access to that information.
4198 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
4199 // // the entries.
4200 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4201 // // entries (non inclusive).
4202 // };
4203 if (TgtDeviceImageQTy.isNull()) {
4204 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004205 RecordDecl *RD = C.buildImplicitRecord("__tgt_device_image");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004206 RD->startDefinition();
4207 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4208 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4209 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4210 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4211 RD->completeDefinition();
4212 TgtDeviceImageQTy = C.getRecordType(RD);
4213 }
4214 return TgtDeviceImageQTy;
4215}
4216
4217QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
4218 // struct __tgt_bin_desc{
4219 // int32_t NumDevices; // Number of devices supported.
4220 // __tgt_device_image *DeviceImages; // Arrays of device images
4221 // // (one per device).
4222 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
4223 // // entries.
4224 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4225 // // entries (non inclusive).
4226 // };
4227 if (TgtBinaryDescriptorQTy.isNull()) {
4228 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004229 RecordDecl *RD = C.buildImplicitRecord("__tgt_bin_desc");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004230 RD->startDefinition();
4231 addFieldToRecordDecl(
4232 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4233 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
4234 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4235 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4236 RD->completeDefinition();
4237 TgtBinaryDescriptorQTy = C.getRecordType(RD);
4238 }
4239 return TgtBinaryDescriptorQTy;
4240}
4241
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004242namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00004243struct PrivateHelpersTy {
4244 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
4245 const VarDecl *PrivateElemInit)
4246 : Original(Original), PrivateCopy(PrivateCopy),
4247 PrivateElemInit(PrivateElemInit) {}
4248 const VarDecl *Original;
4249 const VarDecl *PrivateCopy;
4250 const VarDecl *PrivateElemInit;
4251};
4252typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00004253} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004254
Alexey Bataev9e034042015-05-05 04:05:12 +00004255static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00004256createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004257 if (!Privates.empty()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004258 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004259 // Build struct .kmp_privates_t. {
4260 // /* private vars */
4261 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004262 RecordDecl *RD = C.buildImplicitRecord(".kmp_privates.t");
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004263 RD->startDefinition();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004264 for (const auto &Pair : Privates) {
4265 const VarDecl *VD = Pair.second.Original;
4266 QualType Type = VD->getType().getNonReferenceType();
4267 FieldDecl *FD = addFieldToRecordDecl(C, RD, Type);
Alexey Bataevc71a4092015-09-11 10:29:41 +00004268 if (VD->hasAttrs()) {
4269 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
4270 E(VD->getAttrs().end());
4271 I != E; ++I)
4272 FD->addAttr(*I);
4273 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004274 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004275 RD->completeDefinition();
4276 return RD;
4277 }
4278 return nullptr;
4279}
4280
Alexey Bataev9e034042015-05-05 04:05:12 +00004281static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00004282createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
4283 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004284 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004285 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004286 // Build struct kmp_task_t {
4287 // void * shareds;
4288 // kmp_routine_entry_t routine;
4289 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00004290 // kmp_cmplrdata_t data1;
4291 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00004292 // For taskloops additional fields:
4293 // kmp_uint64 lb;
4294 // kmp_uint64 ub;
4295 // kmp_int64 st;
4296 // kmp_int32 liter;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004297 // void * reductions;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004298 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004299 RecordDecl *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004300 UD->startDefinition();
4301 addFieldToRecordDecl(C, UD, KmpInt32Ty);
4302 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
4303 UD->completeDefinition();
4304 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004305 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t");
Alexey Bataev62b63b12015-03-10 07:28:44 +00004306 RD->startDefinition();
4307 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4308 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
4309 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004310 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
4311 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004312 if (isOpenMPTaskLoopDirective(Kind)) {
4313 QualType KmpUInt64Ty =
4314 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4315 QualType KmpInt64Ty =
4316 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4317 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4318 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4319 addFieldToRecordDecl(C, RD, KmpInt64Ty);
4320 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004321 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004322 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004323 RD->completeDefinition();
4324 return RD;
4325}
4326
4327static RecordDecl *
4328createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004329 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004330 ASTContext &C = CGM.getContext();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004331 // Build struct kmp_task_t_with_privates {
4332 // kmp_task_t task_data;
4333 // .kmp_privates_t. privates;
4334 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004335 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004336 RD->startDefinition();
4337 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004338 if (const RecordDecl *PrivateRD = createPrivatesRecordDecl(CGM, Privates))
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004339 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004340 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004341 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004342}
4343
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004344/// Emit a proxy function which accepts kmp_task_t as the second
Alexey Bataev62b63b12015-03-10 07:28:44 +00004345/// argument.
4346/// \code
4347/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004348/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00004349/// For taskloops:
4350/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004351/// tt->reductions, tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004352/// return 0;
4353/// }
4354/// \endcode
4355static llvm::Value *
4356emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00004357 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
4358 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004359 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004360 QualType SharedsPtrTy, llvm::Value *TaskFunction,
4361 llvm::Value *TaskPrivatesMap) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004362 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004363 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004364 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4365 ImplicitParamDecl::Other);
4366 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4367 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4368 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004369 Args.push_back(&GtidArg);
4370 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004371 const auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004372 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004373 llvm::FunctionType *TaskEntryTy =
4374 CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004375 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_entry", ""});
4376 auto *TaskEntry = llvm::Function::Create(
4377 TaskEntryTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004378 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskEntry, TaskEntryFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004379 TaskEntry->setDoesNotRecurse();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004380 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004381 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args,
4382 Loc, Loc);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004383
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004384 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00004385 // tt,
4386 // For taskloops:
4387 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
4388 // tt->task_data.shareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004389 llvm::Value *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00004390 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00004391 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4392 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4393 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004394 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004395 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004396 LValue Base =
4397 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004398 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004399 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004400 LValue PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
4401 llvm::Value *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004402
4403 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004404 LValue SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
4405 llvm::Value *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev1e491372018-01-23 18:44:14 +00004406 CGF.EmitLoadOfScalar(SharedsLVal, Loc),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004407 CGF.ConvertTypeForMem(SharedsPtrTy));
4408
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004409 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4410 llvm::Value *PrivatesParam;
4411 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004412 LValue PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004413 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004414 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004415 } else {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004416 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004417 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004418
Alexey Bataev7292c292016-04-25 12:22:29 +00004419 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
4420 TaskPrivatesMap,
4421 CGF.Builder
4422 .CreatePointerBitCastOrAddrSpaceCast(
4423 TDBase.getAddress(), CGF.VoidPtrTy)
4424 .getPointer()};
4425 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
4426 std::end(CommonArgs));
4427 if (isOpenMPTaskLoopDirective(Kind)) {
4428 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004429 LValue LBLVal = CGF.EmitLValueForField(Base, *LBFI);
4430 llvm::Value *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004431 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004432 LValue UBLVal = CGF.EmitLValueForField(Base, *UBFI);
4433 llvm::Value *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004434 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004435 LValue StLVal = CGF.EmitLValueForField(Base, *StFI);
4436 llvm::Value *StParam = CGF.EmitLoadOfScalar(StLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004437 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004438 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4439 llvm::Value *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004440 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004441 LValue RLVal = CGF.EmitLValueForField(Base, *RFI);
4442 llvm::Value *RParam = CGF.EmitLoadOfScalar(RLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004443 CallArgs.push_back(LBParam);
4444 CallArgs.push_back(UBParam);
4445 CallArgs.push_back(StParam);
4446 CallArgs.push_back(LIParam);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004447 CallArgs.push_back(RParam);
Alexey Bataev7292c292016-04-25 12:22:29 +00004448 }
4449 CallArgs.push_back(SharedsParam);
4450
Alexey Bataev3c595a62017-08-14 15:01:03 +00004451 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
4452 CallArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004453 CGF.EmitStoreThroughLValue(RValue::get(CGF.Builder.getInt32(/*C=*/0)),
4454 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004455 CGF.FinishFunction();
4456 return TaskEntry;
4457}
4458
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004459static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
4460 SourceLocation Loc,
4461 QualType KmpInt32Ty,
4462 QualType KmpTaskTWithPrivatesPtrQTy,
4463 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004464 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004465 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004466 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4467 ImplicitParamDecl::Other);
4468 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4469 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4470 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004471 Args.push_back(&GtidArg);
4472 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004473 const auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004474 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004475 llvm::FunctionType *DestructorFnTy =
4476 CGM.getTypes().GetFunctionType(DestructorFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004477 std::string Name =
4478 CGM.getOpenMPRuntime().getName({"omp_task_destructor", ""});
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004479 auto *DestructorFn =
4480 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00004481 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004482 CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004483 DestructorFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004484 DestructorFn->setDoesNotRecurse();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004485 CodeGenFunction CGF(CGM);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004486 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004487 Args, Loc, Loc);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004488
Alexey Bataev31300ed2016-02-04 11:27:03 +00004489 LValue Base = CGF.EmitLoadOfPointerLValue(
4490 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4491 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004492 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004493 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
4494 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004495 Base = CGF.EmitLValueForField(Base, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004496 for (const auto *Field :
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004497 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004498 if (QualType::DestructionKind DtorKind =
4499 Field->getType().isDestructedType()) {
4500 LValue FieldLValue = CGF.EmitLValueForField(Base, Field);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004501 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
4502 }
4503 }
4504 CGF.FinishFunction();
4505 return DestructorFn;
4506}
4507
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004508/// Emit a privates mapping function for correct handling of private and
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004509/// firstprivate variables.
4510/// \code
4511/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
4512/// **noalias priv1,..., <tyn> **noalias privn) {
4513/// *priv1 = &.privates.priv1;
4514/// ...;
4515/// *privn = &.privates.privn;
4516/// }
4517/// \endcode
4518static llvm::Value *
4519emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00004520 ArrayRef<const Expr *> PrivateVars,
4521 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004522 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004523 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004524 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004525 ASTContext &C = CGM.getContext();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004526 FunctionArgList Args;
4527 ImplicitParamDecl TaskPrivatesArg(
4528 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00004529 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
4530 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004531 Args.push_back(&TaskPrivatesArg);
4532 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
4533 unsigned Counter = 1;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004534 for (const Expr *E : PrivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004535 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004536 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4537 C.getPointerType(C.getPointerType(E->getType()))
4538 .withConst()
4539 .withRestrict(),
4540 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004541 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004542 PrivateVarsPos[VD] = Counter;
4543 ++Counter;
4544 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004545 for (const Expr *E : FirstprivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004546 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004547 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4548 C.getPointerType(C.getPointerType(E->getType()))
4549 .withConst()
4550 .withRestrict(),
4551 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004552 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004553 PrivateVarsPos[VD] = Counter;
4554 ++Counter;
4555 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004556 for (const Expr *E : LastprivateVars) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004557 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004558 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4559 C.getPointerType(C.getPointerType(E->getType()))
4560 .withConst()
4561 .withRestrict(),
4562 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004563 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004564 PrivateVarsPos[VD] = Counter;
4565 ++Counter;
4566 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004567 const auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004568 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004569 llvm::FunctionType *TaskPrivatesMapTy =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004570 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004571 std::string Name =
4572 CGM.getOpenMPRuntime().getName({"omp_task_privates_map", ""});
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004573 auto *TaskPrivatesMap = llvm::Function::Create(
Alexey Bataev18fa2322018-05-02 14:20:50 +00004574 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage, Name,
4575 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004576 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004577 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00004578 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00004579 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00004580 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004581 CodeGenFunction CGF(CGM);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004582 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004583 TaskPrivatesMapFnInfo, Args, Loc, Loc);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004584
4585 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00004586 LValue Base = CGF.EmitLoadOfPointerLValue(
4587 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4588 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004589 const auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004590 Counter = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004591 for (const FieldDecl *Field : PrivatesQTyRD->fields()) {
4592 LValue FieldLVal = CGF.EmitLValueForField(Base, Field);
4593 const VarDecl *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
4594 LValue RefLVal =
4595 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
4596 LValue RefLoadLVal = CGF.EmitLoadOfPointerLValue(
Alexey Bataev31300ed2016-02-04 11:27:03 +00004597 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00004598 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004599 ++Counter;
4600 }
4601 CGF.FinishFunction();
4602 return TaskPrivatesMap;
4603}
4604
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004605static bool stable_sort_comparator(const PrivateDataTy P1,
4606 const PrivateDataTy P2) {
4607 return P1.first > P2.first;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004608}
4609
Alexey Bataevf93095a2016-05-05 08:46:22 +00004610/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00004611static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004612 const OMPExecutableDirective &D,
4613 Address KmpTaskSharedsPtr, LValue TDBase,
4614 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4615 QualType SharedsTy, QualType SharedsPtrTy,
4616 const OMPTaskDataTy &Data,
4617 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004618 ASTContext &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004619 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4620 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004621 OpenMPDirectiveKind Kind = isOpenMPTaskLoopDirective(D.getDirectiveKind())
4622 ? OMPD_taskloop
4623 : OMPD_task;
4624 const CapturedStmt &CS = *D.getCapturedStmt(Kind);
4625 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004626 LValue SrcBase;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004627 bool IsTargetTask =
4628 isOpenMPTargetDataManagementDirective(D.getDirectiveKind()) ||
4629 isOpenMPTargetExecutionDirective(D.getDirectiveKind());
4630 // For target-based directives skip 3 firstprivate arrays BasePointersArray,
4631 // PointersArray and SizesArray. The original variables for these arrays are
4632 // not captured and we get their addresses explicitly.
4633 if ((!IsTargetTask && !Data.FirstprivateVars.empty()) ||
Alexey Bataev8451efa2018-01-15 19:06:12 +00004634 (IsTargetTask && KmpTaskSharedsPtr.isValid())) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004635 SrcBase = CGF.MakeAddrLValue(
4636 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4637 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4638 SharedsTy);
4639 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004640 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004641 for (const PrivateDataTy &Pair : Privates) {
4642 const VarDecl *VD = Pair.second.PrivateCopy;
4643 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004644 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4645 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004646 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004647 if (const VarDecl *Elem = Pair.second.PrivateElemInit) {
4648 const VarDecl *OriginalVD = Pair.second.Original;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004649 // Check if the variable is the target-based BasePointersArray,
4650 // PointersArray or SizesArray.
4651 LValue SharedRefLValue;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004652 QualType Type = OriginalVD->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004653 const FieldDecl *SharedField = CapturesInfo.lookup(OriginalVD);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004654 if (IsTargetTask && !SharedField) {
4655 assert(isa<ImplicitParamDecl>(OriginalVD) &&
4656 isa<CapturedDecl>(OriginalVD->getDeclContext()) &&
4657 cast<CapturedDecl>(OriginalVD->getDeclContext())
4658 ->getNumParams() == 0 &&
4659 isa<TranslationUnitDecl>(
4660 cast<CapturedDecl>(OriginalVD->getDeclContext())
4661 ->getDeclContext()) &&
4662 "Expected artificial target data variable.");
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004663 SharedRefLValue =
4664 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type);
4665 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004666 SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4667 SharedRefLValue = CGF.MakeAddrLValue(
4668 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
4669 SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl),
4670 SharedRefLValue.getTBAAInfo());
4671 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004672 if (Type->isArrayType()) {
4673 // Initialize firstprivate array.
4674 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4675 // Perform simple memcpy.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004676 CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004677 } else {
4678 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00004679 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00004680 CGF.EmitOMPAggregateAssign(
4681 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4682 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4683 Address SrcElement) {
4684 // Clean up any temporaries needed by the initialization.
4685 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4686 InitScope.addPrivate(
4687 Elem, [SrcElement]() -> Address { return SrcElement; });
4688 (void)InitScope.Privatize();
4689 // Emit initialization for single element.
4690 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4691 CGF, &CapturesInfo);
4692 CGF.EmitAnyExprToMem(Init, DestElement,
4693 Init->getType().getQualifiers(),
4694 /*IsInitializer=*/false);
4695 });
4696 }
4697 } else {
4698 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4699 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4700 return SharedRefLValue.getAddress();
4701 });
4702 (void)InitScope.Privatize();
4703 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4704 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4705 /*capturedByInit=*/false);
4706 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004707 } else {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004708 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004709 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004710 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004711 ++FI;
4712 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004713}
4714
4715/// Check if duplication function is required for taskloops.
4716static bool checkInitIsRequired(CodeGenFunction &CGF,
4717 ArrayRef<PrivateDataTy> Privates) {
4718 bool InitRequired = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004719 for (const PrivateDataTy &Pair : Privates) {
4720 const VarDecl *VD = Pair.second.PrivateCopy;
4721 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004722 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4723 !CGF.isTrivialInitializer(Init));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004724 if (InitRequired)
4725 break;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004726 }
4727 return InitRequired;
4728}
4729
4730
4731/// Emit task_dup function (for initialization of
4732/// private/firstprivate/lastprivate vars and last_iter flag)
4733/// \code
4734/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4735/// lastpriv) {
4736/// // setup lastprivate flag
4737/// task_dst->last = lastpriv;
4738/// // could be constructor calls here...
4739/// }
4740/// \endcode
4741static llvm::Value *
4742emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4743 const OMPExecutableDirective &D,
4744 QualType KmpTaskTWithPrivatesPtrQTy,
4745 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4746 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4747 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4748 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004749 ASTContext &C = CGM.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004750 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004751 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4752 KmpTaskTWithPrivatesPtrQTy,
4753 ImplicitParamDecl::Other);
4754 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4755 KmpTaskTWithPrivatesPtrQTy,
4756 ImplicitParamDecl::Other);
4757 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4758 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004759 Args.push_back(&DstArg);
4760 Args.push_back(&SrcArg);
4761 Args.push_back(&LastprivArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004762 const auto &TaskDupFnInfo =
Alexey Bataevf93095a2016-05-05 08:46:22 +00004763 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004764 llvm::FunctionType *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004765 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_dup", ""});
4766 auto *TaskDup = llvm::Function::Create(
4767 TaskDupTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004768 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskDup, TaskDupFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004769 TaskDup->setDoesNotRecurse();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004770 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004771 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args, Loc,
4772 Loc);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004773
4774 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4775 CGF.GetAddrOfLocalVar(&DstArg),
4776 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4777 // task_dst->liter = lastpriv;
4778 if (WithLastIter) {
4779 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4780 LValue Base = CGF.EmitLValueForField(
4781 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4782 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4783 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4784 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4785 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4786 }
4787
4788 // Emit initial values for private copies (if any).
4789 assert(!Privates.empty());
4790 Address KmpTaskSharedsPtr = Address::invalid();
4791 if (!Data.FirstprivateVars.empty()) {
4792 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4793 CGF.GetAddrOfLocalVar(&SrcArg),
4794 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4795 LValue Base = CGF.EmitLValueForField(
4796 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4797 KmpTaskSharedsPtr = Address(
4798 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4799 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4800 KmpTaskTShareds)),
4801 Loc),
4802 CGF.getNaturalTypeAlignment(SharedsTy));
4803 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004804 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4805 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004806 CGF.FinishFunction();
4807 return TaskDup;
4808}
4809
Alexey Bataev8a831592016-05-10 10:36:51 +00004810/// Checks if destructor function is required to be generated.
4811/// \return true if cleanups are required, false otherwise.
4812static bool
4813checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4814 bool NeedsCleanup = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004815 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4816 const auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4817 for (const FieldDecl *FD : PrivateRD->fields()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004818 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4819 if (NeedsCleanup)
4820 break;
4821 }
4822 return NeedsCleanup;
4823}
4824
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004825CGOpenMPRuntime::TaskResultTy
4826CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4827 const OMPExecutableDirective &D,
4828 llvm::Value *TaskFunction, QualType SharedsTy,
4829 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004830 ASTContext &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004831 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004832 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004833 auto I = Data.PrivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004834 for (const Expr *E : Data.PrivateVars) {
4835 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004836 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004837 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004838 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004839 /*PrivateElemInit=*/nullptr));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004840 ++I;
4841 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004842 I = Data.FirstprivateCopies.begin();
4843 auto IElemInitRef = Data.FirstprivateInits.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004844 for (const Expr *E : Data.FirstprivateVars) {
4845 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004846 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004847 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004848 PrivateHelpersTy(
4849 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004850 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl())));
Richard Trieucc3949d2016-02-18 22:34:54 +00004851 ++I;
4852 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004853 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004854 I = Data.LastprivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004855 for (const Expr *E : Data.LastprivateVars) {
4856 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004857 Privates.emplace_back(
Alexey Bataevf93095a2016-05-05 08:46:22 +00004858 C.getDeclAlign(VD),
4859 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004860 /*PrivateElemInit=*/nullptr));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004861 ++I;
4862 }
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004863 std::stable_sort(Privates.begin(), Privates.end(), stable_sort_comparator);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004864 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004865 // Build type kmp_routine_entry_t (if not built yet).
4866 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004867 // Build type kmp_task_t (if not built yet).
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004868 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
4869 if (SavedKmpTaskloopTQTy.isNull()) {
4870 SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4871 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4872 }
4873 KmpTaskTQTy = SavedKmpTaskloopTQTy;
Alexey Bataev3a03a7f2017-10-11 15:56:38 +00004874 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004875 assert((D.getDirectiveKind() == OMPD_task ||
4876 isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||
4877 isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) &&
4878 "Expected taskloop, task or target directive");
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004879 if (SavedKmpTaskTQTy.isNull()) {
4880 SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4881 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4882 }
4883 KmpTaskTQTy = SavedKmpTaskTQTy;
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004884 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004885 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004886 // Build particular struct kmp_task_t for the given task.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004887 const RecordDecl *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004888 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004889 QualType KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004890 QualType KmpTaskTWithPrivatesPtrQTy =
4891 C.getPointerType(KmpTaskTWithPrivatesQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004892 llvm::Type *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4893 llvm::Type *KmpTaskTWithPrivatesPtrTy =
4894 KmpTaskTWithPrivatesTy->getPointerTo();
4895 llvm::Value *KmpTaskTWithPrivatesTySize =
4896 CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004897 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4898
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004899 // Emit initial values for private copies (if any).
4900 llvm::Value *TaskPrivatesMap = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004901 llvm::Type *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00004902 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004903 if (!Privates.empty()) {
4904 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004905 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4906 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4907 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004908 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4909 TaskPrivatesMap, TaskPrivatesMapTy);
4910 } else {
4911 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4912 cast<llvm::PointerType>(TaskPrivatesMapTy));
4913 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004914 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4915 // kmp_task_t *tt);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004916 llvm::Value *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004917 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4918 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4919 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004920
4921 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4922 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4923 // kmp_routine_entry_t *task_entry);
4924 // Task flags. Format is taken from
4925 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4926 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004927 enum {
4928 TiedFlag = 0x1,
4929 FinalFlag = 0x2,
4930 DestructorsFlag = 0x8,
4931 PriorityFlag = 0x20
4932 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004933 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004934 bool NeedsCleanup = false;
4935 if (!Privates.empty()) {
4936 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4937 if (NeedsCleanup)
4938 Flags = Flags | DestructorsFlag;
4939 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004940 if (Data.Priority.getInt())
4941 Flags = Flags | PriorityFlag;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004942 llvm::Value *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004943 Data.Final.getPointer()
4944 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00004945 CGF.Builder.getInt32(FinalFlag),
4946 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004947 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004948 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004949 llvm::Value *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004950 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4951 getThreadID(CGF, Loc), TaskFlags,
4952 KmpTaskTWithPrivatesTySize, SharedsSize,
4953 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4954 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004955 llvm::Value *NewTask = CGF.EmitRuntimeCall(
Alexey Bataev62b63b12015-03-10 07:28:44 +00004956 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004957 llvm::Value *NewTaskNewTaskTTy =
4958 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4959 NewTask, KmpTaskTWithPrivatesPtrTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004960 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4961 KmpTaskTWithPrivatesQTy);
4962 LValue TDBase =
4963 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004964 // Fill the data in the resulting kmp_task_t record.
4965 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00004966 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004967 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00004968 KmpTaskSharedsPtr =
4969 Address(CGF.EmitLoadOfScalar(
4970 CGF.EmitLValueForField(
4971 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4972 KmpTaskTShareds)),
4973 Loc),
4974 CGF.getNaturalTypeAlignment(SharedsTy));
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004975 LValue Dest = CGF.MakeAddrLValue(KmpTaskSharedsPtr, SharedsTy);
4976 LValue Src = CGF.MakeAddrLValue(Shareds, SharedsTy);
Richard Smithe78fac52018-04-05 20:52:58 +00004977 CGF.EmitAggregateCopy(Dest, Src, SharedsTy, AggValueSlot::DoesNotOverlap);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004978 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004979 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00004980 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004981 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004982 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4983 SharedsTy, SharedsPtrTy, Data, Privates,
4984 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004985 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4986 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4987 Result.TaskDupFn = emitTaskDupFunction(
4988 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4989 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4990 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004991 }
4992 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00004993 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4994 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00004995 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00004996 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004997 const RecordDecl *KmpCmplrdataUD =
4998 (*FI)->getType()->getAsUnionType()->getDecl();
Alexey Bataevad537bb2016-05-30 09:06:50 +00004999 if (NeedsCleanup) {
5000 llvm::Value *DestructorFn = emitDestructorsFunction(
5001 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
5002 KmpTaskTWithPrivatesQTy);
5003 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
5004 LValue DestructorsLV = CGF.EmitLValueForField(
5005 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
5006 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5007 DestructorFn, KmpRoutineEntryPtrTy),
5008 DestructorsLV);
5009 }
5010 // Set priority.
5011 if (Data.Priority.getInt()) {
5012 LValue Data2LV = CGF.EmitLValueForField(
5013 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
5014 LValue PriorityLV = CGF.EmitLValueForField(
5015 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
5016 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
5017 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005018 Result.NewTask = NewTask;
5019 Result.TaskEntry = TaskEntry;
5020 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
5021 Result.TDBase = TDBase;
5022 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
5023 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00005024}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005025
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005026void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
5027 const OMPExecutableDirective &D,
5028 llvm::Value *TaskFunction,
5029 QualType SharedsTy, Address Shareds,
5030 const Expr *IfCond,
5031 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005032 if (!CGF.HaveInsertPoint())
5033 return;
5034
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005035 TaskResultTy Result =
5036 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
5037 llvm::Value *NewTask = Result.NewTask;
5038 llvm::Value *TaskEntry = Result.TaskEntry;
5039 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
5040 LValue TDBase = Result.TDBase;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005041 const RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
5042 ASTContext &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005043 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00005044 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005045 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00005046 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005047 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00005048 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005049 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
5050 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005051 QualType FlagsTy =
5052 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005053 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
5054 if (KmpDependInfoTy.isNull()) {
5055 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
5056 KmpDependInfoRD->startDefinition();
5057 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
5058 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
5059 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
5060 KmpDependInfoRD->completeDefinition();
5061 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005062 } else {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005063 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005064 }
John McCall7f416cc2015-09-08 08:05:57 +00005065 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005066 // Define type kmp_depend_info[<Dependences.size()>];
5067 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00005068 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005069 ArrayType::Normal, /*IndexTypeQuals=*/0);
5070 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00005071 DependenciesArray =
5072 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005073 for (unsigned I = 0; I < NumDependencies; ++I) {
5074 const Expr *E = Data.Dependences[I].second;
5075 LValue Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005076 llvm::Value *Size;
5077 QualType Ty = E->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005078 if (const auto *ASE =
5079 dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005080 LValue UpAddrLVal =
5081 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
5082 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00005083 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005084 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00005085 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005086 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
5087 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005088 } else {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005089 Size = CGF.getTypeSize(Ty);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005090 }
5091 LValue Base = CGF.MakeAddrLValue(
5092 CGF.Builder.CreateConstArrayGEP(DependenciesArray, I, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005093 KmpDependInfoTy);
5094 // deps[i].base_addr = &<Dependences[i].second>;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005095 LValue BaseAddrLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005096 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00005097 CGF.EmitStoreOfScalar(
5098 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
5099 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005100 // deps[i].len = sizeof(<Dependences[i].second>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005101 LValue LenLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005102 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
5103 CGF.EmitStoreOfScalar(Size, LenLVal);
5104 // deps[i].flags = <Dependences[i].first>;
5105 RTLDependenceKindTy DepKind;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005106 switch (Data.Dependences[I].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005107 case OMPC_DEPEND_in:
5108 DepKind = DepIn;
5109 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00005110 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005111 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005112 case OMPC_DEPEND_inout:
5113 DepKind = DepInOut;
5114 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00005115 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005116 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005117 case OMPC_DEPEND_unknown:
5118 llvm_unreachable("Unknown task dependence type");
5119 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005120 LValue FlagsLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005121 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
5122 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
5123 FlagsLVal);
5124 }
John McCall7f416cc2015-09-08 08:05:57 +00005125 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5126 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005127 CGF.VoidPtrTy);
5128 }
5129
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005130 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev62b63b12015-03-10 07:28:44 +00005131 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005132 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
5133 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
5134 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
5135 // list is not empty
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005136 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5137 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00005138 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
5139 llvm::Value *DepTaskArgs[7];
5140 if (NumDependencies) {
5141 DepTaskArgs[0] = UpLoc;
5142 DepTaskArgs[1] = ThreadID;
5143 DepTaskArgs[2] = NewTask;
5144 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
5145 DepTaskArgs[4] = DependenciesArray.getPointer();
5146 DepTaskArgs[5] = CGF.Builder.getInt32(0);
5147 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5148 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005149 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
5150 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005151 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005152 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005153 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005154 LValue PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005155 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
5156 }
John McCall7f416cc2015-09-08 08:05:57 +00005157 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005158 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00005159 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00005160 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005161 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00005162 TaskArgs);
5163 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00005164 // Check if parent region is untied and build return for untied task;
5165 if (auto *Region =
5166 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5167 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00005168 };
John McCall7f416cc2015-09-08 08:05:57 +00005169
5170 llvm::Value *DepWaitTaskArgs[6];
5171 if (NumDependencies) {
5172 DepWaitTaskArgs[0] = UpLoc;
5173 DepWaitTaskArgs[1] = ThreadID;
5174 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
5175 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
5176 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
5177 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5178 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005179 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00005180 NumDependencies, &DepWaitTaskArgs,
5181 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005182 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005183 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
5184 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
5185 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
5186 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
5187 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00005188 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005189 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005190 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005191 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00005192 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
5193 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005194 Action.Enter(CGF);
5195 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00005196 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00005197 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005198 };
5199
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005200 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
5201 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005202 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
5203 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005204 RegionCodeGenTy RCG(CodeGen);
5205 CommonActionTy Action(
5206 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
5207 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
5208 RCG.setAction(Action);
5209 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005210 };
John McCall7f416cc2015-09-08 08:05:57 +00005211
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005212 if (IfCond) {
Alexey Bataev1d677132015-04-22 13:57:31 +00005213 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005214 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005215 RegionCodeGenTy ThenRCG(ThenCodeGen);
5216 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00005217 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00005218}
5219
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005220void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
5221 const OMPLoopDirective &D,
5222 llvm::Value *TaskFunction,
5223 QualType SharedsTy, Address Shareds,
5224 const Expr *IfCond,
5225 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005226 if (!CGF.HaveInsertPoint())
5227 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005228 TaskResultTy Result =
5229 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005230 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev7292c292016-04-25 12:22:29 +00005231 // libcall.
5232 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
5233 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
5234 // sched, kmp_uint64 grainsize, void *task_dup);
5235 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5236 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
5237 llvm::Value *IfVal;
5238 if (IfCond) {
5239 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
5240 /*isSigned=*/true);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005241 } else {
Alexey Bataev7292c292016-04-25 12:22:29 +00005242 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005243 }
Alexey Bataev7292c292016-04-25 12:22:29 +00005244
5245 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005246 Result.TDBase,
5247 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005248 const auto *LBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005249 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
5250 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
5251 /*IsInitializer=*/true);
5252 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005253 Result.TDBase,
5254 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005255 const auto *UBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005256 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
5257 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
5258 /*IsInitializer=*/true);
5259 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005260 Result.TDBase,
5261 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005262 const auto *StVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005263 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
5264 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
5265 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005266 // Store reductions address.
5267 LValue RedLVal = CGF.EmitLValueForField(
5268 Result.TDBase,
5269 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005270 if (Data.Reductions) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005271 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005272 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005273 CGF.EmitNullInitialization(RedLVal.getAddress(),
5274 CGF.getContext().VoidPtrTy);
5275 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005276 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00005277 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00005278 UpLoc,
5279 ThreadID,
5280 Result.NewTask,
5281 IfVal,
5282 LBLVal.getPointer(),
5283 UBLVal.getPointer(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005284 CGF.EmitLoadOfScalar(StLVal, Loc),
Alexey Bataevac6e4de2018-10-24 19:06:37 +00005285 llvm::ConstantInt::getSigned(
5286 CGF.IntTy, 1), // Always 1 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005287 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005288 CGF.IntTy, Data.Schedule.getPointer()
5289 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005290 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005291 Data.Schedule.getPointer()
5292 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005293 /*isSigned=*/false)
5294 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00005295 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5296 Result.TaskDupFn, CGF.VoidPtrTy)
5297 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00005298 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
5299}
5300
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005301/// Emit reduction operation for each element of array (required for
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005302/// array sections) LHS op = RHS.
5303/// \param Type Type of array.
5304/// \param LHSVar Variable on the left side of the reduction operation
5305/// (references element of array in original variable).
5306/// \param RHSVar Variable on the right side of the reduction operation
5307/// (references element of array in original variable).
5308/// \param RedOpGen Generator of reduction operation with use of LHSVar and
5309/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00005310static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005311 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
5312 const VarDecl *RHSVar,
5313 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
5314 const Expr *, const Expr *)> &RedOpGen,
5315 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
5316 const Expr *UpExpr = nullptr) {
5317 // Perform element-by-element initialization.
5318 QualType ElementTy;
5319 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
5320 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
5321
5322 // Drill down to the base element type on both arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005323 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
5324 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005325
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005326 llvm::Value *RHSBegin = RHSAddr.getPointer();
5327 llvm::Value *LHSBegin = LHSAddr.getPointer();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005328 // Cast from pointer to array type to pointer to single element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005329 llvm::Value *LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005330 // The basic structure here is a while-do loop.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005331 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
5332 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
5333 llvm::Value *IsEmpty =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005334 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
5335 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
5336
5337 // Enter the loop body, making that address the current address.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005338 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005339 CGF.EmitBlock(BodyBB);
5340
5341 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
5342
5343 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
5344 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
5345 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
5346 Address RHSElementCurrent =
5347 Address(RHSElementPHI,
5348 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5349
5350 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
5351 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
5352 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
5353 Address LHSElementCurrent =
5354 Address(LHSElementPHI,
5355 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5356
5357 // Emit copy.
5358 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005359 Scope.addPrivate(LHSVar, [=]() { return LHSElementCurrent; });
5360 Scope.addPrivate(RHSVar, [=]() { return RHSElementCurrent; });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005361 Scope.Privatize();
5362 RedOpGen(CGF, XExpr, EExpr, UpExpr);
5363 Scope.ForceCleanup();
5364
5365 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005366 llvm::Value *LHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005367 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005368 llvm::Value *RHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005369 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
5370 // Check whether we've reached the end.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005371 llvm::Value *Done =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005372 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
5373 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
5374 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
5375 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
5376
5377 // Done.
5378 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
5379}
5380
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005381/// Emit reduction combiner. If the combiner is a simple expression emit it as
5382/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
5383/// UDR combiner function.
5384static void emitReductionCombiner(CodeGenFunction &CGF,
5385 const Expr *ReductionOp) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005386 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
5387 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
5388 if (const auto *DRE =
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005389 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005390 if (const auto *DRD =
5391 dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005392 std::pair<llvm::Function *, llvm::Function *> Reduction =
5393 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
5394 RValue Func = RValue::get(Reduction.first);
5395 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
5396 CGF.EmitIgnoredExpr(ReductionOp);
5397 return;
5398 }
5399 CGF.EmitIgnoredExpr(ReductionOp);
5400}
5401
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005402llvm::Value *CGOpenMPRuntime::emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005403 CodeGenModule &CGM, SourceLocation Loc, llvm::Type *ArgsType,
5404 ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs,
5405 ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005406 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005407
5408 // void reduction_func(void *LHSArg, void *RHSArg);
5409 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005410 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5411 ImplicitParamDecl::Other);
5412 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5413 ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005414 Args.push_back(&LHSArg);
5415 Args.push_back(&RHSArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005416 const auto &CGFI =
5417 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005418 std::string Name = getName({"omp", "reduction", "reduction_func"});
5419 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
5420 llvm::GlobalValue::InternalLinkage, Name,
5421 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005422 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005423 Fn->setDoesNotRecurse();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005424 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005425 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005426
5427 // Dst = (void*[n])(LHSArg);
5428 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00005429 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5430 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
5431 ArgsType), CGF.getPointerAlign());
5432 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5433 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
5434 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005435
5436 // ...
5437 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
5438 // ...
5439 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005440 auto IPriv = Privates.begin();
5441 unsigned Idx = 0;
5442 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005443 const auto *RHSVar =
5444 cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
5445 Scope.addPrivate(RHSVar, [&CGF, RHS, Idx, RHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005446 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005447 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005448 const auto *LHSVar =
5449 cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
5450 Scope.addPrivate(LHSVar, [&CGF, LHS, Idx, LHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005451 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005452 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005453 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00005454 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005455 // Get array size and emit VLA type.
5456 ++Idx;
5457 Address Elem =
5458 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
5459 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005460 const VariableArrayType *VLA =
5461 CGF.getContext().getAsVariableArrayType(PrivTy);
5462 const auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005463 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00005464 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005465 CGF.EmitVariablyModifiedType(PrivTy);
5466 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005467 }
5468 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005469 IPriv = Privates.begin();
5470 auto ILHS = LHSExprs.begin();
5471 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005472 for (const Expr *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005473 if ((*IPriv)->getType()->isArrayType()) {
5474 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005475 const auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5476 const auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005477 EmitOMPAggregateReduction(
5478 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5479 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5480 emitReductionCombiner(CGF, E);
5481 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005482 } else {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005483 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005484 emitReductionCombiner(CGF, E);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005485 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005486 ++IPriv;
5487 ++ILHS;
5488 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005489 }
5490 Scope.ForceCleanup();
5491 CGF.FinishFunction();
5492 return Fn;
5493}
5494
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005495void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
5496 const Expr *ReductionOp,
5497 const Expr *PrivateRef,
5498 const DeclRefExpr *LHS,
5499 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005500 if (PrivateRef->getType()->isArrayType()) {
5501 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005502 const auto *LHSVar = cast<VarDecl>(LHS->getDecl());
5503 const auto *RHSVar = cast<VarDecl>(RHS->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005504 EmitOMPAggregateReduction(
5505 CGF, PrivateRef->getType(), LHSVar, RHSVar,
5506 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5507 emitReductionCombiner(CGF, ReductionOp);
5508 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005509 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005510 // Emit reduction for array subscript or single variable.
5511 emitReductionCombiner(CGF, ReductionOp);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005512 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005513}
5514
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005515void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005516 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005517 ArrayRef<const Expr *> LHSExprs,
5518 ArrayRef<const Expr *> RHSExprs,
5519 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005520 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005521 if (!CGF.HaveInsertPoint())
5522 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005523
5524 bool WithNowait = Options.WithNowait;
5525 bool SimpleReduction = Options.SimpleReduction;
5526
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005527 // Next code should be emitted for reduction:
5528 //
5529 // static kmp_critical_name lock = { 0 };
5530 //
5531 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
5532 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
5533 // ...
5534 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
5535 // *(Type<n>-1*)rhs[<n>-1]);
5536 // }
5537 //
5538 // ...
5539 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
5540 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5541 // RedList, reduce_func, &<lock>)) {
5542 // case 1:
5543 // ...
5544 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5545 // ...
5546 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5547 // break;
5548 // case 2:
5549 // ...
5550 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5551 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00005552 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005553 // break;
5554 // default:;
5555 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005556 //
5557 // if SimpleReduction is true, only the next code is generated:
5558 // ...
5559 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5560 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005561
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005562 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005563
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005564 if (SimpleReduction) {
5565 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005566 auto IPriv = Privates.begin();
5567 auto ILHS = LHSExprs.begin();
5568 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005569 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005570 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5571 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005572 ++IPriv;
5573 ++ILHS;
5574 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005575 }
5576 return;
5577 }
5578
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005579 // 1. Build a list of reduction variables.
5580 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005581 auto Size = RHSExprs.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005582 for (const Expr *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005583 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005584 // Reserve place for array size.
5585 ++Size;
5586 }
5587 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005588 QualType ReductionArrayTy =
5589 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
5590 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00005591 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005592 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005593 auto IPriv = Privates.begin();
5594 unsigned Idx = 0;
5595 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00005596 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005597 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00005598 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005599 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00005600 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
5601 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005602 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005603 // Store array size.
5604 ++Idx;
5605 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
5606 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00005607 llvm::Value *Size = CGF.Builder.CreateIntCast(
5608 CGF.getVLASize(
5609 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
Sander de Smalen891af03a2018-02-03 13:55:59 +00005610 .NumElts,
Alexey Bataev1189bd02016-01-26 12:20:39 +00005611 CGF.SizeTy, /*isSigned=*/false);
5612 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
5613 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005614 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005615 }
5616
5617 // 2. Emit reduce_func().
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005618 llvm::Value *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005619 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
5620 Privates, LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005621
5622 // 3. Create static kmp_critical_name lock = { 0 };
Alexey Bataev18fa2322018-05-02 14:20:50 +00005623 std::string Name = getName({"reduction"});
5624 llvm::Value *Lock = getCriticalRegionLock(Name);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005625
5626 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5627 // RedList, reduce_func, &<lock>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005628 llvm::Value *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
5629 llvm::Value *ThreadId = getThreadID(CGF, Loc);
5630 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
5631 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Samuel Antao4c8035b2016-12-12 18:00:20 +00005632 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005633 llvm::Value *Args[] = {
5634 IdentTLoc, // ident_t *<loc>
5635 ThreadId, // i32 <gtid>
5636 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5637 ReductionArrayTySize, // size_type sizeof(RedList)
5638 RL, // void *RedList
5639 ReductionFn, // void (*) (void *, void *) <reduce_func>
5640 Lock // kmp_critical_name *&<lock>
5641 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005642 llvm::Value *Res = CGF.EmitRuntimeCall(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005643 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5644 : OMPRTL__kmpc_reduce),
5645 Args);
5646
5647 // 5. Build switch(res)
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005648 llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5649 llvm::SwitchInst *SwInst =
5650 CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005651
5652 // 6. Build case 1:
5653 // ...
5654 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5655 // ...
5656 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5657 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005658 llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005659 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5660 CGF.EmitBlock(Case1BB);
5661
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005662 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5663 llvm::Value *EndArgs[] = {
5664 IdentTLoc, // ident_t *<loc>
5665 ThreadId, // i32 <gtid>
5666 Lock // kmp_critical_name *&<lock>
5667 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005668 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps](
5669 CodeGenFunction &CGF, PrePostActionTy &Action) {
5670 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005671 auto IPriv = Privates.begin();
5672 auto ILHS = LHSExprs.begin();
5673 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005674 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005675 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5676 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005677 ++IPriv;
5678 ++ILHS;
5679 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005680 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005681 };
5682 RegionCodeGenTy RCG(CodeGen);
5683 CommonActionTy Action(
5684 nullptr, llvm::None,
5685 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5686 : OMPRTL__kmpc_end_reduce),
5687 EndArgs);
5688 RCG.setAction(Action);
5689 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005690
5691 CGF.EmitBranch(DefaultBB);
5692
5693 // 7. Build case 2:
5694 // ...
5695 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5696 // ...
5697 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005698 llvm::BasicBlock *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005699 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5700 CGF.EmitBlock(Case2BB);
5701
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005702 auto &&AtomicCodeGen = [Loc, Privates, LHSExprs, RHSExprs, ReductionOps](
5703 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005704 auto ILHS = LHSExprs.begin();
5705 auto IRHS = RHSExprs.begin();
5706 auto IPriv = Privates.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005707 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005708 const Expr *XExpr = nullptr;
5709 const Expr *EExpr = nullptr;
5710 const Expr *UpExpr = nullptr;
5711 BinaryOperatorKind BO = BO_Comma;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005712 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005713 if (BO->getOpcode() == BO_Assign) {
5714 XExpr = BO->getLHS();
5715 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005716 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005717 }
5718 // Try to emit update expression as a simple atomic.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005719 const Expr *RHSExpr = UpExpr;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005720 if (RHSExpr) {
5721 // Analyze RHS part of the whole expression.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005722 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005723 RHSExpr->IgnoreParenImpCasts())) {
5724 // If this is a conditional operator, analyze its condition for
5725 // min/max reduction operator.
5726 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005727 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005728 if (const auto *BORHS =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005729 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5730 EExpr = BORHS->getRHS();
5731 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005732 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005733 }
5734 if (XExpr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005735 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005736 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005737 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5738 const Expr *EExpr, const Expr *UpExpr) {
5739 LValue X = CGF.EmitLValue(XExpr);
5740 RValue E;
5741 if (EExpr)
5742 E = CGF.EmitAnyExpr(EExpr);
5743 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005744 X, E, BO, /*IsXLHSInRHSPart=*/true,
5745 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005746 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005747 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5748 PrivateScope.addPrivate(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005749 VD, [&CGF, VD, XRValue, Loc]() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005750 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5751 CGF.emitOMPSimpleStore(
5752 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5753 VD->getType().getNonReferenceType(), Loc);
5754 return LHSTemp;
5755 });
5756 (void)PrivateScope.Privatize();
5757 return CGF.EmitAnyExpr(UpExpr);
5758 });
5759 };
5760 if ((*IPriv)->getType()->isArrayType()) {
5761 // Emit atomic reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005762 const auto *RHSVar =
5763 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005764 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5765 AtomicRedGen, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005766 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005767 // Emit atomic reduction for array subscript or single variable.
5768 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005769 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005770 } else {
5771 // Emit as a critical region.
5772 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005773 const Expr *, const Expr *) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005774 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005775 std::string Name = RT.getName({"atomic_reduction"});
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005776 RT.emitCriticalRegion(
Alexey Bataev18fa2322018-05-02 14:20:50 +00005777 CGF, Name,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005778 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5779 Action.Enter(CGF);
5780 emitReductionCombiner(CGF, E);
5781 },
5782 Loc);
5783 };
5784 if ((*IPriv)->getType()->isArrayType()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005785 const auto *LHSVar =
5786 cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5787 const auto *RHSVar =
5788 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005789 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5790 CritRedGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005791 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005792 CritRedGen(CGF, nullptr, nullptr, nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005793 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005794 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005795 ++ILHS;
5796 ++IRHS;
5797 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005798 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005799 };
5800 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5801 if (!WithNowait) {
5802 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5803 llvm::Value *EndArgs[] = {
5804 IdentTLoc, // ident_t *<loc>
5805 ThreadId, // i32 <gtid>
5806 Lock // kmp_critical_name *&<lock>
5807 };
5808 CommonActionTy Action(nullptr, llvm::None,
5809 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5810 EndArgs);
5811 AtomicRCG.setAction(Action);
5812 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005813 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005814 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005815 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005816
5817 CGF.EmitBranch(DefaultBB);
5818 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5819}
5820
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005821/// Generates unique name for artificial threadprivate variables.
Alexey Bataev1c44e152018-03-06 18:59:43 +00005822/// Format is: <Prefix> "." <Decl_mangled_name> "_" "<Decl_start_loc_raw_enc>"
5823static std::string generateUniqueName(CodeGenModule &CGM, StringRef Prefix,
5824 const Expr *Ref) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005825 SmallString<256> Buffer;
5826 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev1c44e152018-03-06 18:59:43 +00005827 const clang::DeclRefExpr *DE;
5828 const VarDecl *D = ::getBaseDecl(Ref, DE);
5829 if (!D)
5830 D = cast<VarDecl>(cast<DeclRefExpr>(Ref)->getDecl());
5831 D = D->getCanonicalDecl();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005832 std::string Name = CGM.getOpenMPRuntime().getName(
5833 {D->isLocalVarDeclOrParm() ? D->getName() : CGM.getMangledName(D)});
5834 Out << Prefix << Name << "_"
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005835 << D->getCanonicalDecl()->getBeginLoc().getRawEncoding();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005836 return Out.str();
5837}
5838
5839/// Emits reduction initializer function:
5840/// \code
5841/// void @.red_init(void* %arg) {
5842/// %0 = bitcast void* %arg to <type>*
5843/// store <type> <init>, <type>* %0
5844/// ret void
5845/// }
5846/// \endcode
5847static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5848 SourceLocation Loc,
5849 ReductionCodeGen &RCG, unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005850 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005851 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005852 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5853 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005854 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005855 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005856 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005857 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005858 std::string Name = CGM.getOpenMPRuntime().getName({"red_init", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005859 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005860 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005861 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005862 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005863 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005864 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005865 Address PrivateAddr = CGF.EmitLoadOfPointer(
5866 CGF.GetAddrOfLocalVar(&Param),
5867 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5868 llvm::Value *Size = nullptr;
5869 // If the size of the reduction item is non-constant, load it from global
5870 // threadprivate variable.
5871 if (RCG.getSizes(N).second) {
5872 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5873 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005874 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005875 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5876 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005877 }
5878 RCG.emitAggregateType(CGF, N, Size);
5879 LValue SharedLVal;
5880 // If initializer uses initializer from declare reduction construct, emit a
5881 // pointer to the address of the original reduction item (reuired by reduction
5882 // initializer)
5883 if (RCG.usesReductionInitializer(N)) {
5884 Address SharedAddr =
5885 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5886 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00005887 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataev21dab122018-03-09 15:20:30 +00005888 SharedAddr = CGF.EmitLoadOfPointer(
5889 SharedAddr,
5890 CGM.getContext().VoidPtrTy.castAs<PointerType>()->getTypePtr());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005891 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5892 } else {
5893 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5894 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5895 CGM.getContext().VoidPtrTy);
5896 }
5897 // Emit the initializer:
5898 // %0 = bitcast void* %arg to <type>*
5899 // store <type> <init>, <type>* %0
5900 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5901 [](CodeGenFunction &) { return false; });
5902 CGF.FinishFunction();
5903 return Fn;
5904}
5905
5906/// Emits reduction combiner function:
5907/// \code
5908/// void @.red_comb(void* %arg0, void* %arg1) {
5909/// %lhs = bitcast void* %arg0 to <type>*
5910/// %rhs = bitcast void* %arg1 to <type>*
5911/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5912/// store <type> %2, <type>* %lhs
5913/// ret void
5914/// }
5915/// \endcode
5916static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5917 SourceLocation Loc,
5918 ReductionCodeGen &RCG, unsigned N,
5919 const Expr *ReductionOp,
5920 const Expr *LHS, const Expr *RHS,
5921 const Expr *PrivateRef) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005922 ASTContext &C = CGM.getContext();
5923 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5924 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005925 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005926 ImplicitParamDecl ParamInOut(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
5927 C.VoidPtrTy, ImplicitParamDecl::Other);
5928 ImplicitParamDecl ParamIn(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5929 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005930 Args.emplace_back(&ParamInOut);
5931 Args.emplace_back(&ParamIn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005932 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005933 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005934 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005935 std::string Name = CGM.getOpenMPRuntime().getName({"red_comb", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005936 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005937 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005938 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005939 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005940 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005941 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005942 llvm::Value *Size = nullptr;
5943 // If the size of the reduction item is non-constant, load it from global
5944 // threadprivate variable.
5945 if (RCG.getSizes(N).second) {
5946 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5947 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005948 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005949 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5950 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005951 }
5952 RCG.emitAggregateType(CGF, N, Size);
5953 // Remap lhs and rhs variables to the addresses of the function arguments.
5954 // %lhs = bitcast void* %arg0 to <type>*
5955 // %rhs = bitcast void* %arg1 to <type>*
5956 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005957 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005958 // Pull out the pointer to the variable.
5959 Address PtrAddr = CGF.EmitLoadOfPointer(
5960 CGF.GetAddrOfLocalVar(&ParamInOut),
5961 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5962 return CGF.Builder.CreateElementBitCast(
5963 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
5964 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005965 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005966 // Pull out the pointer to the variable.
5967 Address PtrAddr = CGF.EmitLoadOfPointer(
5968 CGF.GetAddrOfLocalVar(&ParamIn),
5969 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5970 return CGF.Builder.CreateElementBitCast(
5971 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
5972 });
5973 PrivateScope.Privatize();
5974 // Emit the combiner body:
5975 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
5976 // store <type> %2, <type>* %lhs
5977 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
5978 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
5979 cast<DeclRefExpr>(RHS));
5980 CGF.FinishFunction();
5981 return Fn;
5982}
5983
5984/// Emits reduction finalizer function:
5985/// \code
5986/// void @.red_fini(void* %arg) {
5987/// %0 = bitcast void* %arg to <type>*
5988/// <destroy>(<type>* %0)
5989/// ret void
5990/// }
5991/// \endcode
5992static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
5993 SourceLocation Loc,
5994 ReductionCodeGen &RCG, unsigned N) {
5995 if (!RCG.needCleanups(N))
5996 return nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005997 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005998 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005999 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
6000 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006001 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006002 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006003 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006004 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00006005 std::string Name = CGM.getOpenMPRuntime().getName({"red_fini", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006006 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00006007 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00006008 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00006009 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006010 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00006011 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006012 Address PrivateAddr = CGF.EmitLoadOfPointer(
6013 CGF.GetAddrOfLocalVar(&Param),
6014 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
6015 llvm::Value *Size = nullptr;
6016 // If the size of the reduction item is non-constant, load it from global
6017 // threadprivate variable.
6018 if (RCG.getSizes(N).second) {
6019 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
6020 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00006021 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00006022 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
6023 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006024 }
6025 RCG.emitAggregateType(CGF, N, Size);
6026 // Emit the finalizer body:
6027 // <destroy>(<type>* %0)
6028 RCG.emitCleanups(CGF, N, PrivateAddr);
6029 CGF.FinishFunction();
6030 return Fn;
6031}
6032
6033llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
6034 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
6035 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
6036 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
6037 return nullptr;
6038
6039 // Build typedef struct:
6040 // kmp_task_red_input {
6041 // void *reduce_shar; // shared reduction item
6042 // size_t reduce_size; // size of data item
6043 // void *reduce_init; // data initialization routine
6044 // void *reduce_fini; // data finalization routine
6045 // void *reduce_comb; // data combiner routine
6046 // kmp_task_red_flags_t flags; // flags for additional info from compiler
6047 // } kmp_task_red_input_t;
6048 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006049 RecordDecl *RD = C.buildImplicitRecord("kmp_task_red_input_t");
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006050 RD->startDefinition();
6051 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6052 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
6053 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6054 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6055 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6056 const FieldDecl *FlagsFD = addFieldToRecordDecl(
6057 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
6058 RD->completeDefinition();
6059 QualType RDType = C.getRecordType(RD);
6060 unsigned Size = Data.ReductionVars.size();
6061 llvm::APInt ArraySize(/*numBits=*/64, Size);
6062 QualType ArrayRDType = C.getConstantArrayType(
6063 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
6064 // kmp_task_red_input_t .rd_input.[Size];
6065 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
6066 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
6067 Data.ReductionOps);
6068 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
6069 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
6070 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
6071 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
6072 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
6073 TaskRedInput.getPointer(), Idxs,
6074 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
6075 ".rd_input.gep.");
6076 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
6077 // ElemLVal.reduce_shar = &Shareds[Cnt];
6078 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
6079 RCG.emitSharedLValue(CGF, Cnt);
6080 llvm::Value *CastedShared =
6081 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
6082 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
6083 RCG.emitAggregateType(CGF, Cnt);
6084 llvm::Value *SizeValInChars;
6085 llvm::Value *SizeVal;
6086 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
6087 // We use delayed creation/initialization for VLAs, array sections and
6088 // custom reduction initializations. It is required because runtime does not
6089 // provide the way to pass the sizes of VLAs/array sections to
6090 // initializer/combiner/finalizer functions and does not pass the pointer to
6091 // original reduction item to the initializer. Instead threadprivate global
6092 // variables are used to store these values and use them in the functions.
6093 bool DelayedCreation = !!SizeVal;
6094 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
6095 /*isSigned=*/false);
6096 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
6097 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
6098 // ElemLVal.reduce_init = init;
6099 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
6100 llvm::Value *InitAddr =
6101 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
6102 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
6103 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
6104 // ElemLVal.reduce_fini = fini;
6105 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
6106 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
6107 llvm::Value *FiniAddr = Fini
6108 ? CGF.EmitCastToVoidPtr(Fini)
6109 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
6110 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
6111 // ElemLVal.reduce_comb = comb;
6112 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
6113 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
6114 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
6115 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
6116 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
6117 // ElemLVal.flags = 0;
6118 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
6119 if (DelayedCreation) {
6120 CGF.EmitStoreOfScalar(
6121 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
6122 FlagsLVal);
6123 } else
6124 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
6125 }
6126 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
6127 // *data);
6128 llvm::Value *Args[] = {
6129 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6130 /*isSigned=*/true),
6131 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
6132 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
6133 CGM.VoidPtrTy)};
6134 return CGF.EmitRuntimeCall(
6135 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
6136}
6137
6138void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
6139 SourceLocation Loc,
6140 ReductionCodeGen &RCG,
6141 unsigned N) {
6142 auto Sizes = RCG.getSizes(N);
6143 // Emit threadprivate global variable if the type is non-constant
6144 // (Sizes.second = nullptr).
6145 if (Sizes.second) {
6146 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
6147 /*isSigned=*/false);
6148 Address SizeAddr = getAddrOfArtificialThreadPrivate(
6149 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00006150 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006151 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
6152 }
6153 // Store address of the original reduction item if custom initializer is used.
6154 if (RCG.usesReductionInitializer(N)) {
6155 Address SharedAddr = getAddrOfArtificialThreadPrivate(
6156 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00006157 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006158 CGF.Builder.CreateStore(
6159 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6160 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
6161 SharedAddr, /*IsVolatile=*/false);
6162 }
6163}
6164
6165Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
6166 SourceLocation Loc,
6167 llvm::Value *ReductionsPtr,
6168 LValue SharedLVal) {
6169 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
6170 // *d);
6171 llvm::Value *Args[] = {
6172 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6173 /*isSigned=*/true),
6174 ReductionsPtr,
6175 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
6176 CGM.VoidPtrTy)};
6177 return Address(
6178 CGF.EmitRuntimeCall(
6179 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
6180 SharedLVal.getAlignment());
6181}
6182
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006183void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
6184 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006185 if (!CGF.HaveInsertPoint())
6186 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006187 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
6188 // global_tid);
6189 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
6190 // Ignore return result until untied tasks are supported.
6191 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00006192 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
6193 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006194}
6195
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006196void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006197 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006198 const RegionCodeGenTy &CodeGen,
6199 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006200 if (!CGF.HaveInsertPoint())
6201 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00006202 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006203 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00006204}
6205
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006206namespace {
6207enum RTCancelKind {
6208 CancelNoreq = 0,
6209 CancelParallel = 1,
6210 CancelLoop = 2,
6211 CancelSections = 3,
6212 CancelTaskgroup = 4
6213};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00006214} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006215
6216static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
6217 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00006218 if (CancelRegion == OMPD_parallel)
6219 CancelKind = CancelParallel;
6220 else if (CancelRegion == OMPD_for)
6221 CancelKind = CancelLoop;
6222 else if (CancelRegion == OMPD_sections)
6223 CancelKind = CancelSections;
6224 else {
6225 assert(CancelRegion == OMPD_taskgroup);
6226 CancelKind = CancelTaskgroup;
6227 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006228 return CancelKind;
6229}
6230
6231void CGOpenMPRuntime::emitCancellationPointCall(
6232 CodeGenFunction &CGF, SourceLocation Loc,
6233 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006234 if (!CGF.HaveInsertPoint())
6235 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006236 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
6237 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006238 if (auto *OMPRegionInfo =
6239 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00006240 // For 'cancellation point taskgroup', the task region info may not have a
6241 // cancel. This may instead happen in another adjacent task.
6242 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006243 llvm::Value *Args[] = {
6244 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
6245 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006246 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006247 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006248 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
6249 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006250 // exit from construct;
6251 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006252 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6253 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6254 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006255 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6256 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006257 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006258 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev25e5b442015-09-15 12:52:43 +00006259 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006260 CGF.EmitBranchThroughCleanup(CancelDest);
6261 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6262 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006263 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006264}
6265
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006266void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00006267 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006268 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006269 if (!CGF.HaveInsertPoint())
6270 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006271 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
6272 // kmp_int32 cncl_kind);
6273 if (auto *OMPRegionInfo =
6274 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006275 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
6276 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006277 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00006278 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006279 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00006280 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
6281 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006282 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006283 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00006284 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00006285 // exit from construct;
6286 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006287 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6288 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6289 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev87933c72015-09-18 08:07:34 +00006290 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6291 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00006292 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006293 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev87933c72015-09-18 08:07:34 +00006294 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
6295 CGF.EmitBranchThroughCleanup(CancelDest);
6296 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6297 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006298 if (IfCond) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006299 emitOMPIfClause(CGF, IfCond, ThenGen,
6300 [](CodeGenFunction &, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006301 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006302 RegionCodeGenTy ThenRCG(ThenGen);
6303 ThenRCG(CGF);
6304 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006305 }
6306}
Samuel Antaobed3c462015-10-02 16:14:20 +00006307
Samuel Antaoee8fb302016-01-06 13:42:12 +00006308void CGOpenMPRuntime::emitTargetOutlinedFunction(
6309 const OMPExecutableDirective &D, StringRef ParentName,
6310 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006311 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00006312 assert(!ParentName.empty() && "Invalid target region parent name!");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006313 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
6314 IsOffloadEntry, CodeGen);
6315}
6316
6317void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
6318 const OMPExecutableDirective &D, StringRef ParentName,
6319 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
6320 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00006321 // Create a unique name for the entry function using the source location
6322 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00006323 //
Samuel Antao2de62b02016-02-13 23:35:10 +00006324 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00006325 //
6326 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00006327 // mangled name of the function that encloses the target region and BB is the
6328 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00006329
6330 unsigned DeviceID;
6331 unsigned FileID;
6332 unsigned Line;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006333 getTargetEntryUniqueInfo(CGM.getContext(), D.getBeginLoc(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00006334 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006335 SmallString<64> EntryFnName;
6336 {
6337 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00006338 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
6339 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00006340 }
6341
Alexey Bataev475a7442018-01-12 19:39:11 +00006342 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006343
Samuel Antaobed3c462015-10-02 16:14:20 +00006344 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006345 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00006346 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006347
Samuel Antao6d004262016-06-16 18:39:34 +00006348 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006349
6350 // If this target outline function is not an offload entry, we don't need to
6351 // register it.
6352 if (!IsOffloadEntry)
6353 return;
6354
6355 // The target region ID is used by the runtime library to identify the current
6356 // target region, so it only has to be unique and not necessarily point to
6357 // anything. It could be the pointer to the outlined function that implements
6358 // the target region, but we aren't using that so that the compiler doesn't
6359 // need to keep that, and could therefore inline the host function if proven
6360 // worthwhile during optimization. In the other hand, if emitting code for the
6361 // device, the ID has to be the function address so that it can retrieved from
6362 // the offloading entry and launched by the runtime library. We also mark the
6363 // outlined function to have external linkage in case we are emitting code for
6364 // the device, because these functions will be entry points to the device.
6365
6366 if (CGM.getLangOpts().OpenMPIsDevice) {
6367 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
Alexey Bataev9a700172018-05-08 14:16:57 +00006368 OutlinedFn->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Rafael Espindolacbca4872018-01-11 22:15:12 +00006369 OutlinedFn->setDSOLocal(false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006370 } else {
Alexey Bataevc15ea702018-05-09 18:02:37 +00006371 std::string Name = getName({EntryFnName, "region_id"});
Samuel Antaoee8fb302016-01-06 13:42:12 +00006372 OutlinedFnID = new llvm::GlobalVariable(
6373 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
Alexey Bataev9a700172018-05-08 14:16:57 +00006374 llvm::GlobalValue::WeakAnyLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00006375 llvm::Constant::getNullValue(CGM.Int8Ty), Name);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006376 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00006377
6378 // Register the information for the entry associated with this target region.
6379 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00006380 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
Alexey Bataev03f270c2018-03-30 18:31:07 +00006381 OffloadEntriesInfoManagerTy::OMPTargetRegionEntryTargetRegion);
Samuel Antaobed3c462015-10-02 16:14:20 +00006382}
6383
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006384/// discard all CompoundStmts intervening between two constructs
6385static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006386 while (const auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006387 Body = CS->body_front();
6388
6389 return Body;
6390}
6391
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006392/// Emit the number of teams for a target directive. Inspect the num_teams
6393/// clause associated with a teams construct combined or closely nested
6394/// with the target directive.
6395///
6396/// Emit a team of size one for directives such as 'target parallel' that
6397/// have no associated teams construct.
6398///
6399/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006400static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006401emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6402 CodeGenFunction &CGF,
6403 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006404 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6405 "teams directive expected to be "
6406 "emitted only for the host!");
6407
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006408 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006409
6410 // If the target directive is combined with a teams directive:
6411 // Return the value in the num_teams clause, if any.
6412 // Otherwise, return 0 to denote the runtime default.
6413 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
6414 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
6415 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006416 llvm::Value *NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
6417 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006418 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6419 /*IsSigned=*/true);
6420 }
6421
6422 // The default value is 0.
6423 return Bld.getInt32(0);
6424 }
6425
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006426 // If the target directive is combined with a parallel directive but not a
6427 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006428 if (isOpenMPParallelDirective(D.getDirectiveKind()))
6429 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006430
6431 // If the current target region has a teams region enclosed, we need to get
6432 // the number of teams to pass to the runtime function call. This is done
6433 // by generating the expression in a inlined region. This is required because
6434 // the expression is captured in the enclosing target environment when the
6435 // teams directive is not combined with target.
6436
Alexey Bataev475a7442018-01-12 19:39:11 +00006437 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006438
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006439 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006440 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006441 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006442 if (const auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006443 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6444 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6445 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
6446 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6447 /*IsSigned=*/true);
6448 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006449
Alexey Bataev50a1c782017-12-01 21:31:08 +00006450 // If we have an enclosed teams directive but no num_teams clause we use
6451 // the default value 0.
6452 return Bld.getInt32(0);
6453 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006454 }
6455
6456 // No teams associated with the directive.
6457 return nullptr;
6458}
6459
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006460/// Emit the number of threads for a target directive. Inspect the
6461/// thread_limit clause associated with a teams construct combined or closely
6462/// nested with the target directive.
6463///
6464/// Emit the num_threads clause for directives such as 'target parallel' that
6465/// have no associated teams construct.
6466///
6467/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006468static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006469emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6470 CodeGenFunction &CGF,
6471 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006472 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6473 "teams directive expected to be "
6474 "emitted only for the host!");
6475
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006476 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006477
6478 //
6479 // If the target directive is combined with a teams directive:
6480 // Return the value in the thread_limit clause, if any.
6481 //
6482 // If the target directive is combined with a parallel directive:
6483 // Return the value in the num_threads clause, if any.
6484 //
6485 // If both clauses are set, select the minimum of the two.
6486 //
6487 // If neither teams or parallel combined directives set the number of threads
6488 // in a team, return 0 to denote the runtime default.
6489 //
6490 // If this is not a teams directive return nullptr.
6491
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006492 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
6493 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006494 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
6495 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006496 llvm::Value *ThreadLimitVal = nullptr;
6497
6498 if (const auto *ThreadLimitClause =
6499 D.getSingleClause<OMPThreadLimitClause>()) {
6500 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006501 llvm::Value *ThreadLimit =
6502 CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
6503 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006504 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6505 /*IsSigned=*/true);
6506 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006507
6508 if (const auto *NumThreadsClause =
6509 D.getSingleClause<OMPNumThreadsClause>()) {
6510 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
6511 llvm::Value *NumThreads =
6512 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
6513 /*IgnoreResultAssign*/ true);
6514 NumThreadsVal =
6515 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
6516 }
6517
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006518 // Select the lesser of thread_limit and num_threads.
6519 if (NumThreadsVal)
6520 ThreadLimitVal = ThreadLimitVal
6521 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
6522 ThreadLimitVal),
6523 NumThreadsVal, ThreadLimitVal)
6524 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00006525
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006526 // Set default value passed to the runtime if either teams or a target
6527 // parallel type directive is found but no clause is specified.
6528 if (!ThreadLimitVal)
6529 ThreadLimitVal = DefaultThreadLimitVal;
6530
6531 return ThreadLimitVal;
6532 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00006533
Samuel Antaob68e2db2016-03-03 16:20:23 +00006534 // If the current target region has a teams region enclosed, we need to get
6535 // the thread limit to pass to the runtime function call. This is done
6536 // by generating the expression in a inlined region. This is required because
6537 // the expression is captured in the enclosing target environment when the
6538 // teams directive is not combined with target.
6539
Alexey Bataev475a7442018-01-12 19:39:11 +00006540 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006541
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006542 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006543 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006544 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006545 if (const auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006546 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6547 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6548 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
6549 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6550 /*IsSigned=*/true);
6551 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006552
Alexey Bataev50a1c782017-12-01 21:31:08 +00006553 // If we have an enclosed teams directive but no thread_limit clause we
6554 // use the default value 0.
6555 return CGF.Builder.getInt32(0);
6556 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006557 }
6558
6559 // No teams associated with the directive.
6560 return nullptr;
6561}
6562
Samuel Antao86ace552016-04-27 22:40:57 +00006563namespace {
Alexey Bataevb3638132018-07-19 16:34:13 +00006564LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
6565
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006566// Utility to handle information from clauses associated with a given
Samuel Antao86ace552016-04-27 22:40:57 +00006567// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
6568// It provides a convenient interface to obtain the information and generate
6569// code for that information.
6570class MappableExprsHandler {
6571public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006572 /// Values for bit flags used to specify the mapping type for
Samuel Antao86ace552016-04-27 22:40:57 +00006573 /// offloading.
Alexey Bataevb3638132018-07-19 16:34:13 +00006574 enum OpenMPOffloadMappingFlags : uint64_t {
6575 /// No flags
6576 OMP_MAP_NONE = 0x0,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006577 /// Allocate memory on the device and move data from host to device.
Samuel Antao86ace552016-04-27 22:40:57 +00006578 OMP_MAP_TO = 0x01,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006579 /// Allocate memory on the device and move data from device to host.
Samuel Antao86ace552016-04-27 22:40:57 +00006580 OMP_MAP_FROM = 0x02,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006581 /// Always perform the requested mapping action on the element, even
Samuel Antao86ace552016-04-27 22:40:57 +00006582 /// if it was already mapped before.
6583 OMP_MAP_ALWAYS = 0x04,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006584 /// Delete the element from the device environment, ignoring the
Samuel Antao86ace552016-04-27 22:40:57 +00006585 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00006586 OMP_MAP_DELETE = 0x08,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006587 /// The element being mapped is a pointer-pointee pair; both the
George Rokos065755d2017-11-07 18:27:04 +00006588 /// pointer and the pointee should be mapped.
6589 OMP_MAP_PTR_AND_OBJ = 0x10,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006590 /// This flags signals that the base address of an entry should be
George Rokos065755d2017-11-07 18:27:04 +00006591 /// passed to the target kernel as an argument.
6592 OMP_MAP_TARGET_PARAM = 0x20,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006593 /// Signal that the runtime library has to return the device pointer
George Rokos065755d2017-11-07 18:27:04 +00006594 /// in the current position for the data being mapped. Used when we have the
6595 /// use_device_ptr clause.
6596 OMP_MAP_RETURN_PARAM = 0x40,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006597 /// This flag signals that the reference being passed is a pointer to
Samuel Antaod486f842016-05-26 16:53:38 +00006598 /// private data.
George Rokos065755d2017-11-07 18:27:04 +00006599 OMP_MAP_PRIVATE = 0x80,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006600 /// Pass the element to the device by value.
George Rokos065755d2017-11-07 18:27:04 +00006601 OMP_MAP_LITERAL = 0x100,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006602 /// Implicit map
6603 OMP_MAP_IMPLICIT = 0x200,
Alexey Bataevb3638132018-07-19 16:34:13 +00006604 /// The 16 MSBs of the flags indicate whether the entry is member of some
6605 /// struct/class.
6606 OMP_MAP_MEMBER_OF = 0xffff000000000000,
6607 LLVM_MARK_AS_BITMASK_ENUM(/* LargestFlag = */ OMP_MAP_MEMBER_OF),
Samuel Antao86ace552016-04-27 22:40:57 +00006608 };
6609
Samuel Antaocc10b852016-07-28 14:23:26 +00006610 /// Class that associates information with a base pointer to be passed to the
6611 /// runtime library.
6612 class BasePointerInfo {
6613 /// The base pointer.
6614 llvm::Value *Ptr = nullptr;
6615 /// The base declaration that refers to this device pointer, or null if
6616 /// there is none.
6617 const ValueDecl *DevPtrDecl = nullptr;
6618
6619 public:
6620 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
6621 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
6622 llvm::Value *operator*() const { return Ptr; }
6623 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
6624 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
6625 };
6626
Alexey Bataevb3638132018-07-19 16:34:13 +00006627 using MapBaseValuesArrayTy = SmallVector<BasePointerInfo, 4>;
6628 using MapValuesArrayTy = SmallVector<llvm::Value *, 4>;
6629 using MapFlagsArrayTy = SmallVector<OpenMPOffloadMappingFlags, 4>;
6630
6631 /// Map between a struct and the its lowest & highest elements which have been
6632 /// mapped.
6633 /// [ValueDecl *] --> {LE(FieldIndex, Pointer),
6634 /// HE(FieldIndex, Pointer)}
6635 struct StructRangeInfoTy {
6636 std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> LowestElem = {
6637 0, Address::invalid()};
6638 std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> HighestElem = {
6639 0, Address::invalid()};
6640 Address Base = Address::invalid();
6641 };
Samuel Antao86ace552016-04-27 22:40:57 +00006642
6643private:
Alexey Bataevb3638132018-07-19 16:34:13 +00006644 /// Kind that defines how a device pointer has to be returned.
6645 struct MapInfo {
6646 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
6647 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
Kelvin Lief579432018-12-18 22:18:41 +00006648 ArrayRef<OpenMPMapModifierKind> MapModifiers;
Alexey Bataevb3638132018-07-19 16:34:13 +00006649 bool ReturnDevicePointer = false;
6650 bool IsImplicit = false;
6651
6652 MapInfo() = default;
6653 MapInfo(
6654 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Kelvin Lief579432018-12-18 22:18:41 +00006655 OpenMPMapClauseKind MapType,
6656 ArrayRef<OpenMPMapModifierKind> MapModifiers,
Alexey Bataevb3638132018-07-19 16:34:13 +00006657 bool ReturnDevicePointer, bool IsImplicit)
Kelvin Lief579432018-12-18 22:18:41 +00006658 : Components(Components), MapType(MapType), MapModifiers(MapModifiers),
Alexey Bataevb3638132018-07-19 16:34:13 +00006659 ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
6660 };
6661
6662 /// If use_device_ptr is used on a pointer which is a struct member and there
6663 /// is no map information about it, then emission of that entry is deferred
6664 /// until the whole struct has been processed.
6665 struct DeferredDevicePtrEntryTy {
6666 const Expr *IE = nullptr;
6667 const ValueDecl *VD = nullptr;
6668
6669 DeferredDevicePtrEntryTy(const Expr *IE, const ValueDecl *VD)
6670 : IE(IE), VD(VD) {}
6671 };
6672
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006673 /// Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00006674 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00006675
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006676 /// Function the directive is being generated for.
Samuel Antao86ace552016-04-27 22:40:57 +00006677 CodeGenFunction &CGF;
6678
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006679 /// Set of all first private variables in the current directive.
Samuel Antaod486f842016-05-26 16:53:38 +00006680 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
6681
Samuel Antao6890b092016-07-28 14:25:09 +00006682 /// Map between device pointer declarations and their expression components.
6683 /// The key value for declarations in 'this' is null.
6684 llvm::DenseMap<
6685 const ValueDecl *,
6686 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6687 DevPointersMap;
6688
Samuel Antao86ace552016-04-27 22:40:57 +00006689 llvm::Value *getExprTypeSize(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006690 QualType ExprTy = E->getType().getCanonicalType();
Samuel Antao86ace552016-04-27 22:40:57 +00006691
6692 // Reference types are ignored for mapping purposes.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006693 if (const auto *RefTy = ExprTy->getAs<ReferenceType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006694 ExprTy = RefTy->getPointeeType().getCanonicalType();
6695
6696 // Given that an array section is considered a built-in type, we need to
6697 // do the calculation based on the length of the section instead of relying
6698 // on CGF.getTypeSize(E->getType()).
6699 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6700 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6701 OAE->getBase()->IgnoreParenImpCasts())
6702 .getCanonicalType();
6703
6704 // If there is no length associated with the expression, that means we
6705 // are using the whole length of the base.
6706 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6707 return CGF.getTypeSize(BaseTy);
6708
6709 llvm::Value *ElemSize;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006710 if (const auto *PTy = BaseTy->getAs<PointerType>()) {
Samuel Antao86ace552016-04-27 22:40:57 +00006711 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006712 } else {
6713 const auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
Samuel Antao86ace552016-04-27 22:40:57 +00006714 assert(ATy && "Expecting array type if not a pointer type.");
6715 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6716 }
6717
6718 // If we don't have a length at this point, that is because we have an
6719 // array section with a single element.
6720 if (!OAE->getLength())
6721 return ElemSize;
6722
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006723 llvm::Value *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
Samuel Antao86ace552016-04-27 22:40:57 +00006724 LengthVal =
6725 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6726 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6727 }
6728 return CGF.getTypeSize(ExprTy);
6729 }
6730
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006731 /// Return the corresponding bits for a given map clause modifier. Add
Samuel Antao86ace552016-04-27 22:40:57 +00006732 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006733 /// map as the first one of a series of maps that relate to the same map
6734 /// expression.
Kelvin Lief579432018-12-18 22:18:41 +00006735 OpenMPOffloadMappingFlags getMapTypeBits(
6736 OpenMPMapClauseKind MapType, ArrayRef<OpenMPMapModifierKind> MapModifiers,
6737 bool IsImplicit, bool AddPtrFlag, bool AddIsTargetParamFlag) const {
Alexey Bataevb3638132018-07-19 16:34:13 +00006738 OpenMPOffloadMappingFlags Bits =
6739 IsImplicit ? OMP_MAP_IMPLICIT : OMP_MAP_NONE;
Samuel Antao86ace552016-04-27 22:40:57 +00006740 switch (MapType) {
6741 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006742 case OMPC_MAP_release:
6743 // alloc and release is the default behavior in the runtime library, i.e.
6744 // if we don't pass any bits alloc/release that is what the runtime is
6745 // going to do. Therefore, we don't need to signal anything for these two
6746 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006747 break;
6748 case OMPC_MAP_to:
Alexey Bataevb3638132018-07-19 16:34:13 +00006749 Bits |= OMP_MAP_TO;
Samuel Antao86ace552016-04-27 22:40:57 +00006750 break;
6751 case OMPC_MAP_from:
Alexey Bataevb3638132018-07-19 16:34:13 +00006752 Bits |= OMP_MAP_FROM;
Samuel Antao86ace552016-04-27 22:40:57 +00006753 break;
6754 case OMPC_MAP_tofrom:
Alexey Bataevb3638132018-07-19 16:34:13 +00006755 Bits |= OMP_MAP_TO | OMP_MAP_FROM;
Samuel Antao86ace552016-04-27 22:40:57 +00006756 break;
6757 case OMPC_MAP_delete:
Alexey Bataevb3638132018-07-19 16:34:13 +00006758 Bits |= OMP_MAP_DELETE;
Samuel Antao86ace552016-04-27 22:40:57 +00006759 break;
Alexey Bataevb3638132018-07-19 16:34:13 +00006760 case OMPC_MAP_unknown:
Samuel Antao86ace552016-04-27 22:40:57 +00006761 llvm_unreachable("Unexpected map type!");
Samuel Antao86ace552016-04-27 22:40:57 +00006762 }
6763 if (AddPtrFlag)
George Rokos065755d2017-11-07 18:27:04 +00006764 Bits |= OMP_MAP_PTR_AND_OBJ;
6765 if (AddIsTargetParamFlag)
6766 Bits |= OMP_MAP_TARGET_PARAM;
Kelvin Lief579432018-12-18 22:18:41 +00006767 if (llvm::find(MapModifiers, OMPC_MAP_MODIFIER_always)
6768 != MapModifiers.end())
Samuel Antao86ace552016-04-27 22:40:57 +00006769 Bits |= OMP_MAP_ALWAYS;
6770 return Bits;
6771 }
6772
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006773 /// Return true if the provided expression is a final array section. A
Samuel Antao86ace552016-04-27 22:40:57 +00006774 /// final array section, is one whose length can't be proved to be one.
6775 bool isFinalArraySectionExpression(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006776 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antao86ace552016-04-27 22:40:57 +00006777
6778 // It is not an array section and therefore not a unity-size one.
6779 if (!OASE)
6780 return false;
6781
6782 // An array section with no colon always refer to a single element.
6783 if (OASE->getColonLoc().isInvalid())
6784 return false;
6785
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006786 const Expr *Length = OASE->getLength();
Samuel Antao86ace552016-04-27 22:40:57 +00006787
6788 // If we don't have a length we have to check if the array has size 1
6789 // for this dimension. Also, we should always expect a length if the
6790 // base type is pointer.
6791 if (!Length) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006792 QualType BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6793 OASE->getBase()->IgnoreParenImpCasts())
6794 .getCanonicalType();
6795 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antao86ace552016-04-27 22:40:57 +00006796 return ATy->getSize().getSExtValue() != 1;
6797 // If we don't have a constant dimension length, we have to consider
6798 // the current section as having any size, so it is not necessarily
6799 // unitary. If it happen to be unity size, that's user fault.
6800 return true;
6801 }
6802
6803 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +00006804 Expr::EvalResult Result;
6805 if (!Length->EvaluateAsInt(Result, CGF.getContext()))
Samuel Antao86ace552016-04-27 22:40:57 +00006806 return true; // Can have more that size 1.
6807
Fangrui Song407659a2018-11-30 23:41:18 +00006808 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antao86ace552016-04-27 22:40:57 +00006809 return ConstLength.getSExtValue() != 1;
6810 }
6811
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006812 /// Generate the base pointers, section pointers, sizes and map type
Samuel Antao86ace552016-04-27 22:40:57 +00006813 /// bits for the provided map type, map modifier, and expression components.
6814 /// \a IsFirstComponent should be set to true if the provided set of
6815 /// components is the first associated with a capture.
6816 void generateInfoForComponentList(
Kelvin Lief579432018-12-18 22:18:41 +00006817 OpenMPMapClauseKind MapType,
6818 ArrayRef<OpenMPMapModifierKind> MapModifiers,
Samuel Antao86ace552016-04-27 22:40:57 +00006819 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006820 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006821 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
Alexey Bataevb3638132018-07-19 16:34:13 +00006822 StructRangeInfoTy &PartialStruct, bool IsFirstComponentList,
Alexey Bataeve82445f2018-09-20 13:54:02 +00006823 bool IsImplicit,
6824 ArrayRef<OMPClauseMappableExprCommon::MappableExprComponentListRef>
6825 OverlappedElements = llvm::None) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006826 // The following summarizes what has to be generated for each map and the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006827 // types below. The generated information is expressed in this order:
Samuel Antao86ace552016-04-27 22:40:57 +00006828 // base pointer, section pointer, size, flags
6829 // (to add to the ones that come from the map type and modifier).
6830 //
6831 // double d;
6832 // int i[100];
6833 // float *p;
6834 //
6835 // struct S1 {
6836 // int i;
6837 // float f[50];
6838 // }
6839 // struct S2 {
6840 // int i;
6841 // float f[50];
6842 // S1 s;
6843 // double *p;
6844 // struct S2 *ps;
6845 // }
6846 // S2 s;
6847 // S2 *ps;
6848 //
6849 // map(d)
Alexey Bataevb3638132018-07-19 16:34:13 +00006850 // &d, &d, sizeof(double), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006851 //
6852 // map(i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006853 // &i, &i, 100*sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006854 //
6855 // map(i[1:23])
Alexey Bataevb3638132018-07-19 16:34:13 +00006856 // &i(=&i[0]), &i[1], 23*sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006857 //
6858 // map(p)
Alexey Bataevb3638132018-07-19 16:34:13 +00006859 // &p, &p, sizeof(float*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006860 //
6861 // map(p[1:24])
Alexey Bataevb3638132018-07-19 16:34:13 +00006862 // p, &p[1], 24*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006863 //
6864 // map(s)
Alexey Bataevb3638132018-07-19 16:34:13 +00006865 // &s, &s, sizeof(S2), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006866 //
6867 // map(s.i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006868 // &s, &(s.i), sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006869 //
6870 // map(s.s.f)
Alexey Bataevb3638132018-07-19 16:34:13 +00006871 // &s, &(s.s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006872 //
6873 // map(s.p)
Alexey Bataevb3638132018-07-19 16:34:13 +00006874 // &s, &(s.p), sizeof(double*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006875 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006876 // map(to: s.p[:22])
6877 // &s, &(s.p), sizeof(double*), TARGET_PARAM (*)
6878 // &s, &(s.p), sizeof(double*), MEMBER_OF(1) (**)
6879 // &(s.p), &(s.p[0]), 22*sizeof(double),
6880 // MEMBER_OF(1) | PTR_AND_OBJ | TO (***)
6881 // (*) alloc space for struct members, only this is a target parameter
6882 // (**) map the pointer (nothing to be mapped in this example) (the compiler
6883 // optimizes this entry out, same in the examples below)
6884 // (***) map the pointee (map: to)
Samuel Antao86ace552016-04-27 22:40:57 +00006885 //
6886 // map(s.ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006887 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006888 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006889 // map(from: s.ps->s.i)
6890 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6891 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6892 // &(s.ps), &(s.ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006893 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006894 // map(to: s.ps->ps)
6895 // &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 | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006898 //
6899 // map(s.ps->ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006900 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6901 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6902 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6903 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006904 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006905 // map(to: s.ps->ps->s.f[:22])
6906 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6907 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6908 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6909 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006910 //
6911 // map(ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006912 // &ps, &ps, sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006913 //
6914 // map(ps->i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006915 // ps, &(ps->i), sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006916 //
6917 // map(ps->s.f)
Alexey Bataevb3638132018-07-19 16:34:13 +00006918 // ps, &(ps->s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006919 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006920 // map(from: ps->p)
6921 // ps, &(ps->p), sizeof(double*), TARGET_PARAM | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006922 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006923 // map(to: ps->p[:22])
6924 // ps, &(ps->p), sizeof(double*), TARGET_PARAM
6925 // ps, &(ps->p), sizeof(double*), MEMBER_OF(1)
6926 // &(ps->p), &(ps->p[0]), 22*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006927 //
6928 // map(ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006929 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006930 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006931 // map(from: ps->ps->s.i)
6932 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6933 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6934 // &(ps->ps), &(ps->ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006935 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006936 // map(from: ps->ps->ps)
6937 // 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 | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006940 //
6941 // map(ps->ps->ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006942 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6943 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6944 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6945 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006946 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006947 // map(to: ps->ps->ps->s.f[:22])
6948 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6949 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6950 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6951 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO
6952 //
6953 // map(to: s.f[:22]) map(from: s.p[:33])
6954 // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1) +
6955 // sizeof(double*) (**), TARGET_PARAM
6956 // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | TO
6957 // &s, &(s.p), sizeof(double*), MEMBER_OF(1)
6958 // &(s.p), &(s.p[0]), 33*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | FROM
6959 // (*) allocate contiguous space needed to fit all mapped members even if
6960 // we allocate space for members not mapped (in this example,
6961 // s.f[22..49] and s.s are not mapped, yet we must allocate space for
6962 // them as well because they fall between &s.f[0] and &s.p)
6963 //
6964 // map(from: s.f[:22]) map(to: ps->p[:33])
6965 // &s, &(s.f[0]), 22*sizeof(float), TARGET_PARAM | FROM
6966 // ps, &(ps->p), sizeof(S2*), TARGET_PARAM
6967 // ps, &(ps->p), sizeof(double*), MEMBER_OF(2) (*)
6968 // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(2) | PTR_AND_OBJ | TO
6969 // (*) the struct this entry pertains to is the 2nd element in the list of
6970 // arguments, hence MEMBER_OF(2)
6971 //
6972 // map(from: s.f[:22], s.s) map(to: ps->p[:33])
6973 // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1), TARGET_PARAM
6974 // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | FROM
6975 // &s, &(s.s), sizeof(struct S1), MEMBER_OF(1) | FROM
6976 // ps, &(ps->p), sizeof(S2*), TARGET_PARAM
6977 // ps, &(ps->p), sizeof(double*), MEMBER_OF(4) (*)
6978 // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(4) | PTR_AND_OBJ | TO
6979 // (*) the struct this entry pertains to is the 4th element in the list
6980 // of arguments, hence MEMBER_OF(4)
Samuel Antao86ace552016-04-27 22:40:57 +00006981
6982 // Track if the map information being generated is the first for a capture.
6983 bool IsCaptureFirstInfo = IsFirstComponentList;
Alexey Bataev92327c52018-03-26 16:40:55 +00006984 bool IsLink = false; // Is this variable a "declare target link"?
Samuel Antao86ace552016-04-27 22:40:57 +00006985
6986 // Scan the components from the base to the complete expression.
6987 auto CI = Components.rbegin();
6988 auto CE = Components.rend();
6989 auto I = CI;
6990
6991 // Track if the map information being generated is the first for a list of
6992 // components.
6993 bool IsExpressionFirstInfo = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00006994 Address BP = Address::invalid();
Patrick Lystere13b1e32019-01-02 19:28:48 +00006995 const Expr *AssocExpr = I->getAssociatedExpression();
6996 const auto *AE = dyn_cast<ArraySubscriptExpr>(AssocExpr);
6997 const auto *OASE = dyn_cast<OMPArraySectionExpr>(AssocExpr);
Samuel Antao86ace552016-04-27 22:40:57 +00006998
Patrick Lystere13b1e32019-01-02 19:28:48 +00006999 if (isa<MemberExpr>(AssocExpr)) {
Samuel Antao86ace552016-04-27 22:40:57 +00007000 // The base is the 'this' pointer. The content of the pointer is going
7001 // to be the base of the field being mapped.
Alexey Bataevb3638132018-07-19 16:34:13 +00007002 BP = CGF.LoadCXXThisAddress();
Patrick Lystere13b1e32019-01-02 19:28:48 +00007003 } else if ((AE && isa<CXXThisExpr>(AE->getBase()->IgnoreParenImpCasts())) ||
7004 (OASE &&
7005 isa<CXXThisExpr>(OASE->getBase()->IgnoreParenImpCasts()))) {
7006 BP = CGF.EmitOMPSharedLValue(AssocExpr).getAddress();
Samuel Antao86ace552016-04-27 22:40:57 +00007007 } else {
7008 // The base is the reference to the variable.
7009 // BP = &Var.
Patrick Lystere13b1e32019-01-02 19:28:48 +00007010 BP = CGF.EmitOMPSharedLValue(AssocExpr).getAddress();
Alexey Bataev92327c52018-03-26 16:40:55 +00007011 if (const auto *VD =
7012 dyn_cast_or_null<VarDecl>(I->getAssociatedDeclaration())) {
7013 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00007014 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataev2c1dffe2018-04-16 20:34:41 +00007015 if (*Res == OMPDeclareTargetDeclAttr::MT_Link) {
7016 IsLink = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00007017 BP = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
Alexey Bataev2c1dffe2018-04-16 20:34:41 +00007018 }
Alexey Bataev92327c52018-03-26 16:40:55 +00007019 }
Samuel Antao86ace552016-04-27 22:40:57 +00007020
7021 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00007022 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00007023 // reference. References are ignored for mapping purposes.
7024 QualType Ty =
7025 I->getAssociatedDeclaration()->getType().getNonReferenceType();
7026 if (Ty->isAnyPointerType() && std::next(I) != CE) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007027 BP = CGF.EmitLoadOfPointer(BP, Ty->castAs<PointerType>());
Samuel Antao86ace552016-04-27 22:40:57 +00007028
7029 // We do not need to generate individual map information for the
7030 // pointer, it can be associated with the combined storage.
7031 ++I;
7032 }
7033 }
7034
Alexey Bataevb3638132018-07-19 16:34:13 +00007035 // Track whether a component of the list should be marked as MEMBER_OF some
7036 // combined entry (for partial structs). Only the first PTR_AND_OBJ entry
7037 // in a component list should be marked as MEMBER_OF, all subsequent entries
7038 // do not belong to the base struct. E.g.
7039 // struct S2 s;
7040 // s.ps->ps->ps->f[:]
7041 // (1) (2) (3) (4)
7042 // ps(1) is a member pointer, ps(2) is a pointee of ps(1), so it is a
7043 // PTR_AND_OBJ entry; the PTR is ps(1), so MEMBER_OF the base struct. ps(3)
7044 // is the pointee of ps(2) which is not member of struct s, so it should not
7045 // be marked as such (it is still PTR_AND_OBJ).
7046 // The variable is initialized to false so that PTR_AND_OBJ entries which
7047 // are not struct members are not considered (e.g. array of pointers to
7048 // data).
7049 bool ShouldBeMemberOf = false;
7050
7051 // Variable keeping track of whether or not we have encountered a component
7052 // in the component list which is a member expression. Useful when we have a
7053 // pointer or a final array section, in which case it is the previous
7054 // component in the list which tells us whether we have a member expression.
7055 // E.g. X.f[:]
7056 // While processing the final array section "[:]" it is "f" which tells us
7057 // whether we are dealing with a member of a declared struct.
7058 const MemberExpr *EncounteredME = nullptr;
7059
Samuel Antao86ace552016-04-27 22:40:57 +00007060 for (; I != CE; ++I) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007061 // If the current component is member of a struct (parent struct) mark it.
7062 if (!EncounteredME) {
7063 EncounteredME = dyn_cast<MemberExpr>(I->getAssociatedExpression());
7064 // If we encounter a PTR_AND_OBJ entry from now on it should be marked
7065 // as MEMBER_OF the parent struct.
7066 if (EncounteredME)
7067 ShouldBeMemberOf = true;
7068 }
7069
Samuel Antao86ace552016-04-27 22:40:57 +00007070 auto Next = std::next(I);
7071
7072 // We need to generate the addresses and sizes if this is the last
7073 // component, if the component is a pointer or if it is an array section
7074 // whose length can't be proved to be one. If this is a pointer, it
7075 // becomes the base address for the following components.
7076
7077 // A final array section, is one whose length can't be proved to be one.
7078 bool IsFinalArraySection =
7079 isFinalArraySectionExpression(I->getAssociatedExpression());
7080
7081 // Get information on whether the element is a pointer. Have to do a
7082 // special treatment for array sections given that they are built-in
7083 // types.
7084 const auto *OASE =
7085 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
7086 bool IsPointer =
Alexey Bataevb3638132018-07-19 16:34:13 +00007087 (OASE && OMPArraySectionExpr::getBaseOriginalType(OASE)
7088 .getCanonicalType()
7089 ->isAnyPointerType()) ||
Samuel Antao86ace552016-04-27 22:40:57 +00007090 I->getAssociatedExpression()->getType()->isAnyPointerType();
7091
7092 if (Next == CE || IsPointer || IsFinalArraySection) {
Samuel Antao86ace552016-04-27 22:40:57 +00007093 // If this is not the last component, we expect the pointer to be
7094 // associated with an array expression or member expression.
7095 assert((Next == CE ||
7096 isa<MemberExpr>(Next->getAssociatedExpression()) ||
7097 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
7098 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
7099 "Unexpected expression");
7100
Alexey Bataevb3638132018-07-19 16:34:13 +00007101 Address LB =
7102 CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getAddress();
Samuel Antao86ace552016-04-27 22:40:57 +00007103
Alexey Bataevb3638132018-07-19 16:34:13 +00007104 // If this component is a pointer inside the base struct then we don't
7105 // need to create any entry for it - it will be combined with the object
7106 // it is pointing to into a single PTR_AND_OBJ entry.
7107 bool IsMemberPointer =
7108 IsPointer && EncounteredME &&
7109 (dyn_cast<MemberExpr>(I->getAssociatedExpression()) ==
7110 EncounteredME);
Alexey Bataeve82445f2018-09-20 13:54:02 +00007111 if (!OverlappedElements.empty()) {
7112 // Handle base element with the info for overlapped elements.
7113 assert(!PartialStruct.Base.isValid() && "The base element is set.");
7114 assert(Next == CE &&
7115 "Expected last element for the overlapped elements.");
7116 assert(!IsPointer &&
7117 "Unexpected base element with the pointer type.");
7118 // Mark the whole struct as the struct that requires allocation on the
7119 // device.
7120 PartialStruct.LowestElem = {0, LB};
7121 CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(
7122 I->getAssociatedExpression()->getType());
7123 Address HB = CGF.Builder.CreateConstGEP(
7124 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(LB,
7125 CGF.VoidPtrTy),
7126 TypeSize.getQuantity() - 1, CharUnits::One());
7127 PartialStruct.HighestElem = {
7128 std::numeric_limits<decltype(
7129 PartialStruct.HighestElem.first)>::max(),
7130 HB};
7131 PartialStruct.Base = BP;
7132 // Emit data for non-overlapped data.
7133 OpenMPOffloadMappingFlags Flags =
7134 OMP_MAP_MEMBER_OF |
Kelvin Lief579432018-12-18 22:18:41 +00007135 getMapTypeBits(MapType, MapModifiers, IsImplicit,
Alexey Bataeve82445f2018-09-20 13:54:02 +00007136 /*AddPtrFlag=*/false,
7137 /*AddIsTargetParamFlag=*/false);
7138 LB = BP;
7139 llvm::Value *Size = nullptr;
7140 // Do bitcopy of all non-overlapped structure elements.
7141 for (OMPClauseMappableExprCommon::MappableExprComponentListRef
7142 Component : OverlappedElements) {
7143 Address ComponentLB = Address::invalid();
7144 for (const OMPClauseMappableExprCommon::MappableComponent &MC :
7145 Component) {
7146 if (MC.getAssociatedDeclaration()) {
7147 ComponentLB =
7148 CGF.EmitOMPSharedLValue(MC.getAssociatedExpression())
7149 .getAddress();
7150 Size = CGF.Builder.CreatePtrDiff(
7151 CGF.EmitCastToVoidPtr(ComponentLB.getPointer()),
7152 CGF.EmitCastToVoidPtr(LB.getPointer()));
7153 break;
7154 }
7155 }
7156 BasePointers.push_back(BP.getPointer());
7157 Pointers.push_back(LB.getPointer());
7158 Sizes.push_back(Size);
7159 Types.push_back(Flags);
7160 LB = CGF.Builder.CreateConstGEP(ComponentLB, 1,
7161 CGF.getPointerSize());
7162 }
7163 BasePointers.push_back(BP.getPointer());
7164 Pointers.push_back(LB.getPointer());
7165 Size = CGF.Builder.CreatePtrDiff(
7166 CGF.EmitCastToVoidPtr(
7167 CGF.Builder.CreateConstGEP(HB, 1, CharUnits::One())
7168 .getPointer()),
7169 CGF.EmitCastToVoidPtr(LB.getPointer()));
7170 Sizes.push_back(Size);
7171 Types.push_back(Flags);
7172 break;
7173 }
7174 llvm::Value *Size = getExprTypeSize(I->getAssociatedExpression());
Alexey Bataevb3638132018-07-19 16:34:13 +00007175 if (!IsMemberPointer) {
7176 BasePointers.push_back(BP.getPointer());
7177 Pointers.push_back(LB.getPointer());
7178 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00007179
Alexey Bataevb3638132018-07-19 16:34:13 +00007180 // We need to add a pointer flag for each map that comes from the
7181 // same expression except for the first one. We also need to signal
7182 // this map is the first one that relates with the current capture
7183 // (there is a set of entries for each capture).
7184 OpenMPOffloadMappingFlags Flags = getMapTypeBits(
Kelvin Lief579432018-12-18 22:18:41 +00007185 MapType, MapModifiers, IsImplicit,
Alexey Bataevb3638132018-07-19 16:34:13 +00007186 !IsExpressionFirstInfo || IsLink, IsCaptureFirstInfo && !IsLink);
7187
7188 if (!IsExpressionFirstInfo) {
7189 // If we have a PTR_AND_OBJ pair where the OBJ is a pointer as well,
7190 // then we reset the TO/FROM/ALWAYS/DELETE flags.
7191 if (IsPointer)
7192 Flags &= ~(OMP_MAP_TO | OMP_MAP_FROM | OMP_MAP_ALWAYS |
7193 OMP_MAP_DELETE);
7194
7195 if (ShouldBeMemberOf) {
7196 // Set placeholder value MEMBER_OF=FFFF to indicate that the flag
7197 // should be later updated with the correct value of MEMBER_OF.
7198 Flags |= OMP_MAP_MEMBER_OF;
7199 // From now on, all subsequent PTR_AND_OBJ entries should not be
7200 // marked as MEMBER_OF.
7201 ShouldBeMemberOf = false;
7202 }
7203 }
7204
7205 Types.push_back(Flags);
Samuel Antao03a3cec2016-07-27 22:52:16 +00007206 }
7207
Alexey Bataevb3638132018-07-19 16:34:13 +00007208 // If we have encountered a member expression so far, keep track of the
7209 // mapped member. If the parent is "*this", then the value declaration
7210 // is nullptr.
7211 if (EncounteredME) {
7212 const auto *FD = dyn_cast<FieldDecl>(EncounteredME->getMemberDecl());
7213 unsigned FieldIndex = FD->getFieldIndex();
Samuel Antao03a3cec2016-07-27 22:52:16 +00007214
Alexey Bataevb3638132018-07-19 16:34:13 +00007215 // Update info about the lowest and highest elements for this struct
7216 if (!PartialStruct.Base.isValid()) {
7217 PartialStruct.LowestElem = {FieldIndex, LB};
7218 PartialStruct.HighestElem = {FieldIndex, LB};
7219 PartialStruct.Base = BP;
7220 } else if (FieldIndex < PartialStruct.LowestElem.first) {
7221 PartialStruct.LowestElem = {FieldIndex, LB};
7222 } else if (FieldIndex > PartialStruct.HighestElem.first) {
7223 PartialStruct.HighestElem = {FieldIndex, LB};
7224 }
7225 }
Samuel Antao86ace552016-04-27 22:40:57 +00007226
7227 // If we have a final array section, we are done with this expression.
7228 if (IsFinalArraySection)
7229 break;
7230
7231 // The pointer becomes the base for the next element.
7232 if (Next != CE)
7233 BP = LB;
7234
7235 IsExpressionFirstInfo = false;
7236 IsCaptureFirstInfo = false;
Samuel Antao86ace552016-04-27 22:40:57 +00007237 }
7238 }
7239 }
7240
Alexey Bataevb3638132018-07-19 16:34:13 +00007241 /// Return the adjusted map modifiers if the declaration a capture refers to
7242 /// appears in a first-private clause. This is expected to be used only with
7243 /// directives that start with 'target'.
7244 MappableExprsHandler::OpenMPOffloadMappingFlags
7245 getMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap) const {
7246 assert(Cap.capturesVariable() && "Expected capture by reference only!");
7247
7248 // A first private variable captured by reference will use only the
7249 // 'private ptr' and 'map to' flag. Return the right flags if the captured
7250 // declaration is known as first-private in this handler.
7251 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
7252 return MappableExprsHandler::OMP_MAP_PRIVATE |
7253 MappableExprsHandler::OMP_MAP_TO;
7254 return MappableExprsHandler::OMP_MAP_TO |
7255 MappableExprsHandler::OMP_MAP_FROM;
7256 }
7257
7258 static OpenMPOffloadMappingFlags getMemberOfFlag(unsigned Position) {
7259 // Member of is given by the 16 MSB of the flag, so rotate by 48 bits.
7260 return static_cast<OpenMPOffloadMappingFlags>(((uint64_t)Position + 1)
7261 << 48);
7262 }
7263
7264 static void setCorrectMemberOfFlag(OpenMPOffloadMappingFlags &Flags,
7265 OpenMPOffloadMappingFlags MemberOfFlag) {
7266 // If the entry is PTR_AND_OBJ but has not been marked with the special
7267 // placeholder value 0xFFFF in the MEMBER_OF field, then it should not be
7268 // marked as MEMBER_OF.
7269 if ((Flags & OMP_MAP_PTR_AND_OBJ) &&
7270 ((Flags & OMP_MAP_MEMBER_OF) != OMP_MAP_MEMBER_OF))
7271 return;
7272
7273 // Reset the placeholder value to prepare the flag for the assignment of the
7274 // proper MEMBER_OF value.
7275 Flags &= ~OMP_MAP_MEMBER_OF;
7276 Flags |= MemberOfFlag;
7277 }
7278
Alexey Bataeve82445f2018-09-20 13:54:02 +00007279 void getPlainLayout(const CXXRecordDecl *RD,
7280 llvm::SmallVectorImpl<const FieldDecl *> &Layout,
7281 bool AsBase) const {
7282 const CGRecordLayout &RL = CGF.getTypes().getCGRecordLayout(RD);
7283
7284 llvm::StructType *St =
7285 AsBase ? RL.getBaseSubobjectLLVMType() : RL.getLLVMType();
7286
7287 unsigned NumElements = St->getNumElements();
7288 llvm::SmallVector<
7289 llvm::PointerUnion<const CXXRecordDecl *, const FieldDecl *>, 4>
7290 RecordLayout(NumElements);
7291
7292 // Fill bases.
7293 for (const auto &I : RD->bases()) {
7294 if (I.isVirtual())
7295 continue;
7296 const auto *Base = I.getType()->getAsCXXRecordDecl();
7297 // Ignore empty bases.
7298 if (Base->isEmpty() || CGF.getContext()
7299 .getASTRecordLayout(Base)
7300 .getNonVirtualSize()
7301 .isZero())
7302 continue;
7303
7304 unsigned FieldIndex = RL.getNonVirtualBaseLLVMFieldNo(Base);
7305 RecordLayout[FieldIndex] = Base;
7306 }
7307 // Fill in virtual bases.
7308 for (const auto &I : RD->vbases()) {
7309 const auto *Base = I.getType()->getAsCXXRecordDecl();
7310 // Ignore empty bases.
7311 if (Base->isEmpty())
7312 continue;
7313 unsigned FieldIndex = RL.getVirtualBaseIndex(Base);
7314 if (RecordLayout[FieldIndex])
7315 continue;
7316 RecordLayout[FieldIndex] = Base;
7317 }
7318 // Fill in all the fields.
7319 assert(!RD->isUnion() && "Unexpected union.");
7320 for (const auto *Field : RD->fields()) {
7321 // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
7322 // will fill in later.)
7323 if (!Field->isBitField()) {
7324 unsigned FieldIndex = RL.getLLVMFieldNo(Field);
7325 RecordLayout[FieldIndex] = Field;
7326 }
7327 }
7328 for (const llvm::PointerUnion<const CXXRecordDecl *, const FieldDecl *>
7329 &Data : RecordLayout) {
7330 if (Data.isNull())
7331 continue;
7332 if (const auto *Base = Data.dyn_cast<const CXXRecordDecl *>())
7333 getPlainLayout(Base, Layout, /*AsBase=*/true);
7334 else
7335 Layout.push_back(Data.get<const FieldDecl *>());
7336 }
7337 }
7338
Alexey Bataevb3638132018-07-19 16:34:13 +00007339public:
7340 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
7341 : CurDir(Dir), CGF(CGF) {
7342 // Extract firstprivate clause information.
7343 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
7344 for (const auto *D : C->varlists())
7345 FirstPrivateDecls.insert(
7346 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
7347 // Extract device pointer clause information.
7348 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
7349 for (auto L : C->component_lists())
7350 DevPointersMap[L.first].push_back(L.second);
7351 }
7352
7353 /// Generate code for the combined entry if we have a partially mapped struct
7354 /// and take care of the mapping flags of the arguments corresponding to
7355 /// individual struct members.
7356 void emitCombinedEntry(MapBaseValuesArrayTy &BasePointers,
7357 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7358 MapFlagsArrayTy &Types, MapFlagsArrayTy &CurTypes,
7359 const StructRangeInfoTy &PartialStruct) const {
7360 // Base is the base of the struct
7361 BasePointers.push_back(PartialStruct.Base.getPointer());
7362 // Pointer is the address of the lowest element
7363 llvm::Value *LB = PartialStruct.LowestElem.second.getPointer();
7364 Pointers.push_back(LB);
7365 // Size is (addr of {highest+1} element) - (addr of lowest element)
7366 llvm::Value *HB = PartialStruct.HighestElem.second.getPointer();
7367 llvm::Value *HAddr = CGF.Builder.CreateConstGEP1_32(HB, /*Idx0=*/1);
7368 llvm::Value *CLAddr = CGF.Builder.CreatePointerCast(LB, CGF.VoidPtrTy);
7369 llvm::Value *CHAddr = CGF.Builder.CreatePointerCast(HAddr, CGF.VoidPtrTy);
7370 llvm::Value *Diff = CGF.Builder.CreatePtrDiff(CHAddr, CLAddr);
7371 llvm::Value *Size = CGF.Builder.CreateIntCast(Diff, CGF.SizeTy,
7372 /*isSinged=*/false);
7373 Sizes.push_back(Size);
7374 // Map type is always TARGET_PARAM
7375 Types.push_back(OMP_MAP_TARGET_PARAM);
7376 // Remove TARGET_PARAM flag from the first element
7377 (*CurTypes.begin()) &= ~OMP_MAP_TARGET_PARAM;
7378
7379 // All other current entries will be MEMBER_OF the combined entry
7380 // (except for PTR_AND_OBJ entries which do not have a placeholder value
7381 // 0xFFFF in the MEMBER_OF field).
7382 OpenMPOffloadMappingFlags MemberOfFlag =
7383 getMemberOfFlag(BasePointers.size() - 1);
7384 for (auto &M : CurTypes)
7385 setCorrectMemberOfFlag(M, MemberOfFlag);
7386 }
7387
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007388 /// Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00007389 /// types for the extracted mappable expressions. Also, for each item that
7390 /// relates with a device pointer, a pair of the relevant declaration and
7391 /// index where it occurs is appended to the device pointers info array.
7392 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007393 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7394 MapFlagsArrayTy &Types) const {
Samuel Antao86ace552016-04-27 22:40:57 +00007395 // We have to process the component lists that relate with the same
7396 // declaration in a single chunk so that we can generate the map flags
7397 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00007398 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00007399
7400 // Helper function to fill the information map for the different supported
7401 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00007402 auto &&InfoGen = [&Info](
7403 const ValueDecl *D,
7404 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
Kelvin Lief579432018-12-18 22:18:41 +00007405 OpenMPMapClauseKind MapType,
7406 ArrayRef<OpenMPMapModifierKind> MapModifiers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007407 bool ReturnDevicePointer, bool IsImplicit) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007408 const ValueDecl *VD =
7409 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Kelvin Lief579432018-12-18 22:18:41 +00007410 Info[VD].emplace_back(L, MapType, MapModifiers, ReturnDevicePointer,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007411 IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007412 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00007413
Paul Robinson78fb1322016-08-01 22:12:46 +00007414 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007415 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
7416 for (const auto &L : C->component_lists()) {
Kelvin Lief579432018-12-18 22:18:41 +00007417 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifiers(),
Alexey Bataevb3638132018-07-19 16:34:13 +00007418 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007419 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007420 for (const auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
7421 for (const auto &L : C->component_lists()) {
Kelvin Lief579432018-12-18 22:18:41 +00007422 InfoGen(L.first, L.second, OMPC_MAP_to, llvm::None,
Alexey Bataevb3638132018-07-19 16:34:13 +00007423 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007424 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007425 for (const auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
7426 for (const auto &L : C->component_lists()) {
Kelvin Lief579432018-12-18 22:18:41 +00007427 InfoGen(L.first, L.second, OMPC_MAP_from, llvm::None,
Alexey Bataevb3638132018-07-19 16:34:13 +00007428 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007429 }
Samuel Antao86ace552016-04-27 22:40:57 +00007430
Samuel Antaocc10b852016-07-28 14:23:26 +00007431 // Look at the use_device_ptr clause information and mark the existing map
7432 // entries as such. If there is no map information for an entry in the
7433 // use_device_ptr list, we create one with map type 'alloc' and zero size
Alexey Bataevb3638132018-07-19 16:34:13 +00007434 // section. It is the user fault if that was not mapped before. If there is
7435 // no map information and the pointer is a struct member, then we defer the
7436 // emission of that entry until the whole struct has been processed.
7437 llvm::MapVector<const ValueDecl *, SmallVector<DeferredDevicePtrEntryTy, 4>>
7438 DeferredInfo;
7439
Paul Robinson78fb1322016-08-01 22:12:46 +00007440 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataevb3638132018-07-19 16:34:13 +00007441 for (const auto *C :
7442 this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007443 for (const auto &L : C->component_lists()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007444 assert(!L.second.empty() && "Not expecting empty list of components!");
7445 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
7446 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007447 const Expr *IE = L.second.back().getAssociatedExpression();
Samuel Antaocc10b852016-07-28 14:23:26 +00007448 // If the first component is a member expression, we have to look into
7449 // 'this', which maps to null in the map of map information. Otherwise
7450 // look directly for the information.
7451 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
7452
7453 // We potentially have map information for this declaration already.
7454 // Look for the first set of components that refer to it.
7455 if (It != Info.end()) {
7456 auto CI = std::find_if(
7457 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
7458 return MI.Components.back().getAssociatedDeclaration() == VD;
7459 });
7460 // If we found a map entry, signal that the pointer has to be returned
7461 // and move on to the next declaration.
7462 if (CI != It->second.end()) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007463 CI->ReturnDevicePointer = true;
Samuel Antaocc10b852016-07-28 14:23:26 +00007464 continue;
7465 }
7466 }
7467
7468 // We didn't find any match in our map information - generate a zero
Alexey Bataevb3638132018-07-19 16:34:13 +00007469 // size array section - if the pointer is a struct member we defer this
7470 // action until the whole struct has been processed.
Paul Robinson78fb1322016-08-01 22:12:46 +00007471 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Alexey Bataevb3638132018-07-19 16:34:13 +00007472 if (isa<MemberExpr>(IE)) {
7473 // Insert the pointer into Info to be processed by
7474 // generateInfoForComponentList. Because it is a member pointer
7475 // without a pointee, no entry will be generated for it, therefore
7476 // we need to generate one after the whole struct has been processed.
7477 // Nonetheless, generateInfoForComponentList must be called to take
7478 // the pointer into account for the calculation of the range of the
7479 // partial struct.
Kelvin Lief579432018-12-18 22:18:41 +00007480 InfoGen(nullptr, L.second, OMPC_MAP_unknown, llvm::None,
Alexey Bataevb3638132018-07-19 16:34:13 +00007481 /*ReturnDevicePointer=*/false, C->isImplicit());
7482 DeferredInfo[nullptr].emplace_back(IE, VD);
7483 } else {
7484 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(
7485 this->CGF.EmitLValue(IE), IE->getExprLoc());
7486 BasePointers.emplace_back(Ptr, VD);
7487 Pointers.push_back(Ptr);
7488 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
7489 Types.push_back(OMP_MAP_RETURN_PARAM | OMP_MAP_TARGET_PARAM);
7490 }
Samuel Antaocc10b852016-07-28 14:23:26 +00007491 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007492 }
Samuel Antaocc10b852016-07-28 14:23:26 +00007493
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007494 for (const auto &M : Info) {
Samuel Antao86ace552016-04-27 22:40:57 +00007495 // We need to know when we generate information for the first component
7496 // associated with a capture, because the mapping flags depend on it.
7497 bool IsFirstComponentList = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00007498
7499 // Temporary versions of arrays
7500 MapBaseValuesArrayTy CurBasePointers;
7501 MapValuesArrayTy CurPointers;
7502 MapValuesArrayTy CurSizes;
7503 MapFlagsArrayTy CurTypes;
7504 StructRangeInfoTy PartialStruct;
7505
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007506 for (const MapInfo &L : M.second) {
Samuel Antao86ace552016-04-27 22:40:57 +00007507 assert(!L.Components.empty() &&
7508 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00007509
7510 // Remember the current base pointer index.
Alexey Bataevb3638132018-07-19 16:34:13 +00007511 unsigned CurrentBasePointersIdx = CurBasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00007512 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007513 this->generateInfoForComponentList(
Kelvin Lief579432018-12-18 22:18:41 +00007514 L.MapType, L.MapModifiers, L.Components, CurBasePointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007515 CurPointers, CurSizes, CurTypes, PartialStruct,
7516 IsFirstComponentList, L.IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007517
7518 // If this entry relates with a device pointer, set the relevant
7519 // declaration and add the 'return pointer' flag.
Alexey Bataevb3638132018-07-19 16:34:13 +00007520 if (L.ReturnDevicePointer) {
7521 assert(CurBasePointers.size() > CurrentBasePointersIdx &&
Samuel Antaocc10b852016-07-28 14:23:26 +00007522 "Unexpected number of mapped base pointers.");
7523
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007524 const ValueDecl *RelevantVD =
7525 L.Components.back().getAssociatedDeclaration();
Samuel Antaocc10b852016-07-28 14:23:26 +00007526 assert(RelevantVD &&
7527 "No relevant declaration related with device pointer??");
7528
Alexey Bataevb3638132018-07-19 16:34:13 +00007529 CurBasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
7530 CurTypes[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PARAM;
Samuel Antaocc10b852016-07-28 14:23:26 +00007531 }
Samuel Antao86ace552016-04-27 22:40:57 +00007532 IsFirstComponentList = false;
7533 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007534
7535 // Append any pending zero-length pointers which are struct members and
7536 // used with use_device_ptr.
7537 auto CI = DeferredInfo.find(M.first);
7538 if (CI != DeferredInfo.end()) {
7539 for (const DeferredDevicePtrEntryTy &L : CI->second) {
7540 llvm::Value *BasePtr = this->CGF.EmitLValue(L.IE).getPointer();
7541 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(
7542 this->CGF.EmitLValue(L.IE), L.IE->getExprLoc());
7543 CurBasePointers.emplace_back(BasePtr, L.VD);
7544 CurPointers.push_back(Ptr);
7545 CurSizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
7546 // Entry is PTR_AND_OBJ and RETURN_PARAM. Also, set the placeholder
7547 // value MEMBER_OF=FFFF so that the entry is later updated with the
7548 // correct value of MEMBER_OF.
7549 CurTypes.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_RETURN_PARAM |
7550 OMP_MAP_MEMBER_OF);
7551 }
7552 }
7553
7554 // If there is an entry in PartialStruct it means we have a struct with
7555 // individual members mapped. Emit an extra combined entry.
7556 if (PartialStruct.Base.isValid())
7557 emitCombinedEntry(BasePointers, Pointers, Sizes, Types, CurTypes,
7558 PartialStruct);
7559
7560 // We need to append the results of this capture to what we already have.
7561 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
7562 Pointers.append(CurPointers.begin(), CurPointers.end());
7563 Sizes.append(CurSizes.begin(), CurSizes.end());
7564 Types.append(CurTypes.begin(), CurTypes.end());
Samuel Antao86ace552016-04-27 22:40:57 +00007565 }
7566 }
7567
Alexey Bataev60705422018-10-30 15:50:12 +00007568 /// Emit capture info for lambdas for variables captured by reference.
Alexey Bataev969dbc02018-11-08 15:47:39 +00007569 void generateInfoForLambdaCaptures(
7570 const ValueDecl *VD, llvm::Value *Arg, MapBaseValuesArrayTy &BasePointers,
7571 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7572 MapFlagsArrayTy &Types,
7573 llvm::DenseMap<llvm::Value *, llvm::Value *> &LambdaPointers) const {
Alexey Bataev60705422018-10-30 15:50:12 +00007574 const auto *RD = VD->getType()
7575 .getCanonicalType()
7576 .getNonReferenceType()
7577 ->getAsCXXRecordDecl();
7578 if (!RD || !RD->isLambda())
7579 return;
7580 Address VDAddr = Address(Arg, CGF.getContext().getDeclAlign(VD));
7581 LValue VDLVal = CGF.MakeAddrLValue(
7582 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
7583 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
7584 FieldDecl *ThisCapture = nullptr;
7585 RD->getCaptureFields(Captures, ThisCapture);
7586 if (ThisCapture) {
7587 LValue ThisLVal =
7588 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
Alexey Bataev969dbc02018-11-08 15:47:39 +00007589 LValue ThisLValVal = CGF.EmitLValueForField(VDLVal, ThisCapture);
7590 LambdaPointers.try_emplace(ThisLVal.getPointer(), VDLVal.getPointer());
7591 BasePointers.push_back(ThisLVal.getPointer());
7592 Pointers.push_back(ThisLValVal.getPointer());
Alexey Bataev60705422018-10-30 15:50:12 +00007593 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
Alexey Bataev2dc07d02018-11-02 15:25:06 +00007594 Types.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
Alexey Bataev60705422018-10-30 15:50:12 +00007595 OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT);
7596 }
7597 for (const LambdaCapture &LC : RD->captures()) {
7598 if (LC.getCaptureKind() != LCK_ByRef)
7599 continue;
7600 const VarDecl *VD = LC.getCapturedVar();
7601 auto It = Captures.find(VD);
7602 assert(It != Captures.end() && "Found lambda capture without field.");
7603 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
Alexey Bataev969dbc02018-11-08 15:47:39 +00007604 LValue VarLValVal = CGF.EmitLValueForField(VDLVal, It->second);
7605 LambdaPointers.try_emplace(VarLVal.getPointer(), VDLVal.getPointer());
7606 BasePointers.push_back(VarLVal.getPointer());
7607 Pointers.push_back(VarLValVal.getPointer());
Alexey Bataev60705422018-10-30 15:50:12 +00007608 Sizes.push_back(CGF.getTypeSize(
7609 VD->getType().getCanonicalType().getNonReferenceType()));
Alexey Bataev2dc07d02018-11-02 15:25:06 +00007610 Types.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
Alexey Bataev60705422018-10-30 15:50:12 +00007611 OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT);
7612 }
7613 }
7614
7615 /// Set correct indices for lambdas captures.
Alexey Bataev969dbc02018-11-08 15:47:39 +00007616 void adjustMemberOfForLambdaCaptures(
7617 const llvm::DenseMap<llvm::Value *, llvm::Value *> &LambdaPointers,
7618 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
7619 MapFlagsArrayTy &Types) const {
Alexey Bataev60705422018-10-30 15:50:12 +00007620 for (unsigned I = 0, E = Types.size(); I < E; ++I) {
7621 // Set correct member_of idx for all implicit lambda captures.
Alexey Bataev2dc07d02018-11-02 15:25:06 +00007622 if (Types[I] != (OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
Alexey Bataev60705422018-10-30 15:50:12 +00007623 OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT))
7624 continue;
Alexey Bataev969dbc02018-11-08 15:47:39 +00007625 llvm::Value *BasePtr = LambdaPointers.lookup(*BasePointers[I]);
7626 assert(BasePtr && "Unable to find base lambda address.");
Alexey Bataev60705422018-10-30 15:50:12 +00007627 int TgtIdx = -1;
7628 for (unsigned J = I; J > 0; --J) {
7629 unsigned Idx = J - 1;
7630 if (Pointers[Idx] != BasePtr)
7631 continue;
7632 TgtIdx = Idx;
7633 break;
7634 }
7635 assert(TgtIdx != -1 && "Unable to find parent lambda.");
7636 // All other current entries will be MEMBER_OF the combined entry
7637 // (except for PTR_AND_OBJ entries which do not have a placeholder value
7638 // 0xFFFF in the MEMBER_OF field).
7639 OpenMPOffloadMappingFlags MemberOfFlag = getMemberOfFlag(TgtIdx);
7640 setCorrectMemberOfFlag(Types[I], MemberOfFlag);
7641 }
7642 }
7643
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007644 /// Generate the base pointers, section pointers, sizes and map types
Samuel Antao86ace552016-04-27 22:40:57 +00007645 /// associated to a given capture.
7646 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00007647 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007648 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007649 MapValuesArrayTy &Pointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007650 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
7651 StructRangeInfoTy &PartialStruct) const {
Samuel Antao86ace552016-04-27 22:40:57 +00007652 assert(!Cap->capturesVariableArrayType() &&
7653 "Not expecting to generate map info for a variable array type!");
7654
Samuel Antao6890b092016-07-28 14:25:09 +00007655 // We need to know when we generating information for the first component
Alexey Bataevb3638132018-07-19 16:34:13 +00007656 const ValueDecl *VD = Cap->capturesThis()
7657 ? nullptr
7658 : Cap->getCapturedVar()->getCanonicalDecl();
Samuel Antao86ace552016-04-27 22:40:57 +00007659
Samuel Antao6890b092016-07-28 14:25:09 +00007660 // If this declaration appears in a is_device_ptr clause we just have to
7661 // pass the pointer by value. If it is a reference to a declaration, we just
Alexey Bataevb3638132018-07-19 16:34:13 +00007662 // pass its value.
7663 if (DevPointersMap.count(VD)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007664 BasePointers.emplace_back(Arg, VD);
Samuel Antao6890b092016-07-28 14:25:09 +00007665 Pointers.push_back(Arg);
7666 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
George Rokos065755d2017-11-07 18:27:04 +00007667 Types.push_back(OMP_MAP_LITERAL | OMP_MAP_TARGET_PARAM);
Samuel Antao6890b092016-07-28 14:25:09 +00007668 return;
7669 }
7670
Alexey Bataeve82445f2018-09-20 13:54:02 +00007671 using MapData =
7672 std::tuple<OMPClauseMappableExprCommon::MappableExprComponentListRef,
Kelvin Lief579432018-12-18 22:18:41 +00007673 OpenMPMapClauseKind, ArrayRef<OpenMPMapModifierKind>, bool>;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007674 SmallVector<MapData, 4> DeclComponentLists;
Paul Robinson78fb1322016-08-01 22:12:46 +00007675 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeve82445f2018-09-20 13:54:02 +00007676 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007677 for (const auto &L : C->decl_component_lists(VD)) {
Samuel Antao86ace552016-04-27 22:40:57 +00007678 assert(L.first == VD &&
7679 "We got information for the wrong declaration??");
7680 assert(!L.second.empty() &&
7681 "Not expecting declaration with no component lists.");
Alexey Bataeve82445f2018-09-20 13:54:02 +00007682 DeclComponentLists.emplace_back(L.second, C->getMapType(),
Kelvin Lief579432018-12-18 22:18:41 +00007683 C->getMapTypeModifiers(),
Alexey Bataeve82445f2018-09-20 13:54:02 +00007684 C->isImplicit());
Samuel Antao86ace552016-04-27 22:40:57 +00007685 }
Alexey Bataeve82445f2018-09-20 13:54:02 +00007686 }
7687
7688 // Find overlapping elements (including the offset from the base element).
7689 llvm::SmallDenseMap<
7690 const MapData *,
7691 llvm::SmallVector<
7692 OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>,
7693 4>
7694 OverlappedData;
7695 size_t Count = 0;
7696 for (const MapData &L : DeclComponentLists) {
7697 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7698 OpenMPMapClauseKind MapType;
Kelvin Lief579432018-12-18 22:18:41 +00007699 ArrayRef<OpenMPMapModifierKind> MapModifiers;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007700 bool IsImplicit;
Kelvin Lief579432018-12-18 22:18:41 +00007701 std::tie(Components, MapType, MapModifiers, IsImplicit) = L;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007702 ++Count;
7703 for (const MapData &L1 : makeArrayRef(DeclComponentLists).slice(Count)) {
7704 OMPClauseMappableExprCommon::MappableExprComponentListRef Components1;
Kelvin Lief579432018-12-18 22:18:41 +00007705 std::tie(Components1, MapType, MapModifiers, IsImplicit) = L1;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007706 auto CI = Components.rbegin();
7707 auto CE = Components.rend();
7708 auto SI = Components1.rbegin();
7709 auto SE = Components1.rend();
7710 for (; CI != CE && SI != SE; ++CI, ++SI) {
7711 if (CI->getAssociatedExpression()->getStmtClass() !=
7712 SI->getAssociatedExpression()->getStmtClass())
7713 break;
7714 // Are we dealing with different variables/fields?
7715 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
7716 break;
7717 }
7718 // Found overlapping if, at least for one component, reached the head of
7719 // the components list.
7720 if (CI == CE || SI == SE) {
7721 assert((CI != CE || SI != SE) &&
7722 "Unexpected full match of the mapping components.");
7723 const MapData &BaseData = CI == CE ? L : L1;
7724 OMPClauseMappableExprCommon::MappableExprComponentListRef SubData =
7725 SI == SE ? Components : Components1;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007726 auto &OverlappedElements = OverlappedData.FindAndConstruct(&BaseData);
7727 OverlappedElements.getSecond().push_back(SubData);
7728 }
7729 }
7730 }
7731 // Sort the overlapped elements for each item.
7732 llvm::SmallVector<const FieldDecl *, 4> Layout;
7733 if (!OverlappedData.empty()) {
7734 if (const auto *CRD =
7735 VD->getType().getCanonicalType()->getAsCXXRecordDecl())
7736 getPlainLayout(CRD, Layout, /*AsBase=*/false);
7737 else {
7738 const auto *RD = VD->getType().getCanonicalType()->getAsRecordDecl();
7739 Layout.append(RD->field_begin(), RD->field_end());
7740 }
7741 }
7742 for (auto &Pair : OverlappedData) {
7743 llvm::sort(
7744 Pair.getSecond(),
7745 [&Layout](
7746 OMPClauseMappableExprCommon::MappableExprComponentListRef First,
7747 OMPClauseMappableExprCommon::MappableExprComponentListRef
7748 Second) {
7749 auto CI = First.rbegin();
7750 auto CE = First.rend();
7751 auto SI = Second.rbegin();
7752 auto SE = Second.rend();
7753 for (; CI != CE && SI != SE; ++CI, ++SI) {
7754 if (CI->getAssociatedExpression()->getStmtClass() !=
7755 SI->getAssociatedExpression()->getStmtClass())
7756 break;
7757 // Are we dealing with different variables/fields?
7758 if (CI->getAssociatedDeclaration() !=
7759 SI->getAssociatedDeclaration())
7760 break;
7761 }
Richard Trieu5061e832018-09-21 21:20:33 +00007762
7763 // Lists contain the same elements.
7764 if (CI == CE && SI == SE)
7765 return false;
7766
7767 // List with less elements is less than list with more elements.
7768 if (CI == CE || SI == SE)
7769 return CI == CE;
7770
Alexey Bataeve82445f2018-09-20 13:54:02 +00007771 const auto *FD1 = cast<FieldDecl>(CI->getAssociatedDeclaration());
7772 const auto *FD2 = cast<FieldDecl>(SI->getAssociatedDeclaration());
7773 if (FD1->getParent() == FD2->getParent())
7774 return FD1->getFieldIndex() < FD2->getFieldIndex();
7775 const auto It =
7776 llvm::find_if(Layout, [FD1, FD2](const FieldDecl *FD) {
7777 return FD == FD1 || FD == FD2;
7778 });
7779 return *It == FD1;
7780 });
7781 }
7782
7783 // Associated with a capture, because the mapping flags depend on it.
7784 // Go through all of the elements with the overlapped elements.
7785 for (const auto &Pair : OverlappedData) {
7786 const MapData &L = *Pair.getFirst();
7787 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7788 OpenMPMapClauseKind MapType;
Kelvin Lief579432018-12-18 22:18:41 +00007789 ArrayRef<OpenMPMapModifierKind> MapModifiers;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007790 bool IsImplicit;
Kelvin Lief579432018-12-18 22:18:41 +00007791 std::tie(Components, MapType, MapModifiers, IsImplicit) = L;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007792 ArrayRef<OMPClauseMappableExprCommon::MappableExprComponentListRef>
7793 OverlappedComponents = Pair.getSecond();
7794 bool IsFirstComponentList = true;
Kelvin Lief579432018-12-18 22:18:41 +00007795 generateInfoForComponentList(MapType, MapModifiers, Components,
Alexey Bataeve82445f2018-09-20 13:54:02 +00007796 BasePointers, Pointers, Sizes, Types,
7797 PartialStruct, IsFirstComponentList,
7798 IsImplicit, OverlappedComponents);
7799 }
7800 // Go through other elements without overlapped elements.
7801 bool IsFirstComponentList = OverlappedData.empty();
7802 for (const MapData &L : DeclComponentLists) {
7803 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7804 OpenMPMapClauseKind MapType;
Kelvin Lief579432018-12-18 22:18:41 +00007805 ArrayRef<OpenMPMapModifierKind> MapModifiers;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007806 bool IsImplicit;
Kelvin Lief579432018-12-18 22:18:41 +00007807 std::tie(Components, MapType, MapModifiers, IsImplicit) = L;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007808 auto It = OverlappedData.find(&L);
7809 if (It == OverlappedData.end())
Kelvin Lief579432018-12-18 22:18:41 +00007810 generateInfoForComponentList(MapType, MapModifiers, Components,
Alexey Bataeve82445f2018-09-20 13:54:02 +00007811 BasePointers, Pointers, Sizes, Types,
7812 PartialStruct, IsFirstComponentList,
7813 IsImplicit);
7814 IsFirstComponentList = false;
7815 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007816 }
Samuel Antao86ace552016-04-27 22:40:57 +00007817
Alexey Bataevb3638132018-07-19 16:34:13 +00007818 /// Generate the base pointers, section pointers, sizes and map types
7819 /// associated with the declare target link variables.
7820 void generateInfoForDeclareTargetLink(MapBaseValuesArrayTy &BasePointers,
7821 MapValuesArrayTy &Pointers,
7822 MapValuesArrayTy &Sizes,
7823 MapFlagsArrayTy &Types) const {
7824 // Map other list items in the map clause which are not captured variables
7825 // but "declare target link" global variables.,
7826 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) {
7827 for (const auto &L : C->component_lists()) {
7828 if (!L.first)
7829 continue;
7830 const auto *VD = dyn_cast<VarDecl>(L.first);
7831 if (!VD)
7832 continue;
7833 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00007834 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataevb3638132018-07-19 16:34:13 +00007835 if (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link)
7836 continue;
7837 StructRangeInfoTy PartialStruct;
7838 generateInfoForComponentList(
Kelvin Lief579432018-12-18 22:18:41 +00007839 C->getMapType(), C->getMapTypeModifiers(), L.second, BasePointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007840 Pointers, Sizes, Types, PartialStruct,
7841 /*IsFirstComponentList=*/true, C->isImplicit());
7842 assert(!PartialStruct.Base.isValid() &&
7843 "No partial structs for declare target link expected.");
7844 }
7845 }
Samuel Antao86ace552016-04-27 22:40:57 +00007846 }
Samuel Antaod486f842016-05-26 16:53:38 +00007847
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007848 /// Generate the default map information for a given capture \a CI,
Samuel Antaod486f842016-05-26 16:53:38 +00007849 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00007850 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
7851 const FieldDecl &RI, llvm::Value *CV,
7852 MapBaseValuesArrayTy &CurBasePointers,
7853 MapValuesArrayTy &CurPointers,
7854 MapValuesArrayTy &CurSizes,
Alexey Bataevb3638132018-07-19 16:34:13 +00007855 MapFlagsArrayTy &CurMapTypes) const {
Samuel Antaod486f842016-05-26 16:53:38 +00007856 // Do the default mapping.
7857 if (CI.capturesThis()) {
7858 CurBasePointers.push_back(CV);
7859 CurPointers.push_back(CV);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007860 const auto *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007861 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
7862 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00007863 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00007864 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007865 CurBasePointers.push_back(CV);
7866 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00007867 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007868 // We have to signal to the runtime captures passed by value that are
7869 // not pointers.
George Rokos065755d2017-11-07 18:27:04 +00007870 CurMapTypes.push_back(OMP_MAP_LITERAL);
Samuel Antaod486f842016-05-26 16:53:38 +00007871 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
7872 } else {
7873 // Pointers are implicitly mapped with a zero size and no flags
7874 // (other than first map that is added for all implicit maps).
Alexey Bataevb3638132018-07-19 16:34:13 +00007875 CurMapTypes.push_back(OMP_MAP_NONE);
Samuel Antaod486f842016-05-26 16:53:38 +00007876 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
7877 }
7878 } else {
7879 assert(CI.capturesVariable() && "Expected captured reference.");
7880 CurBasePointers.push_back(CV);
7881 CurPointers.push_back(CV);
7882
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007883 const auto *PtrTy = cast<ReferenceType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007884 QualType ElementType = PtrTy->getPointeeType();
7885 CurSizes.push_back(CGF.getTypeSize(ElementType));
7886 // The default map type for a scalar/complex type is 'to' because by
7887 // default the value doesn't have to be retrieved. For an aggregate
7888 // type, the default is 'tofrom'.
Alexey Bataevb3638132018-07-19 16:34:13 +00007889 CurMapTypes.push_back(getMapModifiersForPrivateClauses(CI));
Samuel Antaod486f842016-05-26 16:53:38 +00007890 }
George Rokos065755d2017-11-07 18:27:04 +00007891 // Every default map produces a single argument which is a target parameter.
7892 CurMapTypes.back() |= OMP_MAP_TARGET_PARAM;
Alexey Bataevb3638132018-07-19 16:34:13 +00007893
7894 // Add flag stating this is an implicit map.
7895 CurMapTypes.back() |= OMP_MAP_IMPLICIT;
Samuel Antaod486f842016-05-26 16:53:38 +00007896 }
Samuel Antao86ace552016-04-27 22:40:57 +00007897};
Samuel Antaodf158d52016-04-27 22:58:19 +00007898
7899enum OpenMPOffloadingReservedDeviceIDs {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007900 /// Device ID if the device was not defined, runtime should get it
Samuel Antaodf158d52016-04-27 22:58:19 +00007901 /// from environment variables in the spec.
7902 OMP_DEVICEID_UNDEF = -1,
7903};
7904} // anonymous namespace
7905
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007906/// Emit the arrays used to pass the captures and map information to the
Samuel Antaodf158d52016-04-27 22:58:19 +00007907/// offloading runtime library. If there is no map or capture information,
7908/// return nullptr by reference.
7909static void
Samuel Antaocc10b852016-07-28 14:23:26 +00007910emitOffloadingArrays(CodeGenFunction &CGF,
7911 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00007912 MappableExprsHandler::MapValuesArrayTy &Pointers,
7913 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00007914 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
7915 CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007916 CodeGenModule &CGM = CGF.CGM;
7917 ASTContext &Ctx = CGF.getContext();
Samuel Antaodf158d52016-04-27 22:58:19 +00007918
Samuel Antaocc10b852016-07-28 14:23:26 +00007919 // Reset the array information.
7920 Info.clearArrayInfo();
7921 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00007922
Samuel Antaocc10b852016-07-28 14:23:26 +00007923 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007924 // Detect if we have any capture size requiring runtime evaluation of the
7925 // size so that a constant array could be eventually used.
7926 bool hasRuntimeEvaluationCaptureSize = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007927 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00007928 if (!isa<llvm::Constant>(S)) {
7929 hasRuntimeEvaluationCaptureSize = true;
7930 break;
7931 }
7932
Samuel Antaocc10b852016-07-28 14:23:26 +00007933 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00007934 QualType PointerArrayType =
7935 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
7936 /*IndexTypeQuals=*/0);
7937
Samuel Antaocc10b852016-07-28 14:23:26 +00007938 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007939 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00007940 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007941 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
7942
7943 // If we don't have any VLA types or other types that require runtime
7944 // evaluation, we can use a constant array for the map sizes, otherwise we
7945 // need to fill up the arrays as we do for the pointers.
7946 if (hasRuntimeEvaluationCaptureSize) {
7947 QualType SizeArrayType = Ctx.getConstantArrayType(
7948 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
7949 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00007950 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007951 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
7952 } else {
7953 // We expect all the sizes to be constant, so we collect them to create
7954 // a constant array.
7955 SmallVector<llvm::Constant *, 16> ConstSizes;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007956 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00007957 ConstSizes.push_back(cast<llvm::Constant>(S));
7958
7959 auto *SizesArrayInit = llvm::ConstantArray::get(
7960 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
Alexey Bataev18fa2322018-05-02 14:20:50 +00007961 std::string Name = CGM.getOpenMPRuntime().getName({"offload_sizes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00007962 auto *SizesArrayGbl = new llvm::GlobalVariable(
7963 CGM.getModule(), SizesArrayInit->getType(),
7964 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00007965 SizesArrayInit, Name);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00007966 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00007967 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00007968 }
7969
7970 // The map types are always constant so we don't need to generate code to
7971 // fill arrays. Instead, we create an array constant.
Alexey Bataevb3638132018-07-19 16:34:13 +00007972 SmallVector<uint64_t, 4> Mapping(MapTypes.size(), 0);
7973 llvm::copy(MapTypes, Mapping.begin());
Samuel Antaodf158d52016-04-27 22:58:19 +00007974 llvm::Constant *MapTypesArrayInit =
Alexey Bataevb3638132018-07-19 16:34:13 +00007975 llvm::ConstantDataArray::get(CGF.Builder.getContext(), Mapping);
Alexey Bataev18fa2322018-05-02 14:20:50 +00007976 std::string MaptypesName =
7977 CGM.getOpenMPRuntime().getName({"offload_maptypes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00007978 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
7979 CGM.getModule(), MapTypesArrayInit->getType(),
7980 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00007981 MapTypesArrayInit, MaptypesName);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00007982 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00007983 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00007984
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007985 for (unsigned I = 0; I < Info.NumberOfPtrs; ++I) {
7986 llvm::Value *BPVal = *BasePointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00007987 llvm::Value *BP = 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.BasePointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00007990 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7991 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00007992 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
7993 CGF.Builder.CreateStore(BPVal, BPAddr);
7994
Samuel Antaocc10b852016-07-28 14:23:26 +00007995 if (Info.requiresDevicePointerInfo())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007996 if (const ValueDecl *DevVD = BasePointers[I].getDevicePtrDecl())
Alexey Bataev43a919f2018-04-13 17:48:43 +00007997 Info.CaptureDeviceAddrMap.try_emplace(DevVD, BPAddr);
Samuel Antaocc10b852016-07-28 14:23:26 +00007998
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007999 llvm::Value *PVal = Pointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00008000 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008001 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008002 Info.PointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00008003 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
8004 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00008005 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
8006 CGF.Builder.CreateStore(PVal, PAddr);
8007
8008 if (hasRuntimeEvaluationCaptureSize) {
8009 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008010 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
8011 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008012 /*Idx0=*/0,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008013 /*Idx1=*/I);
Samuel Antaodf158d52016-04-27 22:58:19 +00008014 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
8015 CGF.Builder.CreateStore(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008016 CGF.Builder.CreateIntCast(Sizes[I], CGM.SizeTy, /*isSigned=*/true),
Samuel Antaodf158d52016-04-27 22:58:19 +00008017 SAddr);
8018 }
8019 }
8020 }
8021}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008022/// Emit the arguments to be passed to the runtime library based on the
Samuel Antaodf158d52016-04-27 22:58:19 +00008023/// arrays of pointers, sizes and map types.
8024static void emitOffloadingArraysArgument(
8025 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
8026 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008027 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008028 CodeGenModule &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00008029 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008030 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008031 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
8032 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008033 /*Idx0=*/0, /*Idx1=*/0);
8034 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008035 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
8036 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008037 /*Idx0=*/0,
8038 /*Idx1=*/0);
8039 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008040 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008041 /*Idx0=*/0, /*Idx1=*/0);
8042 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
George Rokos63bc9d62017-11-21 18:25:12 +00008043 llvm::ArrayType::get(CGM.Int64Ty, Info.NumberOfPtrs),
Samuel Antaocc10b852016-07-28 14:23:26 +00008044 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008045 /*Idx0=*/0,
8046 /*Idx1=*/0);
8047 } else {
8048 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
8049 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
8050 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
8051 MapTypesArrayArg =
George Rokos63bc9d62017-11-21 18:25:12 +00008052 llvm::ConstantPointerNull::get(CGM.Int64Ty->getPointerTo());
Samuel Antaodf158d52016-04-27 22:58:19 +00008053 }
Samuel Antao86ace552016-04-27 22:40:57 +00008054}
8055
Samuel Antaobed3c462015-10-02 16:14:20 +00008056void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
8057 const OMPExecutableDirective &D,
8058 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00008059 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00008060 const Expr *IfCond, const Expr *Device) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00008061 if (!CGF.HaveInsertPoint())
8062 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00008063
Samuel Antaoee8fb302016-01-06 13:42:12 +00008064 assert(OutlinedFn && "Invalid outlined function!");
8065
Alexey Bataev8451efa2018-01-15 19:06:12 +00008066 const bool RequiresOuterTask = D.hasClausesOfKind<OMPDependClause>();
8067 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Alexey Bataev475a7442018-01-12 19:39:11 +00008068 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008069 auto &&ArgsCodegen = [&CS, &CapturedVars](CodeGenFunction &CGF,
8070 PrePostActionTy &) {
8071 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
8072 };
8073 emitInlinedDirective(CGF, OMPD_unknown, ArgsCodegen);
Samuel Antao86ace552016-04-27 22:40:57 +00008074
Alexey Bataev8451efa2018-01-15 19:06:12 +00008075 CodeGenFunction::OMPTargetDataInfo InputInfo;
8076 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00008077 // Fill up the pointer arrays and transfer execution to the device.
Alexey Bataev8451efa2018-01-15 19:06:12 +00008078 auto &&ThenGen = [this, Device, OutlinedFn, OutlinedFnID, &D, &InputInfo,
8079 &MapTypesArray, &CS, RequiresOuterTask,
8080 &CapturedVars](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobed3c462015-10-02 16:14:20 +00008081 // On top of the arrays that were filled up, the target offloading call
8082 // takes as arguments the device id as well as the host pointer. The host
8083 // pointer is used by the runtime library to identify the current target
8084 // region, so it only has to be unique and not necessarily point to
8085 // anything. It could be the pointer to the outlined function that
8086 // implements the target region, but we aren't using that so that the
8087 // compiler doesn't need to keep that, and could therefore inline the host
8088 // function if proven worthwhile during optimization.
8089
Samuel Antaoee8fb302016-01-06 13:42:12 +00008090 // From this point on, we need to have an ID of the target region defined.
8091 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00008092
8093 // Emit device ID if any.
8094 llvm::Value *DeviceID;
George Rokos63bc9d62017-11-21 18:25:12 +00008095 if (Device) {
Samuel Antaobed3c462015-10-02 16:14:20 +00008096 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008097 CGF.Int64Ty, /*isSigned=*/true);
8098 } else {
8099 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8100 }
Samuel Antaobed3c462015-10-02 16:14:20 +00008101
Samuel Antaodf158d52016-04-27 22:58:19 +00008102 // Emit the number of elements in the offloading arrays.
Alexey Bataev8451efa2018-01-15 19:06:12 +00008103 llvm::Value *PointerNum =
8104 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaodf158d52016-04-27 22:58:19 +00008105
Samuel Antaob68e2db2016-03-03 16:20:23 +00008106 // Return value of the runtime offloading call.
8107 llvm::Value *Return;
8108
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008109 llvm::Value *NumTeams = emitNumTeamsForTargetDirective(*this, CGF, D);
8110 llvm::Value *NumThreads = emitNumThreadsForTargetDirective(*this, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00008111
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008112 bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008113 // The target region is an outlined function launched by the runtime
8114 // via calls __tgt_target() or __tgt_target_teams().
8115 //
8116 // __tgt_target() launches a target region with one team and one thread,
8117 // executing a serial region. This master thread may in turn launch
8118 // more threads within its team upon encountering a parallel region,
8119 // however, no additional teams can be launched on the device.
8120 //
8121 // __tgt_target_teams() launches a target region with one or more teams,
8122 // each with one or more threads. This call is required for target
8123 // constructs such as:
8124 // 'target teams'
8125 // 'target' / 'teams'
8126 // 'target teams distribute parallel for'
8127 // 'target parallel'
8128 // and so on.
8129 //
8130 // Note that on the host and CPU targets, the runtime implementation of
8131 // these calls simply call the outlined function without forking threads.
8132 // The outlined functions themselves have runtime calls to
8133 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
8134 // the compiler in emitTeamsCall() and emitParallelCall().
8135 //
8136 // In contrast, on the NVPTX target, the implementation of
8137 // __tgt_target_teams() launches a GPU kernel with the requested number
8138 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00008139 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008140 // If we have NumTeams defined this means that we have an enclosed teams
8141 // region. Therefore we also expect to have NumThreads defined. These two
8142 // values should be defined in the presence of a teams directive,
8143 // regardless of having any clauses associated. If the user is using teams
8144 // but no clauses, these two values will be the default that should be
8145 // passed to the runtime library - a 32-bit integer with the value zero.
8146 assert(NumThreads && "Thread limit expression should be available along "
8147 "with number of teams.");
Alexey Bataev8451efa2018-01-15 19:06:12 +00008148 llvm::Value *OffloadingArgs[] = {DeviceID,
8149 OutlinedFnID,
8150 PointerNum,
8151 InputInfo.BasePointersArray.getPointer(),
8152 InputInfo.PointersArray.getPointer(),
8153 InputInfo.SizesArray.getPointer(),
8154 MapTypesArray,
8155 NumTeams,
8156 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00008157 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00008158 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_teams_nowait
8159 : OMPRTL__tgt_target_teams),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008160 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00008161 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00008162 llvm::Value *OffloadingArgs[] = {DeviceID,
8163 OutlinedFnID,
8164 PointerNum,
8165 InputInfo.BasePointersArray.getPointer(),
8166 InputInfo.PointersArray.getPointer(),
8167 InputInfo.SizesArray.getPointer(),
8168 MapTypesArray};
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008169 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00008170 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_nowait
8171 : OMPRTL__tgt_target),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008172 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00008173 }
Samuel Antaobed3c462015-10-02 16:14:20 +00008174
Alexey Bataev2a007e02017-10-02 14:20:58 +00008175 // Check the error code and execute the host version if required.
8176 llvm::BasicBlock *OffloadFailedBlock =
8177 CGF.createBasicBlock("omp_offload.failed");
8178 llvm::BasicBlock *OffloadContBlock =
8179 CGF.createBasicBlock("omp_offload.cont");
8180 llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
8181 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
8182
8183 CGF.EmitBlock(OffloadFailedBlock);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008184 if (RequiresOuterTask) {
8185 CapturedVars.clear();
8186 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
8187 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008188 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars);
Alexey Bataev2a007e02017-10-02 14:20:58 +00008189 CGF.EmitBranch(OffloadContBlock);
8190
8191 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00008192 };
8193
Samuel Antaoee8fb302016-01-06 13:42:12 +00008194 // Notify that the host version must be executed.
Alexey Bataev8451efa2018-01-15 19:06:12 +00008195 auto &&ElseGen = [this, &D, OutlinedFn, &CS, &CapturedVars,
8196 RequiresOuterTask](CodeGenFunction &CGF,
8197 PrePostActionTy &) {
8198 if (RequiresOuterTask) {
8199 CapturedVars.clear();
8200 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
8201 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008202 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008203 };
8204
8205 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray,
8206 &CapturedVars, RequiresOuterTask,
8207 &CS](CodeGenFunction &CGF, PrePostActionTy &) {
8208 // Fill up the arrays with all the captured variables.
8209 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
8210 MappableExprsHandler::MapValuesArrayTy Pointers;
8211 MappableExprsHandler::MapValuesArrayTy Sizes;
8212 MappableExprsHandler::MapFlagsArrayTy MapTypes;
8213
Alexey Bataev8451efa2018-01-15 19:06:12 +00008214 // Get mappable expression information.
8215 MappableExprsHandler MEHandler(D, CGF);
Alexey Bataev969dbc02018-11-08 15:47:39 +00008216 llvm::DenseMap<llvm::Value *, llvm::Value *> LambdaPointers;
Alexey Bataev8451efa2018-01-15 19:06:12 +00008217
8218 auto RI = CS.getCapturedRecordDecl()->field_begin();
8219 auto CV = CapturedVars.begin();
8220 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
8221 CE = CS.capture_end();
8222 CI != CE; ++CI, ++RI, ++CV) {
Alexey Bataevb3638132018-07-19 16:34:13 +00008223 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
8224 MappableExprsHandler::MapValuesArrayTy CurPointers;
8225 MappableExprsHandler::MapValuesArrayTy CurSizes;
8226 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
8227 MappableExprsHandler::StructRangeInfoTy PartialStruct;
Alexey Bataev8451efa2018-01-15 19:06:12 +00008228
8229 // VLA sizes are passed to the outlined region by copy and do not have map
8230 // information associated.
8231 if (CI->capturesVariableArrayType()) {
8232 CurBasePointers.push_back(*CV);
8233 CurPointers.push_back(*CV);
8234 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
8235 // Copy to the device as an argument. No need to retrieve it.
8236 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_LITERAL |
8237 MappableExprsHandler::OMP_MAP_TARGET_PARAM);
8238 } else {
8239 // If we have any information in the map clause, we use it, otherwise we
8240 // just do a default mapping.
8241 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00008242 CurSizes, CurMapTypes, PartialStruct);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008243 if (CurBasePointers.empty())
8244 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
8245 CurPointers, CurSizes, CurMapTypes);
Alexey Bataev60705422018-10-30 15:50:12 +00008246 // Generate correct mapping for variables captured by reference in
8247 // lambdas.
8248 if (CI->capturesVariable())
Alexey Bataev969dbc02018-11-08 15:47:39 +00008249 MEHandler.generateInfoForLambdaCaptures(
8250 CI->getCapturedVar(), *CV, CurBasePointers, CurPointers, CurSizes,
8251 CurMapTypes, LambdaPointers);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008252 }
8253 // We expect to have at least an element of information for this capture.
8254 assert(!CurBasePointers.empty() &&
8255 "Non-existing map pointer for capture!");
8256 assert(CurBasePointers.size() == CurPointers.size() &&
8257 CurBasePointers.size() == CurSizes.size() &&
8258 CurBasePointers.size() == CurMapTypes.size() &&
8259 "Inconsistent map information sizes!");
8260
Alexey Bataevb3638132018-07-19 16:34:13 +00008261 // If there is an entry in PartialStruct it means we have a struct with
8262 // individual members mapped. Emit an extra combined entry.
8263 if (PartialStruct.Base.isValid())
8264 MEHandler.emitCombinedEntry(BasePointers, Pointers, Sizes, MapTypes,
8265 CurMapTypes, PartialStruct);
8266
Alexey Bataev8451efa2018-01-15 19:06:12 +00008267 // We need to append the results of this capture to what we already have.
8268 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
8269 Pointers.append(CurPointers.begin(), CurPointers.end());
8270 Sizes.append(CurSizes.begin(), CurSizes.end());
8271 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
8272 }
Alexey Bataev60705422018-10-30 15:50:12 +00008273 // Adjust MEMBER_OF flags for the lambdas captures.
Alexey Bataev969dbc02018-11-08 15:47:39 +00008274 MEHandler.adjustMemberOfForLambdaCaptures(LambdaPointers, BasePointers,
8275 Pointers, MapTypes);
Alexey Bataev92327c52018-03-26 16:40:55 +00008276 // Map other list items in the map clause which are not captured variables
8277 // but "declare target link" global variables.
Alexey Bataevb3638132018-07-19 16:34:13 +00008278 MEHandler.generateInfoForDeclareTargetLink(BasePointers, Pointers, Sizes,
8279 MapTypes);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008280
8281 TargetDataInfo Info;
8282 // Fill up the arrays and create the arguments.
8283 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
8284 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
8285 Info.PointersArray, Info.SizesArray,
8286 Info.MapTypesArray, Info);
8287 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
8288 InputInfo.BasePointersArray =
8289 Address(Info.BasePointersArray, CGM.getPointerAlign());
8290 InputInfo.PointersArray =
8291 Address(Info.PointersArray, CGM.getPointerAlign());
8292 InputInfo.SizesArray = Address(Info.SizesArray, CGM.getPointerAlign());
8293 MapTypesArray = Info.MapTypesArray;
8294 if (RequiresOuterTask)
8295 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
8296 else
8297 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
8298 };
8299
8300 auto &&TargetElseGen = [this, &ElseGen, &D, RequiresOuterTask](
8301 CodeGenFunction &CGF, PrePostActionTy &) {
8302 if (RequiresOuterTask) {
8303 CodeGenFunction::OMPTargetDataInfo InputInfo;
8304 CGF.EmitOMPTargetTaskBasedDirective(D, ElseGen, InputInfo);
8305 } else {
8306 emitInlinedDirective(CGF, D.getDirectiveKind(), ElseGen);
8307 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00008308 };
8309
8310 // If we have a target function ID it means that we need to support
8311 // offloading, otherwise, just execute on the host. We need to execute on host
8312 // regardless of the conditional in the if clause if, e.g., the user do not
8313 // specify target triples.
8314 if (OutlinedFnID) {
Alexey Bataev8451efa2018-01-15 19:06:12 +00008315 if (IfCond) {
8316 emitOMPIfClause(CGF, IfCond, TargetThenGen, TargetElseGen);
8317 } else {
8318 RegionCodeGenTy ThenRCG(TargetThenGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00008319 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00008320 }
8321 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00008322 RegionCodeGenTy ElseRCG(TargetElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00008323 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00008324 }
Samuel Antaobed3c462015-10-02 16:14:20 +00008325}
Samuel Antaoee8fb302016-01-06 13:42:12 +00008326
8327void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
8328 StringRef ParentName) {
8329 if (!S)
8330 return;
8331
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008332 // Codegen OMP target directives that offload compute to the device.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008333 bool RequiresDeviceCodegen =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008334 isa<OMPExecutableDirective>(S) &&
8335 isOpenMPTargetExecutionDirective(
8336 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00008337
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008338 if (RequiresDeviceCodegen) {
8339 const auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008340 unsigned DeviceID;
8341 unsigned FileID;
8342 unsigned Line;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008343 getTargetEntryUniqueInfo(CGM.getContext(), E.getBeginLoc(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00008344 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008345
8346 // Is this a target region that should not be emitted as an entry point? If
8347 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00008348 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
8349 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008350 return;
8351
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008352 switch (E.getDirectiveKind()) {
8353 case OMPD_target:
8354 CodeGenFunction::EmitOMPTargetDeviceFunction(CGM, ParentName,
8355 cast<OMPTargetDirective>(E));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008356 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008357 case OMPD_target_parallel:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00008358 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008359 CGM, ParentName, cast<OMPTargetParallelDirective>(E));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00008360 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008361 case OMPD_target_teams:
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00008362 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008363 CGM, ParentName, cast<OMPTargetTeamsDirective>(E));
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00008364 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008365 case OMPD_target_teams_distribute:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008366 CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008367 CGM, ParentName, cast<OMPTargetTeamsDistributeDirective>(E));
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008368 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008369 case OMPD_target_teams_distribute_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008370 CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008371 CGM, ParentName, cast<OMPTargetTeamsDistributeSimdDirective>(E));
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008372 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008373 case OMPD_target_parallel_for:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008374 CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008375 CGM, ParentName, cast<OMPTargetParallelForDirective>(E));
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008376 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008377 case OMPD_target_parallel_for_simd:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008378 CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008379 CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(E));
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008380 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008381 case OMPD_target_simd:
Alexey Bataevf8365372017-11-17 17:57:25 +00008382 CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008383 CGM, ParentName, cast<OMPTargetSimdDirective>(E));
Alexey Bataevf8365372017-11-17 17:57:25 +00008384 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008385 case OMPD_target_teams_distribute_parallel_for:
Carlo Bertolli52978c32018-01-03 21:12:44 +00008386 CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
8387 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008388 cast<OMPTargetTeamsDistributeParallelForDirective>(E));
Carlo Bertolli52978c32018-01-03 21:12:44 +00008389 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008390 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00008391 CodeGenFunction::
8392 EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
8393 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008394 cast<OMPTargetTeamsDistributeParallelForSimdDirective>(E));
Alexey Bataev647dd842018-01-15 20:59:40 +00008395 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008396 case OMPD_parallel:
8397 case OMPD_for:
8398 case OMPD_parallel_for:
8399 case OMPD_parallel_sections:
8400 case OMPD_for_simd:
8401 case OMPD_parallel_for_simd:
8402 case OMPD_cancel:
8403 case OMPD_cancellation_point:
8404 case OMPD_ordered:
8405 case OMPD_threadprivate:
8406 case OMPD_task:
8407 case OMPD_simd:
8408 case OMPD_sections:
8409 case OMPD_section:
8410 case OMPD_single:
8411 case OMPD_master:
8412 case OMPD_critical:
8413 case OMPD_taskyield:
8414 case OMPD_barrier:
8415 case OMPD_taskwait:
8416 case OMPD_taskgroup:
8417 case OMPD_atomic:
8418 case OMPD_flush:
8419 case OMPD_teams:
8420 case OMPD_target_data:
8421 case OMPD_target_exit_data:
8422 case OMPD_target_enter_data:
8423 case OMPD_distribute:
8424 case OMPD_distribute_simd:
8425 case OMPD_distribute_parallel_for:
8426 case OMPD_distribute_parallel_for_simd:
8427 case OMPD_teams_distribute:
8428 case OMPD_teams_distribute_simd:
8429 case OMPD_teams_distribute_parallel_for:
8430 case OMPD_teams_distribute_parallel_for_simd:
8431 case OMPD_target_update:
8432 case OMPD_declare_simd:
8433 case OMPD_declare_target:
8434 case OMPD_end_declare_target:
8435 case OMPD_declare_reduction:
8436 case OMPD_taskloop:
8437 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008438 case OMPD_requires:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008439 case OMPD_unknown:
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008440 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
8441 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00008442 return;
8443 }
8444
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008445 if (const auto *E = dyn_cast<OMPExecutableDirective>(S)) {
Alexey Bataev475a7442018-01-12 19:39:11 +00008446 if (!E->hasAssociatedStmt() || !E->getAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00008447 return;
8448
8449 scanForTargetRegionsFunctions(
Alexey Bataev475a7442018-01-12 19:39:11 +00008450 E->getInnermostCapturedStmt()->getCapturedStmt(), ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008451 return;
8452 }
8453
8454 // If this is a lambda function, look into its body.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008455 if (const auto *L = dyn_cast<LambdaExpr>(S))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008456 S = L->getBody();
8457
8458 // Keep looking for target regions recursively.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008459 for (const Stmt *II : S->children())
Samuel Antaoee8fb302016-01-06 13:42:12 +00008460 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008461}
8462
8463bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008464 // If emitting code for the host, we do not process FD here. Instead we do
8465 // the normal code generation.
8466 if (!CGM.getLangOpts().OpenMPIsDevice)
8467 return false;
8468
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008469 const ValueDecl *VD = cast<ValueDecl>(GD.getDecl());
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008470 StringRef Name = CGM.getMangledName(GD);
8471 // Try to detect target regions in the function.
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008472 if (const auto *FD = dyn_cast<FunctionDecl>(VD))
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008473 scanForTargetRegionsFunctions(FD->getBody(), Name);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008474
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008475 // Do not to emit function if it is not marked as declare target.
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008476 return !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008477 AlreadyEmittedTargetFunctions.count(Name) == 0;
Samuel Antaoee8fb302016-01-06 13:42:12 +00008478}
8479
8480bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
8481 if (!CGM.getLangOpts().OpenMPIsDevice)
8482 return false;
8483
8484 // Check if there are Ctors/Dtors in this declaration and look for target
8485 // regions in it. We use the complete variant to produce the kernel name
8486 // mangling.
8487 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008488 if (const auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
8489 for (const CXXConstructorDecl *Ctor : RD->ctors()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008490 StringRef ParentName =
8491 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
8492 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
8493 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008494 if (const CXXDestructorDecl *Dtor = RD->getDestructor()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008495 StringRef ParentName =
8496 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
8497 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
8498 }
8499 }
8500
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008501 // Do not to emit variable if it is not marked as declare target.
Alexey Bataev92327c52018-03-26 16:40:55 +00008502 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00008503 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
8504 cast<VarDecl>(GD.getDecl()));
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008505 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Alexey Bataevd01b7492018-08-15 19:45:12 +00008506 DeferredGlobalVariables.insert(cast<VarDecl>(GD.getDecl()));
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008507 return true;
8508 }
8509 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00008510}
8511
Alexey Bataev03f270c2018-03-30 18:31:07 +00008512void CGOpenMPRuntime::registerTargetGlobalVariable(const VarDecl *VD,
8513 llvm::Constant *Addr) {
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008514 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
8515 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
8516 if (!Res) {
8517 if (CGM.getLangOpts().OpenMPIsDevice) {
8518 // Register non-target variables being emitted in device code (debug info
8519 // may cause this).
8520 StringRef VarName = CGM.getMangledName(VD);
8521 EmittedNonTargetVariables.try_emplace(VarName, Addr);
Alexey Bataev03f270c2018-03-30 18:31:07 +00008522 }
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008523 return;
Alexey Bataev03f270c2018-03-30 18:31:07 +00008524 }
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008525 // Register declare target variables.
8526 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags;
8527 StringRef VarName;
8528 CharUnits VarSize;
8529 llvm::GlobalValue::LinkageTypes Linkage;
8530 switch (*Res) {
8531 case OMPDeclareTargetDeclAttr::MT_To:
8532 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo;
8533 VarName = CGM.getMangledName(VD);
8534 if (VD->hasDefinition(CGM.getContext()) != VarDecl::DeclarationOnly) {
8535 VarSize = CGM.getContext().getTypeSizeInChars(VD->getType());
8536 assert(!VarSize.isZero() && "Expected non-zero size of the variable");
8537 } else {
8538 VarSize = CharUnits::Zero();
8539 }
8540 Linkage = CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false);
8541 // Temp solution to prevent optimizations of the internal variables.
8542 if (CGM.getLangOpts().OpenMPIsDevice && !VD->isExternallyVisible()) {
8543 std::string RefName = getName({VarName, "ref"});
8544 if (!CGM.GetGlobalValue(RefName)) {
8545 llvm::Constant *AddrRef =
8546 getOrCreateInternalVariable(Addr->getType(), RefName);
8547 auto *GVAddrRef = cast<llvm::GlobalVariable>(AddrRef);
8548 GVAddrRef->setConstant(/*Val=*/true);
8549 GVAddrRef->setLinkage(llvm::GlobalValue::InternalLinkage);
8550 GVAddrRef->setInitializer(Addr);
8551 CGM.addCompilerUsedGlobal(GVAddrRef);
8552 }
8553 }
8554 break;
8555 case OMPDeclareTargetDeclAttr::MT_Link:
8556 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink;
8557 if (CGM.getLangOpts().OpenMPIsDevice) {
8558 VarName = Addr->getName();
8559 Addr = nullptr;
8560 } else {
8561 VarName = getAddrOfDeclareTargetLink(VD).getName();
8562 Addr = cast<llvm::Constant>(getAddrOfDeclareTargetLink(VD).getPointer());
8563 }
8564 VarSize = CGM.getPointerSize();
8565 Linkage = llvm::GlobalValue::WeakAnyLinkage;
8566 break;
8567 }
8568 OffloadEntriesInfoManager.registerDeviceGlobalVarEntryInfo(
8569 VarName, Addr, VarSize, Flags, Linkage);
Alexey Bataev03f270c2018-03-30 18:31:07 +00008570}
8571
Samuel Antaoee8fb302016-01-06 13:42:12 +00008572bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008573 if (isa<FunctionDecl>(GD.getDecl()) ||
8574 isa<OMPDeclareReductionDecl>(GD.getDecl()))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008575 return emitTargetFunctions(GD);
8576
8577 return emitTargetGlobalVariable(GD);
8578}
8579
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008580void CGOpenMPRuntime::emitDeferredTargetDecls() const {
8581 for (const VarDecl *VD : DeferredGlobalVariables) {
8582 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00008583 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataevd01b7492018-08-15 19:45:12 +00008584 if (!Res)
8585 continue;
8586 if (*Res == OMPDeclareTargetDeclAttr::MT_To) {
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008587 CGM.EmitGlobal(VD);
Alexey Bataevd01b7492018-08-15 19:45:12 +00008588 } else {
8589 assert(*Res == OMPDeclareTargetDeclAttr::MT_Link &&
8590 "Expected to or link clauses.");
8591 (void)CGM.getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008592 }
8593 }
8594}
8595
Alexey Bataev60705422018-10-30 15:50:12 +00008596void CGOpenMPRuntime::adjustTargetSpecificDataForLambdas(
8597 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
8598 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
8599 " Expected target-based directive.");
8600}
8601
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008602CGOpenMPRuntime::DisableAutoDeclareTargetRAII::DisableAutoDeclareTargetRAII(
8603 CodeGenModule &CGM)
8604 : CGM(CGM) {
8605 if (CGM.getLangOpts().OpenMPIsDevice) {
8606 SavedShouldMarkAsGlobal = CGM.getOpenMPRuntime().ShouldMarkAsGlobal;
8607 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = false;
8608 }
8609}
8610
8611CGOpenMPRuntime::DisableAutoDeclareTargetRAII::~DisableAutoDeclareTargetRAII() {
8612 if (CGM.getLangOpts().OpenMPIsDevice)
8613 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = SavedShouldMarkAsGlobal;
8614}
8615
Alexey Bataev6d944102018-05-02 15:45:28 +00008616bool CGOpenMPRuntime::markAsGlobalTarget(GlobalDecl GD) {
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008617 if (!CGM.getLangOpts().OpenMPIsDevice || !ShouldMarkAsGlobal)
8618 return true;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008619
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008620 StringRef Name = CGM.getMangledName(GD);
Alexey Bataev6d944102018-05-02 15:45:28 +00008621 const auto *D = cast<FunctionDecl>(GD.getDecl());
Alexey Bataev34f8a702018-03-28 14:28:54 +00008622 // Do not to emit function if it is marked as declare target as it was already
8623 // emitted.
Alexey Bataev97b72212018-08-14 18:31:20 +00008624 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(D)) {
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008625 if (D->hasBody() && AlreadyEmittedTargetFunctions.count(Name) == 0) {
8626 if (auto *F = dyn_cast_or_null<llvm::Function>(CGM.GetGlobalValue(Name)))
Alexey Bataev34f8a702018-03-28 14:28:54 +00008627 return !F->isDeclaration();
8628 return false;
8629 }
8630 return true;
8631 }
8632
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008633 return !AlreadyEmittedTargetFunctions.insert(Name).second;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008634}
8635
Samuel Antaoee8fb302016-01-06 13:42:12 +00008636llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
8637 // If we have offloading in the current module, we need to emit the entries
8638 // now and register the offloading descriptor.
8639 createOffloadEntriesAndInfoMetadata();
8640
8641 // Create and register the offloading binary descriptors. This is the main
8642 // entity that captures all the information about offloading in the current
8643 // compilation unit.
8644 return createOffloadingBinaryDescriptorRegistration();
8645}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008646
8647void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
8648 const OMPExecutableDirective &D,
8649 SourceLocation Loc,
8650 llvm::Value *OutlinedFn,
8651 ArrayRef<llvm::Value *> CapturedVars) {
8652 if (!CGF.HaveInsertPoint())
8653 return;
8654
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008655 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008656 CodeGenFunction::RunCleanupsScope Scope(CGF);
8657
8658 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
8659 llvm::Value *Args[] = {
8660 RTLoc,
8661 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
8662 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
8663 llvm::SmallVector<llvm::Value *, 16> RealArgs;
8664 RealArgs.append(std::begin(Args), std::end(Args));
8665 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
8666
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008667 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008668 CGF.EmitRuntimeCall(RTLFn, RealArgs);
8669}
8670
8671void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00008672 const Expr *NumTeams,
8673 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008674 SourceLocation Loc) {
8675 if (!CGF.HaveInsertPoint())
8676 return;
8677
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008678 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008679
Carlo Bertollic6872252016-04-04 15:55:02 +00008680 llvm::Value *NumTeamsVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008681 NumTeams
Carlo Bertollic6872252016-04-04 15:55:02 +00008682 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
8683 CGF.CGM.Int32Ty, /* isSigned = */ true)
8684 : CGF.Builder.getInt32(0);
8685
8686 llvm::Value *ThreadLimitVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008687 ThreadLimit
Carlo Bertollic6872252016-04-04 15:55:02 +00008688 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
8689 CGF.CGM.Int32Ty, /* isSigned = */ true)
8690 : CGF.Builder.getInt32(0);
8691
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008692 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00008693 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
8694 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008695 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
8696 PushNumTeamsArgs);
8697}
Samuel Antaodf158d52016-04-27 22:58:19 +00008698
Samuel Antaocc10b852016-07-28 14:23:26 +00008699void CGOpenMPRuntime::emitTargetDataCalls(
8700 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8701 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008702 if (!CGF.HaveInsertPoint())
8703 return;
8704
Samuel Antaocc10b852016-07-28 14:23:26 +00008705 // Action used to replace the default codegen action and turn privatization
8706 // off.
8707 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00008708
8709 // Generate the code for the opening of the data environment. Capture all the
8710 // arguments of the runtime call by reference because they are used in the
8711 // closing of the region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008712 auto &&BeginThenGen = [this, &D, Device, &Info,
8713 &CodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008714 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00008715 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00008716 MappableExprsHandler::MapValuesArrayTy Pointers;
8717 MappableExprsHandler::MapValuesArrayTy Sizes;
8718 MappableExprsHandler::MapFlagsArrayTy MapTypes;
8719
8720 // Get map clause information.
8721 MappableExprsHandler MCHandler(D, CGF);
8722 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00008723
8724 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00008725 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008726
8727 llvm::Value *BasePointersArrayArg = nullptr;
8728 llvm::Value *PointersArrayArg = nullptr;
8729 llvm::Value *SizesArrayArg = nullptr;
8730 llvm::Value *MapTypesArrayArg = nullptr;
8731 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008732 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008733
8734 // Emit device ID if any.
8735 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008736 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008737 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008738 CGF.Int64Ty, /*isSigned=*/true);
8739 } else {
8740 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8741 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008742
8743 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008744 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00008745
8746 llvm::Value *OffloadingArgs[] = {
8747 DeviceID, PointerNum, BasePointersArrayArg,
8748 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008749 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_begin),
Samuel Antaodf158d52016-04-27 22:58:19 +00008750 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00008751
8752 // If device pointer privatization is required, emit the body of the region
8753 // here. It will have to be duplicated: with and without privatization.
8754 if (!Info.CaptureDeviceAddrMap.empty())
8755 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008756 };
8757
8758 // Generate code for the closing of the data region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008759 auto &&EndThenGen = [this, Device, &Info](CodeGenFunction &CGF,
8760 PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008761 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00008762
8763 llvm::Value *BasePointersArrayArg = nullptr;
8764 llvm::Value *PointersArrayArg = nullptr;
8765 llvm::Value *SizesArrayArg = nullptr;
8766 llvm::Value *MapTypesArrayArg = nullptr;
8767 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008768 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008769
8770 // Emit device ID if any.
8771 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008772 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008773 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008774 CGF.Int64Ty, /*isSigned=*/true);
8775 } else {
8776 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8777 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008778
8779 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008780 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00008781
8782 llvm::Value *OffloadingArgs[] = {
8783 DeviceID, PointerNum, BasePointersArrayArg,
8784 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008785 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_end),
Samuel Antaodf158d52016-04-27 22:58:19 +00008786 OffloadingArgs);
8787 };
8788
Samuel Antaocc10b852016-07-28 14:23:26 +00008789 // If we need device pointer privatization, we need to emit the body of the
8790 // region with no privatization in the 'else' branch of the conditional.
8791 // Otherwise, we don't have to do anything.
8792 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
8793 PrePostActionTy &) {
8794 if (!Info.CaptureDeviceAddrMap.empty()) {
8795 CodeGen.setAction(NoPrivAction);
8796 CodeGen(CGF);
8797 }
8798 };
8799
8800 // We don't have to do anything to close the region if the if clause evaluates
8801 // to false.
8802 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00008803
8804 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008805 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00008806 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00008807 RegionCodeGenTy RCG(BeginThenGen);
8808 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008809 }
8810
Samuel Antaocc10b852016-07-28 14:23:26 +00008811 // If we don't require privatization of device pointers, we emit the body in
8812 // between the runtime calls. This avoids duplicating the body code.
8813 if (Info.CaptureDeviceAddrMap.empty()) {
8814 CodeGen.setAction(NoPrivAction);
8815 CodeGen(CGF);
8816 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008817
8818 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008819 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00008820 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00008821 RegionCodeGenTy RCG(EndThenGen);
8822 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008823 }
8824}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008825
Samuel Antao8d2d7302016-05-26 18:30:22 +00008826void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00008827 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8828 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008829 if (!CGF.HaveInsertPoint())
8830 return;
8831
Samuel Antao8dd66282016-04-27 23:14:30 +00008832 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00008833 isa<OMPTargetExitDataDirective>(D) ||
8834 isa<OMPTargetUpdateDirective>(D)) &&
8835 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00008836
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008837 CodeGenFunction::OMPTargetDataInfo InputInfo;
8838 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008839 // Generate the code for the opening of the data environment.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008840 auto &&ThenGen = [this, &D, Device, &InputInfo,
8841 &MapTypesArray](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008842 // Emit device ID if any.
8843 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008844 if (Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008845 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008846 CGF.Int64Ty, /*isSigned=*/true);
8847 } else {
8848 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8849 }
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008850
8851 // Emit the number of elements in the offloading arrays.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008852 llvm::Constant *PointerNum =
8853 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008854
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008855 llvm::Value *OffloadingArgs[] = {DeviceID,
8856 PointerNum,
8857 InputInfo.BasePointersArray.getPointer(),
8858 InputInfo.PointersArray.getPointer(),
8859 InputInfo.SizesArray.getPointer(),
8860 MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00008861
Samuel Antao8d2d7302016-05-26 18:30:22 +00008862 // Select the right runtime function call for each expected standalone
8863 // directive.
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008864 const bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Samuel Antao8d2d7302016-05-26 18:30:22 +00008865 OpenMPRTLFunction RTLFn;
8866 switch (D.getDirectiveKind()) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00008867 case OMPD_target_enter_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008868 RTLFn = HasNowait ? OMPRTL__tgt_target_data_begin_nowait
8869 : OMPRTL__tgt_target_data_begin;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008870 break;
8871 case OMPD_target_exit_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008872 RTLFn = HasNowait ? OMPRTL__tgt_target_data_end_nowait
8873 : OMPRTL__tgt_target_data_end;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008874 break;
8875 case OMPD_target_update:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008876 RTLFn = HasNowait ? OMPRTL__tgt_target_data_update_nowait
8877 : OMPRTL__tgt_target_data_update;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008878 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008879 case OMPD_parallel:
8880 case OMPD_for:
8881 case OMPD_parallel_for:
8882 case OMPD_parallel_sections:
8883 case OMPD_for_simd:
8884 case OMPD_parallel_for_simd:
8885 case OMPD_cancel:
8886 case OMPD_cancellation_point:
8887 case OMPD_ordered:
8888 case OMPD_threadprivate:
8889 case OMPD_task:
8890 case OMPD_simd:
8891 case OMPD_sections:
8892 case OMPD_section:
8893 case OMPD_single:
8894 case OMPD_master:
8895 case OMPD_critical:
8896 case OMPD_taskyield:
8897 case OMPD_barrier:
8898 case OMPD_taskwait:
8899 case OMPD_taskgroup:
8900 case OMPD_atomic:
8901 case OMPD_flush:
8902 case OMPD_teams:
8903 case OMPD_target_data:
8904 case OMPD_distribute:
8905 case OMPD_distribute_simd:
8906 case OMPD_distribute_parallel_for:
8907 case OMPD_distribute_parallel_for_simd:
8908 case OMPD_teams_distribute:
8909 case OMPD_teams_distribute_simd:
8910 case OMPD_teams_distribute_parallel_for:
8911 case OMPD_teams_distribute_parallel_for_simd:
8912 case OMPD_declare_simd:
8913 case OMPD_declare_target:
8914 case OMPD_end_declare_target:
8915 case OMPD_declare_reduction:
8916 case OMPD_taskloop:
8917 case OMPD_taskloop_simd:
8918 case OMPD_target:
8919 case OMPD_target_simd:
8920 case OMPD_target_teams_distribute:
8921 case OMPD_target_teams_distribute_simd:
8922 case OMPD_target_teams_distribute_parallel_for:
8923 case OMPD_target_teams_distribute_parallel_for_simd:
8924 case OMPD_target_teams:
8925 case OMPD_target_parallel:
8926 case OMPD_target_parallel_for:
8927 case OMPD_target_parallel_for_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008928 case OMPD_requires:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008929 case OMPD_unknown:
8930 llvm_unreachable("Unexpected standalone target data directive.");
8931 break;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008932 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008933 CGF.EmitRuntimeCall(createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008934 };
8935
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008936 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray](
8937 CodeGenFunction &CGF, PrePostActionTy &) {
8938 // Fill up the arrays with all the mapped variables.
8939 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
8940 MappableExprsHandler::MapValuesArrayTy Pointers;
8941 MappableExprsHandler::MapValuesArrayTy Sizes;
8942 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008943
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008944 // Get map clause information.
8945 MappableExprsHandler MEHandler(D, CGF);
8946 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
8947
8948 TargetDataInfo Info;
8949 // Fill up the arrays and create the arguments.
8950 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
8951 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
8952 Info.PointersArray, Info.SizesArray,
8953 Info.MapTypesArray, Info);
8954 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
8955 InputInfo.BasePointersArray =
8956 Address(Info.BasePointersArray, CGM.getPointerAlign());
8957 InputInfo.PointersArray =
8958 Address(Info.PointersArray, CGM.getPointerAlign());
8959 InputInfo.SizesArray =
8960 Address(Info.SizesArray, CGM.getPointerAlign());
8961 MapTypesArray = Info.MapTypesArray;
8962 if (D.hasClausesOfKind<OMPDependClause>())
8963 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
8964 else
Alexey Bataev768f1f22018-01-09 19:59:25 +00008965 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008966 };
8967
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008968 if (IfCond) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008969 emitOMPIfClause(CGF, IfCond, TargetThenGen,
8970 [](CodeGenFunction &CGF, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008971 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008972 RegionCodeGenTy ThenRCG(TargetThenGen);
8973 ThenRCG(CGF);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008974 }
8975}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008976
8977namespace {
8978 /// Kind of parameter in a function with 'declare simd' directive.
8979 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
8980 /// Attribute set of the parameter.
8981 struct ParamAttrTy {
8982 ParamKindTy Kind = Vector;
8983 llvm::APSInt StrideOrArg;
8984 llvm::APSInt Alignment;
8985 };
8986} // namespace
8987
8988static unsigned evaluateCDTSize(const FunctionDecl *FD,
8989 ArrayRef<ParamAttrTy> ParamAttrs) {
8990 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
8991 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
8992 // of that clause. The VLEN value must be power of 2.
8993 // In other case the notion of the function`s "characteristic data type" (CDT)
8994 // is used to compute the vector length.
8995 // CDT is defined in the following order:
8996 // a) For non-void function, the CDT is the return type.
8997 // b) If the function has any non-uniform, non-linear parameters, then the
8998 // CDT is the type of the first such parameter.
8999 // c) If the CDT determined by a) or b) above is struct, union, or class
9000 // type which is pass-by-value (except for the type that maps to the
9001 // built-in complex data type), the characteristic data type is int.
9002 // d) If none of the above three cases is applicable, the CDT is int.
9003 // The VLEN is then determined based on the CDT and the size of vector
9004 // register of that ISA for which current vector version is generated. The
9005 // VLEN is computed using the formula below:
9006 // VLEN = sizeof(vector_register) / sizeof(CDT),
9007 // where vector register size specified in section 3.2.1 Registers and the
9008 // Stack Frame of original AMD64 ABI document.
9009 QualType RetType = FD->getReturnType();
9010 if (RetType.isNull())
9011 return 0;
9012 ASTContext &C = FD->getASTContext();
9013 QualType CDT;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009014 if (!RetType.isNull() && !RetType->isVoidType()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009015 CDT = RetType;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009016 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009017 unsigned Offset = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009018 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009019 if (ParamAttrs[Offset].Kind == Vector)
9020 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
9021 ++Offset;
9022 }
9023 if (CDT.isNull()) {
9024 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
9025 if (ParamAttrs[I + Offset].Kind == Vector) {
9026 CDT = FD->getParamDecl(I)->getType();
9027 break;
9028 }
9029 }
9030 }
9031 }
9032 if (CDT.isNull())
9033 CDT = C.IntTy;
9034 CDT = CDT->getCanonicalTypeUnqualified();
9035 if (CDT->isRecordType() || CDT->isUnionType())
9036 CDT = C.IntTy;
9037 return C.getTypeSize(CDT);
9038}
9039
9040static void
9041emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00009042 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009043 ArrayRef<ParamAttrTy> ParamAttrs,
9044 OMPDeclareSimdDeclAttr::BranchStateTy State) {
9045 struct ISADataTy {
9046 char ISA;
9047 unsigned VecRegSize;
9048 };
9049 ISADataTy ISAData[] = {
9050 {
9051 'b', 128
9052 }, // SSE
9053 {
9054 'c', 256
9055 }, // AVX
9056 {
9057 'd', 256
9058 }, // AVX2
9059 {
9060 'e', 512
9061 }, // AVX512
9062 };
9063 llvm::SmallVector<char, 2> Masked;
9064 switch (State) {
9065 case OMPDeclareSimdDeclAttr::BS_Undefined:
9066 Masked.push_back('N');
9067 Masked.push_back('M');
9068 break;
9069 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
9070 Masked.push_back('N');
9071 break;
9072 case OMPDeclareSimdDeclAttr::BS_Inbranch:
9073 Masked.push_back('M');
9074 break;
9075 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009076 for (char Mask : Masked) {
9077 for (const ISADataTy &Data : ISAData) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009078 SmallString<256> Buffer;
9079 llvm::raw_svector_ostream Out(Buffer);
9080 Out << "_ZGV" << Data.ISA << Mask;
9081 if (!VLENVal) {
9082 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
9083 evaluateCDTSize(FD, ParamAttrs));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009084 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009085 Out << VLENVal;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009086 }
9087 for (const ParamAttrTy &ParamAttr : ParamAttrs) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009088 switch (ParamAttr.Kind){
9089 case LinearWithVarStride:
9090 Out << 's' << ParamAttr.StrideOrArg;
9091 break;
9092 case Linear:
9093 Out << 'l';
9094 if (!!ParamAttr.StrideOrArg)
9095 Out << ParamAttr.StrideOrArg;
9096 break;
9097 case Uniform:
9098 Out << 'u';
9099 break;
9100 case Vector:
9101 Out << 'v';
9102 break;
9103 }
9104 if (!!ParamAttr.Alignment)
9105 Out << 'a' << ParamAttr.Alignment;
9106 }
9107 Out << '_' << Fn->getName();
9108 Fn->addFnAttr(Out.str());
9109 }
9110 }
9111}
9112
9113void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
9114 llvm::Function *Fn) {
9115 ASTContext &C = CGM.getContext();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009116 FD = FD->getMostRecentDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009117 // Map params to their positions in function decl.
9118 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
9119 if (isa<CXXMethodDecl>(FD))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009120 ParamPositions.try_emplace(FD, 0);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009121 unsigned ParamPos = ParamPositions.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009122 for (const ParmVarDecl *P : FD->parameters()) {
9123 ParamPositions.try_emplace(P->getCanonicalDecl(), ParamPos);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009124 ++ParamPos;
9125 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009126 while (FD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009127 for (const auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009128 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
9129 // Mark uniform parameters.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009130 for (const Expr *E : Attr->uniforms()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009131 E = E->IgnoreParenImpCasts();
9132 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009133 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009134 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009135 } else {
9136 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
9137 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009138 Pos = ParamPositions[PVD];
9139 }
9140 ParamAttrs[Pos].Kind = Uniform;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009141 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009142 // Get alignment info.
9143 auto NI = Attr->alignments_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009144 for (const Expr *E : Attr->aligneds()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009145 E = E->IgnoreParenImpCasts();
9146 unsigned Pos;
9147 QualType ParmTy;
9148 if (isa<CXXThisExpr>(E)) {
9149 Pos = ParamPositions[FD];
9150 ParmTy = E->getType();
9151 } else {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009152 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
9153 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009154 Pos = ParamPositions[PVD];
9155 ParmTy = PVD->getType();
9156 }
9157 ParamAttrs[Pos].Alignment =
9158 (*NI)
9159 ? (*NI)->EvaluateKnownConstInt(C)
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009160 : llvm::APSInt::getUnsigned(
9161 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
9162 .getQuantity());
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009163 ++NI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009164 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009165 // Mark linear parameters.
9166 auto SI = Attr->steps_begin();
9167 auto MI = Attr->modifiers_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009168 for (const Expr *E : Attr->linears()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009169 E = E->IgnoreParenImpCasts();
9170 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009171 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009172 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009173 } else {
9174 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
9175 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009176 Pos = ParamPositions[PVD];
9177 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009178 ParamAttrTy &ParamAttr = ParamAttrs[Pos];
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009179 ParamAttr.Kind = Linear;
9180 if (*SI) {
Fangrui Song407659a2018-11-30 23:41:18 +00009181 Expr::EvalResult Result;
9182 if (!(*SI)->EvaluateAsInt(Result, C, Expr::SE_AllowSideEffects)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009183 if (const auto *DRE =
9184 cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
9185 if (const auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009186 ParamAttr.Kind = LinearWithVarStride;
9187 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
9188 ParamPositions[StridePVD->getCanonicalDecl()]);
9189 }
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009190 }
Fangrui Song407659a2018-11-30 23:41:18 +00009191 } else {
9192 ParamAttr.StrideOrArg = Result.Val.getInt();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009193 }
9194 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009195 ++SI;
9196 ++MI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009197 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009198 llvm::APSInt VLENVal;
9199 if (const Expr *VLEN = Attr->getSimdlen())
9200 VLENVal = VLEN->EvaluateKnownConstInt(C);
9201 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
9202 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
9203 CGM.getTriple().getArch() == llvm::Triple::x86_64)
9204 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009205 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009206 FD = FD->getPreviousDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009207 }
9208}
Alexey Bataev8b427062016-05-25 12:36:08 +00009209
9210namespace {
9211/// Cleanup action for doacross support.
9212class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
9213public:
9214 static const int DoacrossFinArgs = 2;
9215
9216private:
9217 llvm::Value *RTLFn;
9218 llvm::Value *Args[DoacrossFinArgs];
9219
9220public:
9221 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
9222 : RTLFn(RTLFn) {
9223 assert(CallArgs.size() == DoacrossFinArgs);
9224 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
9225 }
9226 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
9227 if (!CGF.HaveInsertPoint())
9228 return;
9229 CGF.EmitRuntimeCall(RTLFn, Args);
9230 }
9231};
9232} // namespace
9233
9234void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
Alexey Bataevf138fda2018-08-13 19:04:24 +00009235 const OMPLoopDirective &D,
9236 ArrayRef<Expr *> NumIterations) {
Alexey Bataev8b427062016-05-25 12:36:08 +00009237 if (!CGF.HaveInsertPoint())
9238 return;
9239
9240 ASTContext &C = CGM.getContext();
9241 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
9242 RecordDecl *RD;
9243 if (KmpDimTy.isNull()) {
9244 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
9245 // kmp_int64 lo; // lower
9246 // kmp_int64 up; // upper
9247 // kmp_int64 st; // stride
9248 // };
9249 RD = C.buildImplicitRecord("kmp_dim");
9250 RD->startDefinition();
9251 addFieldToRecordDecl(C, RD, Int64Ty);
9252 addFieldToRecordDecl(C, RD, Int64Ty);
9253 addFieldToRecordDecl(C, RD, Int64Ty);
9254 RD->completeDefinition();
9255 KmpDimTy = C.getRecordType(RD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009256 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00009257 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009258 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00009259 llvm::APInt Size(/*numBits=*/32, NumIterations.size());
9260 QualType ArrayTy =
9261 C.getConstantArrayType(KmpDimTy, Size, ArrayType::Normal, 0);
Alexey Bataev8b427062016-05-25 12:36:08 +00009262
Alexey Bataevf138fda2018-08-13 19:04:24 +00009263 Address DimsAddr = CGF.CreateMemTemp(ArrayTy, "dims");
9264 CGF.EmitNullInitialization(DimsAddr, ArrayTy);
Alexey Bataev8b427062016-05-25 12:36:08 +00009265 enum { LowerFD = 0, UpperFD, StrideFD };
9266 // Fill dims with data.
Alexey Bataevf138fda2018-08-13 19:04:24 +00009267 for (unsigned I = 0, E = NumIterations.size(); I < E; ++I) {
9268 LValue DimsLVal =
9269 CGF.MakeAddrLValue(CGF.Builder.CreateConstArrayGEP(
9270 DimsAddr, I, C.getTypeSizeInChars(KmpDimTy)),
9271 KmpDimTy);
9272 // dims.upper = num_iterations;
9273 LValue UpperLVal = CGF.EmitLValueForField(
9274 DimsLVal, *std::next(RD->field_begin(), UpperFD));
9275 llvm::Value *NumIterVal =
9276 CGF.EmitScalarConversion(CGF.EmitScalarExpr(NumIterations[I]),
9277 D.getNumIterations()->getType(), Int64Ty,
9278 D.getNumIterations()->getExprLoc());
9279 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
9280 // dims.stride = 1;
9281 LValue StrideLVal = CGF.EmitLValueForField(
9282 DimsLVal, *std::next(RD->field_begin(), StrideFD));
9283 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
9284 StrideLVal);
9285 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009286
9287 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
9288 // kmp_int32 num_dims, struct kmp_dim * dims);
Alexey Bataevf138fda2018-08-13 19:04:24 +00009289 llvm::Value *Args[] = {
9290 emitUpdateLocation(CGF, D.getBeginLoc()),
9291 getThreadID(CGF, D.getBeginLoc()),
9292 llvm::ConstantInt::getSigned(CGM.Int32Ty, NumIterations.size()),
9293 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
9294 CGF.Builder
9295 .CreateConstArrayGEP(DimsAddr, 0, C.getTypeSizeInChars(KmpDimTy))
9296 .getPointer(),
9297 CGM.VoidPtrTy)};
Alexey Bataev8b427062016-05-25 12:36:08 +00009298
9299 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
9300 CGF.EmitRuntimeCall(RTLFn, Args);
9301 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009302 emitUpdateLocation(CGF, D.getEndLoc()), getThreadID(CGF, D.getEndLoc())};
Alexey Bataev8b427062016-05-25 12:36:08 +00009303 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
9304 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
9305 llvm::makeArrayRef(FiniArgs));
9306}
9307
9308void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
9309 const OMPDependClause *C) {
9310 QualType Int64Ty =
9311 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
Alexey Bataevf138fda2018-08-13 19:04:24 +00009312 llvm::APInt Size(/*numBits=*/32, C->getNumLoops());
9313 QualType ArrayTy = CGM.getContext().getConstantArrayType(
9314 Int64Ty, Size, ArrayType::Normal, 0);
9315 Address CntAddr = CGF.CreateMemTemp(ArrayTy, ".cnt.addr");
9316 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I) {
9317 const Expr *CounterVal = C->getLoopData(I);
9318 assert(CounterVal);
9319 llvm::Value *CntVal = CGF.EmitScalarConversion(
9320 CGF.EmitScalarExpr(CounterVal), CounterVal->getType(), Int64Ty,
9321 CounterVal->getExprLoc());
9322 CGF.EmitStoreOfScalar(
9323 CntVal,
9324 CGF.Builder.CreateConstArrayGEP(
9325 CntAddr, I, CGM.getContext().getTypeSizeInChars(Int64Ty)),
9326 /*Volatile=*/false, Int64Ty);
9327 }
9328 llvm::Value *Args[] = {
9329 emitUpdateLocation(CGF, C->getBeginLoc()),
9330 getThreadID(CGF, C->getBeginLoc()),
9331 CGF.Builder
9332 .CreateConstArrayGEP(CntAddr, 0,
9333 CGM.getContext().getTypeSizeInChars(Int64Ty))
9334 .getPointer()};
Alexey Bataev8b427062016-05-25 12:36:08 +00009335 llvm::Value *RTLFn;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009336 if (C->getDependencyKind() == OMPC_DEPEND_source) {
Alexey Bataev8b427062016-05-25 12:36:08 +00009337 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009338 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00009339 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
9340 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
9341 }
9342 CGF.EmitRuntimeCall(RTLFn, Args);
9343}
9344
Alexey Bataev7ef47a62018-02-22 18:33:31 +00009345void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, SourceLocation Loc,
9346 llvm::Value *Callee,
9347 ArrayRef<llvm::Value *> Args) const {
9348 assert(Loc.isValid() && "Outlined function call location must be valid.");
Alexey Bataev3c595a62017-08-14 15:01:03 +00009349 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
9350
9351 if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00009352 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00009353 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00009354 return;
9355 }
9356 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00009357 CGF.EmitRuntimeCall(Callee, Args);
9358}
9359
9360void CGOpenMPRuntime::emitOutlinedFunctionCall(
9361 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
9362 ArrayRef<llvm::Value *> Args) const {
Alexey Bataev7ef47a62018-02-22 18:33:31 +00009363 emitCall(CGF, Loc, OutlinedFn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00009364}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00009365
9366Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
9367 const VarDecl *NativeParam,
9368 const VarDecl *TargetParam) const {
9369 return CGF.GetAddrOfLocalVar(NativeParam);
9370}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009371
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00009372Address CGOpenMPRuntime::getAddressOfLocalVariable(CodeGenFunction &CGF,
9373 const VarDecl *VD) {
9374 return Address::invalid();
9375}
9376
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009377llvm::Value *CGOpenMPSIMDRuntime::emitParallelOutlinedFunction(
9378 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
9379 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
9380 llvm_unreachable("Not supported in SIMD-only mode");
9381}
9382
9383llvm::Value *CGOpenMPSIMDRuntime::emitTeamsOutlinedFunction(
9384 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
9385 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
9386 llvm_unreachable("Not supported in SIMD-only mode");
9387}
9388
9389llvm::Value *CGOpenMPSIMDRuntime::emitTaskOutlinedFunction(
9390 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
9391 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
9392 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
9393 bool Tied, unsigned &NumberOfParts) {
9394 llvm_unreachable("Not supported in SIMD-only mode");
9395}
9396
9397void CGOpenMPSIMDRuntime::emitParallelCall(CodeGenFunction &CGF,
9398 SourceLocation Loc,
9399 llvm::Value *OutlinedFn,
9400 ArrayRef<llvm::Value *> CapturedVars,
9401 const Expr *IfCond) {
9402 llvm_unreachable("Not supported in SIMD-only mode");
9403}
9404
9405void CGOpenMPSIMDRuntime::emitCriticalRegion(
9406 CodeGenFunction &CGF, StringRef CriticalName,
9407 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
9408 const Expr *Hint) {
9409 llvm_unreachable("Not supported in SIMD-only mode");
9410}
9411
9412void CGOpenMPSIMDRuntime::emitMasterRegion(CodeGenFunction &CGF,
9413 const RegionCodeGenTy &MasterOpGen,
9414 SourceLocation Loc) {
9415 llvm_unreachable("Not supported in SIMD-only mode");
9416}
9417
9418void CGOpenMPSIMDRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
9419 SourceLocation Loc) {
9420 llvm_unreachable("Not supported in SIMD-only mode");
9421}
9422
9423void CGOpenMPSIMDRuntime::emitTaskgroupRegion(
9424 CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen,
9425 SourceLocation Loc) {
9426 llvm_unreachable("Not supported in SIMD-only mode");
9427}
9428
9429void CGOpenMPSIMDRuntime::emitSingleRegion(
9430 CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen,
9431 SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars,
9432 ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs,
9433 ArrayRef<const Expr *> AssignmentOps) {
9434 llvm_unreachable("Not supported in SIMD-only mode");
9435}
9436
9437void CGOpenMPSIMDRuntime::emitOrderedRegion(CodeGenFunction &CGF,
9438 const RegionCodeGenTy &OrderedOpGen,
9439 SourceLocation Loc,
9440 bool IsThreads) {
9441 llvm_unreachable("Not supported in SIMD-only mode");
9442}
9443
9444void CGOpenMPSIMDRuntime::emitBarrierCall(CodeGenFunction &CGF,
9445 SourceLocation Loc,
9446 OpenMPDirectiveKind Kind,
9447 bool EmitChecks,
9448 bool ForceSimpleCall) {
9449 llvm_unreachable("Not supported in SIMD-only mode");
9450}
9451
9452void CGOpenMPSIMDRuntime::emitForDispatchInit(
9453 CodeGenFunction &CGF, SourceLocation Loc,
9454 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
9455 bool Ordered, const DispatchRTInput &DispatchValues) {
9456 llvm_unreachable("Not supported in SIMD-only mode");
9457}
9458
9459void CGOpenMPSIMDRuntime::emitForStaticInit(
9460 CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind,
9461 const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values) {
9462 llvm_unreachable("Not supported in SIMD-only mode");
9463}
9464
9465void CGOpenMPSIMDRuntime::emitDistributeStaticInit(
9466 CodeGenFunction &CGF, SourceLocation Loc,
9467 OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values) {
9468 llvm_unreachable("Not supported in SIMD-only mode");
9469}
9470
9471void CGOpenMPSIMDRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
9472 SourceLocation Loc,
9473 unsigned IVSize,
9474 bool IVSigned) {
9475 llvm_unreachable("Not supported in SIMD-only mode");
9476}
9477
9478void CGOpenMPSIMDRuntime::emitForStaticFinish(CodeGenFunction &CGF,
9479 SourceLocation Loc,
9480 OpenMPDirectiveKind DKind) {
9481 llvm_unreachable("Not supported in SIMD-only mode");
9482}
9483
9484llvm::Value *CGOpenMPSIMDRuntime::emitForNext(CodeGenFunction &CGF,
9485 SourceLocation Loc,
9486 unsigned IVSize, bool IVSigned,
9487 Address IL, Address LB,
9488 Address UB, Address ST) {
9489 llvm_unreachable("Not supported in SIMD-only mode");
9490}
9491
9492void CGOpenMPSIMDRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
9493 llvm::Value *NumThreads,
9494 SourceLocation Loc) {
9495 llvm_unreachable("Not supported in SIMD-only mode");
9496}
9497
9498void CGOpenMPSIMDRuntime::emitProcBindClause(CodeGenFunction &CGF,
9499 OpenMPProcBindClauseKind ProcBind,
9500 SourceLocation Loc) {
9501 llvm_unreachable("Not supported in SIMD-only mode");
9502}
9503
9504Address CGOpenMPSIMDRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
9505 const VarDecl *VD,
9506 Address VDAddr,
9507 SourceLocation Loc) {
9508 llvm_unreachable("Not supported in SIMD-only mode");
9509}
9510
9511llvm::Function *CGOpenMPSIMDRuntime::emitThreadPrivateVarDefinition(
9512 const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit,
9513 CodeGenFunction *CGF) {
9514 llvm_unreachable("Not supported in SIMD-only mode");
9515}
9516
9517Address CGOpenMPSIMDRuntime::getAddrOfArtificialThreadPrivate(
9518 CodeGenFunction &CGF, QualType VarType, StringRef Name) {
9519 llvm_unreachable("Not supported in SIMD-only mode");
9520}
9521
9522void CGOpenMPSIMDRuntime::emitFlush(CodeGenFunction &CGF,
9523 ArrayRef<const Expr *> Vars,
9524 SourceLocation Loc) {
9525 llvm_unreachable("Not supported in SIMD-only mode");
9526}
9527
9528void CGOpenMPSIMDRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
9529 const OMPExecutableDirective &D,
9530 llvm::Value *TaskFunction,
9531 QualType SharedsTy, Address Shareds,
9532 const Expr *IfCond,
9533 const OMPTaskDataTy &Data) {
9534 llvm_unreachable("Not supported in SIMD-only mode");
9535}
9536
9537void CGOpenMPSIMDRuntime::emitTaskLoopCall(
9538 CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D,
9539 llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
9540 const Expr *IfCond, const OMPTaskDataTy &Data) {
9541 llvm_unreachable("Not supported in SIMD-only mode");
9542}
9543
9544void CGOpenMPSIMDRuntime::emitReduction(
9545 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
9546 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
9547 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
9548 assert(Options.SimpleReduction && "Only simple reduction is expected.");
9549 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
9550 ReductionOps, Options);
9551}
9552
9553llvm::Value *CGOpenMPSIMDRuntime::emitTaskReductionInit(
9554 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
9555 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
9556 llvm_unreachable("Not supported in SIMD-only mode");
9557}
9558
9559void CGOpenMPSIMDRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
9560 SourceLocation Loc,
9561 ReductionCodeGen &RCG,
9562 unsigned N) {
9563 llvm_unreachable("Not supported in SIMD-only mode");
9564}
9565
9566Address CGOpenMPSIMDRuntime::getTaskReductionItem(CodeGenFunction &CGF,
9567 SourceLocation Loc,
9568 llvm::Value *ReductionsPtr,
9569 LValue SharedLVal) {
9570 llvm_unreachable("Not supported in SIMD-only mode");
9571}
9572
9573void CGOpenMPSIMDRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
9574 SourceLocation Loc) {
9575 llvm_unreachable("Not supported in SIMD-only mode");
9576}
9577
9578void CGOpenMPSIMDRuntime::emitCancellationPointCall(
9579 CodeGenFunction &CGF, SourceLocation Loc,
9580 OpenMPDirectiveKind CancelRegion) {
9581 llvm_unreachable("Not supported in SIMD-only mode");
9582}
9583
9584void CGOpenMPSIMDRuntime::emitCancelCall(CodeGenFunction &CGF,
9585 SourceLocation Loc, const Expr *IfCond,
9586 OpenMPDirectiveKind CancelRegion) {
9587 llvm_unreachable("Not supported in SIMD-only mode");
9588}
9589
9590void CGOpenMPSIMDRuntime::emitTargetOutlinedFunction(
9591 const OMPExecutableDirective &D, StringRef ParentName,
9592 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
9593 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
9594 llvm_unreachable("Not supported in SIMD-only mode");
9595}
9596
9597void CGOpenMPSIMDRuntime::emitTargetCall(CodeGenFunction &CGF,
9598 const OMPExecutableDirective &D,
9599 llvm::Value *OutlinedFn,
9600 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00009601 const Expr *IfCond, const Expr *Device) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009602 llvm_unreachable("Not supported in SIMD-only mode");
9603}
9604
9605bool CGOpenMPSIMDRuntime::emitTargetFunctions(GlobalDecl GD) {
9606 llvm_unreachable("Not supported in SIMD-only mode");
9607}
9608
9609bool CGOpenMPSIMDRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
9610 llvm_unreachable("Not supported in SIMD-only mode");
9611}
9612
9613bool CGOpenMPSIMDRuntime::emitTargetGlobal(GlobalDecl GD) {
9614 return false;
9615}
9616
9617llvm::Function *CGOpenMPSIMDRuntime::emitRegistrationFunction() {
9618 return nullptr;
9619}
9620
9621void CGOpenMPSIMDRuntime::emitTeamsCall(CodeGenFunction &CGF,
9622 const OMPExecutableDirective &D,
9623 SourceLocation Loc,
9624 llvm::Value *OutlinedFn,
9625 ArrayRef<llvm::Value *> CapturedVars) {
9626 llvm_unreachable("Not supported in SIMD-only mode");
9627}
9628
9629void CGOpenMPSIMDRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
9630 const Expr *NumTeams,
9631 const Expr *ThreadLimit,
9632 SourceLocation Loc) {
9633 llvm_unreachable("Not supported in SIMD-only mode");
9634}
9635
9636void CGOpenMPSIMDRuntime::emitTargetDataCalls(
9637 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
9638 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
9639 llvm_unreachable("Not supported in SIMD-only mode");
9640}
9641
9642void CGOpenMPSIMDRuntime::emitTargetDataStandAloneCall(
9643 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
9644 const Expr *Device) {
9645 llvm_unreachable("Not supported in SIMD-only mode");
9646}
9647
9648void CGOpenMPSIMDRuntime::emitDoacrossInit(CodeGenFunction &CGF,
Alexey Bataevf138fda2018-08-13 19:04:24 +00009649 const OMPLoopDirective &D,
9650 ArrayRef<Expr *> NumIterations) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009651 llvm_unreachable("Not supported in SIMD-only mode");
9652}
9653
9654void CGOpenMPSIMDRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
9655 const OMPDependClause *C) {
9656 llvm_unreachable("Not supported in SIMD-only mode");
9657}
9658
9659const VarDecl *
9660CGOpenMPSIMDRuntime::translateParameter(const FieldDecl *FD,
9661 const VarDecl *NativeParam) const {
9662 llvm_unreachable("Not supported in SIMD-only mode");
9663}
9664
9665Address
9666CGOpenMPSIMDRuntime::getParameterAddress(CodeGenFunction &CGF,
9667 const VarDecl *NativeParam,
9668 const VarDecl *TargetParam) const {
9669 llvm_unreachable("Not supported in SIMD-only mode");
9670}
9671