blob: 831412bce61b915cf6704c4972d1264c606bffd9 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===----- CGOpenMPRuntime.cpp - Interface to OpenMP Runtimes -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides a class for OpenMP runtime code generation.
11//
12//===----------------------------------------------------------------------===//
13
Samuel Antaoee8fb302016-01-06 13:42:12 +000014#include "CGCXXABI.h"
15#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000016#include "CGOpenMPRuntime.h"
Alexey Bataeva4fa0b82018-04-16 17:59:34 +000017#include "CGRecordLayout.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000018#include "CodeGenFunction.h"
John McCall5ad74072017-03-02 20:04:19 +000019#include "clang/CodeGen/ConstantInitBuilder.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000020#include "clang/AST/Decl.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000021#include "clang/AST/StmtOpenMP.h"
Richard Smithbf5bcf22018-06-26 23:20:26 +000022#include "clang/Basic/BitmaskEnum.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000023#include "llvm/ADT/ArrayRef.h"
Teresa Johnsonffc4e242016-11-11 05:35:12 +000024#include "llvm/Bitcode/BitcodeReader.h"
Alexey Bataevd74d0602014-10-13 06:02:40 +000025#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000026#include "llvm/IR/DerivedTypes.h"
27#include "llvm/IR/GlobalValue.h"
28#include "llvm/IR/Value.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000029#include "llvm/Support/Format.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000030#include "llvm/Support/raw_ostream.h"
Alexey Bataev23b69422014-06-18 07:08:49 +000031#include <cassert>
Alexey Bataev9959db52014-05-06 10:08:46 +000032
33using namespace clang;
34using namespace CodeGen;
35
Benjamin Kramerc52193f2014-10-10 13:57:57 +000036namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000037/// Base class for handling code generation inside OpenMP regions.
Alexey Bataev18095712014-10-10 12:19:54 +000038class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
39public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000040 /// Kinds of OpenMP regions used in codegen.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000041 enum CGOpenMPRegionKind {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000042 /// Region with outlined function for standalone 'parallel'
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000043 /// directive.
44 ParallelOutlinedRegion,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000045 /// Region with outlined function for standalone 'task' directive.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000046 TaskOutlinedRegion,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000047 /// Region for constructs that do not require function outlining,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000048 /// like 'for', 'sections', 'atomic' etc. directives.
49 InlinedRegion,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000050 /// Region with outlined function for standalone 'target' directive.
Samuel Antaobed3c462015-10-02 16:14:20 +000051 TargetRegion,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000052 };
Alexey Bataev18095712014-10-10 12:19:54 +000053
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000054 CGOpenMPRegionInfo(const CapturedStmt &CS,
55 const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000056 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
57 bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000058 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
Alexey Bataev25e5b442015-09-15 12:52:43 +000059 CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000060
61 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000062 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
63 bool HasCancel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +000064 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
Alexey Bataev25e5b442015-09-15 12:52:43 +000065 Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000066
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000067 /// Get a variable or parameter for storing global thread id
Alexey Bataev18095712014-10-10 12:19:54 +000068 /// inside OpenMP construct.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000069 virtual const VarDecl *getThreadIDVariable() const = 0;
Alexey Bataev18095712014-10-10 12:19:54 +000070
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000071 /// Emit the captured statement body.
Hans Wennborg7eb54642015-09-10 17:07:54 +000072 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000073
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000074 /// Get an LValue for the current ThreadID variable.
Alexey Bataev62b63b12015-03-10 07:28:44 +000075 /// \return LValue for thread id variable. This LValue always has type int32*.
76 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
Alexey Bataev18095712014-10-10 12:19:54 +000077
Alexey Bataev48591dd2016-04-20 04:01:36 +000078 virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {}
79
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000080 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000081
Alexey Bataev81c7ea02015-07-03 09:56:58 +000082 OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
83
Alexey Bataev25e5b442015-09-15 12:52:43 +000084 bool hasCancel() const { return HasCancel; }
85
Alexey Bataev18095712014-10-10 12:19:54 +000086 static bool classof(const CGCapturedStmtInfo *Info) {
87 return Info->getKind() == CR_OpenMP;
88 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000089
Alexey Bataev48591dd2016-04-20 04:01:36 +000090 ~CGOpenMPRegionInfo() override = default;
91
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000092protected:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000093 CGOpenMPRegionKind RegionKind;
Hans Wennborg45c74392016-01-12 20:54:36 +000094 RegionCodeGenTy CodeGen;
Alexey Bataev81c7ea02015-07-03 09:56:58 +000095 OpenMPDirectiveKind Kind;
Alexey Bataev25e5b442015-09-15 12:52:43 +000096 bool HasCancel;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000097};
Alexey Bataev18095712014-10-10 12:19:54 +000098
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000099/// API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000100class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000101public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000102 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000103 const RegionCodeGenTy &CodeGen,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000104 OpenMPDirectiveKind Kind, bool HasCancel,
105 StringRef HelperName)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000106 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
107 HasCancel),
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000108 ThreadIDVar(ThreadIDVar), HelperName(HelperName) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000109 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
110 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000111
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000112 /// Get a variable or parameter for storing global thread id
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000113 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000114 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000115
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000116 /// Get the name of the capture helper.
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000117 StringRef getHelperName() const override { return HelperName; }
Alexey Bataev18095712014-10-10 12:19:54 +0000118
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000119 static bool classof(const CGCapturedStmtInfo *Info) {
120 return CGOpenMPRegionInfo::classof(Info) &&
121 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
122 ParallelOutlinedRegion;
123 }
124
Alexey Bataev18095712014-10-10 12:19:54 +0000125private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000126 /// A variable or parameter storing global thread id for OpenMP
Alexey Bataev18095712014-10-10 12:19:54 +0000127 /// constructs.
128 const VarDecl *ThreadIDVar;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000129 StringRef HelperName;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000130};
131
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000132/// API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000133class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000134public:
Alexey Bataev48591dd2016-04-20 04:01:36 +0000135 class UntiedTaskActionTy final : public PrePostActionTy {
136 bool Untied;
137 const VarDecl *PartIDVar;
138 const RegionCodeGenTy UntiedCodeGen;
139 llvm::SwitchInst *UntiedSwitch = nullptr;
140
141 public:
142 UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
143 const RegionCodeGenTy &UntiedCodeGen)
144 : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
145 void Enter(CodeGenFunction &CGF) override {
146 if (Untied) {
147 // Emit task switching point.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000148 LValue PartIdLVal = CGF.EmitLoadOfPointerLValue(
Alexey Bataev48591dd2016-04-20 04:01:36 +0000149 CGF.GetAddrOfLocalVar(PartIDVar),
150 PartIDVar->getType()->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000151 llvm::Value *Res =
152 CGF.EmitLoadOfScalar(PartIdLVal, PartIDVar->getLocation());
153 llvm::BasicBlock *DoneBB = CGF.createBasicBlock(".untied.done.");
Alexey Bataev48591dd2016-04-20 04:01:36 +0000154 UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
155 CGF.EmitBlock(DoneBB);
156 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
157 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
158 UntiedSwitch->addCase(CGF.Builder.getInt32(0),
159 CGF.Builder.GetInsertBlock());
160 emitUntiedSwitch(CGF);
161 }
162 }
163 void emitUntiedSwitch(CodeGenFunction &CGF) const {
164 if (Untied) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000165 LValue PartIdLVal = CGF.EmitLoadOfPointerLValue(
Alexey Bataev48591dd2016-04-20 04:01:36 +0000166 CGF.GetAddrOfLocalVar(PartIDVar),
167 PartIDVar->getType()->castAs<PointerType>());
168 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
169 PartIdLVal);
170 UntiedCodeGen(CGF);
171 CodeGenFunction::JumpDest CurPoint =
172 CGF.getJumpDestInCurrentScope(".untied.next.");
173 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
174 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
175 UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
176 CGF.Builder.GetInsertBlock());
177 CGF.EmitBranchThroughCleanup(CurPoint);
178 CGF.EmitBlock(CurPoint.getBlock());
179 }
180 }
181 unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
182 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000183 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000184 const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000185 const RegionCodeGenTy &CodeGen,
Alexey Bataev48591dd2016-04-20 04:01:36 +0000186 OpenMPDirectiveKind Kind, bool HasCancel,
187 const UntiedTaskActionTy &Action)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000188 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
Alexey Bataev48591dd2016-04-20 04:01:36 +0000189 ThreadIDVar(ThreadIDVar), Action(Action) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000190 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
191 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000192
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000193 /// Get a variable or parameter for storing global thread id
Alexey Bataev62b63b12015-03-10 07:28:44 +0000194 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000195 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000196
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000197 /// Get an LValue for the current ThreadID variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000198 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000199
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000200 /// Get the name of the capture helper.
Alexey Bataev62b63b12015-03-10 07:28:44 +0000201 StringRef getHelperName() const override { return ".omp_outlined."; }
202
Alexey Bataev48591dd2016-04-20 04:01:36 +0000203 void emitUntiedSwitch(CodeGenFunction &CGF) override {
204 Action.emitUntiedSwitch(CGF);
205 }
206
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000207 static bool classof(const CGCapturedStmtInfo *Info) {
208 return CGOpenMPRegionInfo::classof(Info) &&
209 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
210 TaskOutlinedRegion;
211 }
212
Alexey Bataev62b63b12015-03-10 07:28:44 +0000213private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000214 /// A variable or parameter storing global thread id for OpenMP
Alexey Bataev62b63b12015-03-10 07:28:44 +0000215 /// constructs.
216 const VarDecl *ThreadIDVar;
Alexey Bataev48591dd2016-04-20 04:01:36 +0000217 /// Action for emitting code for untied tasks.
218 const UntiedTaskActionTy &Action;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000219};
220
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000221/// API for inlined captured statement code generation in OpenMP
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000222/// constructs.
223class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
224public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000225 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000226 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000227 OpenMPDirectiveKind Kind, bool HasCancel)
228 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
229 OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000230 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000231
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000232 // Retrieve the value of the context parameter.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000233 llvm::Value *getContextValue() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000234 if (OuterRegionInfo)
235 return OuterRegionInfo->getContextValue();
236 llvm_unreachable("No context value for inlined OpenMP region");
237 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000238
Hans Wennborg7eb54642015-09-10 17:07:54 +0000239 void setContextValue(llvm::Value *V) override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000240 if (OuterRegionInfo) {
241 OuterRegionInfo->setContextValue(V);
242 return;
243 }
244 llvm_unreachable("No context value for inlined OpenMP region");
245 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000246
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000247 /// Lookup the captured field decl for a variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000248 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000249 if (OuterRegionInfo)
250 return OuterRegionInfo->lookup(VD);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000251 // If there is no outer outlined region,no need to lookup in a list of
252 // captured variables, we can use the original one.
253 return nullptr;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000254 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000255
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000256 FieldDecl *getThisFieldDecl() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000257 if (OuterRegionInfo)
258 return OuterRegionInfo->getThisFieldDecl();
259 return nullptr;
260 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000261
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000262 /// Get a variable or parameter for storing global thread id
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000263 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000264 const VarDecl *getThreadIDVariable() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000265 if (OuterRegionInfo)
266 return OuterRegionInfo->getThreadIDVariable();
267 return nullptr;
268 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000269
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000270 /// Get an LValue for the current ThreadID variable.
Alexey Bataev311a9282017-10-12 13:51:32 +0000271 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override {
272 if (OuterRegionInfo)
273 return OuterRegionInfo->getThreadIDVariableLValue(CGF);
274 llvm_unreachable("No LValue for inlined OpenMP construct");
275 }
276
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000277 /// Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000278 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000279 if (auto *OuterRegionInfo = getOldCSI())
280 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000281 llvm_unreachable("No helper name for inlined OpenMP construct");
282 }
283
Alexey Bataev48591dd2016-04-20 04:01:36 +0000284 void emitUntiedSwitch(CodeGenFunction &CGF) override {
285 if (OuterRegionInfo)
286 OuterRegionInfo->emitUntiedSwitch(CGF);
287 }
288
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000289 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
290
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000291 static bool classof(const CGCapturedStmtInfo *Info) {
292 return CGOpenMPRegionInfo::classof(Info) &&
293 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
294 }
295
Alexey Bataev48591dd2016-04-20 04:01:36 +0000296 ~CGOpenMPInlinedRegionInfo() override = default;
297
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000298private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000299 /// CodeGen info about outer OpenMP region.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000300 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
301 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000302};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000303
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000304/// API for captured statement code generation in OpenMP target
Samuel Antaobed3c462015-10-02 16:14:20 +0000305/// constructs. For this captures, implicit parameters are used instead of the
Samuel Antaoee8fb302016-01-06 13:42:12 +0000306/// captured fields. The name of the target region has to be unique in a given
307/// application so it is provided by the client, because only the client has
308/// the information to generate that.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000309class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
Samuel Antaobed3c462015-10-02 16:14:20 +0000310public:
311 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000312 const RegionCodeGenTy &CodeGen, StringRef HelperName)
Samuel Antaobed3c462015-10-02 16:14:20 +0000313 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000314 /*HasCancel=*/false),
315 HelperName(HelperName) {}
Samuel Antaobed3c462015-10-02 16:14:20 +0000316
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000317 /// This is unused for target regions because each starts executing
Samuel Antaobed3c462015-10-02 16:14:20 +0000318 /// with a single thread.
319 const VarDecl *getThreadIDVariable() const override { return nullptr; }
320
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000321 /// Get the name of the capture helper.
Samuel Antaoee8fb302016-01-06 13:42:12 +0000322 StringRef getHelperName() const override { return HelperName; }
Samuel Antaobed3c462015-10-02 16:14:20 +0000323
324 static bool classof(const CGCapturedStmtInfo *Info) {
325 return CGOpenMPRegionInfo::classof(Info) &&
326 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
327 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000328
329private:
330 StringRef HelperName;
Samuel Antaobed3c462015-10-02 16:14:20 +0000331};
332
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000333static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000334 llvm_unreachable("No codegen for expressions");
335}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000336/// API for generation of expressions captured in a innermost OpenMP
Samuel Antaob68e2db2016-03-03 16:20:23 +0000337/// region.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000338class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000339public:
340 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
341 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
342 OMPD_unknown,
343 /*HasCancel=*/false),
344 PrivScope(CGF) {
345 // Make sure the globals captured in the provided statement are local by
346 // using the privatization logic. We assume the same variable is not
347 // captured more than once.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000348 for (const auto &C : CS.captures()) {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000349 if (!C.capturesVariable() && !C.capturesVariableByCopy())
350 continue;
351
352 const VarDecl *VD = C.getCapturedVar();
353 if (VD->isLocalVarDeclOrParm())
354 continue;
355
356 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
357 /*RefersToEnclosingVariableOrCapture=*/false,
358 VD->getType().getNonReferenceType(), VK_LValue,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000359 C.getLocation());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000360 PrivScope.addPrivate(
361 VD, [&CGF, &DRE]() { return CGF.EmitLValue(&DRE).getAddress(); });
Samuel Antaob68e2db2016-03-03 16:20:23 +0000362 }
363 (void)PrivScope.Privatize();
364 }
365
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000366 /// Lookup the captured field decl for a variable.
Samuel Antaob68e2db2016-03-03 16:20:23 +0000367 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000368 if (const FieldDecl *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
Samuel Antaob68e2db2016-03-03 16:20:23 +0000369 return FD;
370 return nullptr;
371 }
372
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000373 /// Emit the captured statement body.
Samuel Antaob68e2db2016-03-03 16:20:23 +0000374 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
375 llvm_unreachable("No body for expressions");
376 }
377
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000378 /// Get a variable or parameter for storing global thread id
Samuel Antaob68e2db2016-03-03 16:20:23 +0000379 /// inside OpenMP construct.
380 const VarDecl *getThreadIDVariable() const override {
381 llvm_unreachable("No thread id for expressions");
382 }
383
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000384 /// Get the name of the capture helper.
Samuel Antaob68e2db2016-03-03 16:20:23 +0000385 StringRef getHelperName() const override {
386 llvm_unreachable("No helper name for expressions");
387 }
388
389 static bool classof(const CGCapturedStmtInfo *Info) { return false; }
390
391private:
392 /// Private scope to capture global variables.
393 CodeGenFunction::OMPPrivateScope PrivScope;
394};
395
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000396/// RAII for emitting code of OpenMP constructs.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000397class InlinedOpenMPRegionRAII {
398 CodeGenFunction &CGF;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000399 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
400 FieldDecl *LambdaThisCaptureField = nullptr;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000401 const CodeGen::CGBlockInfo *BlockInfo = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000402
403public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000404 /// Constructs region for combined constructs.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000405 /// \param CodeGen Code generation sequence for combined directives. Includes
406 /// a list of functions used for code generation of implicitly inlined
407 /// regions.
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000408 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000409 OpenMPDirectiveKind Kind, bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000410 : CGF(CGF) {
411 // Start emission for the construct.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000412 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
413 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000414 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
415 LambdaThisCaptureField = CGF.LambdaThisCaptureField;
416 CGF.LambdaThisCaptureField = nullptr;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000417 BlockInfo = CGF.BlockInfo;
418 CGF.BlockInfo = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000419 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000420
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000421 ~InlinedOpenMPRegionRAII() {
422 // Restore original CapturedStmtInfo only if we're done with code emission.
423 auto *OldCSI =
424 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
425 delete CGF.CapturedStmtInfo;
426 CGF.CapturedStmtInfo = OldCSI;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000427 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
428 CGF.LambdaThisCaptureField = LambdaThisCaptureField;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000429 CGF.BlockInfo = BlockInfo;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000430 }
431};
432
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000433/// Values for bit flags used in the ident_t to describe the fields.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000434/// All enumeric elements are named and described in accordance with the code
435/// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000436enum OpenMPLocationFlags : unsigned {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000437 /// Use trampoline for internal microtask.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000438 OMP_IDENT_IMD = 0x01,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000439 /// Use c-style ident structure.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000440 OMP_IDENT_KMPC = 0x02,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000441 /// Atomic reduction option for kmpc_reduce.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000442 OMP_ATOMIC_REDUCE = 0x10,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000443 /// Explicit 'barrier' directive.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000444 OMP_IDENT_BARRIER_EXPL = 0x20,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000445 /// Implicit barrier in code.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000446 OMP_IDENT_BARRIER_IMPL = 0x40,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000447 /// Implicit barrier in 'for' directive.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000448 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000449 /// Implicit barrier in 'sections' directive.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000450 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000451 /// Implicit barrier in 'single' directive.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000452 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140,
453 /// Call of __kmp_for_static_init for static loop.
454 OMP_IDENT_WORK_LOOP = 0x200,
455 /// Call of __kmp_for_static_init for sections.
456 OMP_IDENT_WORK_SECTIONS = 0x400,
457 /// Call of __kmp_for_static_init for distribute.
458 OMP_IDENT_WORK_DISTRIBUTE = 0x800,
459 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_IDENT_WORK_DISTRIBUTE)
Alexey Bataev50b3c952016-02-19 10:38:26 +0000460};
461
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000462/// Describes ident structure that describes a source location.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000463/// All descriptions are taken from
464/// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
465/// Original structure:
466/// typedef struct ident {
467/// kmp_int32 reserved_1; /**< might be used in Fortran;
468/// see above */
469/// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
470/// KMP_IDENT_KMPC identifies this union
471/// member */
472/// kmp_int32 reserved_2; /**< not really used in Fortran any more;
473/// see above */
474///#if USE_ITT_BUILD
475/// /* but currently used for storing
476/// region-specific ITT */
477/// /* contextual information. */
478///#endif /* USE_ITT_BUILD */
479/// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
480/// C++ */
481/// char const *psource; /**< String describing the source location.
482/// The string is composed of semi-colon separated
483// fields which describe the source file,
484/// the function and a pair of line numbers that
485/// delimit the construct.
486/// */
487/// } ident_t;
488enum IdentFieldIndex {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000489 /// might be used in Fortran
Alexey Bataev50b3c952016-02-19 10:38:26 +0000490 IdentField_Reserved_1,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000491 /// OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000492 IdentField_Flags,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000493 /// Not really used in Fortran any more
Alexey Bataev50b3c952016-02-19 10:38:26 +0000494 IdentField_Reserved_2,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000495 /// Source[4] in Fortran, do not use for C++
Alexey Bataev50b3c952016-02-19 10:38:26 +0000496 IdentField_Reserved_3,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000497 /// String describing the source location. The string is composed of
Alexey Bataev50b3c952016-02-19 10:38:26 +0000498 /// semi-colon separated fields which describe the source file, the function
499 /// and a pair of line numbers that delimit the construct.
500 IdentField_PSource
501};
502
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000503/// Schedule types for 'omp for' loops (these enumerators are taken from
Alexey Bataev50b3c952016-02-19 10:38:26 +0000504/// the enum sched_type in kmp.h).
505enum OpenMPSchedType {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000506 /// Lower bound for default (unordered) versions.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000507 OMP_sch_lower = 32,
508 OMP_sch_static_chunked = 33,
509 OMP_sch_static = 34,
510 OMP_sch_dynamic_chunked = 35,
511 OMP_sch_guided_chunked = 36,
512 OMP_sch_runtime = 37,
513 OMP_sch_auto = 38,
Alexey Bataev6cff6242016-05-30 13:05:14 +0000514 /// static with chunk adjustment (e.g., simd)
Samuel Antao4c8035b2016-12-12 18:00:20 +0000515 OMP_sch_static_balanced_chunked = 45,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000516 /// Lower bound for 'ordered' versions.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000517 OMP_ord_lower = 64,
518 OMP_ord_static_chunked = 65,
519 OMP_ord_static = 66,
520 OMP_ord_dynamic_chunked = 67,
521 OMP_ord_guided_chunked = 68,
522 OMP_ord_runtime = 69,
523 OMP_ord_auto = 70,
524 OMP_sch_default = OMP_sch_static,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000525 /// dist_schedule types
Carlo Bertollifc35ad22016-03-07 16:04:49 +0000526 OMP_dist_sch_static_chunked = 91,
527 OMP_dist_sch_static = 92,
Alexey Bataev9ebd7422016-05-10 09:57:36 +0000528 /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
529 /// Set if the monotonic schedule modifier was present.
530 OMP_sch_modifier_monotonic = (1 << 29),
531 /// Set if the nonmonotonic schedule modifier was present.
532 OMP_sch_modifier_nonmonotonic = (1 << 30),
Alexey Bataev50b3c952016-02-19 10:38:26 +0000533};
534
535enum OpenMPRTLFunction {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000536 /// Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000537 /// kmpc_micro microtask, ...);
538 OMPRTL__kmpc_fork_call,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000539 /// Call to void *__kmpc_threadprivate_cached(ident_t *loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000540 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
541 OMPRTL__kmpc_threadprivate_cached,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000542 /// Call to void __kmpc_threadprivate_register( ident_t *,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000543 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
544 OMPRTL__kmpc_threadprivate_register,
545 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
546 OMPRTL__kmpc_global_thread_num,
547 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
548 // kmp_critical_name *crit);
549 OMPRTL__kmpc_critical,
550 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
551 // global_tid, kmp_critical_name *crit, uintptr_t hint);
552 OMPRTL__kmpc_critical_with_hint,
553 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
554 // kmp_critical_name *crit);
555 OMPRTL__kmpc_end_critical,
556 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
557 // global_tid);
558 OMPRTL__kmpc_cancel_barrier,
559 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
560 OMPRTL__kmpc_barrier,
561 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
562 OMPRTL__kmpc_for_static_fini,
563 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
564 // global_tid);
565 OMPRTL__kmpc_serialized_parallel,
566 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
567 // global_tid);
568 OMPRTL__kmpc_end_serialized_parallel,
569 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
570 // kmp_int32 num_threads);
571 OMPRTL__kmpc_push_num_threads,
572 // Call to void __kmpc_flush(ident_t *loc);
573 OMPRTL__kmpc_flush,
574 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
575 OMPRTL__kmpc_master,
576 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
577 OMPRTL__kmpc_end_master,
578 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
579 // int end_part);
580 OMPRTL__kmpc_omp_taskyield,
581 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
582 OMPRTL__kmpc_single,
583 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
584 OMPRTL__kmpc_end_single,
585 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
586 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
587 // kmp_routine_entry_t *task_entry);
588 OMPRTL__kmpc_omp_task_alloc,
589 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
590 // new_task);
591 OMPRTL__kmpc_omp_task,
592 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
593 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
594 // kmp_int32 didit);
595 OMPRTL__kmpc_copyprivate,
596 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
597 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
598 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
599 OMPRTL__kmpc_reduce,
600 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
601 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
602 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
603 // *lck);
604 OMPRTL__kmpc_reduce_nowait,
605 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
606 // kmp_critical_name *lck);
607 OMPRTL__kmpc_end_reduce,
608 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
609 // kmp_critical_name *lck);
610 OMPRTL__kmpc_end_reduce_nowait,
611 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
612 // kmp_task_t * new_task);
613 OMPRTL__kmpc_omp_task_begin_if0,
614 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
615 // kmp_task_t * new_task);
616 OMPRTL__kmpc_omp_task_complete_if0,
617 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
618 OMPRTL__kmpc_ordered,
619 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
620 OMPRTL__kmpc_end_ordered,
621 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
622 // global_tid);
623 OMPRTL__kmpc_omp_taskwait,
624 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
625 OMPRTL__kmpc_taskgroup,
626 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
627 OMPRTL__kmpc_end_taskgroup,
628 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
629 // int proc_bind);
630 OMPRTL__kmpc_push_proc_bind,
631 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
632 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
633 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
634 OMPRTL__kmpc_omp_task_with_deps,
635 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
636 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
637 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
638 OMPRTL__kmpc_omp_wait_deps,
639 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
640 // global_tid, kmp_int32 cncl_kind);
641 OMPRTL__kmpc_cancellationpoint,
642 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
643 // kmp_int32 cncl_kind);
644 OMPRTL__kmpc_cancel,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000645 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
646 // kmp_int32 num_teams, kmp_int32 thread_limit);
647 OMPRTL__kmpc_push_num_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000648 // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
649 // microtask, ...);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000650 OMPRTL__kmpc_fork_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000651 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
652 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
653 // sched, kmp_uint64 grainsize, void *task_dup);
654 OMPRTL__kmpc_taskloop,
Alexey Bataev8b427062016-05-25 12:36:08 +0000655 // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
656 // num_dims, struct kmp_dim *dims);
657 OMPRTL__kmpc_doacross_init,
658 // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
659 OMPRTL__kmpc_doacross_fini,
660 // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
661 // *vec);
662 OMPRTL__kmpc_doacross_post,
663 // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
664 // *vec);
665 OMPRTL__kmpc_doacross_wait,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000666 // Call to void *__kmpc_task_reduction_init(int gtid, int num_data, void
667 // *data);
668 OMPRTL__kmpc_task_reduction_init,
669 // Call to void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
670 // *d);
671 OMPRTL__kmpc_task_reduction_get_th_data,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000672
673 //
674 // Offloading related calls
675 //
George Rokos63bc9d62017-11-21 18:25:12 +0000676 // Call to int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
677 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Alexey Bataev50b3c952016-02-19 10:38:26 +0000678 // *arg_types);
679 OMPRTL__tgt_target,
Alexey Bataeva9f77c62017-12-13 21:04:20 +0000680 // Call to int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
681 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
682 // *arg_types);
683 OMPRTL__tgt_target_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000684 // Call to int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
685 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
686 // *arg_types, int32_t num_teams, int32_t thread_limit);
Samuel Antaob68e2db2016-03-03 16:20:23 +0000687 OMPRTL__tgt_target_teams,
Alexey Bataeva9f77c62017-12-13 21:04:20 +0000688 // Call to int32_t __tgt_target_teams_nowait(int64_t device_id, void
689 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
690 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
691 OMPRTL__tgt_target_teams_nowait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000692 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
693 OMPRTL__tgt_register_lib,
694 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
695 OMPRTL__tgt_unregister_lib,
George Rokos63bc9d62017-11-21 18:25:12 +0000696 // Call to void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
697 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antaodf158d52016-04-27 22:58:19 +0000698 OMPRTL__tgt_target_data_begin,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000699 // Call to void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
700 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
701 // *arg_types);
702 OMPRTL__tgt_target_data_begin_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000703 // Call to void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
704 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antaodf158d52016-04-27 22:58:19 +0000705 OMPRTL__tgt_target_data_end,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000706 // Call to void __tgt_target_data_end_nowait(int64_t device_id, int32_t
707 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
708 // *arg_types);
709 OMPRTL__tgt_target_data_end_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000710 // Call to void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
711 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antao8d2d7302016-05-26 18:30:22 +0000712 OMPRTL__tgt_target_data_update,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000713 // Call to void __tgt_target_data_update_nowait(int64_t device_id, int32_t
714 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
715 // *arg_types);
716 OMPRTL__tgt_target_data_update_nowait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000717};
718
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000719/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
720/// region.
721class CleanupTy final : public EHScopeStack::Cleanup {
722 PrePostActionTy *Action;
723
724public:
725 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
726 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
727 if (!CGF.HaveInsertPoint())
728 return;
729 Action->Exit(CGF);
730 }
731};
732
Hans Wennborg7eb54642015-09-10 17:07:54 +0000733} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000734
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000735void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
736 CodeGenFunction::RunCleanupsScope Scope(CGF);
737 if (PrePostAction) {
738 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
739 Callback(CodeGen, CGF, *PrePostAction);
740 } else {
741 PrePostActionTy Action;
742 Callback(CodeGen, CGF, Action);
743 }
744}
745
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000746/// Check if the combiner is a call to UDR combiner and if it is so return the
747/// UDR decl used for reduction.
748static const OMPDeclareReductionDecl *
749getReductionInit(const Expr *ReductionOp) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000750 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
751 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
752 if (const auto *DRE =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000753 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000754 if (const auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000755 return DRD;
756 return nullptr;
757}
758
759static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
760 const OMPDeclareReductionDecl *DRD,
761 const Expr *InitOp,
762 Address Private, Address Original,
763 QualType Ty) {
764 if (DRD->getInitializer()) {
765 std::pair<llvm::Function *, llvm::Function *> Reduction =
766 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000767 const auto *CE = cast<CallExpr>(InitOp);
768 const auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000769 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
770 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000771 const auto *LHSDRE =
772 cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
773 const auto *RHSDRE =
774 cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000775 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
776 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000777 [=]() { return Private; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000778 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000779 [=]() { return Original; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000780 (void)PrivateScope.Privatize();
781 RValue Func = RValue::get(Reduction.second);
782 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
783 CGF.EmitIgnoredExpr(InitOp);
784 } else {
785 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
Alexey Bataev18fa2322018-05-02 14:20:50 +0000786 std::string Name = CGF.CGM.getOpenMPRuntime().getName({"init"});
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000787 auto *GV = new llvm::GlobalVariable(
788 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
Alexey Bataev18fa2322018-05-02 14:20:50 +0000789 llvm::GlobalValue::PrivateLinkage, Init, Name);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000790 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
791 RValue InitRVal;
792 switch (CGF.getEvaluationKind(Ty)) {
793 case TEK_Scalar:
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000794 InitRVal = CGF.EmitLoadOfLValue(LV, DRD->getLocation());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000795 break;
796 case TEK_Complex:
797 InitRVal =
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000798 RValue::getComplex(CGF.EmitLoadOfComplex(LV, DRD->getLocation()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000799 break;
800 case TEK_Aggregate:
801 InitRVal = RValue::getAggregate(LV.getAddress());
802 break;
803 }
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000804 OpaqueValueExpr OVE(DRD->getLocation(), Ty, VK_RValue);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000805 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
806 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
807 /*IsInitializer=*/false);
808 }
809}
810
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000811/// Emit initialization of arrays of complex types.
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000812/// \param DestAddr Address of the array.
813/// \param Type Type of array.
814/// \param Init Initial expression of array.
815/// \param SrcAddr Address of the original array.
816static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
Alexey Bataeva7b19152017-10-12 20:03:39 +0000817 QualType Type, bool EmitDeclareReductionInit,
818 const Expr *Init,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000819 const OMPDeclareReductionDecl *DRD,
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000820 Address SrcAddr = Address::invalid()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000821 // Perform element-by-element initialization.
822 QualType ElementTy;
823
824 // Drill down to the base element type on both arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000825 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
826 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000827 DestAddr =
828 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
829 if (DRD)
830 SrcAddr =
831 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
832
833 llvm::Value *SrcBegin = nullptr;
834 if (DRD)
835 SrcBegin = SrcAddr.getPointer();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000836 llvm::Value *DestBegin = DestAddr.getPointer();
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000837 // Cast from pointer to array type to pointer to single element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000838 llvm::Value *DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000839 // The basic structure here is a while-do loop.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000840 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
841 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
842 llvm::Value *IsEmpty =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000843 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
844 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
845
846 // Enter the loop body, making that address the current address.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000847 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000848 CGF.EmitBlock(BodyBB);
849
850 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
851
852 llvm::PHINode *SrcElementPHI = nullptr;
853 Address SrcElementCurrent = Address::invalid();
854 if (DRD) {
855 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
856 "omp.arraycpy.srcElementPast");
857 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
858 SrcElementCurrent =
859 Address(SrcElementPHI,
860 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
861 }
862 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
863 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
864 DestElementPHI->addIncoming(DestBegin, EntryBB);
865 Address DestElementCurrent =
866 Address(DestElementPHI,
867 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
868
869 // Emit copy.
870 {
871 CodeGenFunction::RunCleanupsScope InitScope(CGF);
Alexey Bataeva7b19152017-10-12 20:03:39 +0000872 if (EmitDeclareReductionInit) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000873 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
874 SrcElementCurrent, ElementTy);
875 } else
876 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
877 /*IsInitializer=*/false);
878 }
879
880 if (DRD) {
881 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000882 llvm::Value *SrcElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000883 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
884 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
885 }
886
887 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000888 llvm::Value *DestElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000889 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
890 // Check whether we've reached the end.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000891 llvm::Value *Done =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000892 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
893 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
894 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
895
896 // Done.
897 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
898}
899
900LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000901 return CGF.EmitOMPSharedLValue(E);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000902}
903
904LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
905 const Expr *E) {
906 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
907 return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
908 return LValue();
909}
910
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000911void ReductionCodeGen::emitAggregateInitialization(
912 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
913 const OMPDeclareReductionDecl *DRD) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000914 // Emit VarDecl with copy init for arrays.
915 // Get the address of the original variable captured in current
916 // captured region.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000917 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000918 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva7b19152017-10-12 20:03:39 +0000919 bool EmitDeclareReductionInit =
920 DRD && (DRD->getInitializer() || !PrivateVD->hasInit());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000921 EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
Alexey Bataeva7b19152017-10-12 20:03:39 +0000922 EmitDeclareReductionInit,
923 EmitDeclareReductionInit ? ClausesData[N].ReductionOp
924 : PrivateVD->getInit(),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000925 DRD, SharedLVal.getAddress());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000926}
927
928ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
929 ArrayRef<const Expr *> Privates,
930 ArrayRef<const Expr *> ReductionOps) {
931 ClausesData.reserve(Shareds.size());
932 SharedAddresses.reserve(Shareds.size());
933 Sizes.reserve(Shareds.size());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000934 BaseDecls.reserve(Shareds.size());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000935 auto IPriv = Privates.begin();
936 auto IRed = ReductionOps.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000937 for (const Expr *Ref : Shareds) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000938 ClausesData.emplace_back(Ref, *IPriv, *IRed);
939 std::advance(IPriv, 1);
940 std::advance(IRed, 1);
941 }
942}
943
944void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
945 assert(SharedAddresses.size() == N &&
946 "Number of generated lvalues must be exactly N.");
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000947 LValue First = emitSharedLValue(CGF, ClausesData[N].Ref);
948 LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Ref);
949 SharedAddresses.emplace_back(First, Second);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000950}
951
952void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000953 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000954 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
955 QualType PrivateType = PrivateVD->getType();
956 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000957 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000958 Sizes.emplace_back(
959 CGF.getTypeSize(
960 SharedAddresses[N].first.getType().getNonReferenceType()),
961 nullptr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000962 return;
963 }
964 llvm::Value *Size;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000965 llvm::Value *SizeInChars;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000966 auto *ElemType =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000967 cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
968 ->getElementType();
969 auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000970 if (AsArraySection) {
971 Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
972 SharedAddresses[N].first.getPointer());
973 Size = CGF.Builder.CreateNUWAdd(
974 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000975 SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000976 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000977 SizeInChars = CGF.getTypeSize(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000978 SharedAddresses[N].first.getType().getNonReferenceType());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000979 Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000980 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000981 Sizes.emplace_back(SizeInChars, Size);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000982 CodeGenFunction::OpaqueValueMapping OpaqueMap(
983 CGF,
984 cast<OpaqueValueExpr>(
985 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
986 RValue::get(Size));
987 CGF.EmitVariablyModifiedType(PrivateType);
988}
989
990void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
991 llvm::Value *Size) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000992 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000993 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
994 QualType PrivateType = PrivateVD->getType();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000995 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000996 assert(!Size && !Sizes[N].second &&
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000997 "Size should be nullptr for non-variably modified reduction "
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000998 "items.");
999 return;
1000 }
1001 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1002 CGF,
1003 cast<OpaqueValueExpr>(
1004 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
1005 RValue::get(Size));
1006 CGF.EmitVariablyModifiedType(PrivateType);
1007}
1008
1009void ReductionCodeGen::emitInitialization(
1010 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
1011 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
1012 assert(SharedAddresses.size() > N && "No variable was generated");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001013 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001014 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001015 const OMPDeclareReductionDecl *DRD =
1016 getReductionInit(ClausesData[N].ReductionOp);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001017 QualType PrivateType = PrivateVD->getType();
1018 PrivateAddr = CGF.Builder.CreateElementBitCast(
1019 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1020 QualType SharedType = SharedAddresses[N].first.getType();
1021 SharedLVal = CGF.MakeAddrLValue(
1022 CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
1023 CGF.ConvertTypeForMem(SharedType)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001024 SharedType, SharedAddresses[N].first.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001025 CGF.CGM.getTBAAInfoForSubobject(SharedAddresses[N].first, SharedType));
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001026 if (CGF.getContext().getAsArrayType(PrivateVD->getType())) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001027 emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001028 } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
1029 emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
1030 PrivateAddr, SharedLVal.getAddress(),
1031 SharedLVal.getType());
1032 } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
1033 !CGF.isTrivialInitializer(PrivateVD->getInit())) {
1034 CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
1035 PrivateVD->getType().getQualifiers(),
1036 /*IsInitializer=*/false);
1037 }
1038}
1039
1040bool ReductionCodeGen::needCleanups(unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001041 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001042 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1043 QualType PrivateType = PrivateVD->getType();
1044 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1045 return DTorKind != QualType::DK_none;
1046}
1047
1048void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
1049 Address PrivateAddr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001050 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001051 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1052 QualType PrivateType = PrivateVD->getType();
1053 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1054 if (needCleanups(N)) {
1055 PrivateAddr = CGF.Builder.CreateElementBitCast(
1056 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1057 CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
1058 }
1059}
1060
1061static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1062 LValue BaseLV) {
1063 BaseTy = BaseTy.getNonReferenceType();
1064 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1065 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001066 if (const auto *PtrTy = BaseTy->getAs<PointerType>()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001067 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001068 } else {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00001069 LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(), BaseTy);
1070 BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001071 }
1072 BaseTy = BaseTy->getPointeeType();
1073 }
1074 return CGF.MakeAddrLValue(
1075 CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
1076 CGF.ConvertTypeForMem(ElTy)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001077 BaseLV.getType(), BaseLV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001078 CGF.CGM.getTBAAInfoForSubobject(BaseLV, BaseLV.getType()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001079}
1080
1081static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1082 llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
1083 llvm::Value *Addr) {
1084 Address Tmp = Address::invalid();
1085 Address TopTmp = Address::invalid();
1086 Address MostTopTmp = Address::invalid();
1087 BaseTy = BaseTy.getNonReferenceType();
1088 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1089 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1090 Tmp = CGF.CreateMemTemp(BaseTy);
1091 if (TopTmp.isValid())
1092 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
1093 else
1094 MostTopTmp = Tmp;
1095 TopTmp = Tmp;
1096 BaseTy = BaseTy->getPointeeType();
1097 }
1098 llvm::Type *Ty = BaseLVType;
1099 if (Tmp.isValid())
1100 Ty = Tmp.getElementType();
1101 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
1102 if (Tmp.isValid()) {
1103 CGF.Builder.CreateStore(Addr, Tmp);
1104 return MostTopTmp;
1105 }
1106 return Address(Addr, BaseLVAlignment);
1107}
1108
Alexey Bataev1c44e152018-03-06 18:59:43 +00001109static const VarDecl *getBaseDecl(const Expr *Ref, const DeclRefExpr *&DE) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001110 const VarDecl *OrigVD = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001111 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(Ref)) {
1112 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
1113 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001114 Base = TempOASE->getBase()->IgnoreParenImpCasts();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001115 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001116 Base = TempASE->getBase()->IgnoreParenImpCasts();
1117 DE = cast<DeclRefExpr>(Base);
1118 OrigVD = cast<VarDecl>(DE->getDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001119 } else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Ref)) {
1120 const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
1121 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001122 Base = TempASE->getBase()->IgnoreParenImpCasts();
1123 DE = cast<DeclRefExpr>(Base);
1124 OrigVD = cast<VarDecl>(DE->getDecl());
1125 }
Alexey Bataev1c44e152018-03-06 18:59:43 +00001126 return OrigVD;
1127}
1128
1129Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
1130 Address PrivateAddr) {
1131 const DeclRefExpr *DE;
1132 if (const VarDecl *OrigVD = ::getBaseDecl(ClausesData[N].Ref, DE)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001133 BaseDecls.emplace_back(OrigVD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001134 LValue OriginalBaseLValue = CGF.EmitLValue(DE);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001135 LValue BaseLValue =
1136 loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1137 OriginalBaseLValue);
1138 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1139 BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001140 llvm::Value *PrivatePointer =
1141 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1142 PrivateAddr.getPointer(),
1143 SharedAddresses[N].first.getAddress().getType());
1144 llvm::Value *Ptr = CGF.Builder.CreateGEP(PrivatePointer, Adjustment);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001145 return castToBase(CGF, OrigVD->getType(),
1146 SharedAddresses[N].first.getType(),
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001147 OriginalBaseLValue.getAddress().getType(),
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001148 OriginalBaseLValue.getAlignment(), Ptr);
1149 }
1150 BaseDecls.emplace_back(
1151 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1152 return PrivateAddr;
1153}
1154
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001155bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001156 const OMPDeclareReductionDecl *DRD =
1157 getReductionInit(ClausesData[N].ReductionOp);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001158 return DRD && DRD->getInitializer();
1159}
1160
Alexey Bataev18095712014-10-10 12:19:54 +00001161LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00001162 return CGF.EmitLoadOfPointerLValue(
1163 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1164 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +00001165}
1166
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001167void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001168 if (!CGF.HaveInsertPoint())
1169 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001170 // 1.2.2 OpenMP Language Terminology
1171 // Structured block - An executable statement with a single entry at the
1172 // top and a single exit at the bottom.
1173 // The point of exit cannot be a branch out of the structured block.
1174 // longjmp() and throw() must not violate the entry/exit criteria.
1175 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001176 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001177 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001178}
1179
Alexey Bataev62b63b12015-03-10 07:28:44 +00001180LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1181 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001182 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1183 getThreadIDVariable()->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00001184 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001185}
1186
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001187static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
1188 QualType FieldTy) {
1189 auto *Field = FieldDecl::Create(
1190 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
1191 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
1192 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
1193 Field->setAccess(AS_public);
1194 DC->addDecl(Field);
1195 return Field;
1196}
1197
Alexey Bataev18fa2322018-05-02 14:20:50 +00001198CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM, StringRef FirstSeparator,
1199 StringRef Separator)
1200 : CGM(CGM), FirstSeparator(FirstSeparator), Separator(Separator),
1201 OffloadEntriesInfoManager(CGM) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001202 ASTContext &C = CGM.getContext();
1203 RecordDecl *RD = C.buildImplicitRecord("ident_t");
1204 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1205 RD->startDefinition();
1206 // reserved_1
1207 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1208 // flags
1209 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1210 // reserved_2
1211 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1212 // reserved_3
1213 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1214 // psource
1215 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
1216 RD->completeDefinition();
1217 IdentQTy = C.getRecordType(RD);
1218 IdentTy = CGM.getTypes().ConvertRecordDeclType(RD);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001219 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +00001220
1221 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +00001222}
1223
Alexey Bataev91797552015-03-18 04:13:55 +00001224void CGOpenMPRuntime::clear() {
1225 InternalVars.clear();
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00001226 // Clean non-target variable declarations possibly used only in debug info.
1227 for (const auto &Data : EmittedNonTargetVariables) {
1228 if (!Data.getValue().pointsToAliveValue())
1229 continue;
1230 auto *GV = dyn_cast<llvm::GlobalVariable>(Data.getValue());
1231 if (!GV)
1232 continue;
1233 if (!GV->isDeclaration() || GV->getNumUses() > 0)
1234 continue;
1235 GV->eraseFromParent();
1236 }
Alexey Bataev91797552015-03-18 04:13:55 +00001237}
1238
Alexey Bataev18fa2322018-05-02 14:20:50 +00001239std::string CGOpenMPRuntime::getName(ArrayRef<StringRef> Parts) const {
1240 SmallString<128> Buffer;
1241 llvm::raw_svector_ostream OS(Buffer);
1242 StringRef Sep = FirstSeparator;
1243 for (StringRef Part : Parts) {
1244 OS << Sep << Part;
1245 Sep = Separator;
1246 }
1247 return OS.str();
1248}
1249
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001250static llvm::Function *
1251emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1252 const Expr *CombinerInitializer, const VarDecl *In,
1253 const VarDecl *Out, bool IsCombiner) {
1254 // void .omp_combiner.(Ty *in, Ty *out);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001255 ASTContext &C = CGM.getContext();
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001256 QualType PtrTy = C.getPointerType(Ty).withRestrict();
1257 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001258 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001259 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001260 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001261 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001262 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001263 Args.push_back(&OmpInParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001264 const CGFunctionInfo &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001265 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001266 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00001267 std::string Name = CGM.getOpenMPRuntime().getName(
1268 {IsCombiner ? "omp_combiner" : "omp_initializer", ""});
1269 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
1270 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001271 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001272 Fn->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001273 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001274 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001275 CodeGenFunction CGF(CGM);
1276 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1277 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001278 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, In->getLocation(),
1279 Out->getLocation());
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001280 CodeGenFunction::OMPPrivateScope Scope(CGF);
1281 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001282 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001283 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1284 .getAddress();
1285 });
1286 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001287 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001288 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1289 .getAddress();
1290 });
1291 (void)Scope.Privatize();
Alexey Bataev070f43a2017-09-06 14:49:58 +00001292 if (!IsCombiner && Out->hasInit() &&
1293 !CGF.isTrivialInitializer(Out->getInit())) {
1294 CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
1295 Out->getType().getQualifiers(),
1296 /*IsInitializer=*/true);
1297 }
1298 if (CombinerInitializer)
1299 CGF.EmitIgnoredExpr(CombinerInitializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001300 Scope.ForceCleanup();
1301 CGF.FinishFunction();
1302 return Fn;
1303}
1304
1305void CGOpenMPRuntime::emitUserDefinedReduction(
1306 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1307 if (UDRMap.count(D) > 0)
1308 return;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001309 llvm::Function *Combiner = emitCombinerOrInitializer(
Alexey Bataeve6aa4692018-09-13 16:54:05 +00001310 CGM, D->getType(), D->getCombiner(),
1311 cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerIn())->getDecl()),
1312 cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerOut())->getDecl()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001313 /*IsCombiner=*/true);
1314 llvm::Function *Initializer = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001315 if (const Expr *Init = D->getInitializer()) {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001316 Initializer = emitCombinerOrInitializer(
Alexey Bataev070f43a2017-09-06 14:49:58 +00001317 CGM, D->getType(),
1318 D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init
1319 : nullptr,
Alexey Bataeve6aa4692018-09-13 16:54:05 +00001320 cast<VarDecl>(cast<DeclRefExpr>(D->getInitOrig())->getDecl()),
1321 cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001322 /*IsCombiner=*/false);
1323 }
Alexey Bataev43a919f2018-04-13 17:48:43 +00001324 UDRMap.try_emplace(D, Combiner, Initializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001325 if (CGF) {
1326 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1327 Decls.second.push_back(D);
1328 }
1329}
1330
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001331std::pair<llvm::Function *, llvm::Function *>
1332CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1333 auto I = UDRMap.find(D);
1334 if (I != UDRMap.end())
1335 return I->second;
1336 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1337 return UDRMap.lookup(D);
1338}
1339
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001340static llvm::Value *emitParallelOrTeamsOutlinedFunction(
1341 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1342 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1343 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001344 assert(ThreadIDVar->getType()->isPointerType() &&
1345 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +00001346 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00001347 bool HasCancel = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001348 if (const auto *OPD = dyn_cast<OMPParallelDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001349 HasCancel = OPD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001350 else if (const auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001351 HasCancel = OPSD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001352 else if (const auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001353 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001354 else if (const auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D))
Alexey Bataev2139ed62017-11-16 18:20:21 +00001355 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001356 else if (const auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&D))
Alexey Bataev10a54312017-11-27 16:54:08 +00001357 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001358 else if (const auto *OPFD =
1359 dyn_cast<OMPTeamsDistributeParallelForDirective>(&D))
Alexey Bataev10a54312017-11-27 16:54:08 +00001360 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001361 else if (const auto *OPFD =
Alexey Bataev10a54312017-11-27 16:54:08 +00001362 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D))
1363 HasCancel = OPFD->hasCancel();
Alexey Bataev25e5b442015-09-15 12:52:43 +00001364 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001365 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +00001366 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001367 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +00001368}
1369
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001370llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
1371 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1372 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1373 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1374 return emitParallelOrTeamsOutlinedFunction(
1375 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1376}
1377
1378llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1379 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1380 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1381 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1382 return emitParallelOrTeamsOutlinedFunction(
1383 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1384}
1385
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001386llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
1387 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +00001388 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1389 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1390 bool Tied, unsigned &NumberOfParts) {
1391 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1392 PrePostActionTy &) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001393 llvm::Value *ThreadID = getThreadID(CGF, D.getBeginLoc());
1394 llvm::Value *UpLoc = emitUpdateLocation(CGF, D.getBeginLoc());
Alexey Bataev48591dd2016-04-20 04:01:36 +00001395 llvm::Value *TaskArgs[] = {
1396 UpLoc, ThreadID,
1397 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1398 TaskTVar->getType()->castAs<PointerType>())
1399 .getPointer()};
1400 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1401 };
1402 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1403 UntiedCodeGen);
1404 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001405 assert(!ThreadIDVar->getType()->isPointerType() &&
1406 "thread id variable must be of type kmp_int32 for tasks");
Alexey Bataev475a7442018-01-12 19:39:11 +00001407 const OpenMPDirectiveKind Region =
1408 isOpenMPTaskLoopDirective(D.getDirectiveKind()) ? OMPD_taskloop
1409 : OMPD_task;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001410 const CapturedStmt *CS = D.getCapturedStmt(Region);
1411 const auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001412 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +00001413 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1414 InnermostKind,
1415 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +00001416 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001417 llvm::Value *Res = CGF.GenerateCapturedStmtFunction(*CS);
Alexey Bataev48591dd2016-04-20 04:01:36 +00001418 if (!Tied)
1419 NumberOfParts = Action.getNumberOfParts();
1420 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001421}
1422
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001423static void buildStructValue(ConstantStructBuilder &Fields, CodeGenModule &CGM,
1424 const RecordDecl *RD, const CGRecordLayout &RL,
1425 ArrayRef<llvm::Constant *> Data) {
1426 llvm::StructType *StructTy = RL.getLLVMType();
1427 unsigned PrevIdx = 0;
1428 ConstantInitBuilder CIBuilder(CGM);
1429 auto DI = Data.begin();
1430 for (const FieldDecl *FD : RD->fields()) {
1431 unsigned Idx = RL.getLLVMFieldNo(FD);
1432 // Fill the alignment.
1433 for (unsigned I = PrevIdx; I < Idx; ++I)
1434 Fields.add(llvm::Constant::getNullValue(StructTy->getElementType(I)));
1435 PrevIdx = Idx + 1;
1436 Fields.add(*DI);
1437 ++DI;
1438 }
1439}
1440
1441template <class... As>
1442static llvm::GlobalVariable *
Mike Ricee1ca7b62018-08-29 15:45:11 +00001443createGlobalStruct(CodeGenModule &CGM, QualType Ty, bool IsConstant,
1444 ArrayRef<llvm::Constant *> Data, const Twine &Name,
1445 As &&... Args) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001446 const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1447 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1448 ConstantInitBuilder CIBuilder(CGM);
1449 ConstantStructBuilder Fields = CIBuilder.beginStruct(RL.getLLVMType());
1450 buildStructValue(Fields, CGM, RD, RL, Data);
1451 return Fields.finishAndCreateGlobal(
Mike Ricee1ca7b62018-08-29 15:45:11 +00001452 Name, CGM.getContext().getAlignOfGlobalVarInChars(Ty), IsConstant,
1453 std::forward<As>(Args)...);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001454}
1455
1456template <typename T>
Benjamin Kramer651d0bf2018-05-15 21:26:47 +00001457static void
1458createConstantGlobalStructAndAddToParent(CodeGenModule &CGM, QualType Ty,
1459 ArrayRef<llvm::Constant *> Data,
1460 T &Parent) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001461 const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1462 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1463 ConstantStructBuilder Fields = Parent.beginStruct(RL.getLLVMType());
1464 buildStructValue(Fields, CGM, RD, RL, Data);
1465 Fields.finishAndAddTo(Parent);
1466}
1467
Alexey Bataev50b3c952016-02-19 10:38:26 +00001468Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001469 CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
Alexey Bataev15007ba2014-05-07 06:18:01 +00001470 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +00001471 if (!Entry) {
1472 if (!DefaultOpenMPPSource) {
1473 // Initialize default location for psource field of ident_t structure of
1474 // all ident_t objects. Format is ";file;function;line;column;;".
1475 // Taken from
1476 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1477 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +00001478 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001479 DefaultOpenMPPSource =
1480 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1481 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001482
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001483 llvm::Constant *Data[] = {llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1484 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
1485 llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1486 llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1487 DefaultOpenMPPSource};
Mike Ricee1ca7b62018-08-29 15:45:11 +00001488 llvm::GlobalValue *DefaultOpenMPLocation =
1489 createGlobalStruct(CGM, IdentQTy, /*IsConstant=*/false, Data, "",
1490 llvm::GlobalValue::PrivateLinkage);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001491 DefaultOpenMPLocation->setUnnamedAddr(
1492 llvm::GlobalValue::UnnamedAddr::Global);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001493
John McCall7f416cc2015-09-08 08:05:57 +00001494 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +00001495 }
John McCall7f416cc2015-09-08 08:05:57 +00001496 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +00001497}
1498
Alexey Bataevfd006c42018-10-05 15:08:53 +00001499void CGOpenMPRuntime::setLocThreadIdInsertPt(CodeGenFunction &CGF,
1500 bool AtCurrentPoint) {
1501 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1502 assert(!Elem.second.ServiceInsertPt && "Insert point is set already.");
1503
1504 llvm::Value *Undef = llvm::UndefValue::get(CGF.Int32Ty);
1505 if (AtCurrentPoint) {
1506 Elem.second.ServiceInsertPt = new llvm::BitCastInst(
1507 Undef, CGF.Int32Ty, "svcpt", CGF.Builder.GetInsertBlock());
1508 } else {
1509 Elem.second.ServiceInsertPt =
1510 new llvm::BitCastInst(Undef, CGF.Int32Ty, "svcpt");
1511 Elem.second.ServiceInsertPt->insertAfter(CGF.AllocaInsertPt);
1512 }
1513}
1514
1515void CGOpenMPRuntime::clearLocThreadIdInsertPt(CodeGenFunction &CGF) {
1516 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1517 if (Elem.second.ServiceInsertPt) {
1518 llvm::Instruction *Ptr = Elem.second.ServiceInsertPt;
1519 Elem.second.ServiceInsertPt = nullptr;
1520 Ptr->eraseFromParent();
1521 }
1522}
1523
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001524llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1525 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001526 unsigned Flags) {
1527 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +00001528 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001529 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +00001530 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +00001531 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001532
1533 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1534
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001535 CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
John McCall7f416cc2015-09-08 08:05:57 +00001536 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001537 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1538 if (I != OpenMPLocThreadIDMap.end())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001539 LocValue = Address(I->second.DebugLoc, Align);
John McCall7f416cc2015-09-08 08:05:57 +00001540
Alexander Musmanc6388682014-12-15 07:07:06 +00001541 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1542 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +00001543 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +00001544 // Generate "ident_t .kmpc_loc.addr;"
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001545 Address AI = CGF.CreateMemTemp(IdentQTy, ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +00001546 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +00001547 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001548 LocValue = AI;
1549
Alexey Bataevfd006c42018-10-05 15:08:53 +00001550 if (!Elem.second.ServiceInsertPt)
1551 setLocThreadIdInsertPt(CGF);
Alexey Bataev9959db52014-05-06 10:08:46 +00001552 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001553 CGF.Builder.SetInsertPoint(Elem.second.ServiceInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001554 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001555 CGF.getTypeSize(IdentQTy));
Alexey Bataev9959db52014-05-06 10:08:46 +00001556 }
1557
1558 // char **psource = &.kmpc_loc_<flags>.addr.psource;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001559 LValue Base = CGF.MakeAddrLValue(LocValue, IdentQTy);
1560 auto Fields = cast<RecordDecl>(IdentQTy->getAsTagDecl())->field_begin();
1561 LValue PSource =
1562 CGF.EmitLValueForField(Base, *std::next(Fields, IdentField_PSource));
Alexey Bataev9959db52014-05-06 10:08:46 +00001563
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001564 llvm::Value *OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
Alexey Bataevf002aca2014-05-30 05:48:40 +00001565 if (OMPDebugLoc == nullptr) {
1566 SmallString<128> Buffer2;
1567 llvm::raw_svector_ostream OS2(Buffer2);
1568 // Build debug location
1569 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1570 OS2 << ";" << PLoc.getFilename() << ";";
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001571 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl))
Alexey Bataevf002aca2014-05-30 05:48:40 +00001572 OS2 << FD->getQualifiedNameAsString();
Alexey Bataevf002aca2014-05-30 05:48:40 +00001573 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1574 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1575 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +00001576 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001577 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001578 CGF.EmitStoreOfScalar(OMPDebugLoc, PSource);
Alexey Bataevf002aca2014-05-30 05:48:40 +00001579
John McCall7f416cc2015-09-08 08:05:57 +00001580 // Our callers always pass this to a runtime function, so for
1581 // convenience, go ahead and return a naked pointer.
1582 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001583}
1584
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001585llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1586 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001587 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1588
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001589 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001590 // Check whether we've already cached a load of the thread id in this
1591 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001592 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001593 if (I != OpenMPLocThreadIDMap.end()) {
1594 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001595 if (ThreadID != nullptr)
1596 return ThreadID;
1597 }
Alexey Bataevaee18552017-08-16 14:01:00 +00001598 // If exceptions are enabled, do not use parameter to avoid possible crash.
Alexey Bataev5d2c9a42017-11-02 18:55:05 +00001599 if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions ||
1600 !CGF.getLangOpts().CXXExceptions ||
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001601 CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
Alexey Bataevaee18552017-08-16 14:01:00 +00001602 if (auto *OMPRegionInfo =
1603 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1604 if (OMPRegionInfo->getThreadIDVariable()) {
1605 // Check if this an outlined function with thread id passed as argument.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001606 LValue LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev1e491372018-01-23 18:44:14 +00001607 ThreadID = CGF.EmitLoadOfScalar(LVal, Loc);
Alexey Bataevaee18552017-08-16 14:01:00 +00001608 // If value loaded in entry block, cache it and use it everywhere in
1609 // function.
1610 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1611 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1612 Elem.second.ThreadID = ThreadID;
1613 }
1614 return ThreadID;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001615 }
Alexey Bataevd6c57552014-07-25 07:55:17 +00001616 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001617 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001618
1619 // This is not an outlined function region - need to call __kmpc_int32
1620 // kmpc_global_thread_num(ident_t *loc).
1621 // Generate thread id value and cache this value for use across the
1622 // function.
Alexey Bataevfd006c42018-10-05 15:08:53 +00001623 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1624 if (!Elem.second.ServiceInsertPt)
1625 setLocThreadIdInsertPt(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001626 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001627 CGF.Builder.SetInsertPoint(Elem.second.ServiceInsertPt);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001628 llvm::CallInst *Call = CGF.Builder.CreateCall(
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001629 createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1630 emitUpdateLocation(CGF, Loc));
1631 Call->setCallingConv(CGF.getRuntimeCC());
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001632 Elem.second.ThreadID = Call;
1633 return Call;
Alexey Bataev9959db52014-05-06 10:08:46 +00001634}
1635
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001636void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001637 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataevfd006c42018-10-05 15:08:53 +00001638 if (OpenMPLocThreadIDMap.count(CGF.CurFn)) {
1639 clearLocThreadIdInsertPt(CGF);
Alexey Bataev03b340a2014-10-21 03:16:40 +00001640 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001641 }
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001642 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001643 for(auto *D : FunctionUDRMap[CGF.CurFn])
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001644 UDRMap.erase(D);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001645 FunctionUDRMap.erase(CGF.CurFn);
1646 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001647}
1648
1649llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001650 return IdentTy->getPointerTo();
Alexey Bataev9959db52014-05-06 10:08:46 +00001651}
1652
1653llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001654 if (!Kmpc_MicroTy) {
1655 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1656 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1657 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1658 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1659 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001660 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1661}
1662
1663llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001664CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001665 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001666 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001667 case OMPRTL__kmpc_fork_call: {
1668 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1669 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001670 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1671 getKmpc_MicroPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001672 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001673 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001674 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1675 break;
1676 }
1677 case OMPRTL__kmpc_global_thread_num: {
1678 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001679 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001680 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001681 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001682 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1683 break;
1684 }
Alexey Bataev97720002014-11-11 04:05:39 +00001685 case OMPRTL__kmpc_threadprivate_cached: {
1686 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1687 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1688 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1689 CGM.VoidPtrTy, CGM.SizeTy,
1690 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001691 auto *FnTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001692 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1693 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1694 break;
1695 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001696 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001697 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1698 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001699 llvm::Type *TypeParams[] = {
1700 getIdentTyPointerTy(), CGM.Int32Ty,
1701 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001702 auto *FnTy =
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001703 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1704 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1705 break;
1706 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001707 case OMPRTL__kmpc_critical_with_hint: {
1708 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1709 // kmp_critical_name *crit, uintptr_t hint);
1710 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1711 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1712 CGM.IntPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001713 auto *FnTy =
Alexey Bataevfc57d162015-12-15 10:55:09 +00001714 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1715 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1716 break;
1717 }
Alexey Bataev97720002014-11-11 04:05:39 +00001718 case OMPRTL__kmpc_threadprivate_register: {
1719 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1720 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1721 // typedef void *(*kmpc_ctor)(void *);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001722 auto *KmpcCtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001723 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1724 /*isVarArg*/ false)->getPointerTo();
1725 // typedef void *(*kmpc_cctor)(void *, void *);
1726 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001727 auto *KmpcCopyCtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001728 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001729 /*isVarArg*/ false)
1730 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00001731 // typedef void (*kmpc_dtor)(void *);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001732 auto *KmpcDtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001733 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1734 ->getPointerTo();
1735 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1736 KmpcCopyCtorTy, KmpcDtorTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001737 auto *FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
Alexey Bataev97720002014-11-11 04:05:39 +00001738 /*isVarArg*/ false);
1739 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1740 break;
1741 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001742 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001743 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1744 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001745 llvm::Type *TypeParams[] = {
1746 getIdentTyPointerTy(), CGM.Int32Ty,
1747 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001748 auto *FnTy =
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001749 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1750 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1751 break;
1752 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001753 case OMPRTL__kmpc_cancel_barrier: {
1754 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1755 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001756 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001757 auto *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001758 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1759 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001760 break;
1761 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001762 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001763 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001764 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001765 auto *FnTy =
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001766 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1767 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1768 break;
1769 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001770 case OMPRTL__kmpc_for_static_fini: {
1771 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1772 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001773 auto *FnTy =
Alexander Musmanc6388682014-12-15 07:07:06 +00001774 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1775 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1776 break;
1777 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001778 case OMPRTL__kmpc_push_num_threads: {
1779 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1780 // kmp_int32 num_threads)
1781 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1782 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001783 auto *FnTy =
Alexey Bataevb2059782014-10-13 08:23:51 +00001784 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1785 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1786 break;
1787 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001788 case OMPRTL__kmpc_serialized_parallel: {
1789 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1790 // global_tid);
1791 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001792 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001793 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1794 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1795 break;
1796 }
1797 case OMPRTL__kmpc_end_serialized_parallel: {
1798 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1799 // global_tid);
1800 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001801 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001802 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1803 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1804 break;
1805 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001806 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001807 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001808 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001809 auto *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001810 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001811 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1812 break;
1813 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001814 case OMPRTL__kmpc_master: {
1815 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1816 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001817 auto *FnTy =
Alexey Bataev8d690652014-12-04 07:23:53 +00001818 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1819 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1820 break;
1821 }
1822 case OMPRTL__kmpc_end_master: {
1823 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1824 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001825 auto *FnTy =
Alexey Bataev8d690652014-12-04 07:23:53 +00001826 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1827 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1828 break;
1829 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001830 case OMPRTL__kmpc_omp_taskyield: {
1831 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1832 // int end_part);
1833 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001834 auto *FnTy =
Alexey Bataev9f797f32015-02-05 05:57:51 +00001835 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1836 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1837 break;
1838 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001839 case OMPRTL__kmpc_single: {
1840 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1841 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001842 auto *FnTy =
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001843 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1844 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1845 break;
1846 }
1847 case OMPRTL__kmpc_end_single: {
1848 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1849 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001850 auto *FnTy =
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001851 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1852 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1853 break;
1854 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001855 case OMPRTL__kmpc_omp_task_alloc: {
1856 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1857 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1858 // kmp_routine_entry_t *task_entry);
1859 assert(KmpRoutineEntryPtrTy != nullptr &&
1860 "Type kmp_routine_entry_t must be created.");
1861 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1862 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1863 // Return void * and then cast to particular kmp_task_t type.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001864 auto *FnTy =
Alexey Bataev62b63b12015-03-10 07:28:44 +00001865 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1866 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1867 break;
1868 }
1869 case OMPRTL__kmpc_omp_task: {
1870 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1871 // *new_task);
1872 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1873 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001874 auto *FnTy =
Alexey Bataev62b63b12015-03-10 07:28:44 +00001875 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1876 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1877 break;
1878 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001879 case OMPRTL__kmpc_copyprivate: {
1880 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001881 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001882 // kmp_int32 didit);
1883 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1884 auto *CpyFnTy =
1885 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001886 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001887 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1888 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001889 auto *FnTy =
Alexey Bataeva63048e2015-03-23 06:18:07 +00001890 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1891 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1892 break;
1893 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001894 case OMPRTL__kmpc_reduce: {
1895 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1896 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1897 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1898 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1899 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1900 /*isVarArg=*/false);
1901 llvm::Type *TypeParams[] = {
1902 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1903 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1904 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001905 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001906 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1907 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1908 break;
1909 }
1910 case OMPRTL__kmpc_reduce_nowait: {
1911 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1912 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1913 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1914 // *lck);
1915 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1916 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1917 /*isVarArg=*/false);
1918 llvm::Type *TypeParams[] = {
1919 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1920 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1921 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001922 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001923 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1924 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1925 break;
1926 }
1927 case OMPRTL__kmpc_end_reduce: {
1928 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1929 // kmp_critical_name *lck);
1930 llvm::Type *TypeParams[] = {
1931 getIdentTyPointerTy(), CGM.Int32Ty,
1932 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001933 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001934 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1935 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1936 break;
1937 }
1938 case OMPRTL__kmpc_end_reduce_nowait: {
1939 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1940 // kmp_critical_name *lck);
1941 llvm::Type *TypeParams[] = {
1942 getIdentTyPointerTy(), CGM.Int32Ty,
1943 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001944 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001945 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1946 RTLFn =
1947 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1948 break;
1949 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001950 case OMPRTL__kmpc_omp_task_begin_if0: {
1951 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1952 // *new_task);
1953 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1954 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001955 auto *FnTy =
Alexey Bataev1d677132015-04-22 13:57:31 +00001956 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1957 RTLFn =
1958 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1959 break;
1960 }
1961 case OMPRTL__kmpc_omp_task_complete_if0: {
1962 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1963 // *new_task);
1964 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1965 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001966 auto *FnTy =
Alexey Bataev1d677132015-04-22 13:57:31 +00001967 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1968 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1969 /*Name=*/"__kmpc_omp_task_complete_if0");
1970 break;
1971 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001972 case OMPRTL__kmpc_ordered: {
1973 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1974 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001975 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001976 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1977 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1978 break;
1979 }
1980 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001981 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001982 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001983 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001984 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1985 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1986 break;
1987 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001988 case OMPRTL__kmpc_omp_taskwait: {
1989 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1990 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001991 auto *FnTy =
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001992 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1993 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1994 break;
1995 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001996 case OMPRTL__kmpc_taskgroup: {
1997 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1998 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001999 auto *FnTy =
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002000 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2001 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
2002 break;
2003 }
2004 case OMPRTL__kmpc_end_taskgroup: {
2005 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
2006 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002007 auto *FnTy =
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002008 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2009 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
2010 break;
2011 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00002012 case OMPRTL__kmpc_push_proc_bind: {
2013 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
2014 // int proc_bind)
2015 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002016 auto *FnTy =
Alexey Bataev7f210c62015-06-18 13:40:03 +00002017 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2018 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
2019 break;
2020 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002021 case OMPRTL__kmpc_omp_task_with_deps: {
2022 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
2023 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
2024 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
2025 llvm::Type *TypeParams[] = {
2026 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
2027 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002028 auto *FnTy =
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002029 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
2030 RTLFn =
2031 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
2032 break;
2033 }
2034 case OMPRTL__kmpc_omp_wait_deps: {
2035 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
2036 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
2037 // kmp_depend_info_t *noalias_dep_list);
2038 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2039 CGM.Int32Ty, CGM.VoidPtrTy,
2040 CGM.Int32Ty, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002041 auto *FnTy =
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002042 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2043 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
2044 break;
2045 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00002046 case OMPRTL__kmpc_cancellationpoint: {
2047 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
2048 // global_tid, kmp_int32 cncl_kind)
2049 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002050 auto *FnTy =
Alexey Bataev0f34da12015-07-02 04:17:07 +00002051 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2052 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
2053 break;
2054 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002055 case OMPRTL__kmpc_cancel: {
2056 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
2057 // kmp_int32 cncl_kind)
2058 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002059 auto *FnTy =
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002060 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2061 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
2062 break;
2063 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002064 case OMPRTL__kmpc_push_num_teams: {
2065 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
2066 // kmp_int32 num_teams, kmp_int32 num_threads)
2067 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
2068 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002069 auto *FnTy =
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002070 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2071 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
2072 break;
2073 }
2074 case OMPRTL__kmpc_fork_teams: {
2075 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
2076 // microtask, ...);
2077 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2078 getKmpc_MicroPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002079 auto *FnTy =
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002080 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
2081 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
2082 break;
2083 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002084 case OMPRTL__kmpc_taskloop: {
2085 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
2086 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
2087 // sched, kmp_uint64 grainsize, void *task_dup);
2088 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2089 CGM.IntTy,
2090 CGM.VoidPtrTy,
2091 CGM.IntTy,
2092 CGM.Int64Ty->getPointerTo(),
2093 CGM.Int64Ty->getPointerTo(),
2094 CGM.Int64Ty,
2095 CGM.IntTy,
2096 CGM.IntTy,
2097 CGM.Int64Ty,
2098 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002099 auto *FnTy =
Alexey Bataev7292c292016-04-25 12:22:29 +00002100 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2101 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
2102 break;
2103 }
Alexey Bataev8b427062016-05-25 12:36:08 +00002104 case OMPRTL__kmpc_doacross_init: {
2105 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
2106 // num_dims, struct kmp_dim *dims);
2107 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2108 CGM.Int32Ty,
2109 CGM.Int32Ty,
2110 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002111 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002112 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2113 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
2114 break;
2115 }
2116 case OMPRTL__kmpc_doacross_fini: {
2117 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
2118 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002119 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002120 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2121 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
2122 break;
2123 }
2124 case OMPRTL__kmpc_doacross_post: {
2125 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
2126 // *vec);
2127 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2128 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002129 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002130 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2131 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
2132 break;
2133 }
2134 case OMPRTL__kmpc_doacross_wait: {
2135 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
2136 // *vec);
2137 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2138 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002139 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002140 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2141 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
2142 break;
2143 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002144 case OMPRTL__kmpc_task_reduction_init: {
2145 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
2146 // *data);
2147 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002148 auto *FnTy =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002149 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2150 RTLFn =
2151 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
2152 break;
2153 }
2154 case OMPRTL__kmpc_task_reduction_get_th_data: {
2155 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
2156 // *d);
2157 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002158 auto *FnTy =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002159 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2160 RTLFn = CGM.CreateRuntimeFunction(
2161 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2162 break;
2163 }
Samuel Antaobed3c462015-10-02 16:14:20 +00002164 case OMPRTL__tgt_target: {
George Rokos63bc9d62017-11-21 18:25:12 +00002165 // Build int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
2166 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Samuel Antaobed3c462015-10-02 16:14:20 +00002167 // *arg_types);
George Rokos63bc9d62017-11-21 18:25:12 +00002168 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaobed3c462015-10-02 16:14:20 +00002169 CGM.VoidPtrTy,
2170 CGM.Int32Ty,
2171 CGM.VoidPtrPtrTy,
2172 CGM.VoidPtrPtrTy,
2173 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002174 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002175 auto *FnTy =
Samuel Antaobed3c462015-10-02 16:14:20 +00002176 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2177 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2178 break;
2179 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002180 case OMPRTL__tgt_target_nowait: {
2181 // Build int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
2182 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2183 // int64_t *arg_types);
2184 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2185 CGM.VoidPtrTy,
2186 CGM.Int32Ty,
2187 CGM.VoidPtrPtrTy,
2188 CGM.VoidPtrPtrTy,
2189 CGM.SizeTy->getPointerTo(),
2190 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002191 auto *FnTy =
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002192 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2193 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_nowait");
2194 break;
2195 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00002196 case OMPRTL__tgt_target_teams: {
George Rokos63bc9d62017-11-21 18:25:12 +00002197 // Build int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002198 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
George Rokos63bc9d62017-11-21 18:25:12 +00002199 // int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2200 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002201 CGM.VoidPtrTy,
2202 CGM.Int32Ty,
2203 CGM.VoidPtrPtrTy,
2204 CGM.VoidPtrPtrTy,
2205 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002206 CGM.Int64Ty->getPointerTo(),
Samuel Antaob68e2db2016-03-03 16:20:23 +00002207 CGM.Int32Ty,
2208 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002209 auto *FnTy =
Samuel Antaob68e2db2016-03-03 16:20:23 +00002210 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2211 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2212 break;
2213 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002214 case OMPRTL__tgt_target_teams_nowait: {
2215 // Build int32_t __tgt_target_teams_nowait(int64_t device_id, void
2216 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
2217 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2218 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2219 CGM.VoidPtrTy,
2220 CGM.Int32Ty,
2221 CGM.VoidPtrPtrTy,
2222 CGM.VoidPtrPtrTy,
2223 CGM.SizeTy->getPointerTo(),
2224 CGM.Int64Ty->getPointerTo(),
2225 CGM.Int32Ty,
2226 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002227 auto *FnTy =
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002228 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2229 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams_nowait");
2230 break;
2231 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002232 case OMPRTL__tgt_register_lib: {
2233 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2234 QualType ParamTy =
2235 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2236 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002237 auto *FnTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002238 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2239 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2240 break;
2241 }
2242 case OMPRTL__tgt_unregister_lib: {
2243 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2244 QualType ParamTy =
2245 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2246 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002247 auto *FnTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002248 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2249 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2250 break;
2251 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002252 case OMPRTL__tgt_target_data_begin: {
George Rokos63bc9d62017-11-21 18:25:12 +00002253 // Build void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
2254 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2255 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002256 CGM.Int32Ty,
2257 CGM.VoidPtrPtrTy,
2258 CGM.VoidPtrPtrTy,
2259 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002260 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002261 auto *FnTy =
Samuel Antaodf158d52016-04-27 22:58:19 +00002262 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2263 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2264 break;
2265 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002266 case OMPRTL__tgt_target_data_begin_nowait: {
2267 // Build void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
2268 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2269 // *arg_types);
2270 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2271 CGM.Int32Ty,
2272 CGM.VoidPtrPtrTy,
2273 CGM.VoidPtrPtrTy,
2274 CGM.SizeTy->getPointerTo(),
2275 CGM.Int64Ty->getPointerTo()};
2276 auto *FnTy =
2277 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2278 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin_nowait");
2279 break;
2280 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002281 case OMPRTL__tgt_target_data_end: {
George Rokos63bc9d62017-11-21 18:25:12 +00002282 // Build void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
2283 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2284 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002285 CGM.Int32Ty,
2286 CGM.VoidPtrPtrTy,
2287 CGM.VoidPtrPtrTy,
2288 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002289 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002290 auto *FnTy =
Samuel Antaodf158d52016-04-27 22:58:19 +00002291 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2292 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2293 break;
2294 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002295 case OMPRTL__tgt_target_data_end_nowait: {
2296 // Build void __tgt_target_data_end_nowait(int64_t device_id, int32_t
2297 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2298 // *arg_types);
2299 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2300 CGM.Int32Ty,
2301 CGM.VoidPtrPtrTy,
2302 CGM.VoidPtrPtrTy,
2303 CGM.SizeTy->getPointerTo(),
2304 CGM.Int64Ty->getPointerTo()};
2305 auto *FnTy =
2306 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2307 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end_nowait");
2308 break;
2309 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002310 case OMPRTL__tgt_target_data_update: {
George Rokos63bc9d62017-11-21 18:25:12 +00002311 // Build void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
2312 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2313 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antao8d2d7302016-05-26 18:30:22 +00002314 CGM.Int32Ty,
2315 CGM.VoidPtrPtrTy,
2316 CGM.VoidPtrPtrTy,
2317 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002318 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002319 auto *FnTy =
Samuel Antao8d2d7302016-05-26 18:30:22 +00002320 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2321 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2322 break;
2323 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002324 case OMPRTL__tgt_target_data_update_nowait: {
2325 // Build void __tgt_target_data_update_nowait(int64_t device_id, int32_t
2326 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2327 // *arg_types);
2328 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2329 CGM.Int32Ty,
2330 CGM.VoidPtrPtrTy,
2331 CGM.VoidPtrPtrTy,
2332 CGM.SizeTy->getPointerTo(),
2333 CGM.Int64Ty->getPointerTo()};
2334 auto *FnTy =
2335 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2336 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update_nowait");
2337 break;
2338 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002339 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002340 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002341 return RTLFn;
2342}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002343
Alexander Musman21212e42015-03-13 10:38:23 +00002344llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2345 bool IVSigned) {
2346 assert((IVSize == 32 || IVSize == 64) &&
2347 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002348 StringRef Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2349 : "__kmpc_for_static_init_4u")
2350 : (IVSigned ? "__kmpc_for_static_init_8"
2351 : "__kmpc_for_static_init_8u");
2352 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2353 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
Alexander Musman21212e42015-03-13 10:38:23 +00002354 llvm::Type *TypeParams[] = {
2355 getIdentTyPointerTy(), // loc
2356 CGM.Int32Ty, // tid
2357 CGM.Int32Ty, // schedtype
2358 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2359 PtrTy, // p_lower
2360 PtrTy, // p_upper
2361 PtrTy, // p_stride
2362 ITy, // incr
2363 ITy // chunk
2364 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002365 auto *FnTy =
Alexander Musman21212e42015-03-13 10:38:23 +00002366 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2367 return CGM.CreateRuntimeFunction(FnTy, Name);
2368}
2369
Alexander Musman92bdaab2015-03-12 13:37:50 +00002370llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2371 bool IVSigned) {
2372 assert((IVSize == 32 || IVSize == 64) &&
2373 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002374 StringRef Name =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002375 IVSize == 32
2376 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2377 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002378 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
Alexander Musman92bdaab2015-03-12 13:37:50 +00002379 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2380 CGM.Int32Ty, // tid
2381 CGM.Int32Ty, // schedtype
2382 ITy, // lower
2383 ITy, // upper
2384 ITy, // stride
2385 ITy // chunk
2386 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002387 auto *FnTy =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002388 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2389 return CGM.CreateRuntimeFunction(FnTy, Name);
2390}
2391
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002392llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2393 bool IVSigned) {
2394 assert((IVSize == 32 || IVSize == 64) &&
2395 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002396 StringRef Name =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002397 IVSize == 32
2398 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2399 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2400 llvm::Type *TypeParams[] = {
2401 getIdentTyPointerTy(), // loc
2402 CGM.Int32Ty, // tid
2403 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002404 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002405 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2406 return CGM.CreateRuntimeFunction(FnTy, Name);
2407}
2408
Alexander Musman92bdaab2015-03-12 13:37:50 +00002409llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2410 bool IVSigned) {
2411 assert((IVSize == 32 || IVSize == 64) &&
2412 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002413 StringRef Name =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002414 IVSize == 32
2415 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2416 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002417 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2418 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002419 llvm::Type *TypeParams[] = {
2420 getIdentTyPointerTy(), // loc
2421 CGM.Int32Ty, // tid
2422 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2423 PtrTy, // p_lower
2424 PtrTy, // p_upper
2425 PtrTy // p_stride
2426 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002427 auto *FnTy =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002428 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2429 return CGM.CreateRuntimeFunction(FnTy, Name);
2430}
2431
Alexey Bataev03f270c2018-03-30 18:31:07 +00002432Address CGOpenMPRuntime::getAddrOfDeclareTargetLink(const VarDecl *VD) {
2433 if (CGM.getLangOpts().OpenMPSimd)
2434 return Address::invalid();
Alexey Bataev92327c52018-03-26 16:40:55 +00002435 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002436 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00002437 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2438 SmallString<64> PtrName;
2439 {
2440 llvm::raw_svector_ostream OS(PtrName);
2441 OS << CGM.getMangledName(GlobalDecl(VD)) << "_decl_tgt_link_ptr";
2442 }
2443 llvm::Value *Ptr = CGM.getModule().getNamedValue(PtrName);
2444 if (!Ptr) {
2445 QualType PtrTy = CGM.getContext().getPointerType(VD->getType());
2446 Ptr = getOrCreateInternalVariable(CGM.getTypes().ConvertTypeForMem(PtrTy),
2447 PtrName);
Alexey Bataev03f270c2018-03-30 18:31:07 +00002448 if (!CGM.getLangOpts().OpenMPIsDevice) {
2449 auto *GV = cast<llvm::GlobalVariable>(Ptr);
2450 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2451 GV->setInitializer(CGM.GetAddrOfGlobal(VD));
2452 }
2453 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ptr));
2454 registerTargetGlobalVariable(VD, cast<llvm::Constant>(Ptr));
Alexey Bataev92327c52018-03-26 16:40:55 +00002455 }
2456 return Address(Ptr, CGM.getContext().getDeclAlign(VD));
2457 }
2458 return Address::invalid();
2459}
2460
Alexey Bataev97720002014-11-11 04:05:39 +00002461llvm::Constant *
2462CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002463 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2464 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002465 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev18fa2322018-05-02 14:20:50 +00002466 std::string Suffix = getName({"cache", ""});
2467 return getOrCreateInternalVariable(
2468 CGM.Int8PtrPtrTy, Twine(CGM.getMangledName(VD)).concat(Suffix));
Alexey Bataev97720002014-11-11 04:05:39 +00002469}
2470
John McCall7f416cc2015-09-08 08:05:57 +00002471Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2472 const VarDecl *VD,
2473 Address VDAddr,
2474 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002475 if (CGM.getLangOpts().OpenMPUseTLS &&
2476 CGM.getContext().getTargetInfo().isTLSSupported())
2477 return VDAddr;
2478
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002479 llvm::Type *VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002480 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002481 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2482 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002483 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2484 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002485 return Address(CGF.EmitRuntimeCall(
2486 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2487 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002488}
2489
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002490void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002491 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002492 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2493 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2494 // library.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002495 llvm::Value *OMPLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002496 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002497 OMPLoc);
2498 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2499 // to register constructor/destructor for variable.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002500 llvm::Value *Args[] = {
2501 OMPLoc, CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.VoidPtrTy),
2502 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002503 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002504 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002505}
2506
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002507llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002508 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002509 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002510 if (CGM.getLangOpts().OpenMPUseTLS &&
2511 CGM.getContext().getTargetInfo().isTLSSupported())
2512 return nullptr;
2513
Alexey Bataev97720002014-11-11 04:05:39 +00002514 VD = VD->getDefinition(CGM.getContext());
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00002515 if (VD && ThreadPrivateWithDefinition.insert(CGM.getMangledName(VD)).second) {
Alexey Bataev97720002014-11-11 04:05:39 +00002516 QualType ASTTy = VD->getType();
2517
2518 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002519 const Expr *Init = VD->getAnyInitializer();
Alexey Bataev97720002014-11-11 04:05:39 +00002520 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2521 // Generate function that re-emits the declaration's initializer into the
2522 // threadprivate copy of the variable VD
2523 CodeGenFunction CtorCGF(CGM);
2524 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002525 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2526 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002527 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002528 Args.push_back(&Dst);
2529
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002530 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
John McCallc56a8b32016-03-11 04:30:31 +00002531 CGM.getContext().VoidPtrTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002532 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002533 std::string Name = getName({"__kmpc_global_ctor_", ""});
2534 llvm::Function *Fn =
2535 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002536 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002537 Args, Loc, Loc);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002538 llvm::Value *ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002539 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002540 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002541 Address Arg = Address(ArgVal, VDAddr.getAlignment());
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002542 Arg = CtorCGF.Builder.CreateElementBitCast(
2543 Arg, CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002544 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2545 /*IsInitializer=*/true);
2546 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002547 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002548 CGM.getContext().VoidPtrTy, Dst.getLocation());
2549 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2550 CtorCGF.FinishFunction();
2551 Ctor = Fn;
2552 }
2553 if (VD->getType().isDestructedType() != QualType::DK_none) {
2554 // Generate function that emits destructor call for the threadprivate copy
2555 // of the variable VD
2556 CodeGenFunction DtorCGF(CGM);
2557 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002558 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2559 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002560 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002561 Args.push_back(&Dst);
2562
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002563 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
John McCallc56a8b32016-03-11 04:30:31 +00002564 CGM.getContext().VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002565 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002566 std::string Name = getName({"__kmpc_global_dtor_", ""});
2567 llvm::Function *Fn =
2568 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002569 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002570 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002571 Loc, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002572 // Create a scope with an artificial location for the body of this function.
2573 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002574 llvm::Value *ArgVal = DtorCGF.EmitLoadOfScalar(
Alexey Bataev97720002014-11-11 04:05:39 +00002575 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002576 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2577 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002578 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2579 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2580 DtorCGF.FinishFunction();
2581 Dtor = Fn;
2582 }
2583 // Do not emit init function if it is not required.
2584 if (!Ctor && !Dtor)
2585 return nullptr;
2586
2587 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002588 auto *CopyCtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2589 /*isVarArg=*/false)
2590 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002591 // Copying constructor for the threadprivate variable.
2592 // Must be NULL - reserved by runtime, but currently it requires that this
2593 // parameter is always NULL. Otherwise it fires assertion.
2594 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2595 if (Ctor == nullptr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002596 auto *CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2597 /*isVarArg=*/false)
2598 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002599 Ctor = llvm::Constant::getNullValue(CtorTy);
2600 }
2601 if (Dtor == nullptr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002602 auto *DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2603 /*isVarArg=*/false)
2604 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002605 Dtor = llvm::Constant::getNullValue(DtorTy);
2606 }
2607 if (!CGF) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002608 auto *InitFunctionTy =
Alexey Bataev97720002014-11-11 04:05:39 +00002609 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002610 std::string Name = getName({"__omp_threadprivate_init_", ""});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002611 llvm::Function *InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Alexey Bataev18fa2322018-05-02 14:20:50 +00002612 InitFunctionTy, Name, CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002613 CodeGenFunction InitCGF(CGM);
2614 FunctionArgList ArgList;
2615 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2616 CGM.getTypes().arrangeNullaryFunction(), ArgList,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002617 Loc, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002618 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002619 InitCGF.FinishFunction();
2620 return InitFunction;
2621 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002622 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002623 }
2624 return nullptr;
2625}
2626
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002627/// Obtain information that uniquely identifies a target entry. This
Alexey Bataev34f8a702018-03-28 14:28:54 +00002628/// consists of the file and device IDs as well as line number associated with
2629/// the relevant entry source location.
2630static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
2631 unsigned &DeviceID, unsigned &FileID,
2632 unsigned &LineNum) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002633 SourceManager &SM = C.getSourceManager();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002634
2635 // The loc should be always valid and have a file ID (the user cannot use
2636 // #pragma directives in macros)
2637
2638 assert(Loc.isValid() && "Source location is expected to be always valid.");
Alexey Bataev34f8a702018-03-28 14:28:54 +00002639
2640 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
2641 assert(PLoc.isValid() && "Source location is expected to be always valid.");
2642
2643 llvm::sys::fs::UniqueID ID;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00002644 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
2645 SM.getDiagnostics().Report(diag::err_cannot_open_file)
2646 << PLoc.getFilename() << EC.message();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002647
2648 DeviceID = ID.getDevice();
2649 FileID = ID.getFile();
2650 LineNum = PLoc.getLine();
2651}
2652
2653bool CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD,
2654 llvm::GlobalVariable *Addr,
2655 bool PerformInit) {
2656 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002657 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002658 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link)
Alexey Bataevd01b7492018-08-15 19:45:12 +00002659 return CGM.getLangOpts().OpenMPIsDevice;
Alexey Bataev34f8a702018-03-28 14:28:54 +00002660 VD = VD->getDefinition(CGM.getContext());
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00002661 if (VD && !DeclareTargetWithDefinition.insert(CGM.getMangledName(VD)).second)
Alexey Bataev34f8a702018-03-28 14:28:54 +00002662 return CGM.getLangOpts().OpenMPIsDevice;
2663
2664 QualType ASTTy = VD->getType();
2665
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002666 SourceLocation Loc = VD->getCanonicalDecl()->getBeginLoc();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002667 // Produce the unique prefix to identify the new target regions. We use
2668 // the source location of the variable declaration which we know to not
2669 // conflict with any target region.
2670 unsigned DeviceID;
2671 unsigned FileID;
2672 unsigned Line;
2673 getTargetEntryUniqueInfo(CGM.getContext(), Loc, DeviceID, FileID, Line);
2674 SmallString<128> Buffer, Out;
2675 {
2676 llvm::raw_svector_ostream OS(Buffer);
2677 OS << "__omp_offloading_" << llvm::format("_%x", DeviceID)
2678 << llvm::format("_%x_", FileID) << VD->getName() << "_l" << Line;
2679 }
2680
2681 const Expr *Init = VD->getAnyInitializer();
2682 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2683 llvm::Constant *Ctor;
2684 llvm::Constant *ID;
2685 if (CGM.getLangOpts().OpenMPIsDevice) {
2686 // Generate function that re-emits the declaration's initializer into
2687 // the threadprivate copy of the variable VD
2688 CodeGenFunction CtorCGF(CGM);
2689
2690 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2691 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2692 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2693 FTy, Twine(Buffer, "_ctor"), FI, Loc);
2694 auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF);
2695 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2696 FunctionArgList(), Loc, Loc);
2697 auto AL = ApplyDebugLocation::CreateArtificial(CtorCGF);
2698 CtorCGF.EmitAnyExprToMem(Init,
2699 Address(Addr, CGM.getContext().getDeclAlign(VD)),
2700 Init->getType().getQualifiers(),
2701 /*IsInitializer=*/true);
2702 CtorCGF.FinishFunction();
2703 Ctor = Fn;
2704 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
Alexey Bataeve253f2f2018-05-09 14:15:18 +00002705 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ctor));
Alexey Bataev34f8a702018-03-28 14:28:54 +00002706 } else {
2707 Ctor = new llvm::GlobalVariable(
2708 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2709 llvm::GlobalValue::PrivateLinkage,
2710 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_ctor"));
2711 ID = Ctor;
2712 }
2713
2714 // Register the information for the entry associated with the constructor.
2715 Out.clear();
2716 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2717 DeviceID, FileID, Twine(Buffer, "_ctor").toStringRef(Out), Line, Ctor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002718 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryCtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002719 }
2720 if (VD->getType().isDestructedType() != QualType::DK_none) {
2721 llvm::Constant *Dtor;
2722 llvm::Constant *ID;
2723 if (CGM.getLangOpts().OpenMPIsDevice) {
2724 // Generate function that emits destructor call for the threadprivate
2725 // copy of the variable VD
2726 CodeGenFunction DtorCGF(CGM);
2727
2728 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2729 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2730 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2731 FTy, Twine(Buffer, "_dtor"), FI, Loc);
2732 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
2733 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2734 FunctionArgList(), Loc, Loc);
2735 // Create a scope with an artificial location for the body of this
2736 // function.
2737 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
2738 DtorCGF.emitDestroy(Address(Addr, CGM.getContext().getDeclAlign(VD)),
2739 ASTTy, DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2740 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2741 DtorCGF.FinishFunction();
2742 Dtor = Fn;
2743 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
Alexey Bataeve253f2f2018-05-09 14:15:18 +00002744 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Dtor));
Alexey Bataev34f8a702018-03-28 14:28:54 +00002745 } else {
2746 Dtor = new llvm::GlobalVariable(
2747 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2748 llvm::GlobalValue::PrivateLinkage,
2749 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_dtor"));
2750 ID = Dtor;
2751 }
2752 // Register the information for the entry associated with the destructor.
2753 Out.clear();
2754 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2755 DeviceID, FileID, Twine(Buffer, "_dtor").toStringRef(Out), Line, Dtor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002756 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryDtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002757 }
2758 return CGM.getLangOpts().OpenMPIsDevice;
2759}
2760
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002761Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2762 QualType VarType,
2763 StringRef Name) {
Alexey Bataev18fa2322018-05-02 14:20:50 +00002764 std::string Suffix = getName({"artificial", ""});
2765 std::string CacheSuffix = getName({"cache", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002766 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002767 llvm::Value *GAddr =
2768 getOrCreateInternalVariable(VarLVType, Twine(Name).concat(Suffix));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002769 llvm::Value *Args[] = {
2770 emitUpdateLocation(CGF, SourceLocation()),
2771 getThreadID(CGF, SourceLocation()),
2772 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2773 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2774 /*IsSigned=*/false),
Alexey Bataev18fa2322018-05-02 14:20:50 +00002775 getOrCreateInternalVariable(
2776 CGM.VoidPtrPtrTy, Twine(Name).concat(Suffix).concat(CacheSuffix))};
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002777 return Address(
2778 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2779 CGF.EmitRuntimeCall(
2780 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2781 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2782 CGM.getPointerAlign());
2783}
2784
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002785void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2786 const RegionCodeGenTy &ThenGen,
2787 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002788 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2789
2790 // If the condition constant folds and can be elided, try to avoid emitting
2791 // the condition and the dead arm of the if/else.
2792 bool CondConstant;
2793 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002794 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002795 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002796 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002797 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002798 return;
2799 }
2800
2801 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2802 // emit the conditional branch.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002803 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("omp_if.then");
2804 llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else");
2805 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("omp_if.end");
Alexey Bataev1d677132015-04-22 13:57:31 +00002806 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2807
2808 // Emit the 'then' code.
2809 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002810 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002811 CGF.EmitBranch(ContBlock);
2812 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002813 // There is no need to emit line number for unconditional branch.
2814 (void)ApplyDebugLocation::CreateEmpty(CGF);
2815 CGF.EmitBlock(ElseBlock);
2816 ElseGen(CGF);
2817 // There is no need to emit line number for unconditional branch.
2818 (void)ApplyDebugLocation::CreateEmpty(CGF);
2819 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002820 // Emit the continuation block for code after the if.
2821 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002822}
2823
Alexey Bataev1d677132015-04-22 13:57:31 +00002824void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2825 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002826 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002827 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002828 if (!CGF.HaveInsertPoint())
2829 return;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002830 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002831 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2832 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002833 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002834 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002835 llvm::Value *Args[] = {
2836 RTLoc,
2837 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002838 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002839 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2840 RealArgs.append(std::begin(Args), std::end(Args));
2841 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2842
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002843 llvm::Value *RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002844 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2845 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002846 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2847 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002848 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
2849 llvm::Value *ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00002850 // Build calls:
2851 // __kmpc_serialized_parallel(&Loc, GTid);
2852 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002853 CGF.EmitRuntimeCall(
2854 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002855
Alexey Bataev1d677132015-04-22 13:57:31 +00002856 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002857 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2858 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00002859 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00002860 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataev8521ff62018-07-25 20:03:01 +00002861 // ThreadId for serialized parallels is 0.
2862 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
Alexey Bataev2377fe92015-09-10 08:12:02 +00002863 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2864 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002865 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002866
Alexey Bataev1d677132015-04-22 13:57:31 +00002867 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002868 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00002869 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002870 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2871 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002872 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002873 if (IfCond) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002874 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002875 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002876 RegionCodeGenTy ThenRCG(ThenGen);
2877 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002878 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002879}
2880
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002881// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002882// thread-ID variable (it is passed in a first argument of the outlined function
2883// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2884// regular serial code region, get thread ID by calling kmp_int32
2885// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2886// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002887Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2888 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002889 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002890 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002891 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002892 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002893
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002894 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2895 QualType Int32Ty =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002896 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002897 Address ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
Alexey Bataevd74d0602014-10-13 06:02:40 +00002898 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002899 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002900
2901 return ThreadIDTemp;
2902}
2903
Alexey Bataev97720002014-11-11 04:05:39 +00002904llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002905CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002906 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002907 SmallString<256> Buffer;
2908 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002909 Out << Name;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002910 StringRef RuntimeName = Out.str();
Alexey Bataev43a919f2018-04-13 17:48:43 +00002911 auto &Elem = *InternalVars.try_emplace(RuntimeName, nullptr).first;
David Blaikie13156b62014-11-19 03:06:06 +00002912 if (Elem.second) {
2913 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002914 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002915 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002916 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002917
David Blaikie13156b62014-11-19 03:06:06 +00002918 return Elem.second = new llvm::GlobalVariable(
2919 CGM.getModule(), Ty, /*IsConstant*/ false,
2920 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2921 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002922}
2923
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002924llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev18fa2322018-05-02 14:20:50 +00002925 std::string Prefix = Twine("gomp_critical_user_", CriticalName).str();
2926 std::string Name = getName({Prefix, "var"});
2927 return getOrCreateInternalVariable(KmpCriticalNameTy, Name);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002928}
2929
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002930namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002931/// Common pre(post)-action for different OpenMP constructs.
2932class CommonActionTy final : public PrePostActionTy {
2933 llvm::Value *EnterCallee;
2934 ArrayRef<llvm::Value *> EnterArgs;
2935 llvm::Value *ExitCallee;
2936 ArrayRef<llvm::Value *> ExitArgs;
2937 bool Conditional;
2938 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002939
2940public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002941 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2942 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2943 bool Conditional = false)
2944 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2945 ExitArgs(ExitArgs), Conditional(Conditional) {}
2946 void Enter(CodeGenFunction &CGF) override {
2947 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2948 if (Conditional) {
2949 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2950 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2951 ContBlock = CGF.createBasicBlock("omp_if.end");
2952 // Generate the branch (If-stmt)
2953 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2954 CGF.EmitBlock(ThenBlock);
2955 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002956 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002957 void Done(CodeGenFunction &CGF) {
2958 // Emit the rest of blocks/branches
2959 CGF.EmitBranch(ContBlock);
2960 CGF.EmitBlock(ContBlock, true);
2961 }
2962 void Exit(CodeGenFunction &CGF) override {
2963 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002964 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002965};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002966} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002967
2968void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2969 StringRef CriticalName,
2970 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002971 SourceLocation Loc, const Expr *Hint) {
2972 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002973 // CriticalOpGen();
2974 // __kmpc_end_critical(ident_t *, gtid, Lock);
2975 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002976 if (!CGF.HaveInsertPoint())
2977 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002978 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2979 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002980 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2981 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002982 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002983 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2984 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2985 }
2986 CommonActionTy Action(
2987 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2988 : OMPRTL__kmpc_critical),
2989 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2990 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002991 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002992}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002993
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002994void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002995 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002996 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002997 if (!CGF.HaveInsertPoint())
2998 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002999 // if(__kmpc_master(ident_t *, gtid)) {
3000 // MasterOpGen();
3001 // __kmpc_end_master(ident_t *, gtid);
3002 // }
3003 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00003004 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003005 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
3006 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
3007 /*Conditional=*/true);
3008 MasterOpGen.setAction(Action);
3009 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
3010 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00003011}
3012
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003013void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
3014 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003015 if (!CGF.HaveInsertPoint())
3016 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00003017 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
3018 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003019 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00003020 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003021 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003022 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
3023 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00003024}
3025
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003026void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
3027 const RegionCodeGenTy &TaskgroupOpGen,
3028 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003029 if (!CGF.HaveInsertPoint())
3030 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003031 // __kmpc_taskgroup(ident_t *, gtid);
3032 // TaskgroupOpGen();
3033 // __kmpc_end_taskgroup(ident_t *, gtid);
3034 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003035 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3036 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
3037 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
3038 Args);
3039 TaskgroupOpGen.setAction(Action);
3040 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003041}
3042
John McCall7f416cc2015-09-08 08:05:57 +00003043/// Given an array of pointers to variables, project the address of a
3044/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003045static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
3046 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00003047 // Pull out the pointer to the variable.
3048 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003049 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00003050 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
3051
3052 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003053 Addr = CGF.Builder.CreateElementBitCast(
3054 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00003055 return Addr;
3056}
3057
Alexey Bataeva63048e2015-03-23 06:18:07 +00003058static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00003059 CodeGenModule &CGM, llvm::Type *ArgsType,
3060 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003061 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps,
3062 SourceLocation Loc) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003063 ASTContext &C = CGM.getContext();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003064 // void copy_func(void *LHSArg, void *RHSArg);
3065 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003066 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3067 ImplicitParamDecl::Other);
3068 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3069 ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003070 Args.push_back(&LHSArg);
3071 Args.push_back(&RHSArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003072 const auto &CGFI =
3073 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003074 std::string Name =
3075 CGM.getOpenMPRuntime().getName({"omp", "copyprivate", "copy_func"});
3076 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
3077 llvm::GlobalValue::InternalLinkage, Name,
3078 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003079 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003080 Fn->setDoesNotRecurse();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003081 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003082 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00003083 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003084 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00003085 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3086 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
3087 ArgsType), CGF.getPointerAlign());
3088 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3089 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
3090 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00003091 // *(Type0*)Dst[0] = *(Type0*)Src[0];
3092 // *(Type1*)Dst[1] = *(Type1*)Src[1];
3093 // ...
3094 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00003095 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003096 const auto *DestVar =
3097 cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003098 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
3099
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003100 const auto *SrcVar =
3101 cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003102 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
3103
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003104 const auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003105 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00003106 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003107 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00003108 CGF.FinishFunction();
3109 return Fn;
3110}
3111
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003112void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003113 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00003114 SourceLocation Loc,
3115 ArrayRef<const Expr *> CopyprivateVars,
3116 ArrayRef<const Expr *> SrcExprs,
3117 ArrayRef<const Expr *> DstExprs,
3118 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003119 if (!CGF.HaveInsertPoint())
3120 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00003121 assert(CopyprivateVars.size() == SrcExprs.size() &&
3122 CopyprivateVars.size() == DstExprs.size() &&
3123 CopyprivateVars.size() == AssignmentOps.size());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003124 ASTContext &C = CGM.getContext();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003125 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003126 // if(__kmpc_single(ident_t *, gtid)) {
3127 // SingleOpGen();
3128 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003129 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003130 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00003131 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3132 // <copy_func>, did_it);
3133
John McCall7f416cc2015-09-08 08:05:57 +00003134 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003135 if (!CopyprivateVars.empty()) {
3136 // int32 did_it = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003137 QualType KmpInt32Ty =
3138 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003139 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00003140 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003141 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003142 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00003143 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003144 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
3145 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
3146 /*Conditional=*/true);
3147 SingleOpGen.setAction(Action);
3148 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
3149 if (DidIt.isValid()) {
3150 // did_it = 1;
3151 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
3152 }
3153 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003154 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3155 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00003156 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00003157 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003158 QualType CopyprivateArrayTy =
Alexey Bataeva63048e2015-03-23 06:18:07 +00003159 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3160 /*IndexTypeQuals=*/0);
3161 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00003162 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00003163 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
3164 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00003165 Address Elem = CGF.Builder.CreateConstArrayGEP(
3166 CopyprivateList, I, CGF.getPointerSize());
3167 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00003168 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003169 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
3170 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003171 }
3172 // Build function that copies private values from single region to all other
3173 // threads in the corresponding parallel region.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003174 llvm::Value *CpyFn = emitCopyprivateCopyFunction(
Alexey Bataeva63048e2015-03-23 06:18:07 +00003175 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003176 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps, Loc);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003177 llvm::Value *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00003178 Address CL =
3179 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
3180 CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003181 llvm::Value *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003182 llvm::Value *Args[] = {
3183 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
3184 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00003185 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00003186 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00003187 CpyFn, // void (*) (void *, void *) <copy_func>
3188 DidItVal // i32 did_it
3189 };
3190 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
3191 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003192}
3193
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003194void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
3195 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00003196 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003197 if (!CGF.HaveInsertPoint())
3198 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003199 // __kmpc_ordered(ident_t *, gtid);
3200 // OrderedOpGen();
3201 // __kmpc_end_ordered(ident_t *, gtid);
3202 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00003203 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003204 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003205 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
3206 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
3207 Args);
3208 OrderedOpGen.setAction(Action);
3209 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
3210 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003211 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003212 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003213}
3214
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003215void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00003216 OpenMPDirectiveKind Kind, bool EmitChecks,
3217 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003218 if (!CGF.HaveInsertPoint())
3219 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00003220 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003221 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003222 unsigned Flags;
3223 if (Kind == OMPD_for)
3224 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
3225 else if (Kind == OMPD_sections)
3226 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
3227 else if (Kind == OMPD_single)
3228 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
3229 else if (Kind == OMPD_barrier)
3230 Flags = OMP_IDENT_BARRIER_EXPL;
3231 else
3232 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003233 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
3234 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003235 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
3236 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003237 if (auto *OMPRegionInfo =
3238 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00003239 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003240 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003241 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00003242 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003243 // if (__kmpc_cancel_barrier()) {
3244 // exit from construct;
3245 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003246 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
3247 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
3248 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003249 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
3250 CGF.EmitBlock(ExitBB);
3251 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003252 CodeGenFunction::JumpDest CancelDestination =
Alexey Bataev25e5b442015-09-15 12:52:43 +00003253 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003254 CGF.EmitBranchThroughCleanup(CancelDestination);
3255 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
3256 }
3257 return;
3258 }
3259 }
3260 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00003261}
3262
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003263/// Map the OpenMP loop schedule to the runtime enumeration.
Alexander Musmanc6388682014-12-15 07:07:06 +00003264static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003265 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003266 switch (ScheduleKind) {
3267 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003268 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
3269 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00003270 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003271 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003272 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003273 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003274 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003275 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
3276 case OMPC_SCHEDULE_auto:
3277 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00003278 case OMPC_SCHEDULE_unknown:
3279 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003280 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00003281 }
3282 llvm_unreachable("Unexpected runtime schedule");
3283}
3284
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003285/// Map the OpenMP distribute schedule to the runtime enumeration.
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003286static OpenMPSchedType
3287getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
3288 // only static is allowed for dist_schedule
3289 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
3290}
3291
Alexander Musmanc6388682014-12-15 07:07:06 +00003292bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
3293 bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003294 OpenMPSchedType Schedule =
3295 getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00003296 return Schedule == OMP_sch_static;
3297}
3298
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003299bool CGOpenMPRuntime::isStaticNonchunked(
3300 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003301 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003302 return Schedule == OMP_dist_sch_static;
3303}
3304
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003305bool CGOpenMPRuntime::isStaticChunked(OpenMPScheduleClauseKind ScheduleKind,
3306 bool Chunked) const {
3307 OpenMPSchedType Schedule =
3308 getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
3309 return Schedule == OMP_sch_static_chunked;
3310}
3311
3312bool CGOpenMPRuntime::isStaticChunked(
3313 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
3314 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
3315 return Schedule == OMP_dist_sch_static_chunked;
3316}
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003317
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003318bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003319 OpenMPSchedType Schedule =
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003320 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003321 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
3322 return Schedule != OMP_sch_static;
3323}
3324
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003325static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
3326 OpenMPScheduleClauseModifier M1,
3327 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00003328 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003329 switch (M1) {
3330 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003331 Modifier = OMP_sch_modifier_monotonic;
3332 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003333 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003334 Modifier = OMP_sch_modifier_nonmonotonic;
3335 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003336 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003337 if (Schedule == OMP_sch_static_chunked)
3338 Schedule = OMP_sch_static_balanced_chunked;
3339 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003340 case OMPC_SCHEDULE_MODIFIER_last:
3341 case OMPC_SCHEDULE_MODIFIER_unknown:
3342 break;
3343 }
3344 switch (M2) {
3345 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003346 Modifier = OMP_sch_modifier_monotonic;
3347 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003348 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003349 Modifier = OMP_sch_modifier_nonmonotonic;
3350 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003351 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003352 if (Schedule == OMP_sch_static_chunked)
3353 Schedule = OMP_sch_static_balanced_chunked;
3354 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003355 case OMPC_SCHEDULE_MODIFIER_last:
3356 case OMPC_SCHEDULE_MODIFIER_unknown:
3357 break;
3358 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00003359 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003360}
3361
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003362void CGOpenMPRuntime::emitForDispatchInit(
3363 CodeGenFunction &CGF, SourceLocation Loc,
3364 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
3365 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003366 if (!CGF.HaveInsertPoint())
3367 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003368 OpenMPSchedType Schedule = getRuntimeSchedule(
3369 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00003370 assert(Ordered ||
3371 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00003372 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
3373 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00003374 // Call __kmpc_dispatch_init(
3375 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
3376 // kmp_int[32|64] lower, kmp_int[32|64] upper,
3377 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00003378
John McCall7f416cc2015-09-08 08:05:57 +00003379 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003380 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
3381 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00003382 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003383 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3384 CGF.Builder.getInt32(addMonoNonMonoModifier(
3385 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003386 DispatchValues.LB, // Lower
3387 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003388 CGF.Builder.getIntN(IVSize, 1), // Stride
3389 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00003390 };
3391 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
3392}
3393
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003394static void emitForStaticInitCall(
3395 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
3396 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
3397 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003398 const CGOpenMPRuntime::StaticRTInput &Values) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003399 if (!CGF.HaveInsertPoint())
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003400 return;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003401
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003402 assert(!Values.Ordered);
3403 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
3404 Schedule == OMP_sch_static_balanced_chunked ||
3405 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
3406 Schedule == OMP_dist_sch_static ||
3407 Schedule == OMP_dist_sch_static_chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003408
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003409 // Call __kmpc_for_static_init(
3410 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
3411 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
3412 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
3413 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
3414 llvm::Value *Chunk = Values.Chunk;
3415 if (Chunk == nullptr) {
3416 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
3417 Schedule == OMP_dist_sch_static) &&
3418 "expected static non-chunked schedule");
3419 // If the Chunk was not specified in the clause - use default value 1.
3420 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3421 } else {
3422 assert((Schedule == OMP_sch_static_chunked ||
3423 Schedule == OMP_sch_static_balanced_chunked ||
3424 Schedule == OMP_ord_static_chunked ||
3425 Schedule == OMP_dist_sch_static_chunked) &&
3426 "expected static chunked schedule");
3427 }
3428 llvm::Value *Args[] = {
3429 UpdateLocation,
3430 ThreadId,
3431 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3432 M2)), // Schedule type
3433 Values.IL.getPointer(), // &isLastIter
3434 Values.LB.getPointer(), // &LB
3435 Values.UB.getPointer(), // &UB
3436 Values.ST.getPointer(), // &Stride
3437 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3438 Chunk // Chunk
3439 };
3440 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003441}
3442
John McCall7f416cc2015-09-08 08:05:57 +00003443void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3444 SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003445 OpenMPDirectiveKind DKind,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003446 const OpenMPScheduleTy &ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003447 const StaticRTInput &Values) {
3448 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3449 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3450 assert(isOpenMPWorksharingDirective(DKind) &&
3451 "Expected loop-based or sections-based directive.");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003452 llvm::Value *UpdatedLocation = emitUpdateLocation(CGF, Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003453 isOpenMPLoopDirective(DKind)
3454 ? OMP_IDENT_WORK_LOOP
3455 : OMP_IDENT_WORK_SECTIONS);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003456 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3457 llvm::Constant *StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003458 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003459 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003460 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003461}
John McCall7f416cc2015-09-08 08:05:57 +00003462
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003463void CGOpenMPRuntime::emitDistributeStaticInit(
3464 CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003465 OpenMPDistScheduleClauseKind SchedKind,
3466 const CGOpenMPRuntime::StaticRTInput &Values) {
3467 OpenMPSchedType ScheduleNum =
3468 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003469 llvm::Value *UpdatedLocation =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003470 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003471 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3472 llvm::Constant *StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003473 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003474 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3475 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003476 OMPC_SCHEDULE_MODIFIER_unknown, Values);
Alexander Musmanc6388682014-12-15 07:07:06 +00003477}
3478
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003479void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
Alexey Bataevf43f7142017-09-06 16:17:35 +00003480 SourceLocation Loc,
3481 OpenMPDirectiveKind DKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003482 if (!CGF.HaveInsertPoint())
3483 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003484 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataevf43f7142017-09-06 16:17:35 +00003485 llvm::Value *Args[] = {
3486 emitUpdateLocation(CGF, Loc,
3487 isOpenMPDistributeDirective(DKind)
3488 ? OMP_IDENT_WORK_DISTRIBUTE
3489 : isOpenMPLoopDirective(DKind)
3490 ? OMP_IDENT_WORK_LOOP
3491 : OMP_IDENT_WORK_SECTIONS),
3492 getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003493 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3494 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003495}
3496
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003497void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3498 SourceLocation Loc,
3499 unsigned IVSize,
3500 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003501 if (!CGF.HaveInsertPoint())
3502 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003503 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003504 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003505 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3506}
3507
Alexander Musman92bdaab2015-03-12 13:37:50 +00003508llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3509 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003510 bool IVSigned, Address IL,
3511 Address LB, Address UB,
3512 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003513 // Call __kmpc_dispatch_next(
3514 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3515 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3516 // kmp_int[32|64] *p_stride);
3517 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003518 emitUpdateLocation(CGF, Loc),
3519 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003520 IL.getPointer(), // &isLastIter
3521 LB.getPointer(), // &Lower
3522 UB.getPointer(), // &Upper
3523 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003524 };
3525 llvm::Value *Call =
3526 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3527 return CGF.EmitScalarConversion(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003528 Call, CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/1),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003529 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003530}
3531
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003532void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3533 llvm::Value *NumThreads,
3534 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003535 if (!CGF.HaveInsertPoint())
3536 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003537 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3538 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003539 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003540 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003541 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3542 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003543}
3544
Alexey Bataev7f210c62015-06-18 13:40:03 +00003545void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3546 OpenMPProcBindClauseKind ProcBind,
3547 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003548 if (!CGF.HaveInsertPoint())
3549 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003550 // Constants for proc bind value accepted by the runtime.
3551 enum ProcBindTy {
3552 ProcBindFalse = 0,
3553 ProcBindTrue,
3554 ProcBindMaster,
3555 ProcBindClose,
3556 ProcBindSpread,
3557 ProcBindIntel,
3558 ProcBindDefault
3559 } RuntimeProcBind;
3560 switch (ProcBind) {
3561 case OMPC_PROC_BIND_master:
3562 RuntimeProcBind = ProcBindMaster;
3563 break;
3564 case OMPC_PROC_BIND_close:
3565 RuntimeProcBind = ProcBindClose;
3566 break;
3567 case OMPC_PROC_BIND_spread:
3568 RuntimeProcBind = ProcBindSpread;
3569 break;
3570 case OMPC_PROC_BIND_unknown:
3571 llvm_unreachable("Unsupported proc_bind value.");
3572 }
3573 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3574 llvm::Value *Args[] = {
3575 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3576 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3577 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3578}
3579
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003580void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3581 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003582 if (!CGF.HaveInsertPoint())
3583 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003584 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003585 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3586 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003587}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003588
Alexey Bataev62b63b12015-03-10 07:28:44 +00003589namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003590/// Indexes of fields for type kmp_task_t.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003591enum KmpTaskTFields {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003592 /// List of shared variables.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003593 KmpTaskTShareds,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003594 /// Task routine.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003595 KmpTaskTRoutine,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003596 /// Partition id for the untied tasks.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003597 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003598 /// Function with call of destructors for private variables.
3599 Data1,
3600 /// Task priority.
3601 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003602 /// (Taskloops only) Lower bound.
3603 KmpTaskTLowerBound,
3604 /// (Taskloops only) Upper bound.
3605 KmpTaskTUpperBound,
3606 /// (Taskloops only) Stride.
3607 KmpTaskTStride,
3608 /// (Taskloops only) Is last iteration flag.
3609 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003610 /// (Taskloops only) Reduction data.
3611 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003612};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003613} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003614
Samuel Antaoee8fb302016-01-06 13:42:12 +00003615bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003616 return OffloadEntriesTargetRegion.empty() &&
3617 OffloadEntriesDeviceGlobalVar.empty();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003618}
3619
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003620/// Initialize target region entry.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003621void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3622 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3623 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003624 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003625 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3626 "only required for the device "
3627 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003628 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003629 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003630 OMPTargetRegionEntryTargetRegion);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003631 ++OffloadingEntriesNum;
3632}
3633
3634void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3635 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3636 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003637 llvm::Constant *Addr, llvm::Constant *ID,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003638 OMPTargetRegionEntryKind Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003639 // If we are emitting code for a target, the entry is already initialized,
3640 // only has to be registered.
3641 if (CGM.getLangOpts().OpenMPIsDevice) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00003642 if (!hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum)) {
3643 unsigned DiagID = CGM.getDiags().getCustomDiagID(
3644 DiagnosticsEngine::Error,
3645 "Unable to find target region on line '%0' in the device code.");
3646 CGM.getDiags().Report(DiagID) << LineNum;
3647 return;
3648 }
Samuel Antao2de62b02016-02-13 23:35:10 +00003649 auto &Entry =
3650 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003651 assert(Entry.isValid() && "Entry not initialized!");
3652 Entry.setAddress(Addr);
3653 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003654 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003655 } else {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003656 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003657 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00003658 ++OffloadingEntriesNum;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003659 }
3660}
3661
3662bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003663 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3664 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003665 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3666 if (PerDevice == OffloadEntriesTargetRegion.end())
3667 return false;
3668 auto PerFile = PerDevice->second.find(FileID);
3669 if (PerFile == PerDevice->second.end())
3670 return false;
3671 auto PerParentName = PerFile->second.find(ParentName);
3672 if (PerParentName == PerFile->second.end())
3673 return false;
3674 auto PerLine = PerParentName->second.find(LineNum);
3675 if (PerLine == PerParentName->second.end())
3676 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003677 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003678 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003679 return false;
3680 return true;
3681}
3682
3683void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3684 const OffloadTargetRegionEntryInfoActTy &Action) {
3685 // Scan all target region entries and perform the provided action.
Alexey Bataev03f270c2018-03-30 18:31:07 +00003686 for (const auto &D : OffloadEntriesTargetRegion)
3687 for (const auto &F : D.second)
3688 for (const auto &P : F.second)
3689 for (const auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003690 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003691}
3692
Alexey Bataev03f270c2018-03-30 18:31:07 +00003693void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3694 initializeDeviceGlobalVarEntryInfo(StringRef Name,
3695 OMPTargetGlobalVarEntryKind Flags,
3696 unsigned Order) {
3697 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3698 "only required for the device "
3699 "code generation.");
3700 OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags);
3701 ++OffloadingEntriesNum;
3702}
Samuel Antaoee8fb302016-01-06 13:42:12 +00003703
Alexey Bataev03f270c2018-03-30 18:31:07 +00003704void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3705 registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr,
3706 CharUnits VarSize,
3707 OMPTargetGlobalVarEntryKind Flags,
3708 llvm::GlobalValue::LinkageTypes Linkage) {
3709 if (CGM.getLangOpts().OpenMPIsDevice) {
3710 auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
3711 assert(Entry.isValid() && Entry.getFlags() == Flags &&
3712 "Entry not initialized!");
3713 assert((!Entry.getAddress() || Entry.getAddress() == Addr) &&
3714 "Resetting with the new address.");
3715 if (Entry.getAddress() && hasDeviceGlobalVarEntryInfo(VarName))
3716 return;
3717 Entry.setAddress(Addr);
3718 Entry.setVarSize(VarSize);
3719 Entry.setLinkage(Linkage);
3720 } else {
3721 if (hasDeviceGlobalVarEntryInfo(VarName))
3722 return;
3723 OffloadEntriesDeviceGlobalVar.try_emplace(
3724 VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage);
3725 ++OffloadingEntriesNum;
3726 }
3727}
3728
3729void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3730 actOnDeviceGlobalVarEntriesInfo(
3731 const OffloadDeviceGlobalVarEntryInfoActTy &Action) {
3732 // Scan all target region entries and perform the provided action.
3733 for (const auto &E : OffloadEntriesDeviceGlobalVar)
3734 Action(E.getKey(), E.getValue());
Samuel Antaoee8fb302016-01-06 13:42:12 +00003735}
3736
3737llvm::Function *
3738CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003739 // If we don't have entries or if we are emitting code for the device, we
3740 // don't need to do anything.
3741 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3742 return nullptr;
3743
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003744 llvm::Module &M = CGM.getModule();
3745 ASTContext &C = CGM.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003746
3747 // Get list of devices we care about
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003748 const std::vector<llvm::Triple> &Devices = CGM.getLangOpts().OMPTargetTriples;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003749
3750 // We should be creating an offloading descriptor only if there are devices
3751 // specified.
3752 assert(!Devices.empty() && "No OpenMP offloading devices??");
3753
3754 // Create the external variables that will point to the begin and end of the
3755 // host entries section. These will be defined by the linker.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003756 llvm::Type *OffloadEntryTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00003757 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
Alexey Bataev18fa2322018-05-02 14:20:50 +00003758 std::string EntriesBeginName = getName({"omp_offloading", "entries_begin"});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003759 auto *HostEntriesBegin = new llvm::GlobalVariable(
Samuel Antaoee8fb302016-01-06 13:42:12 +00003760 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003761 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003762 EntriesBeginName);
3763 std::string EntriesEndName = getName({"omp_offloading", "entries_end"});
3764 auto *HostEntriesEnd =
3765 new llvm::GlobalVariable(M, OffloadEntryTy, /*isConstant=*/true,
3766 llvm::GlobalValue::ExternalLinkage,
3767 /*Initializer=*/nullptr, EntriesEndName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003768
3769 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003770 auto *DeviceImageTy = cast<llvm::StructType>(
3771 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003772 ConstantInitBuilder DeviceImagesBuilder(CGM);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003773 ConstantArrayBuilder DeviceImagesEntries =
3774 DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003775
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003776 for (const llvm::Triple &Device : Devices) {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003777 StringRef T = Device.getTriple();
Alexey Bataev18fa2322018-05-02 14:20:50 +00003778 std::string BeginName = getName({"omp_offloading", "img_start", ""});
Samuel Antaoee8fb302016-01-06 13:42:12 +00003779 auto *ImgBegin = new llvm::GlobalVariable(
Alexey Bataev62a4cb02018-07-31 18:27:42 +00003780 M, CGM.Int8Ty, /*isConstant=*/true,
3781 llvm::GlobalValue::ExternalWeakLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003782 /*Initializer=*/nullptr, Twine(BeginName).concat(T));
3783 std::string EndName = getName({"omp_offloading", "img_end", ""});
Samuel Antaoee8fb302016-01-06 13:42:12 +00003784 auto *ImgEnd = new llvm::GlobalVariable(
Alexey Bataev62a4cb02018-07-31 18:27:42 +00003785 M, CGM.Int8Ty, /*isConstant=*/true,
3786 llvm::GlobalValue::ExternalWeakLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003787 /*Initializer=*/nullptr, Twine(EndName).concat(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003788
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003789 llvm::Constant *Data[] = {ImgBegin, ImgEnd, HostEntriesBegin,
3790 HostEntriesEnd};
3791 createConstantGlobalStructAndAddToParent(CGM, getTgtDeviceImageQTy(), Data,
3792 DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003793 }
3794
3795 // Create device images global array.
Alexey Bataev18fa2322018-05-02 14:20:50 +00003796 std::string ImagesName = getName({"omp_offloading", "device_images"});
John McCall6c9f1fdb2016-11-19 08:17:24 +00003797 llvm::GlobalVariable *DeviceImages =
Alexey Bataev18fa2322018-05-02 14:20:50 +00003798 DeviceImagesEntries.finishAndCreateGlobal(ImagesName,
3799 CGM.getPointerAlign(),
3800 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003801 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003802
3803 // This is a Zero array to be used in the creation of the constant expressions
3804 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3805 llvm::Constant::getNullValue(CGM.Int32Ty)};
3806
3807 // Create the target region descriptor.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003808 llvm::Constant *Data[] = {
3809 llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
3810 llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3811 DeviceImages, Index),
3812 HostEntriesBegin, HostEntriesEnd};
Alexey Bataev18fa2322018-05-02 14:20:50 +00003813 std::string Descriptor = getName({"omp_offloading", "descriptor"});
Mike Ricee1ca7b62018-08-29 15:45:11 +00003814 llvm::GlobalVariable *Desc = createGlobalStruct(
3815 CGM, getTgtBinaryDescriptorQTy(), /*IsConstant=*/true, Data, Descriptor);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003816
3817 // Emit code to register or unregister the descriptor at execution
3818 // startup or closing, respectively.
3819
Alexey Bataev03f270c2018-03-30 18:31:07 +00003820 llvm::Function *UnRegFn;
3821 {
3822 FunctionArgList Args;
3823 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
3824 Args.push_back(&DummyPtr);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003825
Alexey Bataev03f270c2018-03-30 18:31:07 +00003826 CodeGenFunction CGF(CGM);
3827 // Disable debug info for global (de-)initializer because they are not part
3828 // of some particular construct.
3829 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003830 const auto &FI =
3831 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3832 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003833 std::string UnregName = getName({"omp_offloading", "descriptor_unreg"});
3834 UnRegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, UnregName, FI);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003835 CGF.StartFunction(GlobalDecl(), C.VoidTy, UnRegFn, FI, Args);
3836 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3837 Desc);
3838 CGF.FinishFunction();
3839 }
3840 llvm::Function *RegFn;
3841 {
3842 CodeGenFunction CGF(CGM);
3843 // Disable debug info for global (de-)initializer because they are not part
3844 // of some particular construct.
3845 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003846 const auto &FI = CGM.getTypes().arrangeNullaryFunction();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003847 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Sergey Dmitrievbde9cf92018-08-03 20:19:28 +00003848
3849 // Encode offload target triples into the registration function name. It
3850 // will serve as a comdat key for the registration/unregistration code for
3851 // this particular combination of offloading targets.
3852 SmallVector<StringRef, 4U> RegFnNameParts(Devices.size() + 2U);
3853 RegFnNameParts[0] = "omp_offloading";
3854 RegFnNameParts[1] = "descriptor_reg";
3855 llvm::transform(Devices, std::next(RegFnNameParts.begin(), 2),
3856 [](const llvm::Triple &T) -> const std::string& {
3857 return T.getTriple();
3858 });
3859 llvm::sort(std::next(RegFnNameParts.begin(), 2), RegFnNameParts.end());
3860 std::string Descriptor = getName(RegFnNameParts);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003861 RegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, Descriptor, FI);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003862 CGF.StartFunction(GlobalDecl(), C.VoidTy, RegFn, FI, FunctionArgList());
3863 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib), Desc);
3864 // Create a variable to drive the registration and unregistration of the
3865 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3866 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(),
3867 SourceLocation(), nullptr, C.CharTy,
3868 ImplicitParamDecl::Other);
3869 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3870 CGF.FinishFunction();
3871 }
George Rokos29d0f002017-05-27 03:03:13 +00003872 if (CGM.supportsCOMDAT()) {
3873 // It is sufficient to call registration function only once, so create a
3874 // COMDAT group for registration/unregistration functions and associated
3875 // data. That would reduce startup time and code size. Registration
3876 // function serves as a COMDAT group key.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003877 llvm::Comdat *ComdatKey = M.getOrInsertComdat(RegFn->getName());
George Rokos29d0f002017-05-27 03:03:13 +00003878 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3879 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3880 RegFn->setComdat(ComdatKey);
3881 UnRegFn->setComdat(ComdatKey);
3882 DeviceImages->setComdat(ComdatKey);
3883 Desc->setComdat(ComdatKey);
3884 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003885 return RegFn;
3886}
3887
Alexey Bataev03f270c2018-03-30 18:31:07 +00003888void CGOpenMPRuntime::createOffloadEntry(
3889 llvm::Constant *ID, llvm::Constant *Addr, uint64_t Size, int32_t Flags,
3890 llvm::GlobalValue::LinkageTypes Linkage) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003891 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003892 llvm::Module &M = CGM.getModule();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003893 llvm::LLVMContext &C = M.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003894
3895 // Create constant string with the name.
3896 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3897
Alexey Bataev18fa2322018-05-02 14:20:50 +00003898 std::string StringName = getName({"omp_offloading", "entry_name"});
3899 auto *Str = new llvm::GlobalVariable(
3900 M, StrPtrInit->getType(), /*isConstant=*/true,
3901 llvm::GlobalValue::InternalLinkage, StrPtrInit, StringName);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003902 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003903
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003904 llvm::Constant *Data[] = {llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy),
3905 llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy),
3906 llvm::ConstantInt::get(CGM.SizeTy, Size),
3907 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
3908 llvm::ConstantInt::get(CGM.Int32Ty, 0)};
Alexey Bataev18fa2322018-05-02 14:20:50 +00003909 std::string EntryName = getName({"omp_offloading", "entry", ""});
Mike Ricee1ca7b62018-08-29 15:45:11 +00003910 llvm::GlobalVariable *Entry = createGlobalStruct(
3911 CGM, getTgtOffloadEntryQTy(), /*IsConstant=*/true, Data,
3912 Twine(EntryName).concat(Name), llvm::GlobalValue::WeakAnyLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003913
3914 // The entry has to be created in the section the linker expects it to be.
Alexey Bataev18fa2322018-05-02 14:20:50 +00003915 std::string Section = getName({"omp_offloading", "entries"});
3916 Entry->setSection(Section);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003917}
3918
3919void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3920 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003921 // can easily figure out what to emit. The produced metadata looks like
3922 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003923 //
3924 // !omp_offload.info = !{!1, ...}
3925 //
3926 // Right now we only generate metadata for function that contain target
3927 // regions.
3928
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003929 // If we do not have entries, we don't need to do anything.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003930 if (OffloadEntriesInfoManager.empty())
3931 return;
3932
3933 llvm::Module &M = CGM.getModule();
3934 llvm::LLVMContext &C = M.getContext();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003935 SmallVector<const OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
Samuel Antaoee8fb302016-01-06 13:42:12 +00003936 OrderedEntries(OffloadEntriesInfoManager.size());
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00003937 llvm::SmallVector<StringRef, 16> ParentFunctions(
3938 OffloadEntriesInfoManager.size());
Samuel Antaoee8fb302016-01-06 13:42:12 +00003939
Simon Pilgrim2c518802017-03-30 14:13:19 +00003940 // Auxiliary methods to create metadata values and strings.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003941 auto &&GetMDInt = [this](unsigned V) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003942 return llvm::ConstantAsMetadata::get(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003943 llvm::ConstantInt::get(CGM.Int32Ty, V));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003944 };
3945
Alexey Bataev03f270c2018-03-30 18:31:07 +00003946 auto &&GetMDString = [&C](StringRef V) { return llvm::MDString::get(C, V); };
3947
3948 // Create the offloading info metadata node.
3949 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003950
3951 // Create function that emits metadata for each target region entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00003952 auto &&TargetRegionMetadataEmitter =
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00003953 [&C, MD, &OrderedEntries, &ParentFunctions, &GetMDInt, &GetMDString](
Alexey Bataev03f270c2018-03-30 18:31:07 +00003954 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3955 unsigned Line,
3956 const OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3957 // Generate metadata for target regions. Each entry of this metadata
3958 // contains:
3959 // - Entry 0 -> Kind of this type of metadata (0).
3960 // - Entry 1 -> Device ID of the file where the entry was identified.
3961 // - Entry 2 -> File ID of the file where the entry was identified.
3962 // - Entry 3 -> Mangled name of the function where the entry was
3963 // identified.
3964 // - Entry 4 -> Line in the file where the entry was identified.
3965 // - Entry 5 -> Order the entry was created.
3966 // The first element of the metadata node is the kind.
3967 llvm::Metadata *Ops[] = {GetMDInt(E.getKind()), GetMDInt(DeviceID),
3968 GetMDInt(FileID), GetMDString(ParentName),
3969 GetMDInt(Line), GetMDInt(E.getOrder())};
Samuel Antaoee8fb302016-01-06 13:42:12 +00003970
Alexey Bataev03f270c2018-03-30 18:31:07 +00003971 // Save this entry in the right position of the ordered entries array.
3972 OrderedEntries[E.getOrder()] = &E;
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00003973 ParentFunctions[E.getOrder()] = ParentName;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003974
Alexey Bataev03f270c2018-03-30 18:31:07 +00003975 // Add metadata to the named metadata node.
3976 MD->addOperand(llvm::MDNode::get(C, Ops));
3977 };
Samuel Antaoee8fb302016-01-06 13:42:12 +00003978
3979 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3980 TargetRegionMetadataEmitter);
3981
Alexey Bataev03f270c2018-03-30 18:31:07 +00003982 // Create function that emits metadata for each device global variable entry;
3983 auto &&DeviceGlobalVarMetadataEmitter =
3984 [&C, &OrderedEntries, &GetMDInt, &GetMDString,
3985 MD](StringRef MangledName,
3986 const OffloadEntriesInfoManagerTy::OffloadEntryInfoDeviceGlobalVar
3987 &E) {
3988 // Generate metadata for global variables. Each entry of this metadata
3989 // contains:
3990 // - Entry 0 -> Kind of this type of metadata (1).
3991 // - Entry 1 -> Mangled name of the variable.
3992 // - Entry 2 -> Declare target kind.
3993 // - Entry 3 -> Order the entry was created.
3994 // The first element of the metadata node is the kind.
3995 llvm::Metadata *Ops[] = {
3996 GetMDInt(E.getKind()), GetMDString(MangledName),
3997 GetMDInt(E.getFlags()), GetMDInt(E.getOrder())};
3998
3999 // Save this entry in the right position of the ordered entries array.
4000 OrderedEntries[E.getOrder()] = &E;
4001
4002 // Add metadata to the named metadata node.
4003 MD->addOperand(llvm::MDNode::get(C, Ops));
4004 };
4005
4006 OffloadEntriesInfoManager.actOnDeviceGlobalVarEntriesInfo(
4007 DeviceGlobalVarMetadataEmitter);
4008
4009 for (const auto *E : OrderedEntries) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004010 assert(E && "All ordered entries must exist!");
Alexey Bataev03f270c2018-03-30 18:31:07 +00004011 if (const auto *CE =
Samuel Antaoee8fb302016-01-06 13:42:12 +00004012 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
4013 E)) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004014 if (!CE->getID() || !CE->getAddress()) {
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00004015 // Do not blame the entry if the parent funtion is not emitted.
4016 StringRef FnName = ParentFunctions[CE->getOrder()];
4017 if (!CGM.GetGlobalValue(FnName))
4018 continue;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004019 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4020 DiagnosticsEngine::Error,
Alexey Bataev7f01d202018-07-16 18:12:18 +00004021 "Offloading entry for target region is incorrect: either the "
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004022 "address or the ID is invalid.");
4023 CGM.getDiags().Report(DiagID);
4024 continue;
4025 }
Alexey Bataev34f8a702018-03-28 14:28:54 +00004026 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0,
Alexey Bataev03f270c2018-03-30 18:31:07 +00004027 CE->getFlags(), llvm::GlobalValue::WeakAnyLinkage);
4028 } else if (const auto *CE =
4029 dyn_cast<OffloadEntriesInfoManagerTy::
4030 OffloadEntryInfoDeviceGlobalVar>(E)) {
Alexey Bataevc52f01d2018-07-16 20:05:25 +00004031 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags =
4032 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
4033 CE->getFlags());
4034 switch (Flags) {
4035 case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo: {
4036 if (!CE->getAddress()) {
4037 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4038 DiagnosticsEngine::Error,
4039 "Offloading entry for declare target variable is incorrect: the "
4040 "address is invalid.");
4041 CGM.getDiags().Report(DiagID);
4042 continue;
4043 }
Alexey Bataevb4dd6d22018-08-29 20:41:37 +00004044 // The vaiable has no definition - no need to add the entry.
4045 if (CE->getVarSize().isZero())
4046 continue;
Alexey Bataevc52f01d2018-07-16 20:05:25 +00004047 break;
4048 }
4049 case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink:
4050 assert(((CGM.getLangOpts().OpenMPIsDevice && !CE->getAddress()) ||
4051 (!CGM.getLangOpts().OpenMPIsDevice && CE->getAddress())) &&
4052 "Declaret target link address is set.");
4053 if (CGM.getLangOpts().OpenMPIsDevice)
4054 continue;
4055 if (!CE->getAddress()) {
4056 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4057 DiagnosticsEngine::Error,
4058 "Offloading entry for declare target variable is incorrect: the "
4059 "address is invalid.");
4060 CGM.getDiags().Report(DiagID);
4061 continue;
4062 }
4063 break;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004064 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00004065 createOffloadEntry(CE->getAddress(), CE->getAddress(),
Alexey Bataevc52f01d2018-07-16 20:05:25 +00004066 CE->getVarSize().getQuantity(), Flags,
Alexey Bataev03f270c2018-03-30 18:31:07 +00004067 CE->getLinkage());
4068 } else {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004069 llvm_unreachable("Unsupported entry kind.");
Alexey Bataev03f270c2018-03-30 18:31:07 +00004070 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004071 }
4072}
4073
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004074/// Loads all the offload entries information from the host IR
Samuel Antaoee8fb302016-01-06 13:42:12 +00004075/// metadata.
4076void CGOpenMPRuntime::loadOffloadInfoMetadata() {
4077 // If we are in target mode, load the metadata from the host IR. This code has
4078 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
4079
4080 if (!CGM.getLangOpts().OpenMPIsDevice)
4081 return;
4082
4083 if (CGM.getLangOpts().OMPHostIRFile.empty())
4084 return;
4085
4086 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004087 if (auto EC = Buf.getError()) {
4088 CGM.getDiags().Report(diag::err_cannot_open_file)
4089 << CGM.getLangOpts().OMPHostIRFile << EC.message();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004090 return;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004091 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004092
4093 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00004094 auto ME = expectedToErrorOrAndEmitErrors(
4095 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004096
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004097 if (auto EC = ME.getError()) {
4098 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4099 DiagnosticsEngine::Error, "Unable to parse host IR file '%0':'%1'");
4100 CGM.getDiags().Report(DiagID)
4101 << CGM.getLangOpts().OMPHostIRFile << EC.message();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004102 return;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004103 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004104
4105 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
4106 if (!MD)
4107 return;
4108
George Burgess IV00f70bd2018-03-01 05:43:23 +00004109 for (llvm::MDNode *MN : MD->operands()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004110 auto &&GetMDInt = [MN](unsigned Idx) {
4111 auto *V = cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004112 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
4113 };
4114
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004115 auto &&GetMDString = [MN](unsigned Idx) {
4116 auto *V = cast<llvm::MDString>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004117 return V->getString();
4118 };
4119
Alexey Bataev03f270c2018-03-30 18:31:07 +00004120 switch (GetMDInt(0)) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004121 default:
4122 llvm_unreachable("Unexpected metadata!");
4123 break;
4124 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
Alexey Bataev34f8a702018-03-28 14:28:54 +00004125 OffloadingEntryInfoTargetRegion:
Samuel Antaoee8fb302016-01-06 13:42:12 +00004126 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
Alexey Bataev03f270c2018-03-30 18:31:07 +00004127 /*DeviceID=*/GetMDInt(1), /*FileID=*/GetMDInt(2),
4128 /*ParentName=*/GetMDString(3), /*Line=*/GetMDInt(4),
4129 /*Order=*/GetMDInt(5));
4130 break;
4131 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
4132 OffloadingEntryInfoDeviceGlobalVar:
4133 OffloadEntriesInfoManager.initializeDeviceGlobalVarEntryInfo(
4134 /*MangledName=*/GetMDString(1),
4135 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
4136 /*Flags=*/GetMDInt(2)),
4137 /*Order=*/GetMDInt(3));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004138 break;
4139 }
4140 }
4141}
4142
Alexey Bataev62b63b12015-03-10 07:28:44 +00004143void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
4144 if (!KmpRoutineEntryPtrTy) {
4145 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004146 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004147 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
4148 FunctionProtoType::ExtProtoInfo EPI;
4149 KmpRoutineEntryPtrQTy = C.getPointerType(
4150 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
4151 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
4152 }
4153}
4154
Samuel Antaoee8fb302016-01-06 13:42:12 +00004155QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004156 // Make sure the type of the entry is already created. This is the type we
4157 // have to create:
4158 // struct __tgt_offload_entry{
4159 // void *addr; // Pointer to the offload entry info.
4160 // // (function or global)
4161 // char *name; // Name of the function or global.
4162 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00004163 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
4164 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004165 // };
4166 if (TgtOffloadEntryQTy.isNull()) {
4167 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004168 RecordDecl *RD = C.buildImplicitRecord("__tgt_offload_entry");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004169 RD->startDefinition();
4170 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4171 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
4172 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00004173 addFieldToRecordDecl(
4174 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4175 addFieldToRecordDecl(
4176 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004177 RD->completeDefinition();
Jonas Hahnfeld5e4df282018-01-18 15:38:03 +00004178 RD->addAttr(PackedAttr::CreateImplicit(C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004179 TgtOffloadEntryQTy = C.getRecordType(RD);
4180 }
4181 return TgtOffloadEntryQTy;
4182}
4183
4184QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
4185 // These are the types we need to build:
4186 // struct __tgt_device_image{
4187 // void *ImageStart; // Pointer to the target code start.
4188 // void *ImageEnd; // Pointer to the target code end.
4189 // // We also add the host entries to the device image, as it may be useful
4190 // // for the target runtime to have access to that information.
4191 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
4192 // // the entries.
4193 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4194 // // entries (non inclusive).
4195 // };
4196 if (TgtDeviceImageQTy.isNull()) {
4197 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004198 RecordDecl *RD = C.buildImplicitRecord("__tgt_device_image");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004199 RD->startDefinition();
4200 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4201 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4202 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4203 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4204 RD->completeDefinition();
4205 TgtDeviceImageQTy = C.getRecordType(RD);
4206 }
4207 return TgtDeviceImageQTy;
4208}
4209
4210QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
4211 // struct __tgt_bin_desc{
4212 // int32_t NumDevices; // Number of devices supported.
4213 // __tgt_device_image *DeviceImages; // Arrays of device images
4214 // // (one per device).
4215 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
4216 // // entries.
4217 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4218 // // entries (non inclusive).
4219 // };
4220 if (TgtBinaryDescriptorQTy.isNull()) {
4221 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004222 RecordDecl *RD = C.buildImplicitRecord("__tgt_bin_desc");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004223 RD->startDefinition();
4224 addFieldToRecordDecl(
4225 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4226 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
4227 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4228 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4229 RD->completeDefinition();
4230 TgtBinaryDescriptorQTy = C.getRecordType(RD);
4231 }
4232 return TgtBinaryDescriptorQTy;
4233}
4234
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004235namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00004236struct PrivateHelpersTy {
4237 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
4238 const VarDecl *PrivateElemInit)
4239 : Original(Original), PrivateCopy(PrivateCopy),
4240 PrivateElemInit(PrivateElemInit) {}
4241 const VarDecl *Original;
4242 const VarDecl *PrivateCopy;
4243 const VarDecl *PrivateElemInit;
4244};
4245typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00004246} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004247
Alexey Bataev9e034042015-05-05 04:05:12 +00004248static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00004249createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004250 if (!Privates.empty()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004251 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004252 // Build struct .kmp_privates_t. {
4253 // /* private vars */
4254 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004255 RecordDecl *RD = C.buildImplicitRecord(".kmp_privates.t");
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004256 RD->startDefinition();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004257 for (const auto &Pair : Privates) {
4258 const VarDecl *VD = Pair.second.Original;
4259 QualType Type = VD->getType().getNonReferenceType();
4260 FieldDecl *FD = addFieldToRecordDecl(C, RD, Type);
Alexey Bataevc71a4092015-09-11 10:29:41 +00004261 if (VD->hasAttrs()) {
4262 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
4263 E(VD->getAttrs().end());
4264 I != E; ++I)
4265 FD->addAttr(*I);
4266 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004267 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004268 RD->completeDefinition();
4269 return RD;
4270 }
4271 return nullptr;
4272}
4273
Alexey Bataev9e034042015-05-05 04:05:12 +00004274static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00004275createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
4276 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004277 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004278 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004279 // Build struct kmp_task_t {
4280 // void * shareds;
4281 // kmp_routine_entry_t routine;
4282 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00004283 // kmp_cmplrdata_t data1;
4284 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00004285 // For taskloops additional fields:
4286 // kmp_uint64 lb;
4287 // kmp_uint64 ub;
4288 // kmp_int64 st;
4289 // kmp_int32 liter;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004290 // void * reductions;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004291 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004292 RecordDecl *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004293 UD->startDefinition();
4294 addFieldToRecordDecl(C, UD, KmpInt32Ty);
4295 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
4296 UD->completeDefinition();
4297 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004298 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t");
Alexey Bataev62b63b12015-03-10 07:28:44 +00004299 RD->startDefinition();
4300 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4301 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
4302 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004303 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
4304 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004305 if (isOpenMPTaskLoopDirective(Kind)) {
4306 QualType KmpUInt64Ty =
4307 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4308 QualType KmpInt64Ty =
4309 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4310 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4311 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4312 addFieldToRecordDecl(C, RD, KmpInt64Ty);
4313 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004314 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004315 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004316 RD->completeDefinition();
4317 return RD;
4318}
4319
4320static RecordDecl *
4321createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004322 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004323 ASTContext &C = CGM.getContext();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004324 // Build struct kmp_task_t_with_privates {
4325 // kmp_task_t task_data;
4326 // .kmp_privates_t. privates;
4327 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004328 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004329 RD->startDefinition();
4330 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004331 if (const RecordDecl *PrivateRD = createPrivatesRecordDecl(CGM, Privates))
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004332 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004333 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004334 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004335}
4336
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004337/// Emit a proxy function which accepts kmp_task_t as the second
Alexey Bataev62b63b12015-03-10 07:28:44 +00004338/// argument.
4339/// \code
4340/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004341/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00004342/// For taskloops:
4343/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004344/// tt->reductions, tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004345/// return 0;
4346/// }
4347/// \endcode
4348static llvm::Value *
4349emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00004350 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
4351 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004352 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004353 QualType SharedsPtrTy, llvm::Value *TaskFunction,
4354 llvm::Value *TaskPrivatesMap) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004355 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004356 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004357 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4358 ImplicitParamDecl::Other);
4359 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4360 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4361 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004362 Args.push_back(&GtidArg);
4363 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004364 const auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004365 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004366 llvm::FunctionType *TaskEntryTy =
4367 CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004368 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_entry", ""});
4369 auto *TaskEntry = llvm::Function::Create(
4370 TaskEntryTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004371 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskEntry, TaskEntryFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004372 TaskEntry->setDoesNotRecurse();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004373 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004374 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args,
4375 Loc, Loc);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004376
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004377 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00004378 // tt,
4379 // For taskloops:
4380 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
4381 // tt->task_data.shareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004382 llvm::Value *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00004383 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00004384 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4385 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4386 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004387 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004388 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004389 LValue Base =
4390 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004391 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004392 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004393 LValue PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
4394 llvm::Value *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004395
4396 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004397 LValue SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
4398 llvm::Value *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev1e491372018-01-23 18:44:14 +00004399 CGF.EmitLoadOfScalar(SharedsLVal, Loc),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004400 CGF.ConvertTypeForMem(SharedsPtrTy));
4401
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004402 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4403 llvm::Value *PrivatesParam;
4404 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004405 LValue PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004406 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004407 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004408 } else {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004409 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004410 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004411
Alexey Bataev7292c292016-04-25 12:22:29 +00004412 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
4413 TaskPrivatesMap,
4414 CGF.Builder
4415 .CreatePointerBitCastOrAddrSpaceCast(
4416 TDBase.getAddress(), CGF.VoidPtrTy)
4417 .getPointer()};
4418 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
4419 std::end(CommonArgs));
4420 if (isOpenMPTaskLoopDirective(Kind)) {
4421 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004422 LValue LBLVal = CGF.EmitLValueForField(Base, *LBFI);
4423 llvm::Value *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004424 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004425 LValue UBLVal = CGF.EmitLValueForField(Base, *UBFI);
4426 llvm::Value *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004427 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004428 LValue StLVal = CGF.EmitLValueForField(Base, *StFI);
4429 llvm::Value *StParam = CGF.EmitLoadOfScalar(StLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004430 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004431 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4432 llvm::Value *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004433 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004434 LValue RLVal = CGF.EmitLValueForField(Base, *RFI);
4435 llvm::Value *RParam = CGF.EmitLoadOfScalar(RLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004436 CallArgs.push_back(LBParam);
4437 CallArgs.push_back(UBParam);
4438 CallArgs.push_back(StParam);
4439 CallArgs.push_back(LIParam);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004440 CallArgs.push_back(RParam);
Alexey Bataev7292c292016-04-25 12:22:29 +00004441 }
4442 CallArgs.push_back(SharedsParam);
4443
Alexey Bataev3c595a62017-08-14 15:01:03 +00004444 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
4445 CallArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004446 CGF.EmitStoreThroughLValue(RValue::get(CGF.Builder.getInt32(/*C=*/0)),
4447 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004448 CGF.FinishFunction();
4449 return TaskEntry;
4450}
4451
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004452static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
4453 SourceLocation Loc,
4454 QualType KmpInt32Ty,
4455 QualType KmpTaskTWithPrivatesPtrQTy,
4456 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004457 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004458 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004459 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4460 ImplicitParamDecl::Other);
4461 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4462 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4463 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004464 Args.push_back(&GtidArg);
4465 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004466 const auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004467 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004468 llvm::FunctionType *DestructorFnTy =
4469 CGM.getTypes().GetFunctionType(DestructorFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004470 std::string Name =
4471 CGM.getOpenMPRuntime().getName({"omp_task_destructor", ""});
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004472 auto *DestructorFn =
4473 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00004474 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004475 CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004476 DestructorFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004477 DestructorFn->setDoesNotRecurse();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004478 CodeGenFunction CGF(CGM);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004479 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004480 Args, Loc, Loc);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004481
Alexey Bataev31300ed2016-02-04 11:27:03 +00004482 LValue Base = CGF.EmitLoadOfPointerLValue(
4483 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4484 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004485 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004486 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
4487 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004488 Base = CGF.EmitLValueForField(Base, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004489 for (const auto *Field :
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004490 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004491 if (QualType::DestructionKind DtorKind =
4492 Field->getType().isDestructedType()) {
4493 LValue FieldLValue = CGF.EmitLValueForField(Base, Field);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004494 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
4495 }
4496 }
4497 CGF.FinishFunction();
4498 return DestructorFn;
4499}
4500
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004501/// Emit a privates mapping function for correct handling of private and
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004502/// firstprivate variables.
4503/// \code
4504/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
4505/// **noalias priv1,..., <tyn> **noalias privn) {
4506/// *priv1 = &.privates.priv1;
4507/// ...;
4508/// *privn = &.privates.privn;
4509/// }
4510/// \endcode
4511static llvm::Value *
4512emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00004513 ArrayRef<const Expr *> PrivateVars,
4514 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004515 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004516 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004517 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004518 ASTContext &C = CGM.getContext();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004519 FunctionArgList Args;
4520 ImplicitParamDecl TaskPrivatesArg(
4521 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00004522 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
4523 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004524 Args.push_back(&TaskPrivatesArg);
4525 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
4526 unsigned Counter = 1;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004527 for (const Expr *E : PrivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004528 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004529 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4530 C.getPointerType(C.getPointerType(E->getType()))
4531 .withConst()
4532 .withRestrict(),
4533 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004534 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004535 PrivateVarsPos[VD] = Counter;
4536 ++Counter;
4537 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004538 for (const Expr *E : FirstprivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004539 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004540 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4541 C.getPointerType(C.getPointerType(E->getType()))
4542 .withConst()
4543 .withRestrict(),
4544 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004545 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004546 PrivateVarsPos[VD] = Counter;
4547 ++Counter;
4548 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004549 for (const Expr *E : LastprivateVars) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004550 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004551 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4552 C.getPointerType(C.getPointerType(E->getType()))
4553 .withConst()
4554 .withRestrict(),
4555 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004556 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004557 PrivateVarsPos[VD] = Counter;
4558 ++Counter;
4559 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004560 const auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004561 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004562 llvm::FunctionType *TaskPrivatesMapTy =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004563 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004564 std::string Name =
4565 CGM.getOpenMPRuntime().getName({"omp_task_privates_map", ""});
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004566 auto *TaskPrivatesMap = llvm::Function::Create(
Alexey Bataev18fa2322018-05-02 14:20:50 +00004567 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage, Name,
4568 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004569 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004570 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00004571 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00004572 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00004573 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004574 CodeGenFunction CGF(CGM);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004575 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004576 TaskPrivatesMapFnInfo, Args, Loc, Loc);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004577
4578 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00004579 LValue Base = CGF.EmitLoadOfPointerLValue(
4580 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4581 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004582 const auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004583 Counter = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004584 for (const FieldDecl *Field : PrivatesQTyRD->fields()) {
4585 LValue FieldLVal = CGF.EmitLValueForField(Base, Field);
4586 const VarDecl *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
4587 LValue RefLVal =
4588 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
4589 LValue RefLoadLVal = CGF.EmitLoadOfPointerLValue(
Alexey Bataev31300ed2016-02-04 11:27:03 +00004590 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00004591 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004592 ++Counter;
4593 }
4594 CGF.FinishFunction();
4595 return TaskPrivatesMap;
4596}
4597
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004598static bool stable_sort_comparator(const PrivateDataTy P1,
4599 const PrivateDataTy P2) {
4600 return P1.first > P2.first;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004601}
4602
Alexey Bataevf93095a2016-05-05 08:46:22 +00004603/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00004604static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004605 const OMPExecutableDirective &D,
4606 Address KmpTaskSharedsPtr, LValue TDBase,
4607 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4608 QualType SharedsTy, QualType SharedsPtrTy,
4609 const OMPTaskDataTy &Data,
4610 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004611 ASTContext &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004612 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4613 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004614 OpenMPDirectiveKind Kind = isOpenMPTaskLoopDirective(D.getDirectiveKind())
4615 ? OMPD_taskloop
4616 : OMPD_task;
4617 const CapturedStmt &CS = *D.getCapturedStmt(Kind);
4618 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004619 LValue SrcBase;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004620 bool IsTargetTask =
4621 isOpenMPTargetDataManagementDirective(D.getDirectiveKind()) ||
4622 isOpenMPTargetExecutionDirective(D.getDirectiveKind());
4623 // For target-based directives skip 3 firstprivate arrays BasePointersArray,
4624 // PointersArray and SizesArray. The original variables for these arrays are
4625 // not captured and we get their addresses explicitly.
4626 if ((!IsTargetTask && !Data.FirstprivateVars.empty()) ||
Alexey Bataev8451efa2018-01-15 19:06:12 +00004627 (IsTargetTask && KmpTaskSharedsPtr.isValid())) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004628 SrcBase = CGF.MakeAddrLValue(
4629 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4630 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4631 SharedsTy);
4632 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004633 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004634 for (const PrivateDataTy &Pair : Privates) {
4635 const VarDecl *VD = Pair.second.PrivateCopy;
4636 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004637 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4638 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004639 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004640 if (const VarDecl *Elem = Pair.second.PrivateElemInit) {
4641 const VarDecl *OriginalVD = Pair.second.Original;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004642 // Check if the variable is the target-based BasePointersArray,
4643 // PointersArray or SizesArray.
4644 LValue SharedRefLValue;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004645 QualType Type = OriginalVD->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004646 const FieldDecl *SharedField = CapturesInfo.lookup(OriginalVD);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004647 if (IsTargetTask && !SharedField) {
4648 assert(isa<ImplicitParamDecl>(OriginalVD) &&
4649 isa<CapturedDecl>(OriginalVD->getDeclContext()) &&
4650 cast<CapturedDecl>(OriginalVD->getDeclContext())
4651 ->getNumParams() == 0 &&
4652 isa<TranslationUnitDecl>(
4653 cast<CapturedDecl>(OriginalVD->getDeclContext())
4654 ->getDeclContext()) &&
4655 "Expected artificial target data variable.");
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004656 SharedRefLValue =
4657 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type);
4658 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004659 SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4660 SharedRefLValue = CGF.MakeAddrLValue(
4661 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
4662 SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl),
4663 SharedRefLValue.getTBAAInfo());
4664 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004665 if (Type->isArrayType()) {
4666 // Initialize firstprivate array.
4667 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4668 // Perform simple memcpy.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004669 CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004670 } else {
4671 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00004672 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00004673 CGF.EmitOMPAggregateAssign(
4674 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4675 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4676 Address SrcElement) {
4677 // Clean up any temporaries needed by the initialization.
4678 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4679 InitScope.addPrivate(
4680 Elem, [SrcElement]() -> Address { return SrcElement; });
4681 (void)InitScope.Privatize();
4682 // Emit initialization for single element.
4683 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4684 CGF, &CapturesInfo);
4685 CGF.EmitAnyExprToMem(Init, DestElement,
4686 Init->getType().getQualifiers(),
4687 /*IsInitializer=*/false);
4688 });
4689 }
4690 } else {
4691 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4692 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4693 return SharedRefLValue.getAddress();
4694 });
4695 (void)InitScope.Privatize();
4696 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4697 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4698 /*capturedByInit=*/false);
4699 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004700 } else {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004701 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004702 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004703 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004704 ++FI;
4705 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004706}
4707
4708/// Check if duplication function is required for taskloops.
4709static bool checkInitIsRequired(CodeGenFunction &CGF,
4710 ArrayRef<PrivateDataTy> Privates) {
4711 bool InitRequired = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004712 for (const PrivateDataTy &Pair : Privates) {
4713 const VarDecl *VD = Pair.second.PrivateCopy;
4714 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004715 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4716 !CGF.isTrivialInitializer(Init));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004717 if (InitRequired)
4718 break;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004719 }
4720 return InitRequired;
4721}
4722
4723
4724/// Emit task_dup function (for initialization of
4725/// private/firstprivate/lastprivate vars and last_iter flag)
4726/// \code
4727/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4728/// lastpriv) {
4729/// // setup lastprivate flag
4730/// task_dst->last = lastpriv;
4731/// // could be constructor calls here...
4732/// }
4733/// \endcode
4734static llvm::Value *
4735emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4736 const OMPExecutableDirective &D,
4737 QualType KmpTaskTWithPrivatesPtrQTy,
4738 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4739 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4740 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4741 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004742 ASTContext &C = CGM.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004743 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004744 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4745 KmpTaskTWithPrivatesPtrQTy,
4746 ImplicitParamDecl::Other);
4747 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4748 KmpTaskTWithPrivatesPtrQTy,
4749 ImplicitParamDecl::Other);
4750 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4751 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004752 Args.push_back(&DstArg);
4753 Args.push_back(&SrcArg);
4754 Args.push_back(&LastprivArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004755 const auto &TaskDupFnInfo =
Alexey Bataevf93095a2016-05-05 08:46:22 +00004756 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004757 llvm::FunctionType *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004758 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_dup", ""});
4759 auto *TaskDup = llvm::Function::Create(
4760 TaskDupTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004761 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskDup, TaskDupFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004762 TaskDup->setDoesNotRecurse();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004763 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004764 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args, Loc,
4765 Loc);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004766
4767 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4768 CGF.GetAddrOfLocalVar(&DstArg),
4769 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4770 // task_dst->liter = lastpriv;
4771 if (WithLastIter) {
4772 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4773 LValue Base = CGF.EmitLValueForField(
4774 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4775 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4776 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4777 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4778 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4779 }
4780
4781 // Emit initial values for private copies (if any).
4782 assert(!Privates.empty());
4783 Address KmpTaskSharedsPtr = Address::invalid();
4784 if (!Data.FirstprivateVars.empty()) {
4785 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4786 CGF.GetAddrOfLocalVar(&SrcArg),
4787 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4788 LValue Base = CGF.EmitLValueForField(
4789 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4790 KmpTaskSharedsPtr = Address(
4791 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4792 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4793 KmpTaskTShareds)),
4794 Loc),
4795 CGF.getNaturalTypeAlignment(SharedsTy));
4796 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004797 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4798 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004799 CGF.FinishFunction();
4800 return TaskDup;
4801}
4802
Alexey Bataev8a831592016-05-10 10:36:51 +00004803/// Checks if destructor function is required to be generated.
4804/// \return true if cleanups are required, false otherwise.
4805static bool
4806checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4807 bool NeedsCleanup = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004808 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4809 const auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4810 for (const FieldDecl *FD : PrivateRD->fields()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004811 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4812 if (NeedsCleanup)
4813 break;
4814 }
4815 return NeedsCleanup;
4816}
4817
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004818CGOpenMPRuntime::TaskResultTy
4819CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4820 const OMPExecutableDirective &D,
4821 llvm::Value *TaskFunction, QualType SharedsTy,
4822 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004823 ASTContext &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004824 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004825 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004826 auto I = Data.PrivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004827 for (const Expr *E : Data.PrivateVars) {
4828 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004829 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004830 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004831 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004832 /*PrivateElemInit=*/nullptr));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004833 ++I;
4834 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004835 I = Data.FirstprivateCopies.begin();
4836 auto IElemInitRef = Data.FirstprivateInits.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004837 for (const Expr *E : Data.FirstprivateVars) {
4838 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004839 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004840 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004841 PrivateHelpersTy(
4842 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004843 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl())));
Richard Trieucc3949d2016-02-18 22:34:54 +00004844 ++I;
4845 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004846 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004847 I = Data.LastprivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004848 for (const Expr *E : Data.LastprivateVars) {
4849 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004850 Privates.emplace_back(
Alexey Bataevf93095a2016-05-05 08:46:22 +00004851 C.getDeclAlign(VD),
4852 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004853 /*PrivateElemInit=*/nullptr));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004854 ++I;
4855 }
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004856 std::stable_sort(Privates.begin(), Privates.end(), stable_sort_comparator);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004857 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004858 // Build type kmp_routine_entry_t (if not built yet).
4859 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004860 // Build type kmp_task_t (if not built yet).
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004861 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
4862 if (SavedKmpTaskloopTQTy.isNull()) {
4863 SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4864 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4865 }
4866 KmpTaskTQTy = SavedKmpTaskloopTQTy;
Alexey Bataev3a03a7f2017-10-11 15:56:38 +00004867 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004868 assert((D.getDirectiveKind() == OMPD_task ||
4869 isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||
4870 isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) &&
4871 "Expected taskloop, task or target directive");
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004872 if (SavedKmpTaskTQTy.isNull()) {
4873 SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4874 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4875 }
4876 KmpTaskTQTy = SavedKmpTaskTQTy;
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004877 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004878 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004879 // Build particular struct kmp_task_t for the given task.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004880 const RecordDecl *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004881 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004882 QualType KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004883 QualType KmpTaskTWithPrivatesPtrQTy =
4884 C.getPointerType(KmpTaskTWithPrivatesQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004885 llvm::Type *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4886 llvm::Type *KmpTaskTWithPrivatesPtrTy =
4887 KmpTaskTWithPrivatesTy->getPointerTo();
4888 llvm::Value *KmpTaskTWithPrivatesTySize =
4889 CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004890 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4891
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004892 // Emit initial values for private copies (if any).
4893 llvm::Value *TaskPrivatesMap = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004894 llvm::Type *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00004895 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004896 if (!Privates.empty()) {
4897 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004898 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4899 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4900 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004901 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4902 TaskPrivatesMap, TaskPrivatesMapTy);
4903 } else {
4904 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4905 cast<llvm::PointerType>(TaskPrivatesMapTy));
4906 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004907 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4908 // kmp_task_t *tt);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004909 llvm::Value *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004910 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4911 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4912 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004913
4914 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4915 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4916 // kmp_routine_entry_t *task_entry);
4917 // Task flags. Format is taken from
4918 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4919 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004920 enum {
4921 TiedFlag = 0x1,
4922 FinalFlag = 0x2,
4923 DestructorsFlag = 0x8,
4924 PriorityFlag = 0x20
4925 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004926 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004927 bool NeedsCleanup = false;
4928 if (!Privates.empty()) {
4929 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4930 if (NeedsCleanup)
4931 Flags = Flags | DestructorsFlag;
4932 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004933 if (Data.Priority.getInt())
4934 Flags = Flags | PriorityFlag;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004935 llvm::Value *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004936 Data.Final.getPointer()
4937 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00004938 CGF.Builder.getInt32(FinalFlag),
4939 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004940 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004941 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004942 llvm::Value *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004943 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4944 getThreadID(CGF, Loc), TaskFlags,
4945 KmpTaskTWithPrivatesTySize, SharedsSize,
4946 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4947 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004948 llvm::Value *NewTask = CGF.EmitRuntimeCall(
Alexey Bataev62b63b12015-03-10 07:28:44 +00004949 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004950 llvm::Value *NewTaskNewTaskTTy =
4951 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4952 NewTask, KmpTaskTWithPrivatesPtrTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004953 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4954 KmpTaskTWithPrivatesQTy);
4955 LValue TDBase =
4956 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004957 // Fill the data in the resulting kmp_task_t record.
4958 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00004959 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004960 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00004961 KmpTaskSharedsPtr =
4962 Address(CGF.EmitLoadOfScalar(
4963 CGF.EmitLValueForField(
4964 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4965 KmpTaskTShareds)),
4966 Loc),
4967 CGF.getNaturalTypeAlignment(SharedsTy));
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004968 LValue Dest = CGF.MakeAddrLValue(KmpTaskSharedsPtr, SharedsTy);
4969 LValue Src = CGF.MakeAddrLValue(Shareds, SharedsTy);
Richard Smithe78fac52018-04-05 20:52:58 +00004970 CGF.EmitAggregateCopy(Dest, Src, SharedsTy, AggValueSlot::DoesNotOverlap);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004971 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004972 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00004973 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004974 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004975 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4976 SharedsTy, SharedsPtrTy, Data, Privates,
4977 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004978 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4979 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4980 Result.TaskDupFn = emitTaskDupFunction(
4981 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4982 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4983 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004984 }
4985 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00004986 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4987 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00004988 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00004989 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004990 const RecordDecl *KmpCmplrdataUD =
4991 (*FI)->getType()->getAsUnionType()->getDecl();
Alexey Bataevad537bb2016-05-30 09:06:50 +00004992 if (NeedsCleanup) {
4993 llvm::Value *DestructorFn = emitDestructorsFunction(
4994 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4995 KmpTaskTWithPrivatesQTy);
4996 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4997 LValue DestructorsLV = CGF.EmitLValueForField(
4998 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4999 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5000 DestructorFn, KmpRoutineEntryPtrTy),
5001 DestructorsLV);
5002 }
5003 // Set priority.
5004 if (Data.Priority.getInt()) {
5005 LValue Data2LV = CGF.EmitLValueForField(
5006 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
5007 LValue PriorityLV = CGF.EmitLValueForField(
5008 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
5009 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
5010 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005011 Result.NewTask = NewTask;
5012 Result.TaskEntry = TaskEntry;
5013 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
5014 Result.TDBase = TDBase;
5015 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
5016 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00005017}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005018
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005019void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
5020 const OMPExecutableDirective &D,
5021 llvm::Value *TaskFunction,
5022 QualType SharedsTy, Address Shareds,
5023 const Expr *IfCond,
5024 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005025 if (!CGF.HaveInsertPoint())
5026 return;
5027
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005028 TaskResultTy Result =
5029 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
5030 llvm::Value *NewTask = Result.NewTask;
5031 llvm::Value *TaskEntry = Result.TaskEntry;
5032 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
5033 LValue TDBase = Result.TDBase;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005034 const RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
5035 ASTContext &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005036 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00005037 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005038 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00005039 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005040 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00005041 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005042 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
5043 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005044 QualType FlagsTy =
5045 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005046 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
5047 if (KmpDependInfoTy.isNull()) {
5048 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
5049 KmpDependInfoRD->startDefinition();
5050 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
5051 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
5052 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
5053 KmpDependInfoRD->completeDefinition();
5054 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005055 } else {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005056 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005057 }
John McCall7f416cc2015-09-08 08:05:57 +00005058 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005059 // Define type kmp_depend_info[<Dependences.size()>];
5060 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00005061 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005062 ArrayType::Normal, /*IndexTypeQuals=*/0);
5063 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00005064 DependenciesArray =
5065 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005066 for (unsigned I = 0; I < NumDependencies; ++I) {
5067 const Expr *E = Data.Dependences[I].second;
5068 LValue Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005069 llvm::Value *Size;
5070 QualType Ty = E->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005071 if (const auto *ASE =
5072 dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005073 LValue UpAddrLVal =
5074 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
5075 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00005076 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005077 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00005078 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005079 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
5080 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005081 } else {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005082 Size = CGF.getTypeSize(Ty);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005083 }
5084 LValue Base = CGF.MakeAddrLValue(
5085 CGF.Builder.CreateConstArrayGEP(DependenciesArray, I, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005086 KmpDependInfoTy);
5087 // deps[i].base_addr = &<Dependences[i].second>;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005088 LValue BaseAddrLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005089 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00005090 CGF.EmitStoreOfScalar(
5091 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
5092 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005093 // deps[i].len = sizeof(<Dependences[i].second>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005094 LValue LenLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005095 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
5096 CGF.EmitStoreOfScalar(Size, LenLVal);
5097 // deps[i].flags = <Dependences[i].first>;
5098 RTLDependenceKindTy DepKind;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005099 switch (Data.Dependences[I].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005100 case OMPC_DEPEND_in:
5101 DepKind = DepIn;
5102 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00005103 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005104 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005105 case OMPC_DEPEND_inout:
5106 DepKind = DepInOut;
5107 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00005108 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005109 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005110 case OMPC_DEPEND_unknown:
5111 llvm_unreachable("Unknown task dependence type");
5112 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005113 LValue FlagsLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005114 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
5115 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
5116 FlagsLVal);
5117 }
John McCall7f416cc2015-09-08 08:05:57 +00005118 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5119 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005120 CGF.VoidPtrTy);
5121 }
5122
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005123 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev62b63b12015-03-10 07:28:44 +00005124 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005125 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
5126 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
5127 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
5128 // list is not empty
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005129 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5130 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00005131 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
5132 llvm::Value *DepTaskArgs[7];
5133 if (NumDependencies) {
5134 DepTaskArgs[0] = UpLoc;
5135 DepTaskArgs[1] = ThreadID;
5136 DepTaskArgs[2] = NewTask;
5137 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
5138 DepTaskArgs[4] = DependenciesArray.getPointer();
5139 DepTaskArgs[5] = CGF.Builder.getInt32(0);
5140 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5141 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005142 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
5143 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005144 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005145 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005146 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005147 LValue PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005148 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
5149 }
John McCall7f416cc2015-09-08 08:05:57 +00005150 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005151 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00005152 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00005153 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005154 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00005155 TaskArgs);
5156 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00005157 // Check if parent region is untied and build return for untied task;
5158 if (auto *Region =
5159 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5160 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00005161 };
John McCall7f416cc2015-09-08 08:05:57 +00005162
5163 llvm::Value *DepWaitTaskArgs[6];
5164 if (NumDependencies) {
5165 DepWaitTaskArgs[0] = UpLoc;
5166 DepWaitTaskArgs[1] = ThreadID;
5167 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
5168 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
5169 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
5170 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5171 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005172 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00005173 NumDependencies, &DepWaitTaskArgs,
5174 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005175 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005176 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
5177 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
5178 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
5179 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
5180 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00005181 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005182 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005183 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005184 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00005185 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
5186 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005187 Action.Enter(CGF);
5188 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00005189 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00005190 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005191 };
5192
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005193 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
5194 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005195 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
5196 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005197 RegionCodeGenTy RCG(CodeGen);
5198 CommonActionTy Action(
5199 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
5200 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
5201 RCG.setAction(Action);
5202 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005203 };
John McCall7f416cc2015-09-08 08:05:57 +00005204
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005205 if (IfCond) {
Alexey Bataev1d677132015-04-22 13:57:31 +00005206 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005207 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005208 RegionCodeGenTy ThenRCG(ThenCodeGen);
5209 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00005210 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00005211}
5212
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005213void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
5214 const OMPLoopDirective &D,
5215 llvm::Value *TaskFunction,
5216 QualType SharedsTy, Address Shareds,
5217 const Expr *IfCond,
5218 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005219 if (!CGF.HaveInsertPoint())
5220 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005221 TaskResultTy Result =
5222 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005223 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev7292c292016-04-25 12:22:29 +00005224 // libcall.
5225 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
5226 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
5227 // sched, kmp_uint64 grainsize, void *task_dup);
5228 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5229 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
5230 llvm::Value *IfVal;
5231 if (IfCond) {
5232 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
5233 /*isSigned=*/true);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005234 } else {
Alexey Bataev7292c292016-04-25 12:22:29 +00005235 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005236 }
Alexey Bataev7292c292016-04-25 12:22:29 +00005237
5238 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005239 Result.TDBase,
5240 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005241 const auto *LBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005242 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
5243 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
5244 /*IsInitializer=*/true);
5245 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005246 Result.TDBase,
5247 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005248 const auto *UBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005249 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
5250 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
5251 /*IsInitializer=*/true);
5252 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005253 Result.TDBase,
5254 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005255 const auto *StVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005256 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
5257 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
5258 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005259 // Store reductions address.
5260 LValue RedLVal = CGF.EmitLValueForField(
5261 Result.TDBase,
5262 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005263 if (Data.Reductions) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005264 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005265 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005266 CGF.EmitNullInitialization(RedLVal.getAddress(),
5267 CGF.getContext().VoidPtrTy);
5268 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005269 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00005270 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00005271 UpLoc,
5272 ThreadID,
5273 Result.NewTask,
5274 IfVal,
5275 LBLVal.getPointer(),
5276 UBLVal.getPointer(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005277 CGF.EmitLoadOfScalar(StLVal, Loc),
Alexey Bataevac6e4de2018-10-24 19:06:37 +00005278 llvm::ConstantInt::getSigned(
5279 CGF.IntTy, 1), // Always 1 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005280 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005281 CGF.IntTy, Data.Schedule.getPointer()
5282 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005283 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005284 Data.Schedule.getPointer()
5285 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005286 /*isSigned=*/false)
5287 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00005288 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5289 Result.TaskDupFn, CGF.VoidPtrTy)
5290 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00005291 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
5292}
5293
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005294/// Emit reduction operation for each element of array (required for
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005295/// array sections) LHS op = RHS.
5296/// \param Type Type of array.
5297/// \param LHSVar Variable on the left side of the reduction operation
5298/// (references element of array in original variable).
5299/// \param RHSVar Variable on the right side of the reduction operation
5300/// (references element of array in original variable).
5301/// \param RedOpGen Generator of reduction operation with use of LHSVar and
5302/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00005303static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005304 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
5305 const VarDecl *RHSVar,
5306 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
5307 const Expr *, const Expr *)> &RedOpGen,
5308 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
5309 const Expr *UpExpr = nullptr) {
5310 // Perform element-by-element initialization.
5311 QualType ElementTy;
5312 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
5313 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
5314
5315 // Drill down to the base element type on both arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005316 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
5317 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005318
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005319 llvm::Value *RHSBegin = RHSAddr.getPointer();
5320 llvm::Value *LHSBegin = LHSAddr.getPointer();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005321 // Cast from pointer to array type to pointer to single element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005322 llvm::Value *LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005323 // The basic structure here is a while-do loop.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005324 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
5325 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
5326 llvm::Value *IsEmpty =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005327 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
5328 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
5329
5330 // Enter the loop body, making that address the current address.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005331 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005332 CGF.EmitBlock(BodyBB);
5333
5334 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
5335
5336 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
5337 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
5338 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
5339 Address RHSElementCurrent =
5340 Address(RHSElementPHI,
5341 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5342
5343 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
5344 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
5345 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
5346 Address LHSElementCurrent =
5347 Address(LHSElementPHI,
5348 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5349
5350 // Emit copy.
5351 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005352 Scope.addPrivate(LHSVar, [=]() { return LHSElementCurrent; });
5353 Scope.addPrivate(RHSVar, [=]() { return RHSElementCurrent; });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005354 Scope.Privatize();
5355 RedOpGen(CGF, XExpr, EExpr, UpExpr);
5356 Scope.ForceCleanup();
5357
5358 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005359 llvm::Value *LHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005360 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005361 llvm::Value *RHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005362 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
5363 // Check whether we've reached the end.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005364 llvm::Value *Done =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005365 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
5366 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
5367 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
5368 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
5369
5370 // Done.
5371 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
5372}
5373
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005374/// Emit reduction combiner. If the combiner is a simple expression emit it as
5375/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
5376/// UDR combiner function.
5377static void emitReductionCombiner(CodeGenFunction &CGF,
5378 const Expr *ReductionOp) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005379 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
5380 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
5381 if (const auto *DRE =
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005382 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005383 if (const auto *DRD =
5384 dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005385 std::pair<llvm::Function *, llvm::Function *> Reduction =
5386 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
5387 RValue Func = RValue::get(Reduction.first);
5388 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
5389 CGF.EmitIgnoredExpr(ReductionOp);
5390 return;
5391 }
5392 CGF.EmitIgnoredExpr(ReductionOp);
5393}
5394
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005395llvm::Value *CGOpenMPRuntime::emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005396 CodeGenModule &CGM, SourceLocation Loc, llvm::Type *ArgsType,
5397 ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs,
5398 ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005399 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005400
5401 // void reduction_func(void *LHSArg, void *RHSArg);
5402 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005403 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5404 ImplicitParamDecl::Other);
5405 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5406 ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005407 Args.push_back(&LHSArg);
5408 Args.push_back(&RHSArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005409 const auto &CGFI =
5410 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005411 std::string Name = getName({"omp", "reduction", "reduction_func"});
5412 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
5413 llvm::GlobalValue::InternalLinkage, Name,
5414 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005415 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005416 Fn->setDoesNotRecurse();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005417 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005418 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005419
5420 // Dst = (void*[n])(LHSArg);
5421 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00005422 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5423 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
5424 ArgsType), CGF.getPointerAlign());
5425 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5426 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
5427 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005428
5429 // ...
5430 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
5431 // ...
5432 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005433 auto IPriv = Privates.begin();
5434 unsigned Idx = 0;
5435 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005436 const auto *RHSVar =
5437 cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
5438 Scope.addPrivate(RHSVar, [&CGF, RHS, Idx, RHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005439 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005440 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005441 const auto *LHSVar =
5442 cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
5443 Scope.addPrivate(LHSVar, [&CGF, LHS, Idx, LHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005444 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005445 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005446 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00005447 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005448 // Get array size and emit VLA type.
5449 ++Idx;
5450 Address Elem =
5451 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
5452 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005453 const VariableArrayType *VLA =
5454 CGF.getContext().getAsVariableArrayType(PrivTy);
5455 const auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005456 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00005457 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005458 CGF.EmitVariablyModifiedType(PrivTy);
5459 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005460 }
5461 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005462 IPriv = Privates.begin();
5463 auto ILHS = LHSExprs.begin();
5464 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005465 for (const Expr *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005466 if ((*IPriv)->getType()->isArrayType()) {
5467 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005468 const auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5469 const auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005470 EmitOMPAggregateReduction(
5471 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5472 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5473 emitReductionCombiner(CGF, E);
5474 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005475 } else {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005476 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005477 emitReductionCombiner(CGF, E);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005478 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005479 ++IPriv;
5480 ++ILHS;
5481 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005482 }
5483 Scope.ForceCleanup();
5484 CGF.FinishFunction();
5485 return Fn;
5486}
5487
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005488void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
5489 const Expr *ReductionOp,
5490 const Expr *PrivateRef,
5491 const DeclRefExpr *LHS,
5492 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005493 if (PrivateRef->getType()->isArrayType()) {
5494 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005495 const auto *LHSVar = cast<VarDecl>(LHS->getDecl());
5496 const auto *RHSVar = cast<VarDecl>(RHS->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005497 EmitOMPAggregateReduction(
5498 CGF, PrivateRef->getType(), LHSVar, RHSVar,
5499 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5500 emitReductionCombiner(CGF, ReductionOp);
5501 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005502 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005503 // Emit reduction for array subscript or single variable.
5504 emitReductionCombiner(CGF, ReductionOp);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005505 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005506}
5507
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005508void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005509 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005510 ArrayRef<const Expr *> LHSExprs,
5511 ArrayRef<const Expr *> RHSExprs,
5512 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005513 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005514 if (!CGF.HaveInsertPoint())
5515 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005516
5517 bool WithNowait = Options.WithNowait;
5518 bool SimpleReduction = Options.SimpleReduction;
5519
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005520 // Next code should be emitted for reduction:
5521 //
5522 // static kmp_critical_name lock = { 0 };
5523 //
5524 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
5525 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
5526 // ...
5527 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
5528 // *(Type<n>-1*)rhs[<n>-1]);
5529 // }
5530 //
5531 // ...
5532 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
5533 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5534 // RedList, reduce_func, &<lock>)) {
5535 // case 1:
5536 // ...
5537 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5538 // ...
5539 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5540 // break;
5541 // case 2:
5542 // ...
5543 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5544 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00005545 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005546 // break;
5547 // default:;
5548 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005549 //
5550 // if SimpleReduction is true, only the next code is generated:
5551 // ...
5552 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5553 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005554
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005555 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005556
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005557 if (SimpleReduction) {
5558 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005559 auto IPriv = Privates.begin();
5560 auto ILHS = LHSExprs.begin();
5561 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005562 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005563 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5564 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005565 ++IPriv;
5566 ++ILHS;
5567 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005568 }
5569 return;
5570 }
5571
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005572 // 1. Build a list of reduction variables.
5573 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005574 auto Size = RHSExprs.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005575 for (const Expr *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005576 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005577 // Reserve place for array size.
5578 ++Size;
5579 }
5580 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005581 QualType ReductionArrayTy =
5582 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
5583 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00005584 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005585 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005586 auto IPriv = Privates.begin();
5587 unsigned Idx = 0;
5588 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00005589 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005590 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00005591 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005592 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00005593 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
5594 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005595 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005596 // Store array size.
5597 ++Idx;
5598 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
5599 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00005600 llvm::Value *Size = CGF.Builder.CreateIntCast(
5601 CGF.getVLASize(
5602 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
Sander de Smalen891af03a2018-02-03 13:55:59 +00005603 .NumElts,
Alexey Bataev1189bd02016-01-26 12:20:39 +00005604 CGF.SizeTy, /*isSigned=*/false);
5605 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
5606 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005607 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005608 }
5609
5610 // 2. Emit reduce_func().
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005611 llvm::Value *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005612 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
5613 Privates, LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005614
5615 // 3. Create static kmp_critical_name lock = { 0 };
Alexey Bataev18fa2322018-05-02 14:20:50 +00005616 std::string Name = getName({"reduction"});
5617 llvm::Value *Lock = getCriticalRegionLock(Name);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005618
5619 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5620 // RedList, reduce_func, &<lock>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005621 llvm::Value *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
5622 llvm::Value *ThreadId = getThreadID(CGF, Loc);
5623 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
5624 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Samuel Antao4c8035b2016-12-12 18:00:20 +00005625 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005626 llvm::Value *Args[] = {
5627 IdentTLoc, // ident_t *<loc>
5628 ThreadId, // i32 <gtid>
5629 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5630 ReductionArrayTySize, // size_type sizeof(RedList)
5631 RL, // void *RedList
5632 ReductionFn, // void (*) (void *, void *) <reduce_func>
5633 Lock // kmp_critical_name *&<lock>
5634 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005635 llvm::Value *Res = CGF.EmitRuntimeCall(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005636 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5637 : OMPRTL__kmpc_reduce),
5638 Args);
5639
5640 // 5. Build switch(res)
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005641 llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5642 llvm::SwitchInst *SwInst =
5643 CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005644
5645 // 6. Build case 1:
5646 // ...
5647 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5648 // ...
5649 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5650 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005651 llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005652 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5653 CGF.EmitBlock(Case1BB);
5654
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005655 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5656 llvm::Value *EndArgs[] = {
5657 IdentTLoc, // ident_t *<loc>
5658 ThreadId, // i32 <gtid>
5659 Lock // kmp_critical_name *&<lock>
5660 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005661 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps](
5662 CodeGenFunction &CGF, PrePostActionTy &Action) {
5663 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005664 auto IPriv = Privates.begin();
5665 auto ILHS = LHSExprs.begin();
5666 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005667 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005668 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5669 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005670 ++IPriv;
5671 ++ILHS;
5672 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005673 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005674 };
5675 RegionCodeGenTy RCG(CodeGen);
5676 CommonActionTy Action(
5677 nullptr, llvm::None,
5678 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5679 : OMPRTL__kmpc_end_reduce),
5680 EndArgs);
5681 RCG.setAction(Action);
5682 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005683
5684 CGF.EmitBranch(DefaultBB);
5685
5686 // 7. Build case 2:
5687 // ...
5688 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5689 // ...
5690 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005691 llvm::BasicBlock *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005692 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5693 CGF.EmitBlock(Case2BB);
5694
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005695 auto &&AtomicCodeGen = [Loc, Privates, LHSExprs, RHSExprs, ReductionOps](
5696 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005697 auto ILHS = LHSExprs.begin();
5698 auto IRHS = RHSExprs.begin();
5699 auto IPriv = Privates.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005700 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005701 const Expr *XExpr = nullptr;
5702 const Expr *EExpr = nullptr;
5703 const Expr *UpExpr = nullptr;
5704 BinaryOperatorKind BO = BO_Comma;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005705 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005706 if (BO->getOpcode() == BO_Assign) {
5707 XExpr = BO->getLHS();
5708 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005709 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005710 }
5711 // Try to emit update expression as a simple atomic.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005712 const Expr *RHSExpr = UpExpr;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005713 if (RHSExpr) {
5714 // Analyze RHS part of the whole expression.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005715 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005716 RHSExpr->IgnoreParenImpCasts())) {
5717 // If this is a conditional operator, analyze its condition for
5718 // min/max reduction operator.
5719 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005720 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005721 if (const auto *BORHS =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005722 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5723 EExpr = BORHS->getRHS();
5724 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005725 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005726 }
5727 if (XExpr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005728 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005729 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005730 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5731 const Expr *EExpr, const Expr *UpExpr) {
5732 LValue X = CGF.EmitLValue(XExpr);
5733 RValue E;
5734 if (EExpr)
5735 E = CGF.EmitAnyExpr(EExpr);
5736 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005737 X, E, BO, /*IsXLHSInRHSPart=*/true,
5738 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005739 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005740 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5741 PrivateScope.addPrivate(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005742 VD, [&CGF, VD, XRValue, Loc]() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005743 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5744 CGF.emitOMPSimpleStore(
5745 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5746 VD->getType().getNonReferenceType(), Loc);
5747 return LHSTemp;
5748 });
5749 (void)PrivateScope.Privatize();
5750 return CGF.EmitAnyExpr(UpExpr);
5751 });
5752 };
5753 if ((*IPriv)->getType()->isArrayType()) {
5754 // Emit atomic reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005755 const auto *RHSVar =
5756 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005757 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5758 AtomicRedGen, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005759 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005760 // Emit atomic reduction for array subscript or single variable.
5761 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005762 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005763 } else {
5764 // Emit as a critical region.
5765 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005766 const Expr *, const Expr *) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005767 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005768 std::string Name = RT.getName({"atomic_reduction"});
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005769 RT.emitCriticalRegion(
Alexey Bataev18fa2322018-05-02 14:20:50 +00005770 CGF, Name,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005771 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5772 Action.Enter(CGF);
5773 emitReductionCombiner(CGF, E);
5774 },
5775 Loc);
5776 };
5777 if ((*IPriv)->getType()->isArrayType()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005778 const auto *LHSVar =
5779 cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5780 const auto *RHSVar =
5781 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005782 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5783 CritRedGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005784 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005785 CritRedGen(CGF, nullptr, nullptr, nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005786 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005787 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005788 ++ILHS;
5789 ++IRHS;
5790 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005791 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005792 };
5793 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5794 if (!WithNowait) {
5795 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5796 llvm::Value *EndArgs[] = {
5797 IdentTLoc, // ident_t *<loc>
5798 ThreadId, // i32 <gtid>
5799 Lock // kmp_critical_name *&<lock>
5800 };
5801 CommonActionTy Action(nullptr, llvm::None,
5802 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5803 EndArgs);
5804 AtomicRCG.setAction(Action);
5805 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005806 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005807 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005808 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005809
5810 CGF.EmitBranch(DefaultBB);
5811 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5812}
5813
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005814/// Generates unique name for artificial threadprivate variables.
Alexey Bataev1c44e152018-03-06 18:59:43 +00005815/// Format is: <Prefix> "." <Decl_mangled_name> "_" "<Decl_start_loc_raw_enc>"
5816static std::string generateUniqueName(CodeGenModule &CGM, StringRef Prefix,
5817 const Expr *Ref) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005818 SmallString<256> Buffer;
5819 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev1c44e152018-03-06 18:59:43 +00005820 const clang::DeclRefExpr *DE;
5821 const VarDecl *D = ::getBaseDecl(Ref, DE);
5822 if (!D)
5823 D = cast<VarDecl>(cast<DeclRefExpr>(Ref)->getDecl());
5824 D = D->getCanonicalDecl();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005825 std::string Name = CGM.getOpenMPRuntime().getName(
5826 {D->isLocalVarDeclOrParm() ? D->getName() : CGM.getMangledName(D)});
5827 Out << Prefix << Name << "_"
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005828 << D->getCanonicalDecl()->getBeginLoc().getRawEncoding();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005829 return Out.str();
5830}
5831
5832/// Emits reduction initializer function:
5833/// \code
5834/// void @.red_init(void* %arg) {
5835/// %0 = bitcast void* %arg to <type>*
5836/// store <type> <init>, <type>* %0
5837/// ret void
5838/// }
5839/// \endcode
5840static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5841 SourceLocation Loc,
5842 ReductionCodeGen &RCG, unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005843 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005844 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005845 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5846 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005847 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005848 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005849 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005850 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005851 std::string Name = CGM.getOpenMPRuntime().getName({"red_init", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005852 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005853 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005854 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005855 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005856 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005857 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005858 Address PrivateAddr = CGF.EmitLoadOfPointer(
5859 CGF.GetAddrOfLocalVar(&Param),
5860 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5861 llvm::Value *Size = nullptr;
5862 // If the size of the reduction item is non-constant, load it from global
5863 // threadprivate variable.
5864 if (RCG.getSizes(N).second) {
5865 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5866 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005867 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005868 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5869 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005870 }
5871 RCG.emitAggregateType(CGF, N, Size);
5872 LValue SharedLVal;
5873 // If initializer uses initializer from declare reduction construct, emit a
5874 // pointer to the address of the original reduction item (reuired by reduction
5875 // initializer)
5876 if (RCG.usesReductionInitializer(N)) {
5877 Address SharedAddr =
5878 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5879 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00005880 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataev21dab122018-03-09 15:20:30 +00005881 SharedAddr = CGF.EmitLoadOfPointer(
5882 SharedAddr,
5883 CGM.getContext().VoidPtrTy.castAs<PointerType>()->getTypePtr());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005884 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5885 } else {
5886 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5887 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5888 CGM.getContext().VoidPtrTy);
5889 }
5890 // Emit the initializer:
5891 // %0 = bitcast void* %arg to <type>*
5892 // store <type> <init>, <type>* %0
5893 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5894 [](CodeGenFunction &) { return false; });
5895 CGF.FinishFunction();
5896 return Fn;
5897}
5898
5899/// Emits reduction combiner function:
5900/// \code
5901/// void @.red_comb(void* %arg0, void* %arg1) {
5902/// %lhs = bitcast void* %arg0 to <type>*
5903/// %rhs = bitcast void* %arg1 to <type>*
5904/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5905/// store <type> %2, <type>* %lhs
5906/// ret void
5907/// }
5908/// \endcode
5909static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5910 SourceLocation Loc,
5911 ReductionCodeGen &RCG, unsigned N,
5912 const Expr *ReductionOp,
5913 const Expr *LHS, const Expr *RHS,
5914 const Expr *PrivateRef) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005915 ASTContext &C = CGM.getContext();
5916 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5917 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005918 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005919 ImplicitParamDecl ParamInOut(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
5920 C.VoidPtrTy, ImplicitParamDecl::Other);
5921 ImplicitParamDecl ParamIn(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5922 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005923 Args.emplace_back(&ParamInOut);
5924 Args.emplace_back(&ParamIn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005925 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005926 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005927 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005928 std::string Name = CGM.getOpenMPRuntime().getName({"red_comb", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005929 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005930 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005931 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005932 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005933 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005934 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005935 llvm::Value *Size = nullptr;
5936 // If the size of the reduction item is non-constant, load it from global
5937 // threadprivate variable.
5938 if (RCG.getSizes(N).second) {
5939 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5940 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005941 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005942 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5943 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005944 }
5945 RCG.emitAggregateType(CGF, N, Size);
5946 // Remap lhs and rhs variables to the addresses of the function arguments.
5947 // %lhs = bitcast void* %arg0 to <type>*
5948 // %rhs = bitcast void* %arg1 to <type>*
5949 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005950 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005951 // Pull out the pointer to the variable.
5952 Address PtrAddr = CGF.EmitLoadOfPointer(
5953 CGF.GetAddrOfLocalVar(&ParamInOut),
5954 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5955 return CGF.Builder.CreateElementBitCast(
5956 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
5957 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005958 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005959 // Pull out the pointer to the variable.
5960 Address PtrAddr = CGF.EmitLoadOfPointer(
5961 CGF.GetAddrOfLocalVar(&ParamIn),
5962 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5963 return CGF.Builder.CreateElementBitCast(
5964 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
5965 });
5966 PrivateScope.Privatize();
5967 // Emit the combiner body:
5968 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
5969 // store <type> %2, <type>* %lhs
5970 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
5971 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
5972 cast<DeclRefExpr>(RHS));
5973 CGF.FinishFunction();
5974 return Fn;
5975}
5976
5977/// Emits reduction finalizer function:
5978/// \code
5979/// void @.red_fini(void* %arg) {
5980/// %0 = bitcast void* %arg to <type>*
5981/// <destroy>(<type>* %0)
5982/// ret void
5983/// }
5984/// \endcode
5985static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
5986 SourceLocation Loc,
5987 ReductionCodeGen &RCG, unsigned N) {
5988 if (!RCG.needCleanups(N))
5989 return nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005990 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005991 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005992 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5993 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005994 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005995 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005996 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005997 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005998 std::string Name = CGM.getOpenMPRuntime().getName({"red_fini", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005999 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00006000 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00006001 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00006002 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006003 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00006004 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006005 Address PrivateAddr = CGF.EmitLoadOfPointer(
6006 CGF.GetAddrOfLocalVar(&Param),
6007 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
6008 llvm::Value *Size = nullptr;
6009 // If the size of the reduction item is non-constant, load it from global
6010 // threadprivate variable.
6011 if (RCG.getSizes(N).second) {
6012 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
6013 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00006014 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00006015 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
6016 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006017 }
6018 RCG.emitAggregateType(CGF, N, Size);
6019 // Emit the finalizer body:
6020 // <destroy>(<type>* %0)
6021 RCG.emitCleanups(CGF, N, PrivateAddr);
6022 CGF.FinishFunction();
6023 return Fn;
6024}
6025
6026llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
6027 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
6028 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
6029 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
6030 return nullptr;
6031
6032 // Build typedef struct:
6033 // kmp_task_red_input {
6034 // void *reduce_shar; // shared reduction item
6035 // size_t reduce_size; // size of data item
6036 // void *reduce_init; // data initialization routine
6037 // void *reduce_fini; // data finalization routine
6038 // void *reduce_comb; // data combiner routine
6039 // kmp_task_red_flags_t flags; // flags for additional info from compiler
6040 // } kmp_task_red_input_t;
6041 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006042 RecordDecl *RD = C.buildImplicitRecord("kmp_task_red_input_t");
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006043 RD->startDefinition();
6044 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6045 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
6046 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6047 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6048 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6049 const FieldDecl *FlagsFD = addFieldToRecordDecl(
6050 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
6051 RD->completeDefinition();
6052 QualType RDType = C.getRecordType(RD);
6053 unsigned Size = Data.ReductionVars.size();
6054 llvm::APInt ArraySize(/*numBits=*/64, Size);
6055 QualType ArrayRDType = C.getConstantArrayType(
6056 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
6057 // kmp_task_red_input_t .rd_input.[Size];
6058 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
6059 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
6060 Data.ReductionOps);
6061 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
6062 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
6063 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
6064 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
6065 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
6066 TaskRedInput.getPointer(), Idxs,
6067 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
6068 ".rd_input.gep.");
6069 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
6070 // ElemLVal.reduce_shar = &Shareds[Cnt];
6071 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
6072 RCG.emitSharedLValue(CGF, Cnt);
6073 llvm::Value *CastedShared =
6074 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
6075 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
6076 RCG.emitAggregateType(CGF, Cnt);
6077 llvm::Value *SizeValInChars;
6078 llvm::Value *SizeVal;
6079 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
6080 // We use delayed creation/initialization for VLAs, array sections and
6081 // custom reduction initializations. It is required because runtime does not
6082 // provide the way to pass the sizes of VLAs/array sections to
6083 // initializer/combiner/finalizer functions and does not pass the pointer to
6084 // original reduction item to the initializer. Instead threadprivate global
6085 // variables are used to store these values and use them in the functions.
6086 bool DelayedCreation = !!SizeVal;
6087 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
6088 /*isSigned=*/false);
6089 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
6090 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
6091 // ElemLVal.reduce_init = init;
6092 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
6093 llvm::Value *InitAddr =
6094 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
6095 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
6096 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
6097 // ElemLVal.reduce_fini = fini;
6098 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
6099 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
6100 llvm::Value *FiniAddr = Fini
6101 ? CGF.EmitCastToVoidPtr(Fini)
6102 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
6103 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
6104 // ElemLVal.reduce_comb = comb;
6105 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
6106 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
6107 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
6108 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
6109 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
6110 // ElemLVal.flags = 0;
6111 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
6112 if (DelayedCreation) {
6113 CGF.EmitStoreOfScalar(
6114 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
6115 FlagsLVal);
6116 } else
6117 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
6118 }
6119 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
6120 // *data);
6121 llvm::Value *Args[] = {
6122 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6123 /*isSigned=*/true),
6124 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
6125 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
6126 CGM.VoidPtrTy)};
6127 return CGF.EmitRuntimeCall(
6128 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
6129}
6130
6131void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
6132 SourceLocation Loc,
6133 ReductionCodeGen &RCG,
6134 unsigned N) {
6135 auto Sizes = RCG.getSizes(N);
6136 // Emit threadprivate global variable if the type is non-constant
6137 // (Sizes.second = nullptr).
6138 if (Sizes.second) {
6139 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
6140 /*isSigned=*/false);
6141 Address SizeAddr = getAddrOfArtificialThreadPrivate(
6142 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00006143 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006144 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
6145 }
6146 // Store address of the original reduction item if custom initializer is used.
6147 if (RCG.usesReductionInitializer(N)) {
6148 Address SharedAddr = getAddrOfArtificialThreadPrivate(
6149 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00006150 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006151 CGF.Builder.CreateStore(
6152 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6153 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
6154 SharedAddr, /*IsVolatile=*/false);
6155 }
6156}
6157
6158Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
6159 SourceLocation Loc,
6160 llvm::Value *ReductionsPtr,
6161 LValue SharedLVal) {
6162 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
6163 // *d);
6164 llvm::Value *Args[] = {
6165 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6166 /*isSigned=*/true),
6167 ReductionsPtr,
6168 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
6169 CGM.VoidPtrTy)};
6170 return Address(
6171 CGF.EmitRuntimeCall(
6172 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
6173 SharedLVal.getAlignment());
6174}
6175
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006176void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
6177 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006178 if (!CGF.HaveInsertPoint())
6179 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006180 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
6181 // global_tid);
6182 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
6183 // Ignore return result until untied tasks are supported.
6184 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00006185 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
6186 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006187}
6188
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006189void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006190 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006191 const RegionCodeGenTy &CodeGen,
6192 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006193 if (!CGF.HaveInsertPoint())
6194 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00006195 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006196 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00006197}
6198
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006199namespace {
6200enum RTCancelKind {
6201 CancelNoreq = 0,
6202 CancelParallel = 1,
6203 CancelLoop = 2,
6204 CancelSections = 3,
6205 CancelTaskgroup = 4
6206};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00006207} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006208
6209static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
6210 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00006211 if (CancelRegion == OMPD_parallel)
6212 CancelKind = CancelParallel;
6213 else if (CancelRegion == OMPD_for)
6214 CancelKind = CancelLoop;
6215 else if (CancelRegion == OMPD_sections)
6216 CancelKind = CancelSections;
6217 else {
6218 assert(CancelRegion == OMPD_taskgroup);
6219 CancelKind = CancelTaskgroup;
6220 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006221 return CancelKind;
6222}
6223
6224void CGOpenMPRuntime::emitCancellationPointCall(
6225 CodeGenFunction &CGF, SourceLocation Loc,
6226 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006227 if (!CGF.HaveInsertPoint())
6228 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006229 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
6230 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006231 if (auto *OMPRegionInfo =
6232 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00006233 // For 'cancellation point taskgroup', the task region info may not have a
6234 // cancel. This may instead happen in another adjacent task.
6235 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006236 llvm::Value *Args[] = {
6237 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
6238 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006239 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006240 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006241 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
6242 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006243 // exit from construct;
6244 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006245 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6246 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6247 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006248 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6249 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006250 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006251 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev25e5b442015-09-15 12:52:43 +00006252 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006253 CGF.EmitBranchThroughCleanup(CancelDest);
6254 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6255 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006256 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006257}
6258
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006259void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00006260 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006261 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006262 if (!CGF.HaveInsertPoint())
6263 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006264 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
6265 // kmp_int32 cncl_kind);
6266 if (auto *OMPRegionInfo =
6267 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006268 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
6269 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006270 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00006271 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006272 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00006273 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
6274 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006275 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006276 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00006277 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00006278 // exit from construct;
6279 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006280 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6281 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6282 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev87933c72015-09-18 08:07:34 +00006283 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6284 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00006285 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006286 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev87933c72015-09-18 08:07:34 +00006287 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
6288 CGF.EmitBranchThroughCleanup(CancelDest);
6289 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6290 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006291 if (IfCond) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006292 emitOMPIfClause(CGF, IfCond, ThenGen,
6293 [](CodeGenFunction &, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006294 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006295 RegionCodeGenTy ThenRCG(ThenGen);
6296 ThenRCG(CGF);
6297 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006298 }
6299}
Samuel Antaobed3c462015-10-02 16:14:20 +00006300
Samuel Antaoee8fb302016-01-06 13:42:12 +00006301void CGOpenMPRuntime::emitTargetOutlinedFunction(
6302 const OMPExecutableDirective &D, StringRef ParentName,
6303 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006304 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00006305 assert(!ParentName.empty() && "Invalid target region parent name!");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006306 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
6307 IsOffloadEntry, CodeGen);
6308}
6309
6310void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
6311 const OMPExecutableDirective &D, StringRef ParentName,
6312 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
6313 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00006314 // Create a unique name for the entry function using the source location
6315 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00006316 //
Samuel Antao2de62b02016-02-13 23:35:10 +00006317 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00006318 //
6319 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00006320 // mangled name of the function that encloses the target region and BB is the
6321 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00006322
6323 unsigned DeviceID;
6324 unsigned FileID;
6325 unsigned Line;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006326 getTargetEntryUniqueInfo(CGM.getContext(), D.getBeginLoc(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00006327 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006328 SmallString<64> EntryFnName;
6329 {
6330 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00006331 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
6332 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00006333 }
6334
Alexey Bataev475a7442018-01-12 19:39:11 +00006335 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006336
Samuel Antaobed3c462015-10-02 16:14:20 +00006337 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006338 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00006339 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006340
Samuel Antao6d004262016-06-16 18:39:34 +00006341 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006342
6343 // If this target outline function is not an offload entry, we don't need to
6344 // register it.
6345 if (!IsOffloadEntry)
6346 return;
6347
6348 // The target region ID is used by the runtime library to identify the current
6349 // target region, so it only has to be unique and not necessarily point to
6350 // anything. It could be the pointer to the outlined function that implements
6351 // the target region, but we aren't using that so that the compiler doesn't
6352 // need to keep that, and could therefore inline the host function if proven
6353 // worthwhile during optimization. In the other hand, if emitting code for the
6354 // device, the ID has to be the function address so that it can retrieved from
6355 // the offloading entry and launched by the runtime library. We also mark the
6356 // outlined function to have external linkage in case we are emitting code for
6357 // the device, because these functions will be entry points to the device.
6358
6359 if (CGM.getLangOpts().OpenMPIsDevice) {
6360 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
Alexey Bataev9a700172018-05-08 14:16:57 +00006361 OutlinedFn->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Rafael Espindolacbca4872018-01-11 22:15:12 +00006362 OutlinedFn->setDSOLocal(false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006363 } else {
Alexey Bataevc15ea702018-05-09 18:02:37 +00006364 std::string Name = getName({EntryFnName, "region_id"});
Samuel Antaoee8fb302016-01-06 13:42:12 +00006365 OutlinedFnID = new llvm::GlobalVariable(
6366 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
Alexey Bataev9a700172018-05-08 14:16:57 +00006367 llvm::GlobalValue::WeakAnyLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00006368 llvm::Constant::getNullValue(CGM.Int8Ty), Name);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006369 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00006370
6371 // Register the information for the entry associated with this target region.
6372 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00006373 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
Alexey Bataev03f270c2018-03-30 18:31:07 +00006374 OffloadEntriesInfoManagerTy::OMPTargetRegionEntryTargetRegion);
Samuel Antaobed3c462015-10-02 16:14:20 +00006375}
6376
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006377/// discard all CompoundStmts intervening between two constructs
6378static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006379 while (const auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006380 Body = CS->body_front();
6381
6382 return Body;
6383}
6384
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006385/// Emit the number of teams for a target directive. Inspect the num_teams
6386/// clause associated with a teams construct combined or closely nested
6387/// with the target directive.
6388///
6389/// Emit a team of size one for directives such as 'target parallel' that
6390/// have no associated teams construct.
6391///
6392/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006393static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006394emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6395 CodeGenFunction &CGF,
6396 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006397 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6398 "teams directive expected to be "
6399 "emitted only for the host!");
6400
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006401 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006402
6403 // If the target directive is combined with a teams directive:
6404 // Return the value in the num_teams clause, if any.
6405 // Otherwise, return 0 to denote the runtime default.
6406 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
6407 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
6408 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006409 llvm::Value *NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
6410 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006411 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6412 /*IsSigned=*/true);
6413 }
6414
6415 // The default value is 0.
6416 return Bld.getInt32(0);
6417 }
6418
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006419 // If the target directive is combined with a parallel directive but not a
6420 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006421 if (isOpenMPParallelDirective(D.getDirectiveKind()))
6422 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006423
6424 // If the current target region has a teams region enclosed, we need to get
6425 // the number of teams to pass to the runtime function call. This is done
6426 // by generating the expression in a inlined region. This is required because
6427 // the expression is captured in the enclosing target environment when the
6428 // teams directive is not combined with target.
6429
Alexey Bataev475a7442018-01-12 19:39:11 +00006430 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006431
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006432 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006433 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006434 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006435 if (const auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006436 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6437 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6438 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
6439 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6440 /*IsSigned=*/true);
6441 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006442
Alexey Bataev50a1c782017-12-01 21:31:08 +00006443 // If we have an enclosed teams directive but no num_teams clause we use
6444 // the default value 0.
6445 return Bld.getInt32(0);
6446 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006447 }
6448
6449 // No teams associated with the directive.
6450 return nullptr;
6451}
6452
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006453/// Emit the number of threads for a target directive. Inspect the
6454/// thread_limit clause associated with a teams construct combined or closely
6455/// nested with the target directive.
6456///
6457/// Emit the num_threads clause for directives such as 'target parallel' that
6458/// have no associated teams construct.
6459///
6460/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006461static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006462emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6463 CodeGenFunction &CGF,
6464 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006465 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6466 "teams directive expected to be "
6467 "emitted only for the host!");
6468
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006469 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006470
6471 //
6472 // If the target directive is combined with a teams directive:
6473 // Return the value in the thread_limit clause, if any.
6474 //
6475 // If the target directive is combined with a parallel directive:
6476 // Return the value in the num_threads clause, if any.
6477 //
6478 // If both clauses are set, select the minimum of the two.
6479 //
6480 // If neither teams or parallel combined directives set the number of threads
6481 // in a team, return 0 to denote the runtime default.
6482 //
6483 // If this is not a teams directive return nullptr.
6484
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006485 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
6486 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006487 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
6488 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006489 llvm::Value *ThreadLimitVal = nullptr;
6490
6491 if (const auto *ThreadLimitClause =
6492 D.getSingleClause<OMPThreadLimitClause>()) {
6493 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006494 llvm::Value *ThreadLimit =
6495 CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
6496 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006497 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6498 /*IsSigned=*/true);
6499 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006500
6501 if (const auto *NumThreadsClause =
6502 D.getSingleClause<OMPNumThreadsClause>()) {
6503 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
6504 llvm::Value *NumThreads =
6505 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
6506 /*IgnoreResultAssign*/ true);
6507 NumThreadsVal =
6508 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
6509 }
6510
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006511 // Select the lesser of thread_limit and num_threads.
6512 if (NumThreadsVal)
6513 ThreadLimitVal = ThreadLimitVal
6514 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
6515 ThreadLimitVal),
6516 NumThreadsVal, ThreadLimitVal)
6517 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00006518
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006519 // Set default value passed to the runtime if either teams or a target
6520 // parallel type directive is found but no clause is specified.
6521 if (!ThreadLimitVal)
6522 ThreadLimitVal = DefaultThreadLimitVal;
6523
6524 return ThreadLimitVal;
6525 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00006526
Samuel Antaob68e2db2016-03-03 16:20:23 +00006527 // If the current target region has a teams region enclosed, we need to get
6528 // the thread limit to pass to the runtime function call. This is done
6529 // by generating the expression in a inlined region. This is required because
6530 // the expression is captured in the enclosing target environment when the
6531 // teams directive is not combined with target.
6532
Alexey Bataev475a7442018-01-12 19:39:11 +00006533 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006534
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006535 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006536 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006537 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006538 if (const auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006539 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6540 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6541 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
6542 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6543 /*IsSigned=*/true);
6544 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006545
Alexey Bataev50a1c782017-12-01 21:31:08 +00006546 // If we have an enclosed teams directive but no thread_limit clause we
6547 // use the default value 0.
6548 return CGF.Builder.getInt32(0);
6549 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006550 }
6551
6552 // No teams associated with the directive.
6553 return nullptr;
6554}
6555
Samuel Antao86ace552016-04-27 22:40:57 +00006556namespace {
Alexey Bataevb3638132018-07-19 16:34:13 +00006557LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
6558
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006559// Utility to handle information from clauses associated with a given
Samuel Antao86ace552016-04-27 22:40:57 +00006560// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
6561// It provides a convenient interface to obtain the information and generate
6562// code for that information.
6563class MappableExprsHandler {
6564public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006565 /// Values for bit flags used to specify the mapping type for
Samuel Antao86ace552016-04-27 22:40:57 +00006566 /// offloading.
Alexey Bataevb3638132018-07-19 16:34:13 +00006567 enum OpenMPOffloadMappingFlags : uint64_t {
6568 /// No flags
6569 OMP_MAP_NONE = 0x0,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006570 /// Allocate memory on the device and move data from host to device.
Samuel Antao86ace552016-04-27 22:40:57 +00006571 OMP_MAP_TO = 0x01,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006572 /// Allocate memory on the device and move data from device to host.
Samuel Antao86ace552016-04-27 22:40:57 +00006573 OMP_MAP_FROM = 0x02,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006574 /// Always perform the requested mapping action on the element, even
Samuel Antao86ace552016-04-27 22:40:57 +00006575 /// if it was already mapped before.
6576 OMP_MAP_ALWAYS = 0x04,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006577 /// Delete the element from the device environment, ignoring the
Samuel Antao86ace552016-04-27 22:40:57 +00006578 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00006579 OMP_MAP_DELETE = 0x08,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006580 /// The element being mapped is a pointer-pointee pair; both the
George Rokos065755d2017-11-07 18:27:04 +00006581 /// pointer and the pointee should be mapped.
6582 OMP_MAP_PTR_AND_OBJ = 0x10,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006583 /// This flags signals that the base address of an entry should be
George Rokos065755d2017-11-07 18:27:04 +00006584 /// passed to the target kernel as an argument.
6585 OMP_MAP_TARGET_PARAM = 0x20,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006586 /// Signal that the runtime library has to return the device pointer
George Rokos065755d2017-11-07 18:27:04 +00006587 /// in the current position for the data being mapped. Used when we have the
6588 /// use_device_ptr clause.
6589 OMP_MAP_RETURN_PARAM = 0x40,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006590 /// This flag signals that the reference being passed is a pointer to
Samuel Antaod486f842016-05-26 16:53:38 +00006591 /// private data.
George Rokos065755d2017-11-07 18:27:04 +00006592 OMP_MAP_PRIVATE = 0x80,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006593 /// Pass the element to the device by value.
George Rokos065755d2017-11-07 18:27:04 +00006594 OMP_MAP_LITERAL = 0x100,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006595 /// Implicit map
6596 OMP_MAP_IMPLICIT = 0x200,
Alexey Bataevb3638132018-07-19 16:34:13 +00006597 /// The 16 MSBs of the flags indicate whether the entry is member of some
6598 /// struct/class.
6599 OMP_MAP_MEMBER_OF = 0xffff000000000000,
6600 LLVM_MARK_AS_BITMASK_ENUM(/* LargestFlag = */ OMP_MAP_MEMBER_OF),
Samuel Antao86ace552016-04-27 22:40:57 +00006601 };
6602
Samuel Antaocc10b852016-07-28 14:23:26 +00006603 /// Class that associates information with a base pointer to be passed to the
6604 /// runtime library.
6605 class BasePointerInfo {
6606 /// The base pointer.
6607 llvm::Value *Ptr = nullptr;
6608 /// The base declaration that refers to this device pointer, or null if
6609 /// there is none.
6610 const ValueDecl *DevPtrDecl = nullptr;
6611
6612 public:
6613 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
6614 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
6615 llvm::Value *operator*() const { return Ptr; }
6616 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
6617 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
6618 };
6619
Alexey Bataevb3638132018-07-19 16:34:13 +00006620 using MapBaseValuesArrayTy = SmallVector<BasePointerInfo, 4>;
6621 using MapValuesArrayTy = SmallVector<llvm::Value *, 4>;
6622 using MapFlagsArrayTy = SmallVector<OpenMPOffloadMappingFlags, 4>;
6623
6624 /// Map between a struct and the its lowest & highest elements which have been
6625 /// mapped.
6626 /// [ValueDecl *] --> {LE(FieldIndex, Pointer),
6627 /// HE(FieldIndex, Pointer)}
6628 struct StructRangeInfoTy {
6629 std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> LowestElem = {
6630 0, Address::invalid()};
6631 std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> HighestElem = {
6632 0, Address::invalid()};
6633 Address Base = Address::invalid();
6634 };
Samuel Antao86ace552016-04-27 22:40:57 +00006635
6636private:
Alexey Bataevb3638132018-07-19 16:34:13 +00006637 /// Kind that defines how a device pointer has to be returned.
6638 struct MapInfo {
6639 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
6640 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
6641 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
6642 bool ReturnDevicePointer = false;
6643 bool IsImplicit = false;
6644
6645 MapInfo() = default;
6646 MapInfo(
6647 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
6648 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6649 bool ReturnDevicePointer, bool IsImplicit)
6650 : Components(Components), MapType(MapType),
6651 MapTypeModifier(MapTypeModifier),
6652 ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
6653 };
6654
6655 /// If use_device_ptr is used on a pointer which is a struct member and there
6656 /// is no map information about it, then emission of that entry is deferred
6657 /// until the whole struct has been processed.
6658 struct DeferredDevicePtrEntryTy {
6659 const Expr *IE = nullptr;
6660 const ValueDecl *VD = nullptr;
6661
6662 DeferredDevicePtrEntryTy(const Expr *IE, const ValueDecl *VD)
6663 : IE(IE), VD(VD) {}
6664 };
6665
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006666 /// Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00006667 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00006668
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006669 /// Function the directive is being generated for.
Samuel Antao86ace552016-04-27 22:40:57 +00006670 CodeGenFunction &CGF;
6671
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006672 /// Set of all first private variables in the current directive.
Samuel Antaod486f842016-05-26 16:53:38 +00006673 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
6674
Samuel Antao6890b092016-07-28 14:25:09 +00006675 /// Map between device pointer declarations and their expression components.
6676 /// The key value for declarations in 'this' is null.
6677 llvm::DenseMap<
6678 const ValueDecl *,
6679 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6680 DevPointersMap;
6681
Samuel Antao86ace552016-04-27 22:40:57 +00006682 llvm::Value *getExprTypeSize(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006683 QualType ExprTy = E->getType().getCanonicalType();
Samuel Antao86ace552016-04-27 22:40:57 +00006684
6685 // Reference types are ignored for mapping purposes.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006686 if (const auto *RefTy = ExprTy->getAs<ReferenceType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006687 ExprTy = RefTy->getPointeeType().getCanonicalType();
6688
6689 // Given that an array section is considered a built-in type, we need to
6690 // do the calculation based on the length of the section instead of relying
6691 // on CGF.getTypeSize(E->getType()).
6692 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6693 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6694 OAE->getBase()->IgnoreParenImpCasts())
6695 .getCanonicalType();
6696
6697 // If there is no length associated with the expression, that means we
6698 // are using the whole length of the base.
6699 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6700 return CGF.getTypeSize(BaseTy);
6701
6702 llvm::Value *ElemSize;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006703 if (const auto *PTy = BaseTy->getAs<PointerType>()) {
Samuel Antao86ace552016-04-27 22:40:57 +00006704 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006705 } else {
6706 const auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
Samuel Antao86ace552016-04-27 22:40:57 +00006707 assert(ATy && "Expecting array type if not a pointer type.");
6708 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6709 }
6710
6711 // If we don't have a length at this point, that is because we have an
6712 // array section with a single element.
6713 if (!OAE->getLength())
6714 return ElemSize;
6715
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006716 llvm::Value *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
Samuel Antao86ace552016-04-27 22:40:57 +00006717 LengthVal =
6718 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6719 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6720 }
6721 return CGF.getTypeSize(ExprTy);
6722 }
6723
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006724 /// Return the corresponding bits for a given map clause modifier. Add
Samuel Antao86ace552016-04-27 22:40:57 +00006725 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006726 /// map as the first one of a series of maps that relate to the same map
6727 /// expression.
Alexey Bataevb3638132018-07-19 16:34:13 +00006728 OpenMPOffloadMappingFlags getMapTypeBits(OpenMPMapClauseKind MapType,
6729 OpenMPMapClauseKind MapTypeModifier,
6730 bool IsImplicit, bool AddPtrFlag,
6731 bool AddIsTargetParamFlag) const {
6732 OpenMPOffloadMappingFlags Bits =
6733 IsImplicit ? OMP_MAP_IMPLICIT : OMP_MAP_NONE;
Samuel Antao86ace552016-04-27 22:40:57 +00006734 switch (MapType) {
6735 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006736 case OMPC_MAP_release:
6737 // alloc and release is the default behavior in the runtime library, i.e.
6738 // if we don't pass any bits alloc/release that is what the runtime is
6739 // going to do. Therefore, we don't need to signal anything for these two
6740 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006741 break;
6742 case OMPC_MAP_to:
Alexey Bataevb3638132018-07-19 16:34:13 +00006743 Bits |= OMP_MAP_TO;
Samuel Antao86ace552016-04-27 22:40:57 +00006744 break;
6745 case OMPC_MAP_from:
Alexey Bataevb3638132018-07-19 16:34:13 +00006746 Bits |= OMP_MAP_FROM;
Samuel Antao86ace552016-04-27 22:40:57 +00006747 break;
6748 case OMPC_MAP_tofrom:
Alexey Bataevb3638132018-07-19 16:34:13 +00006749 Bits |= OMP_MAP_TO | OMP_MAP_FROM;
Samuel Antao86ace552016-04-27 22:40:57 +00006750 break;
6751 case OMPC_MAP_delete:
Alexey Bataevb3638132018-07-19 16:34:13 +00006752 Bits |= OMP_MAP_DELETE;
Samuel Antao86ace552016-04-27 22:40:57 +00006753 break;
Alexey Bataevb3638132018-07-19 16:34:13 +00006754 case OMPC_MAP_always:
6755 case OMPC_MAP_unknown:
Samuel Antao86ace552016-04-27 22:40:57 +00006756 llvm_unreachable("Unexpected map type!");
Samuel Antao86ace552016-04-27 22:40:57 +00006757 }
6758 if (AddPtrFlag)
George Rokos065755d2017-11-07 18:27:04 +00006759 Bits |= OMP_MAP_PTR_AND_OBJ;
6760 if (AddIsTargetParamFlag)
6761 Bits |= OMP_MAP_TARGET_PARAM;
Samuel Antao86ace552016-04-27 22:40:57 +00006762 if (MapTypeModifier == OMPC_MAP_always)
6763 Bits |= OMP_MAP_ALWAYS;
6764 return Bits;
6765 }
6766
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006767 /// Return true if the provided expression is a final array section. A
Samuel Antao86ace552016-04-27 22:40:57 +00006768 /// final array section, is one whose length can't be proved to be one.
6769 bool isFinalArraySectionExpression(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006770 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antao86ace552016-04-27 22:40:57 +00006771
6772 // It is not an array section and therefore not a unity-size one.
6773 if (!OASE)
6774 return false;
6775
6776 // An array section with no colon always refer to a single element.
6777 if (OASE->getColonLoc().isInvalid())
6778 return false;
6779
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006780 const Expr *Length = OASE->getLength();
Samuel Antao86ace552016-04-27 22:40:57 +00006781
6782 // If we don't have a length we have to check if the array has size 1
6783 // for this dimension. Also, we should always expect a length if the
6784 // base type is pointer.
6785 if (!Length) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006786 QualType BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6787 OASE->getBase()->IgnoreParenImpCasts())
6788 .getCanonicalType();
6789 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antao86ace552016-04-27 22:40:57 +00006790 return ATy->getSize().getSExtValue() != 1;
6791 // If we don't have a constant dimension length, we have to consider
6792 // the current section as having any size, so it is not necessarily
6793 // unitary. If it happen to be unity size, that's user fault.
6794 return true;
6795 }
6796
6797 // Check if the length evaluates to 1.
Nico Weber9f0246d2018-11-21 12:47:43 +00006798 llvm::APSInt ConstLength;
6799 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
Samuel Antao86ace552016-04-27 22:40:57 +00006800 return true; // Can have more that size 1.
6801
6802 return ConstLength.getSExtValue() != 1;
6803 }
6804
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006805 /// Generate the base pointers, section pointers, sizes and map type
Samuel Antao86ace552016-04-27 22:40:57 +00006806 /// bits for the provided map type, map modifier, and expression components.
6807 /// \a IsFirstComponent should be set to true if the provided set of
6808 /// components is the first associated with a capture.
6809 void generateInfoForComponentList(
6810 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6811 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006812 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006813 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
Alexey Bataevb3638132018-07-19 16:34:13 +00006814 StructRangeInfoTy &PartialStruct, bool IsFirstComponentList,
Alexey Bataeve82445f2018-09-20 13:54:02 +00006815 bool IsImplicit,
6816 ArrayRef<OMPClauseMappableExprCommon::MappableExprComponentListRef>
6817 OverlappedElements = llvm::None) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006818 // The following summarizes what has to be generated for each map and the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006819 // types below. The generated information is expressed in this order:
Samuel Antao86ace552016-04-27 22:40:57 +00006820 // base pointer, section pointer, size, flags
6821 // (to add to the ones that come from the map type and modifier).
6822 //
6823 // double d;
6824 // int i[100];
6825 // float *p;
6826 //
6827 // struct S1 {
6828 // int i;
6829 // float f[50];
6830 // }
6831 // struct S2 {
6832 // int i;
6833 // float f[50];
6834 // S1 s;
6835 // double *p;
6836 // struct S2 *ps;
6837 // }
6838 // S2 s;
6839 // S2 *ps;
6840 //
6841 // map(d)
Alexey Bataevb3638132018-07-19 16:34:13 +00006842 // &d, &d, sizeof(double), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006843 //
6844 // map(i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006845 // &i, &i, 100*sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006846 //
6847 // map(i[1:23])
Alexey Bataevb3638132018-07-19 16:34:13 +00006848 // &i(=&i[0]), &i[1], 23*sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006849 //
6850 // map(p)
Alexey Bataevb3638132018-07-19 16:34:13 +00006851 // &p, &p, sizeof(float*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006852 //
6853 // map(p[1:24])
Alexey Bataevb3638132018-07-19 16:34:13 +00006854 // p, &p[1], 24*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006855 //
6856 // map(s)
Alexey Bataevb3638132018-07-19 16:34:13 +00006857 // &s, &s, sizeof(S2), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006858 //
6859 // map(s.i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006860 // &s, &(s.i), sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006861 //
6862 // map(s.s.f)
Alexey Bataevb3638132018-07-19 16:34:13 +00006863 // &s, &(s.s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006864 //
6865 // map(s.p)
Alexey Bataevb3638132018-07-19 16:34:13 +00006866 // &s, &(s.p), sizeof(double*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006867 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006868 // map(to: s.p[:22])
6869 // &s, &(s.p), sizeof(double*), TARGET_PARAM (*)
6870 // &s, &(s.p), sizeof(double*), MEMBER_OF(1) (**)
6871 // &(s.p), &(s.p[0]), 22*sizeof(double),
6872 // MEMBER_OF(1) | PTR_AND_OBJ | TO (***)
6873 // (*) alloc space for struct members, only this is a target parameter
6874 // (**) map the pointer (nothing to be mapped in this example) (the compiler
6875 // optimizes this entry out, same in the examples below)
6876 // (***) map the pointee (map: to)
Samuel Antao86ace552016-04-27 22:40:57 +00006877 //
6878 // map(s.ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006879 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006880 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006881 // map(from: s.ps->s.i)
6882 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6883 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6884 // &(s.ps), &(s.ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006885 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006886 // map(to: s.ps->ps)
6887 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6888 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6889 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006890 //
6891 // map(s.ps->ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006892 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6893 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6894 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6895 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006896 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006897 // map(to: s.ps->ps->s.f[:22])
6898 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6899 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6900 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6901 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006902 //
6903 // map(ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006904 // &ps, &ps, sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006905 //
6906 // map(ps->i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006907 // ps, &(ps->i), sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006908 //
6909 // map(ps->s.f)
Alexey Bataevb3638132018-07-19 16:34:13 +00006910 // ps, &(ps->s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006911 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006912 // map(from: ps->p)
6913 // ps, &(ps->p), sizeof(double*), TARGET_PARAM | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006914 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006915 // map(to: ps->p[:22])
6916 // ps, &(ps->p), sizeof(double*), TARGET_PARAM
6917 // ps, &(ps->p), sizeof(double*), MEMBER_OF(1)
6918 // &(ps->p), &(ps->p[0]), 22*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006919 //
6920 // map(ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006921 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006922 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006923 // map(from: ps->ps->s.i)
6924 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6925 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6926 // &(ps->ps), &(ps->ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006927 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006928 // map(from: ps->ps->ps)
6929 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6930 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6931 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006932 //
6933 // map(ps->ps->ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006934 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6935 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6936 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6937 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006938 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006939 // map(to: ps->ps->ps->s.f[:22])
6940 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6941 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6942 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6943 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO
6944 //
6945 // map(to: s.f[:22]) map(from: s.p[:33])
6946 // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1) +
6947 // sizeof(double*) (**), TARGET_PARAM
6948 // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | TO
6949 // &s, &(s.p), sizeof(double*), MEMBER_OF(1)
6950 // &(s.p), &(s.p[0]), 33*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | FROM
6951 // (*) allocate contiguous space needed to fit all mapped members even if
6952 // we allocate space for members not mapped (in this example,
6953 // s.f[22..49] and s.s are not mapped, yet we must allocate space for
6954 // them as well because they fall between &s.f[0] and &s.p)
6955 //
6956 // map(from: s.f[:22]) map(to: ps->p[:33])
6957 // &s, &(s.f[0]), 22*sizeof(float), TARGET_PARAM | FROM
6958 // ps, &(ps->p), sizeof(S2*), TARGET_PARAM
6959 // ps, &(ps->p), sizeof(double*), MEMBER_OF(2) (*)
6960 // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(2) | PTR_AND_OBJ | TO
6961 // (*) the struct this entry pertains to is the 2nd element in the list of
6962 // arguments, hence MEMBER_OF(2)
6963 //
6964 // map(from: s.f[:22], s.s) map(to: ps->p[:33])
6965 // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1), TARGET_PARAM
6966 // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | FROM
6967 // &s, &(s.s), sizeof(struct S1), MEMBER_OF(1) | FROM
6968 // ps, &(ps->p), sizeof(S2*), TARGET_PARAM
6969 // ps, &(ps->p), sizeof(double*), MEMBER_OF(4) (*)
6970 // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(4) | PTR_AND_OBJ | TO
6971 // (*) the struct this entry pertains to is the 4th element in the list
6972 // of arguments, hence MEMBER_OF(4)
Samuel Antao86ace552016-04-27 22:40:57 +00006973
6974 // Track if the map information being generated is the first for a capture.
6975 bool IsCaptureFirstInfo = IsFirstComponentList;
Alexey Bataev92327c52018-03-26 16:40:55 +00006976 bool IsLink = false; // Is this variable a "declare target link"?
Samuel Antao86ace552016-04-27 22:40:57 +00006977
6978 // Scan the components from the base to the complete expression.
6979 auto CI = Components.rbegin();
6980 auto CE = Components.rend();
6981 auto I = CI;
6982
6983 // Track if the map information being generated is the first for a list of
6984 // components.
6985 bool IsExpressionFirstInfo = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00006986 Address BP = Address::invalid();
Samuel Antao86ace552016-04-27 22:40:57 +00006987
Erich Keanee69755a2018-07-19 17:19:16 +00006988 if (isa<MemberExpr>(I->getAssociatedExpression())) {
Samuel Antao86ace552016-04-27 22:40:57 +00006989 // The base is the 'this' pointer. The content of the pointer is going
6990 // to be the base of the field being mapped.
Alexey Bataevb3638132018-07-19 16:34:13 +00006991 BP = CGF.LoadCXXThisAddress();
Samuel Antao86ace552016-04-27 22:40:57 +00006992 } else {
6993 // The base is the reference to the variable.
6994 // BP = &Var.
Alexey Bataevb3638132018-07-19 16:34:13 +00006995 BP = CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getAddress();
Alexey Bataev92327c52018-03-26 16:40:55 +00006996 if (const auto *VD =
6997 dyn_cast_or_null<VarDecl>(I->getAssociatedDeclaration())) {
6998 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00006999 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataev2c1dffe2018-04-16 20:34:41 +00007000 if (*Res == OMPDeclareTargetDeclAttr::MT_Link) {
7001 IsLink = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00007002 BP = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
Alexey Bataev2c1dffe2018-04-16 20:34:41 +00007003 }
Alexey Bataev92327c52018-03-26 16:40:55 +00007004 }
Samuel Antao86ace552016-04-27 22:40:57 +00007005
7006 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00007007 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00007008 // reference. References are ignored for mapping purposes.
7009 QualType Ty =
7010 I->getAssociatedDeclaration()->getType().getNonReferenceType();
7011 if (Ty->isAnyPointerType() && std::next(I) != CE) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007012 BP = CGF.EmitLoadOfPointer(BP, Ty->castAs<PointerType>());
Samuel Antao86ace552016-04-27 22:40:57 +00007013
7014 // We do not need to generate individual map information for the
7015 // pointer, it can be associated with the combined storage.
7016 ++I;
7017 }
7018 }
7019
Alexey Bataevb3638132018-07-19 16:34:13 +00007020 // Track whether a component of the list should be marked as MEMBER_OF some
7021 // combined entry (for partial structs). Only the first PTR_AND_OBJ entry
7022 // in a component list should be marked as MEMBER_OF, all subsequent entries
7023 // do not belong to the base struct. E.g.
7024 // struct S2 s;
7025 // s.ps->ps->ps->f[:]
7026 // (1) (2) (3) (4)
7027 // ps(1) is a member pointer, ps(2) is a pointee of ps(1), so it is a
7028 // PTR_AND_OBJ entry; the PTR is ps(1), so MEMBER_OF the base struct. ps(3)
7029 // is the pointee of ps(2) which is not member of struct s, so it should not
7030 // be marked as such (it is still PTR_AND_OBJ).
7031 // The variable is initialized to false so that PTR_AND_OBJ entries which
7032 // are not struct members are not considered (e.g. array of pointers to
7033 // data).
7034 bool ShouldBeMemberOf = false;
7035
7036 // Variable keeping track of whether or not we have encountered a component
7037 // in the component list which is a member expression. Useful when we have a
7038 // pointer or a final array section, in which case it is the previous
7039 // component in the list which tells us whether we have a member expression.
7040 // E.g. X.f[:]
7041 // While processing the final array section "[:]" it is "f" which tells us
7042 // whether we are dealing with a member of a declared struct.
7043 const MemberExpr *EncounteredME = nullptr;
7044
Samuel Antao86ace552016-04-27 22:40:57 +00007045 for (; I != CE; ++I) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007046 // If the current component is member of a struct (parent struct) mark it.
7047 if (!EncounteredME) {
7048 EncounteredME = dyn_cast<MemberExpr>(I->getAssociatedExpression());
7049 // If we encounter a PTR_AND_OBJ entry from now on it should be marked
7050 // as MEMBER_OF the parent struct.
7051 if (EncounteredME)
7052 ShouldBeMemberOf = true;
7053 }
7054
Samuel Antao86ace552016-04-27 22:40:57 +00007055 auto Next = std::next(I);
7056
7057 // We need to generate the addresses and sizes if this is the last
7058 // component, if the component is a pointer or if it is an array section
7059 // whose length can't be proved to be one. If this is a pointer, it
7060 // becomes the base address for the following components.
7061
7062 // A final array section, is one whose length can't be proved to be one.
7063 bool IsFinalArraySection =
7064 isFinalArraySectionExpression(I->getAssociatedExpression());
7065
7066 // Get information on whether the element is a pointer. Have to do a
7067 // special treatment for array sections given that they are built-in
7068 // types.
7069 const auto *OASE =
7070 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
7071 bool IsPointer =
Alexey Bataevb3638132018-07-19 16:34:13 +00007072 (OASE && OMPArraySectionExpr::getBaseOriginalType(OASE)
7073 .getCanonicalType()
7074 ->isAnyPointerType()) ||
Samuel Antao86ace552016-04-27 22:40:57 +00007075 I->getAssociatedExpression()->getType()->isAnyPointerType();
7076
7077 if (Next == CE || IsPointer || IsFinalArraySection) {
Samuel Antao86ace552016-04-27 22:40:57 +00007078 // If this is not the last component, we expect the pointer to be
7079 // associated with an array expression or member expression.
7080 assert((Next == CE ||
7081 isa<MemberExpr>(Next->getAssociatedExpression()) ||
7082 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
7083 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
7084 "Unexpected expression");
7085
Alexey Bataevb3638132018-07-19 16:34:13 +00007086 Address LB =
7087 CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getAddress();
Samuel Antao86ace552016-04-27 22:40:57 +00007088
Alexey Bataevb3638132018-07-19 16:34:13 +00007089 // If this component is a pointer inside the base struct then we don't
7090 // need to create any entry for it - it will be combined with the object
7091 // it is pointing to into a single PTR_AND_OBJ entry.
7092 bool IsMemberPointer =
7093 IsPointer && EncounteredME &&
7094 (dyn_cast<MemberExpr>(I->getAssociatedExpression()) ==
7095 EncounteredME);
Alexey Bataeve82445f2018-09-20 13:54:02 +00007096 if (!OverlappedElements.empty()) {
7097 // Handle base element with the info for overlapped elements.
7098 assert(!PartialStruct.Base.isValid() && "The base element is set.");
7099 assert(Next == CE &&
7100 "Expected last element for the overlapped elements.");
7101 assert(!IsPointer &&
7102 "Unexpected base element with the pointer type.");
7103 // Mark the whole struct as the struct that requires allocation on the
7104 // device.
7105 PartialStruct.LowestElem = {0, LB};
7106 CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(
7107 I->getAssociatedExpression()->getType());
7108 Address HB = CGF.Builder.CreateConstGEP(
7109 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(LB,
7110 CGF.VoidPtrTy),
7111 TypeSize.getQuantity() - 1, CharUnits::One());
7112 PartialStruct.HighestElem = {
7113 std::numeric_limits<decltype(
7114 PartialStruct.HighestElem.first)>::max(),
7115 HB};
7116 PartialStruct.Base = BP;
7117 // Emit data for non-overlapped data.
7118 OpenMPOffloadMappingFlags Flags =
7119 OMP_MAP_MEMBER_OF |
7120 getMapTypeBits(MapType, MapTypeModifier, IsImplicit,
7121 /*AddPtrFlag=*/false,
7122 /*AddIsTargetParamFlag=*/false);
7123 LB = BP;
7124 llvm::Value *Size = nullptr;
7125 // Do bitcopy of all non-overlapped structure elements.
7126 for (OMPClauseMappableExprCommon::MappableExprComponentListRef
7127 Component : OverlappedElements) {
7128 Address ComponentLB = Address::invalid();
7129 for (const OMPClauseMappableExprCommon::MappableComponent &MC :
7130 Component) {
7131 if (MC.getAssociatedDeclaration()) {
7132 ComponentLB =
7133 CGF.EmitOMPSharedLValue(MC.getAssociatedExpression())
7134 .getAddress();
7135 Size = CGF.Builder.CreatePtrDiff(
7136 CGF.EmitCastToVoidPtr(ComponentLB.getPointer()),
7137 CGF.EmitCastToVoidPtr(LB.getPointer()));
7138 break;
7139 }
7140 }
7141 BasePointers.push_back(BP.getPointer());
7142 Pointers.push_back(LB.getPointer());
7143 Sizes.push_back(Size);
7144 Types.push_back(Flags);
7145 LB = CGF.Builder.CreateConstGEP(ComponentLB, 1,
7146 CGF.getPointerSize());
7147 }
7148 BasePointers.push_back(BP.getPointer());
7149 Pointers.push_back(LB.getPointer());
7150 Size = CGF.Builder.CreatePtrDiff(
7151 CGF.EmitCastToVoidPtr(
7152 CGF.Builder.CreateConstGEP(HB, 1, CharUnits::One())
7153 .getPointer()),
7154 CGF.EmitCastToVoidPtr(LB.getPointer()));
7155 Sizes.push_back(Size);
7156 Types.push_back(Flags);
7157 break;
7158 }
7159 llvm::Value *Size = getExprTypeSize(I->getAssociatedExpression());
Alexey Bataevb3638132018-07-19 16:34:13 +00007160 if (!IsMemberPointer) {
7161 BasePointers.push_back(BP.getPointer());
7162 Pointers.push_back(LB.getPointer());
7163 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00007164
Alexey Bataevb3638132018-07-19 16:34:13 +00007165 // We need to add a pointer flag for each map that comes from the
7166 // same expression except for the first one. We also need to signal
7167 // this map is the first one that relates with the current capture
7168 // (there is a set of entries for each capture).
7169 OpenMPOffloadMappingFlags Flags = getMapTypeBits(
7170 MapType, MapTypeModifier, IsImplicit,
7171 !IsExpressionFirstInfo || IsLink, IsCaptureFirstInfo && !IsLink);
7172
7173 if (!IsExpressionFirstInfo) {
7174 // If we have a PTR_AND_OBJ pair where the OBJ is a pointer as well,
7175 // then we reset the TO/FROM/ALWAYS/DELETE flags.
7176 if (IsPointer)
7177 Flags &= ~(OMP_MAP_TO | OMP_MAP_FROM | OMP_MAP_ALWAYS |
7178 OMP_MAP_DELETE);
7179
7180 if (ShouldBeMemberOf) {
7181 // Set placeholder value MEMBER_OF=FFFF to indicate that the flag
7182 // should be later updated with the correct value of MEMBER_OF.
7183 Flags |= OMP_MAP_MEMBER_OF;
7184 // From now on, all subsequent PTR_AND_OBJ entries should not be
7185 // marked as MEMBER_OF.
7186 ShouldBeMemberOf = false;
7187 }
7188 }
7189
7190 Types.push_back(Flags);
Samuel Antao03a3cec2016-07-27 22:52:16 +00007191 }
7192
Alexey Bataevb3638132018-07-19 16:34:13 +00007193 // If we have encountered a member expression so far, keep track of the
7194 // mapped member. If the parent is "*this", then the value declaration
7195 // is nullptr.
7196 if (EncounteredME) {
7197 const auto *FD = dyn_cast<FieldDecl>(EncounteredME->getMemberDecl());
7198 unsigned FieldIndex = FD->getFieldIndex();
Samuel Antao03a3cec2016-07-27 22:52:16 +00007199
Alexey Bataevb3638132018-07-19 16:34:13 +00007200 // Update info about the lowest and highest elements for this struct
7201 if (!PartialStruct.Base.isValid()) {
7202 PartialStruct.LowestElem = {FieldIndex, LB};
7203 PartialStruct.HighestElem = {FieldIndex, LB};
7204 PartialStruct.Base = BP;
7205 } else if (FieldIndex < PartialStruct.LowestElem.first) {
7206 PartialStruct.LowestElem = {FieldIndex, LB};
7207 } else if (FieldIndex > PartialStruct.HighestElem.first) {
7208 PartialStruct.HighestElem = {FieldIndex, LB};
7209 }
7210 }
Samuel Antao86ace552016-04-27 22:40:57 +00007211
7212 // If we have a final array section, we are done with this expression.
7213 if (IsFinalArraySection)
7214 break;
7215
7216 // The pointer becomes the base for the next element.
7217 if (Next != CE)
7218 BP = LB;
7219
7220 IsExpressionFirstInfo = false;
7221 IsCaptureFirstInfo = false;
Samuel Antao86ace552016-04-27 22:40:57 +00007222 }
7223 }
7224 }
7225
Alexey Bataevb3638132018-07-19 16:34:13 +00007226 /// Return the adjusted map modifiers if the declaration a capture refers to
7227 /// appears in a first-private clause. This is expected to be used only with
7228 /// directives that start with 'target'.
7229 MappableExprsHandler::OpenMPOffloadMappingFlags
7230 getMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap) const {
7231 assert(Cap.capturesVariable() && "Expected capture by reference only!");
7232
7233 // A first private variable captured by reference will use only the
7234 // 'private ptr' and 'map to' flag. Return the right flags if the captured
7235 // declaration is known as first-private in this handler.
7236 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
7237 return MappableExprsHandler::OMP_MAP_PRIVATE |
7238 MappableExprsHandler::OMP_MAP_TO;
7239 return MappableExprsHandler::OMP_MAP_TO |
7240 MappableExprsHandler::OMP_MAP_FROM;
7241 }
7242
7243 static OpenMPOffloadMappingFlags getMemberOfFlag(unsigned Position) {
7244 // Member of is given by the 16 MSB of the flag, so rotate by 48 bits.
7245 return static_cast<OpenMPOffloadMappingFlags>(((uint64_t)Position + 1)
7246 << 48);
7247 }
7248
7249 static void setCorrectMemberOfFlag(OpenMPOffloadMappingFlags &Flags,
7250 OpenMPOffloadMappingFlags MemberOfFlag) {
7251 // If the entry is PTR_AND_OBJ but has not been marked with the special
7252 // placeholder value 0xFFFF in the MEMBER_OF field, then it should not be
7253 // marked as MEMBER_OF.
7254 if ((Flags & OMP_MAP_PTR_AND_OBJ) &&
7255 ((Flags & OMP_MAP_MEMBER_OF) != OMP_MAP_MEMBER_OF))
7256 return;
7257
7258 // Reset the placeholder value to prepare the flag for the assignment of the
7259 // proper MEMBER_OF value.
7260 Flags &= ~OMP_MAP_MEMBER_OF;
7261 Flags |= MemberOfFlag;
7262 }
7263
Alexey Bataeve82445f2018-09-20 13:54:02 +00007264 void getPlainLayout(const CXXRecordDecl *RD,
7265 llvm::SmallVectorImpl<const FieldDecl *> &Layout,
7266 bool AsBase) const {
7267 const CGRecordLayout &RL = CGF.getTypes().getCGRecordLayout(RD);
7268
7269 llvm::StructType *St =
7270 AsBase ? RL.getBaseSubobjectLLVMType() : RL.getLLVMType();
7271
7272 unsigned NumElements = St->getNumElements();
7273 llvm::SmallVector<
7274 llvm::PointerUnion<const CXXRecordDecl *, const FieldDecl *>, 4>
7275 RecordLayout(NumElements);
7276
7277 // Fill bases.
7278 for (const auto &I : RD->bases()) {
7279 if (I.isVirtual())
7280 continue;
7281 const auto *Base = I.getType()->getAsCXXRecordDecl();
7282 // Ignore empty bases.
7283 if (Base->isEmpty() || CGF.getContext()
7284 .getASTRecordLayout(Base)
7285 .getNonVirtualSize()
7286 .isZero())
7287 continue;
7288
7289 unsigned FieldIndex = RL.getNonVirtualBaseLLVMFieldNo(Base);
7290 RecordLayout[FieldIndex] = Base;
7291 }
7292 // Fill in virtual bases.
7293 for (const auto &I : RD->vbases()) {
7294 const auto *Base = I.getType()->getAsCXXRecordDecl();
7295 // Ignore empty bases.
7296 if (Base->isEmpty())
7297 continue;
7298 unsigned FieldIndex = RL.getVirtualBaseIndex(Base);
7299 if (RecordLayout[FieldIndex])
7300 continue;
7301 RecordLayout[FieldIndex] = Base;
7302 }
7303 // Fill in all the fields.
7304 assert(!RD->isUnion() && "Unexpected union.");
7305 for (const auto *Field : RD->fields()) {
7306 // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
7307 // will fill in later.)
7308 if (!Field->isBitField()) {
7309 unsigned FieldIndex = RL.getLLVMFieldNo(Field);
7310 RecordLayout[FieldIndex] = Field;
7311 }
7312 }
7313 for (const llvm::PointerUnion<const CXXRecordDecl *, const FieldDecl *>
7314 &Data : RecordLayout) {
7315 if (Data.isNull())
7316 continue;
7317 if (const auto *Base = Data.dyn_cast<const CXXRecordDecl *>())
7318 getPlainLayout(Base, Layout, /*AsBase=*/true);
7319 else
7320 Layout.push_back(Data.get<const FieldDecl *>());
7321 }
7322 }
7323
Alexey Bataevb3638132018-07-19 16:34:13 +00007324public:
7325 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
7326 : CurDir(Dir), CGF(CGF) {
7327 // Extract firstprivate clause information.
7328 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
7329 for (const auto *D : C->varlists())
7330 FirstPrivateDecls.insert(
7331 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
7332 // Extract device pointer clause information.
7333 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
7334 for (auto L : C->component_lists())
7335 DevPointersMap[L.first].push_back(L.second);
7336 }
7337
7338 /// Generate code for the combined entry if we have a partially mapped struct
7339 /// and take care of the mapping flags of the arguments corresponding to
7340 /// individual struct members.
7341 void emitCombinedEntry(MapBaseValuesArrayTy &BasePointers,
7342 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7343 MapFlagsArrayTy &Types, MapFlagsArrayTy &CurTypes,
7344 const StructRangeInfoTy &PartialStruct) const {
7345 // Base is the base of the struct
7346 BasePointers.push_back(PartialStruct.Base.getPointer());
7347 // Pointer is the address of the lowest element
7348 llvm::Value *LB = PartialStruct.LowestElem.second.getPointer();
7349 Pointers.push_back(LB);
7350 // Size is (addr of {highest+1} element) - (addr of lowest element)
7351 llvm::Value *HB = PartialStruct.HighestElem.second.getPointer();
7352 llvm::Value *HAddr = CGF.Builder.CreateConstGEP1_32(HB, /*Idx0=*/1);
7353 llvm::Value *CLAddr = CGF.Builder.CreatePointerCast(LB, CGF.VoidPtrTy);
7354 llvm::Value *CHAddr = CGF.Builder.CreatePointerCast(HAddr, CGF.VoidPtrTy);
7355 llvm::Value *Diff = CGF.Builder.CreatePtrDiff(CHAddr, CLAddr);
7356 llvm::Value *Size = CGF.Builder.CreateIntCast(Diff, CGF.SizeTy,
7357 /*isSinged=*/false);
7358 Sizes.push_back(Size);
7359 // Map type is always TARGET_PARAM
7360 Types.push_back(OMP_MAP_TARGET_PARAM);
7361 // Remove TARGET_PARAM flag from the first element
7362 (*CurTypes.begin()) &= ~OMP_MAP_TARGET_PARAM;
7363
7364 // All other current entries will be MEMBER_OF the combined entry
7365 // (except for PTR_AND_OBJ entries which do not have a placeholder value
7366 // 0xFFFF in the MEMBER_OF field).
7367 OpenMPOffloadMappingFlags MemberOfFlag =
7368 getMemberOfFlag(BasePointers.size() - 1);
7369 for (auto &M : CurTypes)
7370 setCorrectMemberOfFlag(M, MemberOfFlag);
7371 }
7372
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007373 /// Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00007374 /// types for the extracted mappable expressions. Also, for each item that
7375 /// relates with a device pointer, a pair of the relevant declaration and
7376 /// index where it occurs is appended to the device pointers info array.
7377 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007378 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7379 MapFlagsArrayTy &Types) const {
Samuel Antao86ace552016-04-27 22:40:57 +00007380 // We have to process the component lists that relate with the same
7381 // declaration in a single chunk so that we can generate the map flags
7382 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00007383 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00007384
7385 // Helper function to fill the information map for the different supported
7386 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00007387 auto &&InfoGen = [&Info](
7388 const ValueDecl *D,
7389 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
7390 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Alexey Bataevb3638132018-07-19 16:34:13 +00007391 bool ReturnDevicePointer, bool IsImplicit) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007392 const ValueDecl *VD =
7393 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007394 Info[VD].emplace_back(L, MapType, MapModifier, ReturnDevicePointer,
7395 IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007396 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00007397
Paul Robinson78fb1322016-08-01 22:12:46 +00007398 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007399 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
7400 for (const auto &L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00007401 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
Alexey Bataevb3638132018-07-19 16:34:13 +00007402 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007403 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007404 for (const auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
7405 for (const auto &L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00007406 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
Alexey Bataevb3638132018-07-19 16:34:13 +00007407 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007408 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007409 for (const auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
7410 for (const auto &L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00007411 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
Alexey Bataevb3638132018-07-19 16:34:13 +00007412 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007413 }
Samuel Antao86ace552016-04-27 22:40:57 +00007414
Samuel Antaocc10b852016-07-28 14:23:26 +00007415 // Look at the use_device_ptr clause information and mark the existing map
7416 // entries as such. If there is no map information for an entry in the
7417 // use_device_ptr list, we create one with map type 'alloc' and zero size
Alexey Bataevb3638132018-07-19 16:34:13 +00007418 // section. It is the user fault if that was not mapped before. If there is
7419 // no map information and the pointer is a struct member, then we defer the
7420 // emission of that entry until the whole struct has been processed.
7421 llvm::MapVector<const ValueDecl *, SmallVector<DeferredDevicePtrEntryTy, 4>>
7422 DeferredInfo;
7423
Paul Robinson78fb1322016-08-01 22:12:46 +00007424 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataevb3638132018-07-19 16:34:13 +00007425 for (const auto *C :
7426 this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007427 for (const auto &L : C->component_lists()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007428 assert(!L.second.empty() && "Not expecting empty list of components!");
7429 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
7430 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007431 const Expr *IE = L.second.back().getAssociatedExpression();
Samuel Antaocc10b852016-07-28 14:23:26 +00007432 // If the first component is a member expression, we have to look into
7433 // 'this', which maps to null in the map of map information. Otherwise
7434 // look directly for the information.
7435 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
7436
7437 // We potentially have map information for this declaration already.
7438 // Look for the first set of components that refer to it.
7439 if (It != Info.end()) {
7440 auto CI = std::find_if(
7441 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
7442 return MI.Components.back().getAssociatedDeclaration() == VD;
7443 });
7444 // If we found a map entry, signal that the pointer has to be returned
7445 // and move on to the next declaration.
7446 if (CI != It->second.end()) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007447 CI->ReturnDevicePointer = true;
Samuel Antaocc10b852016-07-28 14:23:26 +00007448 continue;
7449 }
7450 }
7451
7452 // We didn't find any match in our map information - generate a zero
Alexey Bataevb3638132018-07-19 16:34:13 +00007453 // size array section - if the pointer is a struct member we defer this
7454 // action until the whole struct has been processed.
Paul Robinson78fb1322016-08-01 22:12:46 +00007455 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Alexey Bataevb3638132018-07-19 16:34:13 +00007456 if (isa<MemberExpr>(IE)) {
7457 // Insert the pointer into Info to be processed by
7458 // generateInfoForComponentList. Because it is a member pointer
7459 // without a pointee, no entry will be generated for it, therefore
7460 // we need to generate one after the whole struct has been processed.
7461 // Nonetheless, generateInfoForComponentList must be called to take
7462 // the pointer into account for the calculation of the range of the
7463 // partial struct.
7464 InfoGen(nullptr, L.second, OMPC_MAP_unknown, OMPC_MAP_unknown,
7465 /*ReturnDevicePointer=*/false, C->isImplicit());
7466 DeferredInfo[nullptr].emplace_back(IE, VD);
7467 } else {
7468 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(
7469 this->CGF.EmitLValue(IE), IE->getExprLoc());
7470 BasePointers.emplace_back(Ptr, VD);
7471 Pointers.push_back(Ptr);
7472 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
7473 Types.push_back(OMP_MAP_RETURN_PARAM | OMP_MAP_TARGET_PARAM);
7474 }
Samuel Antaocc10b852016-07-28 14:23:26 +00007475 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007476 }
Samuel Antaocc10b852016-07-28 14:23:26 +00007477
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007478 for (const auto &M : Info) {
Samuel Antao86ace552016-04-27 22:40:57 +00007479 // We need to know when we generate information for the first component
7480 // associated with a capture, because the mapping flags depend on it.
7481 bool IsFirstComponentList = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00007482
7483 // Temporary versions of arrays
7484 MapBaseValuesArrayTy CurBasePointers;
7485 MapValuesArrayTy CurPointers;
7486 MapValuesArrayTy CurSizes;
7487 MapFlagsArrayTy CurTypes;
7488 StructRangeInfoTy PartialStruct;
7489
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007490 for (const MapInfo &L : M.second) {
Samuel Antao86ace552016-04-27 22:40:57 +00007491 assert(!L.Components.empty() &&
7492 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00007493
7494 // Remember the current base pointer index.
Alexey Bataevb3638132018-07-19 16:34:13 +00007495 unsigned CurrentBasePointersIdx = CurBasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00007496 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007497 this->generateInfoForComponentList(
Alexey Bataevb3638132018-07-19 16:34:13 +00007498 L.MapType, L.MapTypeModifier, L.Components, CurBasePointers,
7499 CurPointers, CurSizes, CurTypes, PartialStruct,
7500 IsFirstComponentList, L.IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007501
7502 // If this entry relates with a device pointer, set the relevant
7503 // declaration and add the 'return pointer' flag.
Alexey Bataevb3638132018-07-19 16:34:13 +00007504 if (L.ReturnDevicePointer) {
7505 assert(CurBasePointers.size() > CurrentBasePointersIdx &&
Samuel Antaocc10b852016-07-28 14:23:26 +00007506 "Unexpected number of mapped base pointers.");
7507
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007508 const ValueDecl *RelevantVD =
7509 L.Components.back().getAssociatedDeclaration();
Samuel Antaocc10b852016-07-28 14:23:26 +00007510 assert(RelevantVD &&
7511 "No relevant declaration related with device pointer??");
7512
Alexey Bataevb3638132018-07-19 16:34:13 +00007513 CurBasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
7514 CurTypes[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PARAM;
Samuel Antaocc10b852016-07-28 14:23:26 +00007515 }
Samuel Antao86ace552016-04-27 22:40:57 +00007516 IsFirstComponentList = false;
7517 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007518
7519 // Append any pending zero-length pointers which are struct members and
7520 // used with use_device_ptr.
7521 auto CI = DeferredInfo.find(M.first);
7522 if (CI != DeferredInfo.end()) {
7523 for (const DeferredDevicePtrEntryTy &L : CI->second) {
7524 llvm::Value *BasePtr = this->CGF.EmitLValue(L.IE).getPointer();
7525 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(
7526 this->CGF.EmitLValue(L.IE), L.IE->getExprLoc());
7527 CurBasePointers.emplace_back(BasePtr, L.VD);
7528 CurPointers.push_back(Ptr);
7529 CurSizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
7530 // Entry is PTR_AND_OBJ and RETURN_PARAM. Also, set the placeholder
7531 // value MEMBER_OF=FFFF so that the entry is later updated with the
7532 // correct value of MEMBER_OF.
7533 CurTypes.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_RETURN_PARAM |
7534 OMP_MAP_MEMBER_OF);
7535 }
7536 }
7537
7538 // If there is an entry in PartialStruct it means we have a struct with
7539 // individual members mapped. Emit an extra combined entry.
7540 if (PartialStruct.Base.isValid())
7541 emitCombinedEntry(BasePointers, Pointers, Sizes, Types, CurTypes,
7542 PartialStruct);
7543
7544 // We need to append the results of this capture to what we already have.
7545 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
7546 Pointers.append(CurPointers.begin(), CurPointers.end());
7547 Sizes.append(CurSizes.begin(), CurSizes.end());
7548 Types.append(CurTypes.begin(), CurTypes.end());
Samuel Antao86ace552016-04-27 22:40:57 +00007549 }
7550 }
7551
Alexey Bataev60705422018-10-30 15:50:12 +00007552 /// Emit capture info for lambdas for variables captured by reference.
Alexey Bataev969dbc02018-11-08 15:47:39 +00007553 void generateInfoForLambdaCaptures(
7554 const ValueDecl *VD, llvm::Value *Arg, MapBaseValuesArrayTy &BasePointers,
7555 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7556 MapFlagsArrayTy &Types,
7557 llvm::DenseMap<llvm::Value *, llvm::Value *> &LambdaPointers) const {
Alexey Bataev60705422018-10-30 15:50:12 +00007558 const auto *RD = VD->getType()
7559 .getCanonicalType()
7560 .getNonReferenceType()
7561 ->getAsCXXRecordDecl();
7562 if (!RD || !RD->isLambda())
7563 return;
7564 Address VDAddr = Address(Arg, CGF.getContext().getDeclAlign(VD));
7565 LValue VDLVal = CGF.MakeAddrLValue(
7566 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
7567 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
7568 FieldDecl *ThisCapture = nullptr;
7569 RD->getCaptureFields(Captures, ThisCapture);
7570 if (ThisCapture) {
7571 LValue ThisLVal =
7572 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
Alexey Bataev969dbc02018-11-08 15:47:39 +00007573 LValue ThisLValVal = CGF.EmitLValueForField(VDLVal, ThisCapture);
7574 LambdaPointers.try_emplace(ThisLVal.getPointer(), VDLVal.getPointer());
7575 BasePointers.push_back(ThisLVal.getPointer());
7576 Pointers.push_back(ThisLValVal.getPointer());
Alexey Bataev60705422018-10-30 15:50:12 +00007577 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
Alexey Bataev2dc07d02018-11-02 15:25:06 +00007578 Types.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
Alexey Bataev60705422018-10-30 15:50:12 +00007579 OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT);
7580 }
7581 for (const LambdaCapture &LC : RD->captures()) {
7582 if (LC.getCaptureKind() != LCK_ByRef)
7583 continue;
7584 const VarDecl *VD = LC.getCapturedVar();
7585 auto It = Captures.find(VD);
7586 assert(It != Captures.end() && "Found lambda capture without field.");
7587 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
Alexey Bataev969dbc02018-11-08 15:47:39 +00007588 LValue VarLValVal = CGF.EmitLValueForField(VDLVal, It->second);
7589 LambdaPointers.try_emplace(VarLVal.getPointer(), VDLVal.getPointer());
7590 BasePointers.push_back(VarLVal.getPointer());
7591 Pointers.push_back(VarLValVal.getPointer());
Alexey Bataev60705422018-10-30 15:50:12 +00007592 Sizes.push_back(CGF.getTypeSize(
7593 VD->getType().getCanonicalType().getNonReferenceType()));
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 }
7598
7599 /// Set correct indices for lambdas captures.
Alexey Bataev969dbc02018-11-08 15:47:39 +00007600 void adjustMemberOfForLambdaCaptures(
7601 const llvm::DenseMap<llvm::Value *, llvm::Value *> &LambdaPointers,
7602 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
7603 MapFlagsArrayTy &Types) const {
Alexey Bataev60705422018-10-30 15:50:12 +00007604 for (unsigned I = 0, E = Types.size(); I < E; ++I) {
7605 // Set correct member_of idx for all implicit lambda captures.
Alexey Bataev2dc07d02018-11-02 15:25:06 +00007606 if (Types[I] != (OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
Alexey Bataev60705422018-10-30 15:50:12 +00007607 OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT))
7608 continue;
Alexey Bataev969dbc02018-11-08 15:47:39 +00007609 llvm::Value *BasePtr = LambdaPointers.lookup(*BasePointers[I]);
7610 assert(BasePtr && "Unable to find base lambda address.");
Alexey Bataev60705422018-10-30 15:50:12 +00007611 int TgtIdx = -1;
7612 for (unsigned J = I; J > 0; --J) {
7613 unsigned Idx = J - 1;
7614 if (Pointers[Idx] != BasePtr)
7615 continue;
7616 TgtIdx = Idx;
7617 break;
7618 }
7619 assert(TgtIdx != -1 && "Unable to find parent lambda.");
7620 // All other current entries will be MEMBER_OF the combined entry
7621 // (except for PTR_AND_OBJ entries which do not have a placeholder value
7622 // 0xFFFF in the MEMBER_OF field).
7623 OpenMPOffloadMappingFlags MemberOfFlag = getMemberOfFlag(TgtIdx);
7624 setCorrectMemberOfFlag(Types[I], MemberOfFlag);
7625 }
7626 }
7627
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007628 /// Generate the base pointers, section pointers, sizes and map types
Samuel Antao86ace552016-04-27 22:40:57 +00007629 /// associated to a given capture.
7630 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00007631 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007632 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007633 MapValuesArrayTy &Pointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007634 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
7635 StructRangeInfoTy &PartialStruct) const {
Samuel Antao86ace552016-04-27 22:40:57 +00007636 assert(!Cap->capturesVariableArrayType() &&
7637 "Not expecting to generate map info for a variable array type!");
7638
Samuel Antao6890b092016-07-28 14:25:09 +00007639 // We need to know when we generating information for the first component
Alexey Bataevb3638132018-07-19 16:34:13 +00007640 const ValueDecl *VD = Cap->capturesThis()
7641 ? nullptr
7642 : Cap->getCapturedVar()->getCanonicalDecl();
Samuel Antao86ace552016-04-27 22:40:57 +00007643
Samuel Antao6890b092016-07-28 14:25:09 +00007644 // If this declaration appears in a is_device_ptr clause we just have to
7645 // pass the pointer by value. If it is a reference to a declaration, we just
Alexey Bataevb3638132018-07-19 16:34:13 +00007646 // pass its value.
7647 if (DevPointersMap.count(VD)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007648 BasePointers.emplace_back(Arg, VD);
Samuel Antao6890b092016-07-28 14:25:09 +00007649 Pointers.push_back(Arg);
7650 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
George Rokos065755d2017-11-07 18:27:04 +00007651 Types.push_back(OMP_MAP_LITERAL | OMP_MAP_TARGET_PARAM);
Samuel Antao6890b092016-07-28 14:25:09 +00007652 return;
7653 }
7654
Alexey Bataeve82445f2018-09-20 13:54:02 +00007655 using MapData =
7656 std::tuple<OMPClauseMappableExprCommon::MappableExprComponentListRef,
7657 OpenMPMapClauseKind, OpenMPMapClauseKind, bool>;
7658 SmallVector<MapData, 4> DeclComponentLists;
Paul Robinson78fb1322016-08-01 22:12:46 +00007659 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeve82445f2018-09-20 13:54:02 +00007660 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007661 for (const auto &L : C->decl_component_lists(VD)) {
Samuel Antao86ace552016-04-27 22:40:57 +00007662 assert(L.first == VD &&
7663 "We got information for the wrong declaration??");
7664 assert(!L.second.empty() &&
7665 "Not expecting declaration with no component lists.");
Alexey Bataeve82445f2018-09-20 13:54:02 +00007666 DeclComponentLists.emplace_back(L.second, C->getMapType(),
7667 C->getMapTypeModifier(),
7668 C->isImplicit());
Samuel Antao86ace552016-04-27 22:40:57 +00007669 }
Alexey Bataeve82445f2018-09-20 13:54:02 +00007670 }
7671
7672 // Find overlapping elements (including the offset from the base element).
7673 llvm::SmallDenseMap<
7674 const MapData *,
7675 llvm::SmallVector<
7676 OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>,
7677 4>
7678 OverlappedData;
7679 size_t Count = 0;
7680 for (const MapData &L : DeclComponentLists) {
7681 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7682 OpenMPMapClauseKind MapType;
7683 OpenMPMapClauseKind MapTypeModifier;
7684 bool IsImplicit;
7685 std::tie(Components, MapType, MapTypeModifier, IsImplicit) = L;
7686 ++Count;
7687 for (const MapData &L1 : makeArrayRef(DeclComponentLists).slice(Count)) {
7688 OMPClauseMappableExprCommon::MappableExprComponentListRef Components1;
7689 std::tie(Components1, MapType, MapTypeModifier, IsImplicit) = L1;
7690 auto CI = Components.rbegin();
7691 auto CE = Components.rend();
7692 auto SI = Components1.rbegin();
7693 auto SE = Components1.rend();
7694 for (; CI != CE && SI != SE; ++CI, ++SI) {
7695 if (CI->getAssociatedExpression()->getStmtClass() !=
7696 SI->getAssociatedExpression()->getStmtClass())
7697 break;
7698 // Are we dealing with different variables/fields?
7699 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
7700 break;
7701 }
7702 // Found overlapping if, at least for one component, reached the head of
7703 // the components list.
7704 if (CI == CE || SI == SE) {
7705 assert((CI != CE || SI != SE) &&
7706 "Unexpected full match of the mapping components.");
7707 const MapData &BaseData = CI == CE ? L : L1;
7708 OMPClauseMappableExprCommon::MappableExprComponentListRef SubData =
7709 SI == SE ? Components : Components1;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007710 auto &OverlappedElements = OverlappedData.FindAndConstruct(&BaseData);
7711 OverlappedElements.getSecond().push_back(SubData);
7712 }
7713 }
7714 }
7715 // Sort the overlapped elements for each item.
7716 llvm::SmallVector<const FieldDecl *, 4> Layout;
7717 if (!OverlappedData.empty()) {
7718 if (const auto *CRD =
7719 VD->getType().getCanonicalType()->getAsCXXRecordDecl())
7720 getPlainLayout(CRD, Layout, /*AsBase=*/false);
7721 else {
7722 const auto *RD = VD->getType().getCanonicalType()->getAsRecordDecl();
7723 Layout.append(RD->field_begin(), RD->field_end());
7724 }
7725 }
7726 for (auto &Pair : OverlappedData) {
7727 llvm::sort(
7728 Pair.getSecond(),
7729 [&Layout](
7730 OMPClauseMappableExprCommon::MappableExprComponentListRef First,
7731 OMPClauseMappableExprCommon::MappableExprComponentListRef
7732 Second) {
7733 auto CI = First.rbegin();
7734 auto CE = First.rend();
7735 auto SI = Second.rbegin();
7736 auto SE = Second.rend();
7737 for (; CI != CE && SI != SE; ++CI, ++SI) {
7738 if (CI->getAssociatedExpression()->getStmtClass() !=
7739 SI->getAssociatedExpression()->getStmtClass())
7740 break;
7741 // Are we dealing with different variables/fields?
7742 if (CI->getAssociatedDeclaration() !=
7743 SI->getAssociatedDeclaration())
7744 break;
7745 }
Richard Trieu5061e832018-09-21 21:20:33 +00007746
7747 // Lists contain the same elements.
7748 if (CI == CE && SI == SE)
7749 return false;
7750
7751 // List with less elements is less than list with more elements.
7752 if (CI == CE || SI == SE)
7753 return CI == CE;
7754
Alexey Bataeve82445f2018-09-20 13:54:02 +00007755 const auto *FD1 = cast<FieldDecl>(CI->getAssociatedDeclaration());
7756 const auto *FD2 = cast<FieldDecl>(SI->getAssociatedDeclaration());
7757 if (FD1->getParent() == FD2->getParent())
7758 return FD1->getFieldIndex() < FD2->getFieldIndex();
7759 const auto It =
7760 llvm::find_if(Layout, [FD1, FD2](const FieldDecl *FD) {
7761 return FD == FD1 || FD == FD2;
7762 });
7763 return *It == FD1;
7764 });
7765 }
7766
7767 // Associated with a capture, because the mapping flags depend on it.
7768 // Go through all of the elements with the overlapped elements.
7769 for (const auto &Pair : OverlappedData) {
7770 const MapData &L = *Pair.getFirst();
7771 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7772 OpenMPMapClauseKind MapType;
7773 OpenMPMapClauseKind MapTypeModifier;
7774 bool IsImplicit;
7775 std::tie(Components, MapType, MapTypeModifier, IsImplicit) = L;
7776 ArrayRef<OMPClauseMappableExprCommon::MappableExprComponentListRef>
7777 OverlappedComponents = Pair.getSecond();
7778 bool IsFirstComponentList = true;
7779 generateInfoForComponentList(MapType, MapTypeModifier, Components,
7780 BasePointers, Pointers, Sizes, Types,
7781 PartialStruct, IsFirstComponentList,
7782 IsImplicit, OverlappedComponents);
7783 }
7784 // Go through other elements without overlapped elements.
7785 bool IsFirstComponentList = OverlappedData.empty();
7786 for (const MapData &L : DeclComponentLists) {
7787 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7788 OpenMPMapClauseKind MapType;
7789 OpenMPMapClauseKind MapTypeModifier;
7790 bool IsImplicit;
7791 std::tie(Components, MapType, MapTypeModifier, IsImplicit) = L;
7792 auto It = OverlappedData.find(&L);
7793 if (It == OverlappedData.end())
7794 generateInfoForComponentList(MapType, MapTypeModifier, Components,
7795 BasePointers, Pointers, Sizes, Types,
7796 PartialStruct, IsFirstComponentList,
7797 IsImplicit);
7798 IsFirstComponentList = false;
7799 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007800 }
Samuel Antao86ace552016-04-27 22:40:57 +00007801
Alexey Bataevb3638132018-07-19 16:34:13 +00007802 /// Generate the base pointers, section pointers, sizes and map types
7803 /// associated with the declare target link variables.
7804 void generateInfoForDeclareTargetLink(MapBaseValuesArrayTy &BasePointers,
7805 MapValuesArrayTy &Pointers,
7806 MapValuesArrayTy &Sizes,
7807 MapFlagsArrayTy &Types) const {
7808 // Map other list items in the map clause which are not captured variables
7809 // but "declare target link" global variables.,
7810 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) {
7811 for (const auto &L : C->component_lists()) {
7812 if (!L.first)
7813 continue;
7814 const auto *VD = dyn_cast<VarDecl>(L.first);
7815 if (!VD)
7816 continue;
7817 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00007818 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataevb3638132018-07-19 16:34:13 +00007819 if (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link)
7820 continue;
7821 StructRangeInfoTy PartialStruct;
7822 generateInfoForComponentList(
7823 C->getMapType(), C->getMapTypeModifier(), L.second, BasePointers,
7824 Pointers, Sizes, Types, PartialStruct,
7825 /*IsFirstComponentList=*/true, C->isImplicit());
7826 assert(!PartialStruct.Base.isValid() &&
7827 "No partial structs for declare target link expected.");
7828 }
7829 }
Samuel Antao86ace552016-04-27 22:40:57 +00007830 }
Samuel Antaod486f842016-05-26 16:53:38 +00007831
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007832 /// Generate the default map information for a given capture \a CI,
Samuel Antaod486f842016-05-26 16:53:38 +00007833 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00007834 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
7835 const FieldDecl &RI, llvm::Value *CV,
7836 MapBaseValuesArrayTy &CurBasePointers,
7837 MapValuesArrayTy &CurPointers,
7838 MapValuesArrayTy &CurSizes,
Alexey Bataevb3638132018-07-19 16:34:13 +00007839 MapFlagsArrayTy &CurMapTypes) const {
Samuel Antaod486f842016-05-26 16:53:38 +00007840 // Do the default mapping.
7841 if (CI.capturesThis()) {
7842 CurBasePointers.push_back(CV);
7843 CurPointers.push_back(CV);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007844 const auto *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007845 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
7846 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00007847 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00007848 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007849 CurBasePointers.push_back(CV);
7850 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00007851 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007852 // We have to signal to the runtime captures passed by value that are
7853 // not pointers.
George Rokos065755d2017-11-07 18:27:04 +00007854 CurMapTypes.push_back(OMP_MAP_LITERAL);
Samuel Antaod486f842016-05-26 16:53:38 +00007855 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
7856 } else {
7857 // Pointers are implicitly mapped with a zero size and no flags
7858 // (other than first map that is added for all implicit maps).
Alexey Bataevb3638132018-07-19 16:34:13 +00007859 CurMapTypes.push_back(OMP_MAP_NONE);
Samuel Antaod486f842016-05-26 16:53:38 +00007860 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
7861 }
7862 } else {
7863 assert(CI.capturesVariable() && "Expected captured reference.");
7864 CurBasePointers.push_back(CV);
7865 CurPointers.push_back(CV);
7866
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007867 const auto *PtrTy = cast<ReferenceType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007868 QualType ElementType = PtrTy->getPointeeType();
7869 CurSizes.push_back(CGF.getTypeSize(ElementType));
7870 // The default map type for a scalar/complex type is 'to' because by
7871 // default the value doesn't have to be retrieved. For an aggregate
7872 // type, the default is 'tofrom'.
Alexey Bataevb3638132018-07-19 16:34:13 +00007873 CurMapTypes.push_back(getMapModifiersForPrivateClauses(CI));
Samuel Antaod486f842016-05-26 16:53:38 +00007874 }
George Rokos065755d2017-11-07 18:27:04 +00007875 // Every default map produces a single argument which is a target parameter.
7876 CurMapTypes.back() |= OMP_MAP_TARGET_PARAM;
Alexey Bataevb3638132018-07-19 16:34:13 +00007877
7878 // Add flag stating this is an implicit map.
7879 CurMapTypes.back() |= OMP_MAP_IMPLICIT;
Samuel Antaod486f842016-05-26 16:53:38 +00007880 }
Samuel Antao86ace552016-04-27 22:40:57 +00007881};
Samuel Antaodf158d52016-04-27 22:58:19 +00007882
7883enum OpenMPOffloadingReservedDeviceIDs {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007884 /// Device ID if the device was not defined, runtime should get it
Samuel Antaodf158d52016-04-27 22:58:19 +00007885 /// from environment variables in the spec.
7886 OMP_DEVICEID_UNDEF = -1,
7887};
7888} // anonymous namespace
7889
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007890/// Emit the arrays used to pass the captures and map information to the
Samuel Antaodf158d52016-04-27 22:58:19 +00007891/// offloading runtime library. If there is no map or capture information,
7892/// return nullptr by reference.
7893static void
Samuel Antaocc10b852016-07-28 14:23:26 +00007894emitOffloadingArrays(CodeGenFunction &CGF,
7895 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00007896 MappableExprsHandler::MapValuesArrayTy &Pointers,
7897 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00007898 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
7899 CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007900 CodeGenModule &CGM = CGF.CGM;
7901 ASTContext &Ctx = CGF.getContext();
Samuel Antaodf158d52016-04-27 22:58:19 +00007902
Samuel Antaocc10b852016-07-28 14:23:26 +00007903 // Reset the array information.
7904 Info.clearArrayInfo();
7905 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00007906
Samuel Antaocc10b852016-07-28 14:23:26 +00007907 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007908 // Detect if we have any capture size requiring runtime evaluation of the
7909 // size so that a constant array could be eventually used.
7910 bool hasRuntimeEvaluationCaptureSize = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007911 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00007912 if (!isa<llvm::Constant>(S)) {
7913 hasRuntimeEvaluationCaptureSize = true;
7914 break;
7915 }
7916
Samuel Antaocc10b852016-07-28 14:23:26 +00007917 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00007918 QualType PointerArrayType =
7919 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
7920 /*IndexTypeQuals=*/0);
7921
Samuel Antaocc10b852016-07-28 14:23:26 +00007922 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007923 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00007924 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007925 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
7926
7927 // If we don't have any VLA types or other types that require runtime
7928 // evaluation, we can use a constant array for the map sizes, otherwise we
7929 // need to fill up the arrays as we do for the pointers.
7930 if (hasRuntimeEvaluationCaptureSize) {
7931 QualType SizeArrayType = Ctx.getConstantArrayType(
7932 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
7933 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00007934 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007935 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
7936 } else {
7937 // We expect all the sizes to be constant, so we collect them to create
7938 // a constant array.
7939 SmallVector<llvm::Constant *, 16> ConstSizes;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007940 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00007941 ConstSizes.push_back(cast<llvm::Constant>(S));
7942
7943 auto *SizesArrayInit = llvm::ConstantArray::get(
7944 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
Alexey Bataev18fa2322018-05-02 14:20:50 +00007945 std::string Name = CGM.getOpenMPRuntime().getName({"offload_sizes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00007946 auto *SizesArrayGbl = new llvm::GlobalVariable(
7947 CGM.getModule(), SizesArrayInit->getType(),
7948 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00007949 SizesArrayInit, Name);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00007950 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00007951 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00007952 }
7953
7954 // The map types are always constant so we don't need to generate code to
7955 // fill arrays. Instead, we create an array constant.
Alexey Bataevb3638132018-07-19 16:34:13 +00007956 SmallVector<uint64_t, 4> Mapping(MapTypes.size(), 0);
7957 llvm::copy(MapTypes, Mapping.begin());
Samuel Antaodf158d52016-04-27 22:58:19 +00007958 llvm::Constant *MapTypesArrayInit =
Alexey Bataevb3638132018-07-19 16:34:13 +00007959 llvm::ConstantDataArray::get(CGF.Builder.getContext(), Mapping);
Alexey Bataev18fa2322018-05-02 14:20:50 +00007960 std::string MaptypesName =
7961 CGM.getOpenMPRuntime().getName({"offload_maptypes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00007962 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
7963 CGM.getModule(), MapTypesArrayInit->getType(),
7964 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00007965 MapTypesArrayInit, MaptypesName);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00007966 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00007967 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00007968
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007969 for (unsigned I = 0; I < Info.NumberOfPtrs; ++I) {
7970 llvm::Value *BPVal = *BasePointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00007971 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007972 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007973 Info.BasePointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00007974 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7975 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00007976 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
7977 CGF.Builder.CreateStore(BPVal, BPAddr);
7978
Samuel Antaocc10b852016-07-28 14:23:26 +00007979 if (Info.requiresDevicePointerInfo())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007980 if (const ValueDecl *DevVD = BasePointers[I].getDevicePtrDecl())
Alexey Bataev43a919f2018-04-13 17:48:43 +00007981 Info.CaptureDeviceAddrMap.try_emplace(DevVD, BPAddr);
Samuel Antaocc10b852016-07-28 14:23:26 +00007982
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007983 llvm::Value *PVal = Pointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00007984 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007985 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007986 Info.PointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00007987 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7988 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00007989 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
7990 CGF.Builder.CreateStore(PVal, PAddr);
7991
7992 if (hasRuntimeEvaluationCaptureSize) {
7993 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007994 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
7995 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007996 /*Idx0=*/0,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007997 /*Idx1=*/I);
Samuel Antaodf158d52016-04-27 22:58:19 +00007998 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
7999 CGF.Builder.CreateStore(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008000 CGF.Builder.CreateIntCast(Sizes[I], CGM.SizeTy, /*isSigned=*/true),
Samuel Antaodf158d52016-04-27 22:58:19 +00008001 SAddr);
8002 }
8003 }
8004 }
8005}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008006/// Emit the arguments to be passed to the runtime library based on the
Samuel Antaodf158d52016-04-27 22:58:19 +00008007/// arrays of pointers, sizes and map types.
8008static void emitOffloadingArraysArgument(
8009 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
8010 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008011 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008012 CodeGenModule &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00008013 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008014 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008015 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
8016 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008017 /*Idx0=*/0, /*Idx1=*/0);
8018 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008019 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
8020 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008021 /*Idx0=*/0,
8022 /*Idx1=*/0);
8023 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008024 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008025 /*Idx0=*/0, /*Idx1=*/0);
8026 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
George Rokos63bc9d62017-11-21 18:25:12 +00008027 llvm::ArrayType::get(CGM.Int64Ty, Info.NumberOfPtrs),
Samuel Antaocc10b852016-07-28 14:23:26 +00008028 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008029 /*Idx0=*/0,
8030 /*Idx1=*/0);
8031 } else {
8032 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
8033 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
8034 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
8035 MapTypesArrayArg =
George Rokos63bc9d62017-11-21 18:25:12 +00008036 llvm::ConstantPointerNull::get(CGM.Int64Ty->getPointerTo());
Samuel Antaodf158d52016-04-27 22:58:19 +00008037 }
Samuel Antao86ace552016-04-27 22:40:57 +00008038}
8039
Samuel Antaobed3c462015-10-02 16:14:20 +00008040void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
8041 const OMPExecutableDirective &D,
8042 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00008043 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00008044 const Expr *IfCond, const Expr *Device) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00008045 if (!CGF.HaveInsertPoint())
8046 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00008047
Samuel Antaoee8fb302016-01-06 13:42:12 +00008048 assert(OutlinedFn && "Invalid outlined function!");
8049
Alexey Bataev8451efa2018-01-15 19:06:12 +00008050 const bool RequiresOuterTask = D.hasClausesOfKind<OMPDependClause>();
8051 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Alexey Bataev475a7442018-01-12 19:39:11 +00008052 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008053 auto &&ArgsCodegen = [&CS, &CapturedVars](CodeGenFunction &CGF,
8054 PrePostActionTy &) {
8055 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
8056 };
8057 emitInlinedDirective(CGF, OMPD_unknown, ArgsCodegen);
Samuel Antao86ace552016-04-27 22:40:57 +00008058
Alexey Bataev8451efa2018-01-15 19:06:12 +00008059 CodeGenFunction::OMPTargetDataInfo InputInfo;
8060 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00008061 // Fill up the pointer arrays and transfer execution to the device.
Alexey Bataev8451efa2018-01-15 19:06:12 +00008062 auto &&ThenGen = [this, Device, OutlinedFn, OutlinedFnID, &D, &InputInfo,
8063 &MapTypesArray, &CS, RequiresOuterTask,
8064 &CapturedVars](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobed3c462015-10-02 16:14:20 +00008065 // On top of the arrays that were filled up, the target offloading call
8066 // takes as arguments the device id as well as the host pointer. The host
8067 // pointer is used by the runtime library to identify the current target
8068 // region, so it only has to be unique and not necessarily point to
8069 // anything. It could be the pointer to the outlined function that
8070 // implements the target region, but we aren't using that so that the
8071 // compiler doesn't need to keep that, and could therefore inline the host
8072 // function if proven worthwhile during optimization.
8073
Samuel Antaoee8fb302016-01-06 13:42:12 +00008074 // From this point on, we need to have an ID of the target region defined.
8075 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00008076
8077 // Emit device ID if any.
8078 llvm::Value *DeviceID;
George Rokos63bc9d62017-11-21 18:25:12 +00008079 if (Device) {
Samuel Antaobed3c462015-10-02 16:14:20 +00008080 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008081 CGF.Int64Ty, /*isSigned=*/true);
8082 } else {
8083 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8084 }
Samuel Antaobed3c462015-10-02 16:14:20 +00008085
Samuel Antaodf158d52016-04-27 22:58:19 +00008086 // Emit the number of elements in the offloading arrays.
Alexey Bataev8451efa2018-01-15 19:06:12 +00008087 llvm::Value *PointerNum =
8088 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaodf158d52016-04-27 22:58:19 +00008089
Samuel Antaob68e2db2016-03-03 16:20:23 +00008090 // Return value of the runtime offloading call.
8091 llvm::Value *Return;
8092
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008093 llvm::Value *NumTeams = emitNumTeamsForTargetDirective(*this, CGF, D);
8094 llvm::Value *NumThreads = emitNumThreadsForTargetDirective(*this, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00008095
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008096 bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008097 // The target region is an outlined function launched by the runtime
8098 // via calls __tgt_target() or __tgt_target_teams().
8099 //
8100 // __tgt_target() launches a target region with one team and one thread,
8101 // executing a serial region. This master thread may in turn launch
8102 // more threads within its team upon encountering a parallel region,
8103 // however, no additional teams can be launched on the device.
8104 //
8105 // __tgt_target_teams() launches a target region with one or more teams,
8106 // each with one or more threads. This call is required for target
8107 // constructs such as:
8108 // 'target teams'
8109 // 'target' / 'teams'
8110 // 'target teams distribute parallel for'
8111 // 'target parallel'
8112 // and so on.
8113 //
8114 // Note that on the host and CPU targets, the runtime implementation of
8115 // these calls simply call the outlined function without forking threads.
8116 // The outlined functions themselves have runtime calls to
8117 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
8118 // the compiler in emitTeamsCall() and emitParallelCall().
8119 //
8120 // In contrast, on the NVPTX target, the implementation of
8121 // __tgt_target_teams() launches a GPU kernel with the requested number
8122 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00008123 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008124 // If we have NumTeams defined this means that we have an enclosed teams
8125 // region. Therefore we also expect to have NumThreads defined. These two
8126 // values should be defined in the presence of a teams directive,
8127 // regardless of having any clauses associated. If the user is using teams
8128 // but no clauses, these two values will be the default that should be
8129 // passed to the runtime library - a 32-bit integer with the value zero.
8130 assert(NumThreads && "Thread limit expression should be available along "
8131 "with number of teams.");
Alexey Bataev8451efa2018-01-15 19:06:12 +00008132 llvm::Value *OffloadingArgs[] = {DeviceID,
8133 OutlinedFnID,
8134 PointerNum,
8135 InputInfo.BasePointersArray.getPointer(),
8136 InputInfo.PointersArray.getPointer(),
8137 InputInfo.SizesArray.getPointer(),
8138 MapTypesArray,
8139 NumTeams,
8140 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00008141 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00008142 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_teams_nowait
8143 : OMPRTL__tgt_target_teams),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008144 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00008145 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00008146 llvm::Value *OffloadingArgs[] = {DeviceID,
8147 OutlinedFnID,
8148 PointerNum,
8149 InputInfo.BasePointersArray.getPointer(),
8150 InputInfo.PointersArray.getPointer(),
8151 InputInfo.SizesArray.getPointer(),
8152 MapTypesArray};
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008153 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00008154 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_nowait
8155 : OMPRTL__tgt_target),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008156 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00008157 }
Samuel Antaobed3c462015-10-02 16:14:20 +00008158
Alexey Bataev2a007e02017-10-02 14:20:58 +00008159 // Check the error code and execute the host version if required.
8160 llvm::BasicBlock *OffloadFailedBlock =
8161 CGF.createBasicBlock("omp_offload.failed");
8162 llvm::BasicBlock *OffloadContBlock =
8163 CGF.createBasicBlock("omp_offload.cont");
8164 llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
8165 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
8166
8167 CGF.EmitBlock(OffloadFailedBlock);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008168 if (RequiresOuterTask) {
8169 CapturedVars.clear();
8170 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
8171 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008172 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars);
Alexey Bataev2a007e02017-10-02 14:20:58 +00008173 CGF.EmitBranch(OffloadContBlock);
8174
8175 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00008176 };
8177
Samuel Antaoee8fb302016-01-06 13:42:12 +00008178 // Notify that the host version must be executed.
Alexey Bataev8451efa2018-01-15 19:06:12 +00008179 auto &&ElseGen = [this, &D, OutlinedFn, &CS, &CapturedVars,
8180 RequiresOuterTask](CodeGenFunction &CGF,
8181 PrePostActionTy &) {
8182 if (RequiresOuterTask) {
8183 CapturedVars.clear();
8184 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
8185 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008186 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008187 };
8188
8189 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray,
8190 &CapturedVars, RequiresOuterTask,
8191 &CS](CodeGenFunction &CGF, PrePostActionTy &) {
8192 // Fill up the arrays with all the captured variables.
8193 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
8194 MappableExprsHandler::MapValuesArrayTy Pointers;
8195 MappableExprsHandler::MapValuesArrayTy Sizes;
8196 MappableExprsHandler::MapFlagsArrayTy MapTypes;
8197
Alexey Bataev8451efa2018-01-15 19:06:12 +00008198 // Get mappable expression information.
8199 MappableExprsHandler MEHandler(D, CGF);
Alexey Bataev969dbc02018-11-08 15:47:39 +00008200 llvm::DenseMap<llvm::Value *, llvm::Value *> LambdaPointers;
Alexey Bataev8451efa2018-01-15 19:06:12 +00008201
8202 auto RI = CS.getCapturedRecordDecl()->field_begin();
8203 auto CV = CapturedVars.begin();
8204 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
8205 CE = CS.capture_end();
8206 CI != CE; ++CI, ++RI, ++CV) {
Alexey Bataevb3638132018-07-19 16:34:13 +00008207 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
8208 MappableExprsHandler::MapValuesArrayTy CurPointers;
8209 MappableExprsHandler::MapValuesArrayTy CurSizes;
8210 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
8211 MappableExprsHandler::StructRangeInfoTy PartialStruct;
Alexey Bataev8451efa2018-01-15 19:06:12 +00008212
8213 // VLA sizes are passed to the outlined region by copy and do not have map
8214 // information associated.
8215 if (CI->capturesVariableArrayType()) {
8216 CurBasePointers.push_back(*CV);
8217 CurPointers.push_back(*CV);
8218 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
8219 // Copy to the device as an argument. No need to retrieve it.
8220 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_LITERAL |
8221 MappableExprsHandler::OMP_MAP_TARGET_PARAM);
8222 } else {
8223 // If we have any information in the map clause, we use it, otherwise we
8224 // just do a default mapping.
8225 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00008226 CurSizes, CurMapTypes, PartialStruct);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008227 if (CurBasePointers.empty())
8228 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
8229 CurPointers, CurSizes, CurMapTypes);
Alexey Bataev60705422018-10-30 15:50:12 +00008230 // Generate correct mapping for variables captured by reference in
8231 // lambdas.
8232 if (CI->capturesVariable())
Alexey Bataev969dbc02018-11-08 15:47:39 +00008233 MEHandler.generateInfoForLambdaCaptures(
8234 CI->getCapturedVar(), *CV, CurBasePointers, CurPointers, CurSizes,
8235 CurMapTypes, LambdaPointers);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008236 }
8237 // We expect to have at least an element of information for this capture.
8238 assert(!CurBasePointers.empty() &&
8239 "Non-existing map pointer for capture!");
8240 assert(CurBasePointers.size() == CurPointers.size() &&
8241 CurBasePointers.size() == CurSizes.size() &&
8242 CurBasePointers.size() == CurMapTypes.size() &&
8243 "Inconsistent map information sizes!");
8244
Alexey Bataevb3638132018-07-19 16:34:13 +00008245 // If there is an entry in PartialStruct it means we have a struct with
8246 // individual members mapped. Emit an extra combined entry.
8247 if (PartialStruct.Base.isValid())
8248 MEHandler.emitCombinedEntry(BasePointers, Pointers, Sizes, MapTypes,
8249 CurMapTypes, PartialStruct);
8250
Alexey Bataev8451efa2018-01-15 19:06:12 +00008251 // We need to append the results of this capture to what we already have.
8252 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
8253 Pointers.append(CurPointers.begin(), CurPointers.end());
8254 Sizes.append(CurSizes.begin(), CurSizes.end());
8255 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
8256 }
Alexey Bataev60705422018-10-30 15:50:12 +00008257 // Adjust MEMBER_OF flags for the lambdas captures.
Alexey Bataev969dbc02018-11-08 15:47:39 +00008258 MEHandler.adjustMemberOfForLambdaCaptures(LambdaPointers, BasePointers,
8259 Pointers, MapTypes);
Alexey Bataev92327c52018-03-26 16:40:55 +00008260 // Map other list items in the map clause which are not captured variables
8261 // but "declare target link" global variables.
Alexey Bataevb3638132018-07-19 16:34:13 +00008262 MEHandler.generateInfoForDeclareTargetLink(BasePointers, Pointers, Sizes,
8263 MapTypes);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008264
8265 TargetDataInfo Info;
8266 // Fill up the arrays and create the arguments.
8267 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
8268 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
8269 Info.PointersArray, Info.SizesArray,
8270 Info.MapTypesArray, Info);
8271 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
8272 InputInfo.BasePointersArray =
8273 Address(Info.BasePointersArray, CGM.getPointerAlign());
8274 InputInfo.PointersArray =
8275 Address(Info.PointersArray, CGM.getPointerAlign());
8276 InputInfo.SizesArray = Address(Info.SizesArray, CGM.getPointerAlign());
8277 MapTypesArray = Info.MapTypesArray;
8278 if (RequiresOuterTask)
8279 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
8280 else
8281 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
8282 };
8283
8284 auto &&TargetElseGen = [this, &ElseGen, &D, RequiresOuterTask](
8285 CodeGenFunction &CGF, PrePostActionTy &) {
8286 if (RequiresOuterTask) {
8287 CodeGenFunction::OMPTargetDataInfo InputInfo;
8288 CGF.EmitOMPTargetTaskBasedDirective(D, ElseGen, InputInfo);
8289 } else {
8290 emitInlinedDirective(CGF, D.getDirectiveKind(), ElseGen);
8291 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00008292 };
8293
8294 // If we have a target function ID it means that we need to support
8295 // offloading, otherwise, just execute on the host. We need to execute on host
8296 // regardless of the conditional in the if clause if, e.g., the user do not
8297 // specify target triples.
8298 if (OutlinedFnID) {
Alexey Bataev8451efa2018-01-15 19:06:12 +00008299 if (IfCond) {
8300 emitOMPIfClause(CGF, IfCond, TargetThenGen, TargetElseGen);
8301 } else {
8302 RegionCodeGenTy ThenRCG(TargetThenGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00008303 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00008304 }
8305 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00008306 RegionCodeGenTy ElseRCG(TargetElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00008307 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00008308 }
Samuel Antaobed3c462015-10-02 16:14:20 +00008309}
Samuel Antaoee8fb302016-01-06 13:42:12 +00008310
8311void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
8312 StringRef ParentName) {
8313 if (!S)
8314 return;
8315
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008316 // Codegen OMP target directives that offload compute to the device.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008317 bool RequiresDeviceCodegen =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008318 isa<OMPExecutableDirective>(S) &&
8319 isOpenMPTargetExecutionDirective(
8320 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00008321
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008322 if (RequiresDeviceCodegen) {
8323 const auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008324 unsigned DeviceID;
8325 unsigned FileID;
8326 unsigned Line;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008327 getTargetEntryUniqueInfo(CGM.getContext(), E.getBeginLoc(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00008328 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008329
8330 // Is this a target region that should not be emitted as an entry point? If
8331 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00008332 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
8333 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008334 return;
8335
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008336 switch (E.getDirectiveKind()) {
8337 case OMPD_target:
8338 CodeGenFunction::EmitOMPTargetDeviceFunction(CGM, ParentName,
8339 cast<OMPTargetDirective>(E));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008340 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008341 case OMPD_target_parallel:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00008342 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008343 CGM, ParentName, cast<OMPTargetParallelDirective>(E));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00008344 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008345 case OMPD_target_teams:
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00008346 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008347 CGM, ParentName, cast<OMPTargetTeamsDirective>(E));
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00008348 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008349 case OMPD_target_teams_distribute:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008350 CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008351 CGM, ParentName, cast<OMPTargetTeamsDistributeDirective>(E));
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008352 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008353 case OMPD_target_teams_distribute_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008354 CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008355 CGM, ParentName, cast<OMPTargetTeamsDistributeSimdDirective>(E));
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008356 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008357 case OMPD_target_parallel_for:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008358 CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008359 CGM, ParentName, cast<OMPTargetParallelForDirective>(E));
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008360 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008361 case OMPD_target_parallel_for_simd:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008362 CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008363 CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(E));
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008364 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008365 case OMPD_target_simd:
Alexey Bataevf8365372017-11-17 17:57:25 +00008366 CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008367 CGM, ParentName, cast<OMPTargetSimdDirective>(E));
Alexey Bataevf8365372017-11-17 17:57:25 +00008368 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008369 case OMPD_target_teams_distribute_parallel_for:
Carlo Bertolli52978c32018-01-03 21:12:44 +00008370 CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
8371 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008372 cast<OMPTargetTeamsDistributeParallelForDirective>(E));
Carlo Bertolli52978c32018-01-03 21:12:44 +00008373 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008374 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00008375 CodeGenFunction::
8376 EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
8377 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008378 cast<OMPTargetTeamsDistributeParallelForSimdDirective>(E));
Alexey Bataev647dd842018-01-15 20:59:40 +00008379 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008380 case OMPD_parallel:
8381 case OMPD_for:
8382 case OMPD_parallel_for:
8383 case OMPD_parallel_sections:
8384 case OMPD_for_simd:
8385 case OMPD_parallel_for_simd:
8386 case OMPD_cancel:
8387 case OMPD_cancellation_point:
8388 case OMPD_ordered:
8389 case OMPD_threadprivate:
8390 case OMPD_task:
8391 case OMPD_simd:
8392 case OMPD_sections:
8393 case OMPD_section:
8394 case OMPD_single:
8395 case OMPD_master:
8396 case OMPD_critical:
8397 case OMPD_taskyield:
8398 case OMPD_barrier:
8399 case OMPD_taskwait:
8400 case OMPD_taskgroup:
8401 case OMPD_atomic:
8402 case OMPD_flush:
8403 case OMPD_teams:
8404 case OMPD_target_data:
8405 case OMPD_target_exit_data:
8406 case OMPD_target_enter_data:
8407 case OMPD_distribute:
8408 case OMPD_distribute_simd:
8409 case OMPD_distribute_parallel_for:
8410 case OMPD_distribute_parallel_for_simd:
8411 case OMPD_teams_distribute:
8412 case OMPD_teams_distribute_simd:
8413 case OMPD_teams_distribute_parallel_for:
8414 case OMPD_teams_distribute_parallel_for_simd:
8415 case OMPD_target_update:
8416 case OMPD_declare_simd:
8417 case OMPD_declare_target:
8418 case OMPD_end_declare_target:
8419 case OMPD_declare_reduction:
8420 case OMPD_taskloop:
8421 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008422 case OMPD_requires:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008423 case OMPD_unknown:
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008424 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
8425 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00008426 return;
8427 }
8428
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008429 if (const auto *E = dyn_cast<OMPExecutableDirective>(S)) {
Alexey Bataev475a7442018-01-12 19:39:11 +00008430 if (!E->hasAssociatedStmt() || !E->getAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00008431 return;
8432
8433 scanForTargetRegionsFunctions(
Alexey Bataev475a7442018-01-12 19:39:11 +00008434 E->getInnermostCapturedStmt()->getCapturedStmt(), ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008435 return;
8436 }
8437
8438 // If this is a lambda function, look into its body.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008439 if (const auto *L = dyn_cast<LambdaExpr>(S))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008440 S = L->getBody();
8441
8442 // Keep looking for target regions recursively.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008443 for (const Stmt *II : S->children())
Samuel Antaoee8fb302016-01-06 13:42:12 +00008444 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008445}
8446
8447bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008448 // If emitting code for the host, we do not process FD here. Instead we do
8449 // the normal code generation.
8450 if (!CGM.getLangOpts().OpenMPIsDevice)
8451 return false;
8452
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008453 const ValueDecl *VD = cast<ValueDecl>(GD.getDecl());
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008454 StringRef Name = CGM.getMangledName(GD);
8455 // Try to detect target regions in the function.
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008456 if (const auto *FD = dyn_cast<FunctionDecl>(VD))
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008457 scanForTargetRegionsFunctions(FD->getBody(), Name);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008458
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008459 // Do not to emit function if it is not marked as declare target.
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008460 return !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008461 AlreadyEmittedTargetFunctions.count(Name) == 0;
Samuel Antaoee8fb302016-01-06 13:42:12 +00008462}
8463
8464bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
8465 if (!CGM.getLangOpts().OpenMPIsDevice)
8466 return false;
8467
8468 // Check if there are Ctors/Dtors in this declaration and look for target
8469 // regions in it. We use the complete variant to produce the kernel name
8470 // mangling.
8471 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008472 if (const auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
8473 for (const CXXConstructorDecl *Ctor : RD->ctors()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008474 StringRef ParentName =
8475 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
8476 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
8477 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008478 if (const CXXDestructorDecl *Dtor = RD->getDestructor()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008479 StringRef ParentName =
8480 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
8481 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
8482 }
8483 }
8484
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008485 // Do not to emit variable if it is not marked as declare target.
Alexey Bataev92327c52018-03-26 16:40:55 +00008486 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00008487 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
8488 cast<VarDecl>(GD.getDecl()));
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008489 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Alexey Bataevd01b7492018-08-15 19:45:12 +00008490 DeferredGlobalVariables.insert(cast<VarDecl>(GD.getDecl()));
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008491 return true;
8492 }
8493 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00008494}
8495
Alexey Bataev03f270c2018-03-30 18:31:07 +00008496void CGOpenMPRuntime::registerTargetGlobalVariable(const VarDecl *VD,
8497 llvm::Constant *Addr) {
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008498 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
8499 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
8500 if (!Res) {
8501 if (CGM.getLangOpts().OpenMPIsDevice) {
8502 // Register non-target variables being emitted in device code (debug info
8503 // may cause this).
8504 StringRef VarName = CGM.getMangledName(VD);
8505 EmittedNonTargetVariables.try_emplace(VarName, Addr);
Alexey Bataev03f270c2018-03-30 18:31:07 +00008506 }
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008507 return;
Alexey Bataev03f270c2018-03-30 18:31:07 +00008508 }
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008509 // Register declare target variables.
8510 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags;
8511 StringRef VarName;
8512 CharUnits VarSize;
8513 llvm::GlobalValue::LinkageTypes Linkage;
8514 switch (*Res) {
8515 case OMPDeclareTargetDeclAttr::MT_To:
8516 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo;
8517 VarName = CGM.getMangledName(VD);
8518 if (VD->hasDefinition(CGM.getContext()) != VarDecl::DeclarationOnly) {
8519 VarSize = CGM.getContext().getTypeSizeInChars(VD->getType());
8520 assert(!VarSize.isZero() && "Expected non-zero size of the variable");
8521 } else {
8522 VarSize = CharUnits::Zero();
8523 }
8524 Linkage = CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false);
8525 // Temp solution to prevent optimizations of the internal variables.
8526 if (CGM.getLangOpts().OpenMPIsDevice && !VD->isExternallyVisible()) {
8527 std::string RefName = getName({VarName, "ref"});
8528 if (!CGM.GetGlobalValue(RefName)) {
8529 llvm::Constant *AddrRef =
8530 getOrCreateInternalVariable(Addr->getType(), RefName);
8531 auto *GVAddrRef = cast<llvm::GlobalVariable>(AddrRef);
8532 GVAddrRef->setConstant(/*Val=*/true);
8533 GVAddrRef->setLinkage(llvm::GlobalValue::InternalLinkage);
8534 GVAddrRef->setInitializer(Addr);
8535 CGM.addCompilerUsedGlobal(GVAddrRef);
8536 }
8537 }
8538 break;
8539 case OMPDeclareTargetDeclAttr::MT_Link:
8540 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink;
8541 if (CGM.getLangOpts().OpenMPIsDevice) {
8542 VarName = Addr->getName();
8543 Addr = nullptr;
8544 } else {
8545 VarName = getAddrOfDeclareTargetLink(VD).getName();
8546 Addr = cast<llvm::Constant>(getAddrOfDeclareTargetLink(VD).getPointer());
8547 }
8548 VarSize = CGM.getPointerSize();
8549 Linkage = llvm::GlobalValue::WeakAnyLinkage;
8550 break;
8551 }
8552 OffloadEntriesInfoManager.registerDeviceGlobalVarEntryInfo(
8553 VarName, Addr, VarSize, Flags, Linkage);
Alexey Bataev03f270c2018-03-30 18:31:07 +00008554}
8555
Samuel Antaoee8fb302016-01-06 13:42:12 +00008556bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008557 if (isa<FunctionDecl>(GD.getDecl()) ||
8558 isa<OMPDeclareReductionDecl>(GD.getDecl()))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008559 return emitTargetFunctions(GD);
8560
8561 return emitTargetGlobalVariable(GD);
8562}
8563
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008564void CGOpenMPRuntime::emitDeferredTargetDecls() const {
8565 for (const VarDecl *VD : DeferredGlobalVariables) {
8566 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00008567 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataevd01b7492018-08-15 19:45:12 +00008568 if (!Res)
8569 continue;
8570 if (*Res == OMPDeclareTargetDeclAttr::MT_To) {
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008571 CGM.EmitGlobal(VD);
Alexey Bataevd01b7492018-08-15 19:45:12 +00008572 } else {
8573 assert(*Res == OMPDeclareTargetDeclAttr::MT_Link &&
8574 "Expected to or link clauses.");
8575 (void)CGM.getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008576 }
8577 }
8578}
8579
Alexey Bataev60705422018-10-30 15:50:12 +00008580void CGOpenMPRuntime::adjustTargetSpecificDataForLambdas(
8581 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
8582 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
8583 " Expected target-based directive.");
8584}
8585
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008586CGOpenMPRuntime::DisableAutoDeclareTargetRAII::DisableAutoDeclareTargetRAII(
8587 CodeGenModule &CGM)
8588 : CGM(CGM) {
8589 if (CGM.getLangOpts().OpenMPIsDevice) {
8590 SavedShouldMarkAsGlobal = CGM.getOpenMPRuntime().ShouldMarkAsGlobal;
8591 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = false;
8592 }
8593}
8594
8595CGOpenMPRuntime::DisableAutoDeclareTargetRAII::~DisableAutoDeclareTargetRAII() {
8596 if (CGM.getLangOpts().OpenMPIsDevice)
8597 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = SavedShouldMarkAsGlobal;
8598}
8599
Alexey Bataev6d944102018-05-02 15:45:28 +00008600bool CGOpenMPRuntime::markAsGlobalTarget(GlobalDecl GD) {
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008601 if (!CGM.getLangOpts().OpenMPIsDevice || !ShouldMarkAsGlobal)
8602 return true;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008603
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008604 StringRef Name = CGM.getMangledName(GD);
Alexey Bataev6d944102018-05-02 15:45:28 +00008605 const auto *D = cast<FunctionDecl>(GD.getDecl());
Alexey Bataev34f8a702018-03-28 14:28:54 +00008606 // Do not to emit function if it is marked as declare target as it was already
8607 // emitted.
Alexey Bataev97b72212018-08-14 18:31:20 +00008608 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(D)) {
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008609 if (D->hasBody() && AlreadyEmittedTargetFunctions.count(Name) == 0) {
8610 if (auto *F = dyn_cast_or_null<llvm::Function>(CGM.GetGlobalValue(Name)))
Alexey Bataev34f8a702018-03-28 14:28:54 +00008611 return !F->isDeclaration();
8612 return false;
8613 }
8614 return true;
8615 }
8616
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008617 return !AlreadyEmittedTargetFunctions.insert(Name).second;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008618}
8619
Samuel Antaoee8fb302016-01-06 13:42:12 +00008620llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
8621 // If we have offloading in the current module, we need to emit the entries
8622 // now and register the offloading descriptor.
8623 createOffloadEntriesAndInfoMetadata();
8624
8625 // Create and register the offloading binary descriptors. This is the main
8626 // entity that captures all the information about offloading in the current
8627 // compilation unit.
8628 return createOffloadingBinaryDescriptorRegistration();
8629}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008630
8631void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
8632 const OMPExecutableDirective &D,
8633 SourceLocation Loc,
8634 llvm::Value *OutlinedFn,
8635 ArrayRef<llvm::Value *> CapturedVars) {
8636 if (!CGF.HaveInsertPoint())
8637 return;
8638
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008639 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008640 CodeGenFunction::RunCleanupsScope Scope(CGF);
8641
8642 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
8643 llvm::Value *Args[] = {
8644 RTLoc,
8645 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
8646 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
8647 llvm::SmallVector<llvm::Value *, 16> RealArgs;
8648 RealArgs.append(std::begin(Args), std::end(Args));
8649 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
8650
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008651 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008652 CGF.EmitRuntimeCall(RTLFn, RealArgs);
8653}
8654
8655void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00008656 const Expr *NumTeams,
8657 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008658 SourceLocation Loc) {
8659 if (!CGF.HaveInsertPoint())
8660 return;
8661
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008662 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008663
Carlo Bertollic6872252016-04-04 15:55:02 +00008664 llvm::Value *NumTeamsVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008665 NumTeams
Carlo Bertollic6872252016-04-04 15:55:02 +00008666 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
8667 CGF.CGM.Int32Ty, /* isSigned = */ true)
8668 : CGF.Builder.getInt32(0);
8669
8670 llvm::Value *ThreadLimitVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008671 ThreadLimit
Carlo Bertollic6872252016-04-04 15:55:02 +00008672 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
8673 CGF.CGM.Int32Ty, /* isSigned = */ true)
8674 : CGF.Builder.getInt32(0);
8675
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008676 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00008677 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
8678 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008679 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
8680 PushNumTeamsArgs);
8681}
Samuel Antaodf158d52016-04-27 22:58:19 +00008682
Samuel Antaocc10b852016-07-28 14:23:26 +00008683void CGOpenMPRuntime::emitTargetDataCalls(
8684 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8685 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008686 if (!CGF.HaveInsertPoint())
8687 return;
8688
Samuel Antaocc10b852016-07-28 14:23:26 +00008689 // Action used to replace the default codegen action and turn privatization
8690 // off.
8691 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00008692
8693 // Generate the code for the opening of the data environment. Capture all the
8694 // arguments of the runtime call by reference because they are used in the
8695 // closing of the region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008696 auto &&BeginThenGen = [this, &D, Device, &Info,
8697 &CodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008698 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00008699 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00008700 MappableExprsHandler::MapValuesArrayTy Pointers;
8701 MappableExprsHandler::MapValuesArrayTy Sizes;
8702 MappableExprsHandler::MapFlagsArrayTy MapTypes;
8703
8704 // Get map clause information.
8705 MappableExprsHandler MCHandler(D, CGF);
8706 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00008707
8708 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00008709 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008710
8711 llvm::Value *BasePointersArrayArg = nullptr;
8712 llvm::Value *PointersArrayArg = nullptr;
8713 llvm::Value *SizesArrayArg = nullptr;
8714 llvm::Value *MapTypesArrayArg = nullptr;
8715 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008716 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008717
8718 // Emit device ID if any.
8719 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008720 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008721 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008722 CGF.Int64Ty, /*isSigned=*/true);
8723 } else {
8724 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8725 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008726
8727 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008728 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00008729
8730 llvm::Value *OffloadingArgs[] = {
8731 DeviceID, PointerNum, BasePointersArrayArg,
8732 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008733 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_begin),
Samuel Antaodf158d52016-04-27 22:58:19 +00008734 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00008735
8736 // If device pointer privatization is required, emit the body of the region
8737 // here. It will have to be duplicated: with and without privatization.
8738 if (!Info.CaptureDeviceAddrMap.empty())
8739 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008740 };
8741
8742 // Generate code for the closing of the data region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008743 auto &&EndThenGen = [this, Device, &Info](CodeGenFunction &CGF,
8744 PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008745 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00008746
8747 llvm::Value *BasePointersArrayArg = nullptr;
8748 llvm::Value *PointersArrayArg = nullptr;
8749 llvm::Value *SizesArrayArg = nullptr;
8750 llvm::Value *MapTypesArrayArg = nullptr;
8751 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008752 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008753
8754 // Emit device ID if any.
8755 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008756 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008757 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008758 CGF.Int64Ty, /*isSigned=*/true);
8759 } else {
8760 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8761 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008762
8763 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008764 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00008765
8766 llvm::Value *OffloadingArgs[] = {
8767 DeviceID, PointerNum, BasePointersArrayArg,
8768 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008769 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_end),
Samuel Antaodf158d52016-04-27 22:58:19 +00008770 OffloadingArgs);
8771 };
8772
Samuel Antaocc10b852016-07-28 14:23:26 +00008773 // If we need device pointer privatization, we need to emit the body of the
8774 // region with no privatization in the 'else' branch of the conditional.
8775 // Otherwise, we don't have to do anything.
8776 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
8777 PrePostActionTy &) {
8778 if (!Info.CaptureDeviceAddrMap.empty()) {
8779 CodeGen.setAction(NoPrivAction);
8780 CodeGen(CGF);
8781 }
8782 };
8783
8784 // We don't have to do anything to close the region if the if clause evaluates
8785 // to false.
8786 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00008787
8788 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008789 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00008790 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00008791 RegionCodeGenTy RCG(BeginThenGen);
8792 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008793 }
8794
Samuel Antaocc10b852016-07-28 14:23:26 +00008795 // If we don't require privatization of device pointers, we emit the body in
8796 // between the runtime calls. This avoids duplicating the body code.
8797 if (Info.CaptureDeviceAddrMap.empty()) {
8798 CodeGen.setAction(NoPrivAction);
8799 CodeGen(CGF);
8800 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008801
8802 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008803 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00008804 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00008805 RegionCodeGenTy RCG(EndThenGen);
8806 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008807 }
8808}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008809
Samuel Antao8d2d7302016-05-26 18:30:22 +00008810void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00008811 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8812 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008813 if (!CGF.HaveInsertPoint())
8814 return;
8815
Samuel Antao8dd66282016-04-27 23:14:30 +00008816 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00008817 isa<OMPTargetExitDataDirective>(D) ||
8818 isa<OMPTargetUpdateDirective>(D)) &&
8819 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00008820
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008821 CodeGenFunction::OMPTargetDataInfo InputInfo;
8822 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008823 // Generate the code for the opening of the data environment.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008824 auto &&ThenGen = [this, &D, Device, &InputInfo,
8825 &MapTypesArray](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008826 // Emit device ID if any.
8827 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008828 if (Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008829 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008830 CGF.Int64Ty, /*isSigned=*/true);
8831 } else {
8832 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8833 }
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008834
8835 // Emit the number of elements in the offloading arrays.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008836 llvm::Constant *PointerNum =
8837 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008838
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008839 llvm::Value *OffloadingArgs[] = {DeviceID,
8840 PointerNum,
8841 InputInfo.BasePointersArray.getPointer(),
8842 InputInfo.PointersArray.getPointer(),
8843 InputInfo.SizesArray.getPointer(),
8844 MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00008845
Samuel Antao8d2d7302016-05-26 18:30:22 +00008846 // Select the right runtime function call for each expected standalone
8847 // directive.
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008848 const bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Samuel Antao8d2d7302016-05-26 18:30:22 +00008849 OpenMPRTLFunction RTLFn;
8850 switch (D.getDirectiveKind()) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00008851 case OMPD_target_enter_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008852 RTLFn = HasNowait ? OMPRTL__tgt_target_data_begin_nowait
8853 : OMPRTL__tgt_target_data_begin;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008854 break;
8855 case OMPD_target_exit_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008856 RTLFn = HasNowait ? OMPRTL__tgt_target_data_end_nowait
8857 : OMPRTL__tgt_target_data_end;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008858 break;
8859 case OMPD_target_update:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008860 RTLFn = HasNowait ? OMPRTL__tgt_target_data_update_nowait
8861 : OMPRTL__tgt_target_data_update;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008862 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008863 case OMPD_parallel:
8864 case OMPD_for:
8865 case OMPD_parallel_for:
8866 case OMPD_parallel_sections:
8867 case OMPD_for_simd:
8868 case OMPD_parallel_for_simd:
8869 case OMPD_cancel:
8870 case OMPD_cancellation_point:
8871 case OMPD_ordered:
8872 case OMPD_threadprivate:
8873 case OMPD_task:
8874 case OMPD_simd:
8875 case OMPD_sections:
8876 case OMPD_section:
8877 case OMPD_single:
8878 case OMPD_master:
8879 case OMPD_critical:
8880 case OMPD_taskyield:
8881 case OMPD_barrier:
8882 case OMPD_taskwait:
8883 case OMPD_taskgroup:
8884 case OMPD_atomic:
8885 case OMPD_flush:
8886 case OMPD_teams:
8887 case OMPD_target_data:
8888 case OMPD_distribute:
8889 case OMPD_distribute_simd:
8890 case OMPD_distribute_parallel_for:
8891 case OMPD_distribute_parallel_for_simd:
8892 case OMPD_teams_distribute:
8893 case OMPD_teams_distribute_simd:
8894 case OMPD_teams_distribute_parallel_for:
8895 case OMPD_teams_distribute_parallel_for_simd:
8896 case OMPD_declare_simd:
8897 case OMPD_declare_target:
8898 case OMPD_end_declare_target:
8899 case OMPD_declare_reduction:
8900 case OMPD_taskloop:
8901 case OMPD_taskloop_simd:
8902 case OMPD_target:
8903 case OMPD_target_simd:
8904 case OMPD_target_teams_distribute:
8905 case OMPD_target_teams_distribute_simd:
8906 case OMPD_target_teams_distribute_parallel_for:
8907 case OMPD_target_teams_distribute_parallel_for_simd:
8908 case OMPD_target_teams:
8909 case OMPD_target_parallel:
8910 case OMPD_target_parallel_for:
8911 case OMPD_target_parallel_for_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008912 case OMPD_requires:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008913 case OMPD_unknown:
8914 llvm_unreachable("Unexpected standalone target data directive.");
8915 break;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008916 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008917 CGF.EmitRuntimeCall(createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008918 };
8919
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008920 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray](
8921 CodeGenFunction &CGF, PrePostActionTy &) {
8922 // Fill up the arrays with all the mapped variables.
8923 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
8924 MappableExprsHandler::MapValuesArrayTy Pointers;
8925 MappableExprsHandler::MapValuesArrayTy Sizes;
8926 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008927
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008928 // Get map clause information.
8929 MappableExprsHandler MEHandler(D, CGF);
8930 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
8931
8932 TargetDataInfo Info;
8933 // Fill up the arrays and create the arguments.
8934 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
8935 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
8936 Info.PointersArray, Info.SizesArray,
8937 Info.MapTypesArray, Info);
8938 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
8939 InputInfo.BasePointersArray =
8940 Address(Info.BasePointersArray, CGM.getPointerAlign());
8941 InputInfo.PointersArray =
8942 Address(Info.PointersArray, CGM.getPointerAlign());
8943 InputInfo.SizesArray =
8944 Address(Info.SizesArray, CGM.getPointerAlign());
8945 MapTypesArray = Info.MapTypesArray;
8946 if (D.hasClausesOfKind<OMPDependClause>())
8947 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
8948 else
Alexey Bataev768f1f22018-01-09 19:59:25 +00008949 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008950 };
8951
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008952 if (IfCond) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008953 emitOMPIfClause(CGF, IfCond, TargetThenGen,
8954 [](CodeGenFunction &CGF, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008955 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008956 RegionCodeGenTy ThenRCG(TargetThenGen);
8957 ThenRCG(CGF);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008958 }
8959}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008960
8961namespace {
8962 /// Kind of parameter in a function with 'declare simd' directive.
8963 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
8964 /// Attribute set of the parameter.
8965 struct ParamAttrTy {
8966 ParamKindTy Kind = Vector;
8967 llvm::APSInt StrideOrArg;
8968 llvm::APSInt Alignment;
8969 };
8970} // namespace
8971
8972static unsigned evaluateCDTSize(const FunctionDecl *FD,
8973 ArrayRef<ParamAttrTy> ParamAttrs) {
8974 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
8975 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
8976 // of that clause. The VLEN value must be power of 2.
8977 // In other case the notion of the function`s "characteristic data type" (CDT)
8978 // is used to compute the vector length.
8979 // CDT is defined in the following order:
8980 // a) For non-void function, the CDT is the return type.
8981 // b) If the function has any non-uniform, non-linear parameters, then the
8982 // CDT is the type of the first such parameter.
8983 // c) If the CDT determined by a) or b) above is struct, union, or class
8984 // type which is pass-by-value (except for the type that maps to the
8985 // built-in complex data type), the characteristic data type is int.
8986 // d) If none of the above three cases is applicable, the CDT is int.
8987 // The VLEN is then determined based on the CDT and the size of vector
8988 // register of that ISA for which current vector version is generated. The
8989 // VLEN is computed using the formula below:
8990 // VLEN = sizeof(vector_register) / sizeof(CDT),
8991 // where vector register size specified in section 3.2.1 Registers and the
8992 // Stack Frame of original AMD64 ABI document.
8993 QualType RetType = FD->getReturnType();
8994 if (RetType.isNull())
8995 return 0;
8996 ASTContext &C = FD->getASTContext();
8997 QualType CDT;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008998 if (!RetType.isNull() && !RetType->isVoidType()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008999 CDT = RetType;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009000 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009001 unsigned Offset = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009002 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009003 if (ParamAttrs[Offset].Kind == Vector)
9004 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
9005 ++Offset;
9006 }
9007 if (CDT.isNull()) {
9008 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
9009 if (ParamAttrs[I + Offset].Kind == Vector) {
9010 CDT = FD->getParamDecl(I)->getType();
9011 break;
9012 }
9013 }
9014 }
9015 }
9016 if (CDT.isNull())
9017 CDT = C.IntTy;
9018 CDT = CDT->getCanonicalTypeUnqualified();
9019 if (CDT->isRecordType() || CDT->isUnionType())
9020 CDT = C.IntTy;
9021 return C.getTypeSize(CDT);
9022}
9023
9024static void
9025emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00009026 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009027 ArrayRef<ParamAttrTy> ParamAttrs,
9028 OMPDeclareSimdDeclAttr::BranchStateTy State) {
9029 struct ISADataTy {
9030 char ISA;
9031 unsigned VecRegSize;
9032 };
9033 ISADataTy ISAData[] = {
9034 {
9035 'b', 128
9036 }, // SSE
9037 {
9038 'c', 256
9039 }, // AVX
9040 {
9041 'd', 256
9042 }, // AVX2
9043 {
9044 'e', 512
9045 }, // AVX512
9046 };
9047 llvm::SmallVector<char, 2> Masked;
9048 switch (State) {
9049 case OMPDeclareSimdDeclAttr::BS_Undefined:
9050 Masked.push_back('N');
9051 Masked.push_back('M');
9052 break;
9053 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
9054 Masked.push_back('N');
9055 break;
9056 case OMPDeclareSimdDeclAttr::BS_Inbranch:
9057 Masked.push_back('M');
9058 break;
9059 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009060 for (char Mask : Masked) {
9061 for (const ISADataTy &Data : ISAData) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009062 SmallString<256> Buffer;
9063 llvm::raw_svector_ostream Out(Buffer);
9064 Out << "_ZGV" << Data.ISA << Mask;
9065 if (!VLENVal) {
9066 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
9067 evaluateCDTSize(FD, ParamAttrs));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009068 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009069 Out << VLENVal;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009070 }
9071 for (const ParamAttrTy &ParamAttr : ParamAttrs) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009072 switch (ParamAttr.Kind){
9073 case LinearWithVarStride:
9074 Out << 's' << ParamAttr.StrideOrArg;
9075 break;
9076 case Linear:
9077 Out << 'l';
9078 if (!!ParamAttr.StrideOrArg)
9079 Out << ParamAttr.StrideOrArg;
9080 break;
9081 case Uniform:
9082 Out << 'u';
9083 break;
9084 case Vector:
9085 Out << 'v';
9086 break;
9087 }
9088 if (!!ParamAttr.Alignment)
9089 Out << 'a' << ParamAttr.Alignment;
9090 }
9091 Out << '_' << Fn->getName();
9092 Fn->addFnAttr(Out.str());
9093 }
9094 }
9095}
9096
9097void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
9098 llvm::Function *Fn) {
9099 ASTContext &C = CGM.getContext();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009100 FD = FD->getMostRecentDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009101 // Map params to their positions in function decl.
9102 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
9103 if (isa<CXXMethodDecl>(FD))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009104 ParamPositions.try_emplace(FD, 0);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009105 unsigned ParamPos = ParamPositions.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009106 for (const ParmVarDecl *P : FD->parameters()) {
9107 ParamPositions.try_emplace(P->getCanonicalDecl(), ParamPos);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009108 ++ParamPos;
9109 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009110 while (FD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009111 for (const auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009112 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
9113 // Mark uniform parameters.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009114 for (const Expr *E : Attr->uniforms()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009115 E = E->IgnoreParenImpCasts();
9116 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009117 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009118 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009119 } else {
9120 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
9121 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009122 Pos = ParamPositions[PVD];
9123 }
9124 ParamAttrs[Pos].Kind = Uniform;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009125 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009126 // Get alignment info.
9127 auto NI = Attr->alignments_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009128 for (const Expr *E : Attr->aligneds()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009129 E = E->IgnoreParenImpCasts();
9130 unsigned Pos;
9131 QualType ParmTy;
9132 if (isa<CXXThisExpr>(E)) {
9133 Pos = ParamPositions[FD];
9134 ParmTy = E->getType();
9135 } else {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009136 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
9137 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009138 Pos = ParamPositions[PVD];
9139 ParmTy = PVD->getType();
9140 }
9141 ParamAttrs[Pos].Alignment =
9142 (*NI)
9143 ? (*NI)->EvaluateKnownConstInt(C)
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009144 : llvm::APSInt::getUnsigned(
9145 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
9146 .getQuantity());
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009147 ++NI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009148 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009149 // Mark linear parameters.
9150 auto SI = Attr->steps_begin();
9151 auto MI = Attr->modifiers_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009152 for (const Expr *E : Attr->linears()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009153 E = E->IgnoreParenImpCasts();
9154 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009155 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009156 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009157 } else {
9158 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
9159 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009160 Pos = ParamPositions[PVD];
9161 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009162 ParamAttrTy &ParamAttr = ParamAttrs[Pos];
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009163 ParamAttr.Kind = Linear;
9164 if (*SI) {
Nico Weber9f0246d2018-11-21 12:47:43 +00009165 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
9166 Expr::SE_AllowSideEffects)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009167 if (const auto *DRE =
9168 cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
9169 if (const auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009170 ParamAttr.Kind = LinearWithVarStride;
9171 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
9172 ParamPositions[StridePVD->getCanonicalDecl()]);
9173 }
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009174 }
9175 }
9176 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009177 ++SI;
9178 ++MI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009179 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009180 llvm::APSInt VLENVal;
9181 if (const Expr *VLEN = Attr->getSimdlen())
9182 VLENVal = VLEN->EvaluateKnownConstInt(C);
9183 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
9184 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
9185 CGM.getTriple().getArch() == llvm::Triple::x86_64)
9186 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009187 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009188 FD = FD->getPreviousDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009189 }
9190}
Alexey Bataev8b427062016-05-25 12:36:08 +00009191
9192namespace {
9193/// Cleanup action for doacross support.
9194class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
9195public:
9196 static const int DoacrossFinArgs = 2;
9197
9198private:
9199 llvm::Value *RTLFn;
9200 llvm::Value *Args[DoacrossFinArgs];
9201
9202public:
9203 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
9204 : RTLFn(RTLFn) {
9205 assert(CallArgs.size() == DoacrossFinArgs);
9206 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
9207 }
9208 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
9209 if (!CGF.HaveInsertPoint())
9210 return;
9211 CGF.EmitRuntimeCall(RTLFn, Args);
9212 }
9213};
9214} // namespace
9215
9216void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
Alexey Bataevf138fda2018-08-13 19:04:24 +00009217 const OMPLoopDirective &D,
9218 ArrayRef<Expr *> NumIterations) {
Alexey Bataev8b427062016-05-25 12:36:08 +00009219 if (!CGF.HaveInsertPoint())
9220 return;
9221
9222 ASTContext &C = CGM.getContext();
9223 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
9224 RecordDecl *RD;
9225 if (KmpDimTy.isNull()) {
9226 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
9227 // kmp_int64 lo; // lower
9228 // kmp_int64 up; // upper
9229 // kmp_int64 st; // stride
9230 // };
9231 RD = C.buildImplicitRecord("kmp_dim");
9232 RD->startDefinition();
9233 addFieldToRecordDecl(C, RD, Int64Ty);
9234 addFieldToRecordDecl(C, RD, Int64Ty);
9235 addFieldToRecordDecl(C, RD, Int64Ty);
9236 RD->completeDefinition();
9237 KmpDimTy = C.getRecordType(RD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009238 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00009239 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009240 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00009241 llvm::APInt Size(/*numBits=*/32, NumIterations.size());
9242 QualType ArrayTy =
9243 C.getConstantArrayType(KmpDimTy, Size, ArrayType::Normal, 0);
Alexey Bataev8b427062016-05-25 12:36:08 +00009244
Alexey Bataevf138fda2018-08-13 19:04:24 +00009245 Address DimsAddr = CGF.CreateMemTemp(ArrayTy, "dims");
9246 CGF.EmitNullInitialization(DimsAddr, ArrayTy);
Alexey Bataev8b427062016-05-25 12:36:08 +00009247 enum { LowerFD = 0, UpperFD, StrideFD };
9248 // Fill dims with data.
Alexey Bataevf138fda2018-08-13 19:04:24 +00009249 for (unsigned I = 0, E = NumIterations.size(); I < E; ++I) {
9250 LValue DimsLVal =
9251 CGF.MakeAddrLValue(CGF.Builder.CreateConstArrayGEP(
9252 DimsAddr, I, C.getTypeSizeInChars(KmpDimTy)),
9253 KmpDimTy);
9254 // dims.upper = num_iterations;
9255 LValue UpperLVal = CGF.EmitLValueForField(
9256 DimsLVal, *std::next(RD->field_begin(), UpperFD));
9257 llvm::Value *NumIterVal =
9258 CGF.EmitScalarConversion(CGF.EmitScalarExpr(NumIterations[I]),
9259 D.getNumIterations()->getType(), Int64Ty,
9260 D.getNumIterations()->getExprLoc());
9261 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
9262 // dims.stride = 1;
9263 LValue StrideLVal = CGF.EmitLValueForField(
9264 DimsLVal, *std::next(RD->field_begin(), StrideFD));
9265 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
9266 StrideLVal);
9267 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009268
9269 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
9270 // kmp_int32 num_dims, struct kmp_dim * dims);
Alexey Bataevf138fda2018-08-13 19:04:24 +00009271 llvm::Value *Args[] = {
9272 emitUpdateLocation(CGF, D.getBeginLoc()),
9273 getThreadID(CGF, D.getBeginLoc()),
9274 llvm::ConstantInt::getSigned(CGM.Int32Ty, NumIterations.size()),
9275 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
9276 CGF.Builder
9277 .CreateConstArrayGEP(DimsAddr, 0, C.getTypeSizeInChars(KmpDimTy))
9278 .getPointer(),
9279 CGM.VoidPtrTy)};
Alexey Bataev8b427062016-05-25 12:36:08 +00009280
9281 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
9282 CGF.EmitRuntimeCall(RTLFn, Args);
9283 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009284 emitUpdateLocation(CGF, D.getEndLoc()), getThreadID(CGF, D.getEndLoc())};
Alexey Bataev8b427062016-05-25 12:36:08 +00009285 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
9286 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
9287 llvm::makeArrayRef(FiniArgs));
9288}
9289
9290void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
9291 const OMPDependClause *C) {
9292 QualType Int64Ty =
9293 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
Alexey Bataevf138fda2018-08-13 19:04:24 +00009294 llvm::APInt Size(/*numBits=*/32, C->getNumLoops());
9295 QualType ArrayTy = CGM.getContext().getConstantArrayType(
9296 Int64Ty, Size, ArrayType::Normal, 0);
9297 Address CntAddr = CGF.CreateMemTemp(ArrayTy, ".cnt.addr");
9298 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I) {
9299 const Expr *CounterVal = C->getLoopData(I);
9300 assert(CounterVal);
9301 llvm::Value *CntVal = CGF.EmitScalarConversion(
9302 CGF.EmitScalarExpr(CounterVal), CounterVal->getType(), Int64Ty,
9303 CounterVal->getExprLoc());
9304 CGF.EmitStoreOfScalar(
9305 CntVal,
9306 CGF.Builder.CreateConstArrayGEP(
9307 CntAddr, I, CGM.getContext().getTypeSizeInChars(Int64Ty)),
9308 /*Volatile=*/false, Int64Ty);
9309 }
9310 llvm::Value *Args[] = {
9311 emitUpdateLocation(CGF, C->getBeginLoc()),
9312 getThreadID(CGF, C->getBeginLoc()),
9313 CGF.Builder
9314 .CreateConstArrayGEP(CntAddr, 0,
9315 CGM.getContext().getTypeSizeInChars(Int64Ty))
9316 .getPointer()};
Alexey Bataev8b427062016-05-25 12:36:08 +00009317 llvm::Value *RTLFn;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009318 if (C->getDependencyKind() == OMPC_DEPEND_source) {
Alexey Bataev8b427062016-05-25 12:36:08 +00009319 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009320 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00009321 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
9322 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
9323 }
9324 CGF.EmitRuntimeCall(RTLFn, Args);
9325}
9326
Alexey Bataev7ef47a62018-02-22 18:33:31 +00009327void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, SourceLocation Loc,
9328 llvm::Value *Callee,
9329 ArrayRef<llvm::Value *> Args) const {
9330 assert(Loc.isValid() && "Outlined function call location must be valid.");
Alexey Bataev3c595a62017-08-14 15:01:03 +00009331 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
9332
9333 if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00009334 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00009335 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00009336 return;
9337 }
9338 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00009339 CGF.EmitRuntimeCall(Callee, Args);
9340}
9341
9342void CGOpenMPRuntime::emitOutlinedFunctionCall(
9343 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
9344 ArrayRef<llvm::Value *> Args) const {
Alexey Bataev7ef47a62018-02-22 18:33:31 +00009345 emitCall(CGF, Loc, OutlinedFn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00009346}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00009347
9348Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
9349 const VarDecl *NativeParam,
9350 const VarDecl *TargetParam) const {
9351 return CGF.GetAddrOfLocalVar(NativeParam);
9352}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009353
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00009354Address CGOpenMPRuntime::getAddressOfLocalVariable(CodeGenFunction &CGF,
9355 const VarDecl *VD) {
9356 return Address::invalid();
9357}
9358
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009359llvm::Value *CGOpenMPSIMDRuntime::emitParallelOutlinedFunction(
9360 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
9361 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
9362 llvm_unreachable("Not supported in SIMD-only mode");
9363}
9364
9365llvm::Value *CGOpenMPSIMDRuntime::emitTeamsOutlinedFunction(
9366 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
9367 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
9368 llvm_unreachable("Not supported in SIMD-only mode");
9369}
9370
9371llvm::Value *CGOpenMPSIMDRuntime::emitTaskOutlinedFunction(
9372 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
9373 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
9374 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
9375 bool Tied, unsigned &NumberOfParts) {
9376 llvm_unreachable("Not supported in SIMD-only mode");
9377}
9378
9379void CGOpenMPSIMDRuntime::emitParallelCall(CodeGenFunction &CGF,
9380 SourceLocation Loc,
9381 llvm::Value *OutlinedFn,
9382 ArrayRef<llvm::Value *> CapturedVars,
9383 const Expr *IfCond) {
9384 llvm_unreachable("Not supported in SIMD-only mode");
9385}
9386
9387void CGOpenMPSIMDRuntime::emitCriticalRegion(
9388 CodeGenFunction &CGF, StringRef CriticalName,
9389 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
9390 const Expr *Hint) {
9391 llvm_unreachable("Not supported in SIMD-only mode");
9392}
9393
9394void CGOpenMPSIMDRuntime::emitMasterRegion(CodeGenFunction &CGF,
9395 const RegionCodeGenTy &MasterOpGen,
9396 SourceLocation Loc) {
9397 llvm_unreachable("Not supported in SIMD-only mode");
9398}
9399
9400void CGOpenMPSIMDRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
9401 SourceLocation Loc) {
9402 llvm_unreachable("Not supported in SIMD-only mode");
9403}
9404
9405void CGOpenMPSIMDRuntime::emitTaskgroupRegion(
9406 CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen,
9407 SourceLocation Loc) {
9408 llvm_unreachable("Not supported in SIMD-only mode");
9409}
9410
9411void CGOpenMPSIMDRuntime::emitSingleRegion(
9412 CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen,
9413 SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars,
9414 ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs,
9415 ArrayRef<const Expr *> AssignmentOps) {
9416 llvm_unreachable("Not supported in SIMD-only mode");
9417}
9418
9419void CGOpenMPSIMDRuntime::emitOrderedRegion(CodeGenFunction &CGF,
9420 const RegionCodeGenTy &OrderedOpGen,
9421 SourceLocation Loc,
9422 bool IsThreads) {
9423 llvm_unreachable("Not supported in SIMD-only mode");
9424}
9425
9426void CGOpenMPSIMDRuntime::emitBarrierCall(CodeGenFunction &CGF,
9427 SourceLocation Loc,
9428 OpenMPDirectiveKind Kind,
9429 bool EmitChecks,
9430 bool ForceSimpleCall) {
9431 llvm_unreachable("Not supported in SIMD-only mode");
9432}
9433
9434void CGOpenMPSIMDRuntime::emitForDispatchInit(
9435 CodeGenFunction &CGF, SourceLocation Loc,
9436 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
9437 bool Ordered, const DispatchRTInput &DispatchValues) {
9438 llvm_unreachable("Not supported in SIMD-only mode");
9439}
9440
9441void CGOpenMPSIMDRuntime::emitForStaticInit(
9442 CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind,
9443 const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values) {
9444 llvm_unreachable("Not supported in SIMD-only mode");
9445}
9446
9447void CGOpenMPSIMDRuntime::emitDistributeStaticInit(
9448 CodeGenFunction &CGF, SourceLocation Loc,
9449 OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values) {
9450 llvm_unreachable("Not supported in SIMD-only mode");
9451}
9452
9453void CGOpenMPSIMDRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
9454 SourceLocation Loc,
9455 unsigned IVSize,
9456 bool IVSigned) {
9457 llvm_unreachable("Not supported in SIMD-only mode");
9458}
9459
9460void CGOpenMPSIMDRuntime::emitForStaticFinish(CodeGenFunction &CGF,
9461 SourceLocation Loc,
9462 OpenMPDirectiveKind DKind) {
9463 llvm_unreachable("Not supported in SIMD-only mode");
9464}
9465
9466llvm::Value *CGOpenMPSIMDRuntime::emitForNext(CodeGenFunction &CGF,
9467 SourceLocation Loc,
9468 unsigned IVSize, bool IVSigned,
9469 Address IL, Address LB,
9470 Address UB, Address ST) {
9471 llvm_unreachable("Not supported in SIMD-only mode");
9472}
9473
9474void CGOpenMPSIMDRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
9475 llvm::Value *NumThreads,
9476 SourceLocation Loc) {
9477 llvm_unreachable("Not supported in SIMD-only mode");
9478}
9479
9480void CGOpenMPSIMDRuntime::emitProcBindClause(CodeGenFunction &CGF,
9481 OpenMPProcBindClauseKind ProcBind,
9482 SourceLocation Loc) {
9483 llvm_unreachable("Not supported in SIMD-only mode");
9484}
9485
9486Address CGOpenMPSIMDRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
9487 const VarDecl *VD,
9488 Address VDAddr,
9489 SourceLocation Loc) {
9490 llvm_unreachable("Not supported in SIMD-only mode");
9491}
9492
9493llvm::Function *CGOpenMPSIMDRuntime::emitThreadPrivateVarDefinition(
9494 const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit,
9495 CodeGenFunction *CGF) {
9496 llvm_unreachable("Not supported in SIMD-only mode");
9497}
9498
9499Address CGOpenMPSIMDRuntime::getAddrOfArtificialThreadPrivate(
9500 CodeGenFunction &CGF, QualType VarType, StringRef Name) {
9501 llvm_unreachable("Not supported in SIMD-only mode");
9502}
9503
9504void CGOpenMPSIMDRuntime::emitFlush(CodeGenFunction &CGF,
9505 ArrayRef<const Expr *> Vars,
9506 SourceLocation Loc) {
9507 llvm_unreachable("Not supported in SIMD-only mode");
9508}
9509
9510void CGOpenMPSIMDRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
9511 const OMPExecutableDirective &D,
9512 llvm::Value *TaskFunction,
9513 QualType SharedsTy, Address Shareds,
9514 const Expr *IfCond,
9515 const OMPTaskDataTy &Data) {
9516 llvm_unreachable("Not supported in SIMD-only mode");
9517}
9518
9519void CGOpenMPSIMDRuntime::emitTaskLoopCall(
9520 CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D,
9521 llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
9522 const Expr *IfCond, const OMPTaskDataTy &Data) {
9523 llvm_unreachable("Not supported in SIMD-only mode");
9524}
9525
9526void CGOpenMPSIMDRuntime::emitReduction(
9527 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
9528 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
9529 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
9530 assert(Options.SimpleReduction && "Only simple reduction is expected.");
9531 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
9532 ReductionOps, Options);
9533}
9534
9535llvm::Value *CGOpenMPSIMDRuntime::emitTaskReductionInit(
9536 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
9537 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
9538 llvm_unreachable("Not supported in SIMD-only mode");
9539}
9540
9541void CGOpenMPSIMDRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
9542 SourceLocation Loc,
9543 ReductionCodeGen &RCG,
9544 unsigned N) {
9545 llvm_unreachable("Not supported in SIMD-only mode");
9546}
9547
9548Address CGOpenMPSIMDRuntime::getTaskReductionItem(CodeGenFunction &CGF,
9549 SourceLocation Loc,
9550 llvm::Value *ReductionsPtr,
9551 LValue SharedLVal) {
9552 llvm_unreachable("Not supported in SIMD-only mode");
9553}
9554
9555void CGOpenMPSIMDRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
9556 SourceLocation Loc) {
9557 llvm_unreachable("Not supported in SIMD-only mode");
9558}
9559
9560void CGOpenMPSIMDRuntime::emitCancellationPointCall(
9561 CodeGenFunction &CGF, SourceLocation Loc,
9562 OpenMPDirectiveKind CancelRegion) {
9563 llvm_unreachable("Not supported in SIMD-only mode");
9564}
9565
9566void CGOpenMPSIMDRuntime::emitCancelCall(CodeGenFunction &CGF,
9567 SourceLocation Loc, const Expr *IfCond,
9568 OpenMPDirectiveKind CancelRegion) {
9569 llvm_unreachable("Not supported in SIMD-only mode");
9570}
9571
9572void CGOpenMPSIMDRuntime::emitTargetOutlinedFunction(
9573 const OMPExecutableDirective &D, StringRef ParentName,
9574 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
9575 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
9576 llvm_unreachable("Not supported in SIMD-only mode");
9577}
9578
9579void CGOpenMPSIMDRuntime::emitTargetCall(CodeGenFunction &CGF,
9580 const OMPExecutableDirective &D,
9581 llvm::Value *OutlinedFn,
9582 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00009583 const Expr *IfCond, const Expr *Device) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009584 llvm_unreachable("Not supported in SIMD-only mode");
9585}
9586
9587bool CGOpenMPSIMDRuntime::emitTargetFunctions(GlobalDecl GD) {
9588 llvm_unreachable("Not supported in SIMD-only mode");
9589}
9590
9591bool CGOpenMPSIMDRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
9592 llvm_unreachable("Not supported in SIMD-only mode");
9593}
9594
9595bool CGOpenMPSIMDRuntime::emitTargetGlobal(GlobalDecl GD) {
9596 return false;
9597}
9598
9599llvm::Function *CGOpenMPSIMDRuntime::emitRegistrationFunction() {
9600 return nullptr;
9601}
9602
9603void CGOpenMPSIMDRuntime::emitTeamsCall(CodeGenFunction &CGF,
9604 const OMPExecutableDirective &D,
9605 SourceLocation Loc,
9606 llvm::Value *OutlinedFn,
9607 ArrayRef<llvm::Value *> CapturedVars) {
9608 llvm_unreachable("Not supported in SIMD-only mode");
9609}
9610
9611void CGOpenMPSIMDRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
9612 const Expr *NumTeams,
9613 const Expr *ThreadLimit,
9614 SourceLocation Loc) {
9615 llvm_unreachable("Not supported in SIMD-only mode");
9616}
9617
9618void CGOpenMPSIMDRuntime::emitTargetDataCalls(
9619 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
9620 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
9621 llvm_unreachable("Not supported in SIMD-only mode");
9622}
9623
9624void CGOpenMPSIMDRuntime::emitTargetDataStandAloneCall(
9625 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
9626 const Expr *Device) {
9627 llvm_unreachable("Not supported in SIMD-only mode");
9628}
9629
9630void CGOpenMPSIMDRuntime::emitDoacrossInit(CodeGenFunction &CGF,
Alexey Bataevf138fda2018-08-13 19:04:24 +00009631 const OMPLoopDirective &D,
9632 ArrayRef<Expr *> NumIterations) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009633 llvm_unreachable("Not supported in SIMD-only mode");
9634}
9635
9636void CGOpenMPSIMDRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
9637 const OMPDependClause *C) {
9638 llvm_unreachable("Not supported in SIMD-only mode");
9639}
9640
9641const VarDecl *
9642CGOpenMPSIMDRuntime::translateParameter(const FieldDecl *FD,
9643 const VarDecl *NativeParam) const {
9644 llvm_unreachable("Not supported in SIMD-only mode");
9645}
9646
9647Address
9648CGOpenMPSIMDRuntime::getParameterAddress(CodeGenFunction &CGF,
9649 const VarDecl *NativeParam,
9650 const VarDecl *TargetParam) const {
9651 llvm_unreachable("Not supported in SIMD-only mode");
9652}
9653