blob: 050f4a616c33093c65676d0eeecd676cd5872aa6 [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();
1226}
1227
Alexey Bataev18fa2322018-05-02 14:20:50 +00001228std::string CGOpenMPRuntime::getName(ArrayRef<StringRef> Parts) const {
1229 SmallString<128> Buffer;
1230 llvm::raw_svector_ostream OS(Buffer);
1231 StringRef Sep = FirstSeparator;
1232 for (StringRef Part : Parts) {
1233 OS << Sep << Part;
1234 Sep = Separator;
1235 }
1236 return OS.str();
1237}
1238
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001239static llvm::Function *
1240emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1241 const Expr *CombinerInitializer, const VarDecl *In,
1242 const VarDecl *Out, bool IsCombiner) {
1243 // void .omp_combiner.(Ty *in, Ty *out);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001244 ASTContext &C = CGM.getContext();
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001245 QualType PtrTy = C.getPointerType(Ty).withRestrict();
1246 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001247 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001248 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001249 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001250 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001251 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001252 Args.push_back(&OmpInParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001253 const CGFunctionInfo &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001254 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001255 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00001256 std::string Name = CGM.getOpenMPRuntime().getName(
1257 {IsCombiner ? "omp_combiner" : "omp_initializer", ""});
1258 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
1259 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001260 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001261 Fn->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001262 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001263 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001264 CodeGenFunction CGF(CGM);
1265 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1266 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001267 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, In->getLocation(),
1268 Out->getLocation());
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001269 CodeGenFunction::OMPPrivateScope Scope(CGF);
1270 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001271 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001272 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1273 .getAddress();
1274 });
1275 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001276 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001277 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1278 .getAddress();
1279 });
1280 (void)Scope.Privatize();
Alexey Bataev070f43a2017-09-06 14:49:58 +00001281 if (!IsCombiner && Out->hasInit() &&
1282 !CGF.isTrivialInitializer(Out->getInit())) {
1283 CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
1284 Out->getType().getQualifiers(),
1285 /*IsInitializer=*/true);
1286 }
1287 if (CombinerInitializer)
1288 CGF.EmitIgnoredExpr(CombinerInitializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001289 Scope.ForceCleanup();
1290 CGF.FinishFunction();
1291 return Fn;
1292}
1293
1294void CGOpenMPRuntime::emitUserDefinedReduction(
1295 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1296 if (UDRMap.count(D) > 0)
1297 return;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001298 ASTContext &C = CGM.getContext();
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001299 if (!In || !Out) {
1300 In = &C.Idents.get("omp_in");
1301 Out = &C.Idents.get("omp_out");
1302 }
1303 llvm::Function *Combiner = emitCombinerOrInitializer(
1304 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
1305 cast<VarDecl>(D->lookup(Out).front()),
1306 /*IsCombiner=*/true);
1307 llvm::Function *Initializer = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001308 if (const Expr *Init = D->getInitializer()) {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001309 if (!Priv || !Orig) {
1310 Priv = &C.Idents.get("omp_priv");
1311 Orig = &C.Idents.get("omp_orig");
1312 }
1313 Initializer = emitCombinerOrInitializer(
Alexey Bataev070f43a2017-09-06 14:49:58 +00001314 CGM, D->getType(),
1315 D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init
1316 : nullptr,
1317 cast<VarDecl>(D->lookup(Orig).front()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001318 cast<VarDecl>(D->lookup(Priv).front()),
1319 /*IsCombiner=*/false);
1320 }
Alexey Bataev43a919f2018-04-13 17:48:43 +00001321 UDRMap.try_emplace(D, Combiner, Initializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001322 if (CGF) {
1323 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1324 Decls.second.push_back(D);
1325 }
1326}
1327
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001328std::pair<llvm::Function *, llvm::Function *>
1329CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1330 auto I = UDRMap.find(D);
1331 if (I != UDRMap.end())
1332 return I->second;
1333 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1334 return UDRMap.lookup(D);
1335}
1336
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001337static llvm::Value *emitParallelOrTeamsOutlinedFunction(
1338 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1339 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1340 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001341 assert(ThreadIDVar->getType()->isPointerType() &&
1342 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +00001343 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00001344 bool HasCancel = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001345 if (const auto *OPD = dyn_cast<OMPParallelDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001346 HasCancel = OPD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001347 else if (const auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001348 HasCancel = OPSD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001349 else if (const auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001350 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001351 else if (const auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D))
Alexey Bataev2139ed62017-11-16 18:20:21 +00001352 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001353 else if (const auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&D))
Alexey Bataev10a54312017-11-27 16:54:08 +00001354 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001355 else if (const auto *OPFD =
1356 dyn_cast<OMPTeamsDistributeParallelForDirective>(&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 =
Alexey Bataev10a54312017-11-27 16:54:08 +00001359 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D))
1360 HasCancel = OPFD->hasCancel();
Alexey Bataev25e5b442015-09-15 12:52:43 +00001361 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001362 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +00001363 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001364 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +00001365}
1366
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001367llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
1368 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1369 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1370 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1371 return emitParallelOrTeamsOutlinedFunction(
1372 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1373}
1374
1375llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1376 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1377 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1378 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1379 return emitParallelOrTeamsOutlinedFunction(
1380 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1381}
1382
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001383llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
1384 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +00001385 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1386 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1387 bool Tied, unsigned &NumberOfParts) {
1388 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1389 PrePostActionTy &) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001390 llvm::Value *ThreadID = getThreadID(CGF, D.getBeginLoc());
1391 llvm::Value *UpLoc = emitUpdateLocation(CGF, D.getBeginLoc());
Alexey Bataev48591dd2016-04-20 04:01:36 +00001392 llvm::Value *TaskArgs[] = {
1393 UpLoc, ThreadID,
1394 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1395 TaskTVar->getType()->castAs<PointerType>())
1396 .getPointer()};
1397 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1398 };
1399 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1400 UntiedCodeGen);
1401 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001402 assert(!ThreadIDVar->getType()->isPointerType() &&
1403 "thread id variable must be of type kmp_int32 for tasks");
Alexey Bataev475a7442018-01-12 19:39:11 +00001404 const OpenMPDirectiveKind Region =
1405 isOpenMPTaskLoopDirective(D.getDirectiveKind()) ? OMPD_taskloop
1406 : OMPD_task;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001407 const CapturedStmt *CS = D.getCapturedStmt(Region);
1408 const auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001409 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +00001410 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1411 InnermostKind,
1412 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +00001413 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001414 llvm::Value *Res = CGF.GenerateCapturedStmtFunction(*CS);
Alexey Bataev48591dd2016-04-20 04:01:36 +00001415 if (!Tied)
1416 NumberOfParts = Action.getNumberOfParts();
1417 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001418}
1419
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001420static void buildStructValue(ConstantStructBuilder &Fields, CodeGenModule &CGM,
1421 const RecordDecl *RD, const CGRecordLayout &RL,
1422 ArrayRef<llvm::Constant *> Data) {
1423 llvm::StructType *StructTy = RL.getLLVMType();
1424 unsigned PrevIdx = 0;
1425 ConstantInitBuilder CIBuilder(CGM);
1426 auto DI = Data.begin();
1427 for (const FieldDecl *FD : RD->fields()) {
1428 unsigned Idx = RL.getLLVMFieldNo(FD);
1429 // Fill the alignment.
1430 for (unsigned I = PrevIdx; I < Idx; ++I)
1431 Fields.add(llvm::Constant::getNullValue(StructTy->getElementType(I)));
1432 PrevIdx = Idx + 1;
1433 Fields.add(*DI);
1434 ++DI;
1435 }
1436}
1437
1438template <class... As>
1439static llvm::GlobalVariable *
Mike Ricee1ca7b62018-08-29 15:45:11 +00001440createGlobalStruct(CodeGenModule &CGM, QualType Ty, bool IsConstant,
1441 ArrayRef<llvm::Constant *> Data, const Twine &Name,
1442 As &&... Args) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001443 const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1444 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1445 ConstantInitBuilder CIBuilder(CGM);
1446 ConstantStructBuilder Fields = CIBuilder.beginStruct(RL.getLLVMType());
1447 buildStructValue(Fields, CGM, RD, RL, Data);
1448 return Fields.finishAndCreateGlobal(
Mike Ricee1ca7b62018-08-29 15:45:11 +00001449 Name, CGM.getContext().getAlignOfGlobalVarInChars(Ty), IsConstant,
1450 std::forward<As>(Args)...);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001451}
1452
1453template <typename T>
Benjamin Kramer651d0bf2018-05-15 21:26:47 +00001454static void
1455createConstantGlobalStructAndAddToParent(CodeGenModule &CGM, QualType Ty,
1456 ArrayRef<llvm::Constant *> Data,
1457 T &Parent) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001458 const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1459 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1460 ConstantStructBuilder Fields = Parent.beginStruct(RL.getLLVMType());
1461 buildStructValue(Fields, CGM, RD, RL, Data);
1462 Fields.finishAndAddTo(Parent);
1463}
1464
Alexey Bataev50b3c952016-02-19 10:38:26 +00001465Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001466 CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
Alexey Bataev15007ba2014-05-07 06:18:01 +00001467 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +00001468 if (!Entry) {
1469 if (!DefaultOpenMPPSource) {
1470 // Initialize default location for psource field of ident_t structure of
1471 // all ident_t objects. Format is ";file;function;line;column;;".
1472 // Taken from
1473 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1474 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +00001475 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001476 DefaultOpenMPPSource =
1477 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1478 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001479
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001480 llvm::Constant *Data[] = {llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1481 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
1482 llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1483 llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1484 DefaultOpenMPPSource};
Mike Ricee1ca7b62018-08-29 15:45:11 +00001485 llvm::GlobalValue *DefaultOpenMPLocation =
1486 createGlobalStruct(CGM, IdentQTy, /*IsConstant=*/false, Data, "",
1487 llvm::GlobalValue::PrivateLinkage);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001488 DefaultOpenMPLocation->setUnnamedAddr(
1489 llvm::GlobalValue::UnnamedAddr::Global);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001490
John McCall7f416cc2015-09-08 08:05:57 +00001491 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +00001492 }
John McCall7f416cc2015-09-08 08:05:57 +00001493 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +00001494}
1495
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001496llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1497 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001498 unsigned Flags) {
1499 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +00001500 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001501 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +00001502 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +00001503 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001504
1505 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1506
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001507 CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
John McCall7f416cc2015-09-08 08:05:57 +00001508 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001509 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1510 if (I != OpenMPLocThreadIDMap.end())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001511 LocValue = Address(I->second.DebugLoc, Align);
John McCall7f416cc2015-09-08 08:05:57 +00001512
Alexander Musmanc6388682014-12-15 07:07:06 +00001513 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1514 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +00001515 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +00001516 // Generate "ident_t .kmpc_loc.addr;"
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001517 Address AI = CGF.CreateMemTemp(IdentQTy, ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +00001518 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +00001519 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001520 LocValue = AI;
1521
1522 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1523 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001524 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001525 CGF.getTypeSize(IdentQTy));
Alexey Bataev9959db52014-05-06 10:08:46 +00001526 }
1527
1528 // char **psource = &.kmpc_loc_<flags>.addr.psource;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001529 LValue Base = CGF.MakeAddrLValue(LocValue, IdentQTy);
1530 auto Fields = cast<RecordDecl>(IdentQTy->getAsTagDecl())->field_begin();
1531 LValue PSource =
1532 CGF.EmitLValueForField(Base, *std::next(Fields, IdentField_PSource));
Alexey Bataev9959db52014-05-06 10:08:46 +00001533
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001534 llvm::Value *OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
Alexey Bataevf002aca2014-05-30 05:48:40 +00001535 if (OMPDebugLoc == nullptr) {
1536 SmallString<128> Buffer2;
1537 llvm::raw_svector_ostream OS2(Buffer2);
1538 // Build debug location
1539 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1540 OS2 << ";" << PLoc.getFilename() << ";";
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001541 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl))
Alexey Bataevf002aca2014-05-30 05:48:40 +00001542 OS2 << FD->getQualifiedNameAsString();
Alexey Bataevf002aca2014-05-30 05:48:40 +00001543 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1544 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1545 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +00001546 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001547 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001548 CGF.EmitStoreOfScalar(OMPDebugLoc, PSource);
Alexey Bataevf002aca2014-05-30 05:48:40 +00001549
John McCall7f416cc2015-09-08 08:05:57 +00001550 // Our callers always pass this to a runtime function, so for
1551 // convenience, go ahead and return a naked pointer.
1552 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001553}
1554
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001555llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1556 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001557 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1558
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001559 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001560 // Check whether we've already cached a load of the thread id in this
1561 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001562 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001563 if (I != OpenMPLocThreadIDMap.end()) {
1564 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001565 if (ThreadID != nullptr)
1566 return ThreadID;
1567 }
Alexey Bataevaee18552017-08-16 14:01:00 +00001568 // If exceptions are enabled, do not use parameter to avoid possible crash.
Alexey Bataev5d2c9a42017-11-02 18:55:05 +00001569 if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions ||
1570 !CGF.getLangOpts().CXXExceptions ||
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001571 CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
Alexey Bataevaee18552017-08-16 14:01:00 +00001572 if (auto *OMPRegionInfo =
1573 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1574 if (OMPRegionInfo->getThreadIDVariable()) {
1575 // Check if this an outlined function with thread id passed as argument.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001576 LValue LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev1e491372018-01-23 18:44:14 +00001577 ThreadID = CGF.EmitLoadOfScalar(LVal, Loc);
Alexey Bataevaee18552017-08-16 14:01:00 +00001578 // If value loaded in entry block, cache it and use it everywhere in
1579 // function.
1580 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1581 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1582 Elem.second.ThreadID = ThreadID;
1583 }
1584 return ThreadID;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001585 }
Alexey Bataevd6c57552014-07-25 07:55:17 +00001586 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001587 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001588
1589 // This is not an outlined function region - need to call __kmpc_int32
1590 // kmpc_global_thread_num(ident_t *loc).
1591 // Generate thread id value and cache this value for use across the
1592 // function.
1593 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1594 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001595 llvm::CallInst *Call = CGF.Builder.CreateCall(
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001596 createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1597 emitUpdateLocation(CGF, Loc));
1598 Call->setCallingConv(CGF.getRuntimeCC());
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001599 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001600 Elem.second.ThreadID = Call;
1601 return Call;
Alexey Bataev9959db52014-05-06 10:08:46 +00001602}
1603
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001604void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001605 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001606 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1607 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001608 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001609 for(auto *D : FunctionUDRMap[CGF.CurFn])
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001610 UDRMap.erase(D);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001611 FunctionUDRMap.erase(CGF.CurFn);
1612 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001613}
1614
1615llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001616 return IdentTy->getPointerTo();
Alexey Bataev9959db52014-05-06 10:08:46 +00001617}
1618
1619llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001620 if (!Kmpc_MicroTy) {
1621 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1622 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1623 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1624 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1625 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001626 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1627}
1628
1629llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001630CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001631 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001632 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001633 case OMPRTL__kmpc_fork_call: {
1634 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1635 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001636 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1637 getKmpc_MicroPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001638 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001639 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001640 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1641 break;
1642 }
1643 case OMPRTL__kmpc_global_thread_num: {
1644 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001645 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001646 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001647 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001648 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1649 break;
1650 }
Alexey Bataev97720002014-11-11 04:05:39 +00001651 case OMPRTL__kmpc_threadprivate_cached: {
1652 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1653 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1654 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1655 CGM.VoidPtrTy, CGM.SizeTy,
1656 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001657 auto *FnTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001658 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1659 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1660 break;
1661 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001662 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001663 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1664 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001665 llvm::Type *TypeParams[] = {
1666 getIdentTyPointerTy(), CGM.Int32Ty,
1667 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001668 auto *FnTy =
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001669 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1670 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1671 break;
1672 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001673 case OMPRTL__kmpc_critical_with_hint: {
1674 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1675 // kmp_critical_name *crit, uintptr_t hint);
1676 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1677 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1678 CGM.IntPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001679 auto *FnTy =
Alexey Bataevfc57d162015-12-15 10:55:09 +00001680 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1681 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1682 break;
1683 }
Alexey Bataev97720002014-11-11 04:05:39 +00001684 case OMPRTL__kmpc_threadprivate_register: {
1685 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1686 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1687 // typedef void *(*kmpc_ctor)(void *);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001688 auto *KmpcCtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001689 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1690 /*isVarArg*/ false)->getPointerTo();
1691 // typedef void *(*kmpc_cctor)(void *, void *);
1692 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001693 auto *KmpcCopyCtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001694 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001695 /*isVarArg*/ false)
1696 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00001697 // typedef void (*kmpc_dtor)(void *);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001698 auto *KmpcDtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001699 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1700 ->getPointerTo();
1701 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1702 KmpcCopyCtorTy, KmpcDtorTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001703 auto *FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
Alexey Bataev97720002014-11-11 04:05:39 +00001704 /*isVarArg*/ false);
1705 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1706 break;
1707 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001708 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001709 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1710 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001711 llvm::Type *TypeParams[] = {
1712 getIdentTyPointerTy(), CGM.Int32Ty,
1713 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001714 auto *FnTy =
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001715 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1716 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1717 break;
1718 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001719 case OMPRTL__kmpc_cancel_barrier: {
1720 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1721 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001722 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001723 auto *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001724 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1725 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001726 break;
1727 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001728 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001729 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001730 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001731 auto *FnTy =
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001732 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1733 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1734 break;
1735 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001736 case OMPRTL__kmpc_for_static_fini: {
1737 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1738 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001739 auto *FnTy =
Alexander Musmanc6388682014-12-15 07:07:06 +00001740 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1741 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1742 break;
1743 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001744 case OMPRTL__kmpc_push_num_threads: {
1745 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1746 // kmp_int32 num_threads)
1747 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1748 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001749 auto *FnTy =
Alexey Bataevb2059782014-10-13 08:23:51 +00001750 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1751 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1752 break;
1753 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001754 case OMPRTL__kmpc_serialized_parallel: {
1755 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1756 // global_tid);
1757 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001758 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001759 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1760 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1761 break;
1762 }
1763 case OMPRTL__kmpc_end_serialized_parallel: {
1764 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1765 // global_tid);
1766 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001767 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001768 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1769 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1770 break;
1771 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001772 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001773 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001774 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001775 auto *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001776 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001777 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1778 break;
1779 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001780 case OMPRTL__kmpc_master: {
1781 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1782 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001783 auto *FnTy =
Alexey Bataev8d690652014-12-04 07:23:53 +00001784 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1785 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1786 break;
1787 }
1788 case OMPRTL__kmpc_end_master: {
1789 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1790 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001791 auto *FnTy =
Alexey Bataev8d690652014-12-04 07:23:53 +00001792 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1793 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1794 break;
1795 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001796 case OMPRTL__kmpc_omp_taskyield: {
1797 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1798 // int end_part);
1799 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001800 auto *FnTy =
Alexey Bataev9f797f32015-02-05 05:57:51 +00001801 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1802 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1803 break;
1804 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001805 case OMPRTL__kmpc_single: {
1806 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1807 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001808 auto *FnTy =
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001809 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1810 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1811 break;
1812 }
1813 case OMPRTL__kmpc_end_single: {
1814 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1815 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001816 auto *FnTy =
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001817 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1818 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1819 break;
1820 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001821 case OMPRTL__kmpc_omp_task_alloc: {
1822 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1823 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1824 // kmp_routine_entry_t *task_entry);
1825 assert(KmpRoutineEntryPtrTy != nullptr &&
1826 "Type kmp_routine_entry_t must be created.");
1827 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1828 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1829 // Return void * and then cast to particular kmp_task_t type.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001830 auto *FnTy =
Alexey Bataev62b63b12015-03-10 07:28:44 +00001831 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1832 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1833 break;
1834 }
1835 case OMPRTL__kmpc_omp_task: {
1836 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1837 // *new_task);
1838 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1839 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001840 auto *FnTy =
Alexey Bataev62b63b12015-03-10 07:28:44 +00001841 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1842 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1843 break;
1844 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001845 case OMPRTL__kmpc_copyprivate: {
1846 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001847 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001848 // kmp_int32 didit);
1849 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1850 auto *CpyFnTy =
1851 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001852 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001853 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1854 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001855 auto *FnTy =
Alexey Bataeva63048e2015-03-23 06:18:07 +00001856 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1857 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1858 break;
1859 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001860 case OMPRTL__kmpc_reduce: {
1861 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1862 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1863 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1864 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1865 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1866 /*isVarArg=*/false);
1867 llvm::Type *TypeParams[] = {
1868 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1869 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1870 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001871 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001872 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1873 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1874 break;
1875 }
1876 case OMPRTL__kmpc_reduce_nowait: {
1877 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1878 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1879 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1880 // *lck);
1881 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1882 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1883 /*isVarArg=*/false);
1884 llvm::Type *TypeParams[] = {
1885 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1886 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1887 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001888 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001889 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1890 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1891 break;
1892 }
1893 case OMPRTL__kmpc_end_reduce: {
1894 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1895 // kmp_critical_name *lck);
1896 llvm::Type *TypeParams[] = {
1897 getIdentTyPointerTy(), CGM.Int32Ty,
1898 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001899 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001900 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1901 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1902 break;
1903 }
1904 case OMPRTL__kmpc_end_reduce_nowait: {
1905 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1906 // kmp_critical_name *lck);
1907 llvm::Type *TypeParams[] = {
1908 getIdentTyPointerTy(), CGM.Int32Ty,
1909 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001910 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001911 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1912 RTLFn =
1913 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1914 break;
1915 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001916 case OMPRTL__kmpc_omp_task_begin_if0: {
1917 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1918 // *new_task);
1919 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1920 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001921 auto *FnTy =
Alexey Bataev1d677132015-04-22 13:57:31 +00001922 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1923 RTLFn =
1924 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1925 break;
1926 }
1927 case OMPRTL__kmpc_omp_task_complete_if0: {
1928 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1929 // *new_task);
1930 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1931 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001932 auto *FnTy =
Alexey Bataev1d677132015-04-22 13:57:31 +00001933 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1934 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1935 /*Name=*/"__kmpc_omp_task_complete_if0");
1936 break;
1937 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001938 case OMPRTL__kmpc_ordered: {
1939 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1940 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001941 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001942 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1943 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1944 break;
1945 }
1946 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001947 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001948 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001949 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001950 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1951 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1952 break;
1953 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001954 case OMPRTL__kmpc_omp_taskwait: {
1955 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1956 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001957 auto *FnTy =
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001958 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1959 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1960 break;
1961 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001962 case OMPRTL__kmpc_taskgroup: {
1963 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1964 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001965 auto *FnTy =
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001966 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1967 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1968 break;
1969 }
1970 case OMPRTL__kmpc_end_taskgroup: {
1971 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1972 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001973 auto *FnTy =
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001974 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1975 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1976 break;
1977 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001978 case OMPRTL__kmpc_push_proc_bind: {
1979 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1980 // int proc_bind)
1981 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001982 auto *FnTy =
Alexey Bataev7f210c62015-06-18 13:40:03 +00001983 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1984 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1985 break;
1986 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001987 case OMPRTL__kmpc_omp_task_with_deps: {
1988 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1989 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1990 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1991 llvm::Type *TypeParams[] = {
1992 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1993 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001994 auto *FnTy =
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001995 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1996 RTLFn =
1997 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1998 break;
1999 }
2000 case OMPRTL__kmpc_omp_wait_deps: {
2001 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
2002 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
2003 // kmp_depend_info_t *noalias_dep_list);
2004 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2005 CGM.Int32Ty, CGM.VoidPtrTy,
2006 CGM.Int32Ty, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002007 auto *FnTy =
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002008 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2009 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
2010 break;
2011 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00002012 case OMPRTL__kmpc_cancellationpoint: {
2013 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
2014 // global_tid, kmp_int32 cncl_kind)
2015 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002016 auto *FnTy =
Alexey Bataev0f34da12015-07-02 04:17:07 +00002017 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2018 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
2019 break;
2020 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002021 case OMPRTL__kmpc_cancel: {
2022 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
2023 // kmp_int32 cncl_kind)
2024 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002025 auto *FnTy =
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002026 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2027 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
2028 break;
2029 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002030 case OMPRTL__kmpc_push_num_teams: {
2031 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
2032 // kmp_int32 num_teams, kmp_int32 num_threads)
2033 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
2034 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002035 auto *FnTy =
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002036 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2037 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
2038 break;
2039 }
2040 case OMPRTL__kmpc_fork_teams: {
2041 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
2042 // microtask, ...);
2043 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2044 getKmpc_MicroPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002045 auto *FnTy =
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002046 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
2047 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
2048 break;
2049 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002050 case OMPRTL__kmpc_taskloop: {
2051 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
2052 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
2053 // sched, kmp_uint64 grainsize, void *task_dup);
2054 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2055 CGM.IntTy,
2056 CGM.VoidPtrTy,
2057 CGM.IntTy,
2058 CGM.Int64Ty->getPointerTo(),
2059 CGM.Int64Ty->getPointerTo(),
2060 CGM.Int64Ty,
2061 CGM.IntTy,
2062 CGM.IntTy,
2063 CGM.Int64Ty,
2064 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002065 auto *FnTy =
Alexey Bataev7292c292016-04-25 12:22:29 +00002066 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2067 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
2068 break;
2069 }
Alexey Bataev8b427062016-05-25 12:36:08 +00002070 case OMPRTL__kmpc_doacross_init: {
2071 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
2072 // num_dims, struct kmp_dim *dims);
2073 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2074 CGM.Int32Ty,
2075 CGM.Int32Ty,
2076 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002077 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002078 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2079 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
2080 break;
2081 }
2082 case OMPRTL__kmpc_doacross_fini: {
2083 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
2084 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002085 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002086 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2087 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
2088 break;
2089 }
2090 case OMPRTL__kmpc_doacross_post: {
2091 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
2092 // *vec);
2093 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2094 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002095 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002096 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2097 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
2098 break;
2099 }
2100 case OMPRTL__kmpc_doacross_wait: {
2101 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
2102 // *vec);
2103 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2104 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002105 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002106 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2107 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
2108 break;
2109 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002110 case OMPRTL__kmpc_task_reduction_init: {
2111 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
2112 // *data);
2113 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002114 auto *FnTy =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002115 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2116 RTLFn =
2117 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
2118 break;
2119 }
2120 case OMPRTL__kmpc_task_reduction_get_th_data: {
2121 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
2122 // *d);
2123 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002124 auto *FnTy =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002125 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2126 RTLFn = CGM.CreateRuntimeFunction(
2127 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2128 break;
2129 }
Samuel Antaobed3c462015-10-02 16:14:20 +00002130 case OMPRTL__tgt_target: {
George Rokos63bc9d62017-11-21 18:25:12 +00002131 // Build int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
2132 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Samuel Antaobed3c462015-10-02 16:14:20 +00002133 // *arg_types);
George Rokos63bc9d62017-11-21 18:25:12 +00002134 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaobed3c462015-10-02 16:14:20 +00002135 CGM.VoidPtrTy,
2136 CGM.Int32Ty,
2137 CGM.VoidPtrPtrTy,
2138 CGM.VoidPtrPtrTy,
2139 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002140 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002141 auto *FnTy =
Samuel Antaobed3c462015-10-02 16:14:20 +00002142 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2143 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2144 break;
2145 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002146 case OMPRTL__tgt_target_nowait: {
2147 // Build int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
2148 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2149 // int64_t *arg_types);
2150 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2151 CGM.VoidPtrTy,
2152 CGM.Int32Ty,
2153 CGM.VoidPtrPtrTy,
2154 CGM.VoidPtrPtrTy,
2155 CGM.SizeTy->getPointerTo(),
2156 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002157 auto *FnTy =
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002158 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2159 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_nowait");
2160 break;
2161 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00002162 case OMPRTL__tgt_target_teams: {
George Rokos63bc9d62017-11-21 18:25:12 +00002163 // Build int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002164 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
George Rokos63bc9d62017-11-21 18:25:12 +00002165 // int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2166 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002167 CGM.VoidPtrTy,
2168 CGM.Int32Ty,
2169 CGM.VoidPtrPtrTy,
2170 CGM.VoidPtrPtrTy,
2171 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002172 CGM.Int64Ty->getPointerTo(),
Samuel Antaob68e2db2016-03-03 16:20:23 +00002173 CGM.Int32Ty,
2174 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002175 auto *FnTy =
Samuel Antaob68e2db2016-03-03 16:20:23 +00002176 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2177 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2178 break;
2179 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002180 case OMPRTL__tgt_target_teams_nowait: {
2181 // Build int32_t __tgt_target_teams_nowait(int64_t device_id, void
2182 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
2183 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
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(),
2191 CGM.Int32Ty,
2192 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002193 auto *FnTy =
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002194 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2195 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams_nowait");
2196 break;
2197 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002198 case OMPRTL__tgt_register_lib: {
2199 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2200 QualType ParamTy =
2201 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2202 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002203 auto *FnTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002204 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2205 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2206 break;
2207 }
2208 case OMPRTL__tgt_unregister_lib: {
2209 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2210 QualType ParamTy =
2211 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2212 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002213 auto *FnTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002214 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2215 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2216 break;
2217 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002218 case OMPRTL__tgt_target_data_begin: {
George Rokos63bc9d62017-11-21 18:25:12 +00002219 // Build void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
2220 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2221 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002222 CGM.Int32Ty,
2223 CGM.VoidPtrPtrTy,
2224 CGM.VoidPtrPtrTy,
2225 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002226 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002227 auto *FnTy =
Samuel Antaodf158d52016-04-27 22:58:19 +00002228 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2229 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2230 break;
2231 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002232 case OMPRTL__tgt_target_data_begin_nowait: {
2233 // Build void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
2234 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2235 // *arg_types);
2236 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2237 CGM.Int32Ty,
2238 CGM.VoidPtrPtrTy,
2239 CGM.VoidPtrPtrTy,
2240 CGM.SizeTy->getPointerTo(),
2241 CGM.Int64Ty->getPointerTo()};
2242 auto *FnTy =
2243 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2244 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin_nowait");
2245 break;
2246 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002247 case OMPRTL__tgt_target_data_end: {
George Rokos63bc9d62017-11-21 18:25:12 +00002248 // Build void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
2249 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2250 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002251 CGM.Int32Ty,
2252 CGM.VoidPtrPtrTy,
2253 CGM.VoidPtrPtrTy,
2254 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002255 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002256 auto *FnTy =
Samuel Antaodf158d52016-04-27 22:58:19 +00002257 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2258 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2259 break;
2260 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002261 case OMPRTL__tgt_target_data_end_nowait: {
2262 // Build void __tgt_target_data_end_nowait(int64_t device_id, int32_t
2263 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2264 // *arg_types);
2265 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2266 CGM.Int32Ty,
2267 CGM.VoidPtrPtrTy,
2268 CGM.VoidPtrPtrTy,
2269 CGM.SizeTy->getPointerTo(),
2270 CGM.Int64Ty->getPointerTo()};
2271 auto *FnTy =
2272 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2273 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end_nowait");
2274 break;
2275 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002276 case OMPRTL__tgt_target_data_update: {
George Rokos63bc9d62017-11-21 18:25:12 +00002277 // Build void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
2278 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2279 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antao8d2d7302016-05-26 18:30:22 +00002280 CGM.Int32Ty,
2281 CGM.VoidPtrPtrTy,
2282 CGM.VoidPtrPtrTy,
2283 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002284 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002285 auto *FnTy =
Samuel Antao8d2d7302016-05-26 18:30:22 +00002286 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2287 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2288 break;
2289 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002290 case OMPRTL__tgt_target_data_update_nowait: {
2291 // Build void __tgt_target_data_update_nowait(int64_t device_id, int32_t
2292 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2293 // *arg_types);
2294 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2295 CGM.Int32Ty,
2296 CGM.VoidPtrPtrTy,
2297 CGM.VoidPtrPtrTy,
2298 CGM.SizeTy->getPointerTo(),
2299 CGM.Int64Ty->getPointerTo()};
2300 auto *FnTy =
2301 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2302 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update_nowait");
2303 break;
2304 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002305 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002306 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002307 return RTLFn;
2308}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002309
Alexander Musman21212e42015-03-13 10:38:23 +00002310llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2311 bool IVSigned) {
2312 assert((IVSize == 32 || IVSize == 64) &&
2313 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002314 StringRef Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2315 : "__kmpc_for_static_init_4u")
2316 : (IVSigned ? "__kmpc_for_static_init_8"
2317 : "__kmpc_for_static_init_8u");
2318 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2319 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
Alexander Musman21212e42015-03-13 10:38:23 +00002320 llvm::Type *TypeParams[] = {
2321 getIdentTyPointerTy(), // loc
2322 CGM.Int32Ty, // tid
2323 CGM.Int32Ty, // schedtype
2324 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2325 PtrTy, // p_lower
2326 PtrTy, // p_upper
2327 PtrTy, // p_stride
2328 ITy, // incr
2329 ITy // chunk
2330 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002331 auto *FnTy =
Alexander Musman21212e42015-03-13 10:38:23 +00002332 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2333 return CGM.CreateRuntimeFunction(FnTy, Name);
2334}
2335
Alexander Musman92bdaab2015-03-12 13:37:50 +00002336llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2337 bool IVSigned) {
2338 assert((IVSize == 32 || IVSize == 64) &&
2339 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002340 StringRef Name =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002341 IVSize == 32
2342 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2343 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002344 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
Alexander Musman92bdaab2015-03-12 13:37:50 +00002345 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2346 CGM.Int32Ty, // tid
2347 CGM.Int32Ty, // schedtype
2348 ITy, // lower
2349 ITy, // upper
2350 ITy, // stride
2351 ITy // chunk
2352 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002353 auto *FnTy =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002354 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2355 return CGM.CreateRuntimeFunction(FnTy, Name);
2356}
2357
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002358llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2359 bool IVSigned) {
2360 assert((IVSize == 32 || IVSize == 64) &&
2361 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002362 StringRef Name =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002363 IVSize == 32
2364 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2365 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2366 llvm::Type *TypeParams[] = {
2367 getIdentTyPointerTy(), // loc
2368 CGM.Int32Ty, // tid
2369 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002370 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002371 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2372 return CGM.CreateRuntimeFunction(FnTy, Name);
2373}
2374
Alexander Musman92bdaab2015-03-12 13:37:50 +00002375llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2376 bool IVSigned) {
2377 assert((IVSize == 32 || IVSize == 64) &&
2378 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002379 StringRef Name =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002380 IVSize == 32
2381 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2382 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002383 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2384 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002385 llvm::Type *TypeParams[] = {
2386 getIdentTyPointerTy(), // loc
2387 CGM.Int32Ty, // tid
2388 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2389 PtrTy, // p_lower
2390 PtrTy, // p_upper
2391 PtrTy // p_stride
2392 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002393 auto *FnTy =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002394 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2395 return CGM.CreateRuntimeFunction(FnTy, Name);
2396}
2397
Alexey Bataev03f270c2018-03-30 18:31:07 +00002398Address CGOpenMPRuntime::getAddrOfDeclareTargetLink(const VarDecl *VD) {
2399 if (CGM.getLangOpts().OpenMPSimd)
2400 return Address::invalid();
Alexey Bataev92327c52018-03-26 16:40:55 +00002401 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002402 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00002403 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2404 SmallString<64> PtrName;
2405 {
2406 llvm::raw_svector_ostream OS(PtrName);
2407 OS << CGM.getMangledName(GlobalDecl(VD)) << "_decl_tgt_link_ptr";
2408 }
2409 llvm::Value *Ptr = CGM.getModule().getNamedValue(PtrName);
2410 if (!Ptr) {
2411 QualType PtrTy = CGM.getContext().getPointerType(VD->getType());
2412 Ptr = getOrCreateInternalVariable(CGM.getTypes().ConvertTypeForMem(PtrTy),
2413 PtrName);
Alexey Bataev03f270c2018-03-30 18:31:07 +00002414 if (!CGM.getLangOpts().OpenMPIsDevice) {
2415 auto *GV = cast<llvm::GlobalVariable>(Ptr);
2416 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2417 GV->setInitializer(CGM.GetAddrOfGlobal(VD));
2418 }
2419 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ptr));
2420 registerTargetGlobalVariable(VD, cast<llvm::Constant>(Ptr));
Alexey Bataev92327c52018-03-26 16:40:55 +00002421 }
2422 return Address(Ptr, CGM.getContext().getDeclAlign(VD));
2423 }
2424 return Address::invalid();
2425}
2426
Alexey Bataev97720002014-11-11 04:05:39 +00002427llvm::Constant *
2428CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002429 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2430 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002431 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev18fa2322018-05-02 14:20:50 +00002432 std::string Suffix = getName({"cache", ""});
2433 return getOrCreateInternalVariable(
2434 CGM.Int8PtrPtrTy, Twine(CGM.getMangledName(VD)).concat(Suffix));
Alexey Bataev97720002014-11-11 04:05:39 +00002435}
2436
John McCall7f416cc2015-09-08 08:05:57 +00002437Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2438 const VarDecl *VD,
2439 Address VDAddr,
2440 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002441 if (CGM.getLangOpts().OpenMPUseTLS &&
2442 CGM.getContext().getTargetInfo().isTLSSupported())
2443 return VDAddr;
2444
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002445 llvm::Type *VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002446 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002447 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2448 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002449 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2450 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002451 return Address(CGF.EmitRuntimeCall(
2452 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2453 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002454}
2455
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002456void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002457 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002458 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2459 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2460 // library.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002461 llvm::Value *OMPLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002462 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002463 OMPLoc);
2464 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2465 // to register constructor/destructor for variable.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002466 llvm::Value *Args[] = {
2467 OMPLoc, CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.VoidPtrTy),
2468 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002469 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002470 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002471}
2472
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002473llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002474 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002475 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002476 if (CGM.getLangOpts().OpenMPUseTLS &&
2477 CGM.getContext().getTargetInfo().isTLSSupported())
2478 return nullptr;
2479
Alexey Bataev97720002014-11-11 04:05:39 +00002480 VD = VD->getDefinition(CGM.getContext());
2481 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
2482 ThreadPrivateWithDefinition.insert(VD);
2483 QualType ASTTy = VD->getType();
2484
2485 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002486 const Expr *Init = VD->getAnyInitializer();
Alexey Bataev97720002014-11-11 04:05:39 +00002487 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2488 // Generate function that re-emits the declaration's initializer into the
2489 // threadprivate copy of the variable VD
2490 CodeGenFunction CtorCGF(CGM);
2491 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002492 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2493 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002494 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002495 Args.push_back(&Dst);
2496
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002497 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
John McCallc56a8b32016-03-11 04:30:31 +00002498 CGM.getContext().VoidPtrTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002499 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002500 std::string Name = getName({"__kmpc_global_ctor_", ""});
2501 llvm::Function *Fn =
2502 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002503 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002504 Args, Loc, Loc);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002505 llvm::Value *ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002506 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002507 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002508 Address Arg = Address(ArgVal, VDAddr.getAlignment());
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002509 Arg = CtorCGF.Builder.CreateElementBitCast(
2510 Arg, CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002511 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2512 /*IsInitializer=*/true);
2513 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002514 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002515 CGM.getContext().VoidPtrTy, Dst.getLocation());
2516 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2517 CtorCGF.FinishFunction();
2518 Ctor = Fn;
2519 }
2520 if (VD->getType().isDestructedType() != QualType::DK_none) {
2521 // Generate function that emits destructor call for the threadprivate copy
2522 // of the variable VD
2523 CodeGenFunction DtorCGF(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().VoidTy, 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_dtor_", ""});
2534 llvm::Function *Fn =
2535 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002536 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002537 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002538 Loc, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002539 // Create a scope with an artificial location for the body of this function.
2540 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002541 llvm::Value *ArgVal = DtorCGF.EmitLoadOfScalar(
Alexey Bataev97720002014-11-11 04:05:39 +00002542 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002543 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2544 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002545 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2546 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2547 DtorCGF.FinishFunction();
2548 Dtor = Fn;
2549 }
2550 // Do not emit init function if it is not required.
2551 if (!Ctor && !Dtor)
2552 return nullptr;
2553
2554 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002555 auto *CopyCtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2556 /*isVarArg=*/false)
2557 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002558 // Copying constructor for the threadprivate variable.
2559 // Must be NULL - reserved by runtime, but currently it requires that this
2560 // parameter is always NULL. Otherwise it fires assertion.
2561 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2562 if (Ctor == nullptr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002563 auto *CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2564 /*isVarArg=*/false)
2565 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002566 Ctor = llvm::Constant::getNullValue(CtorTy);
2567 }
2568 if (Dtor == nullptr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002569 auto *DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2570 /*isVarArg=*/false)
2571 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002572 Dtor = llvm::Constant::getNullValue(DtorTy);
2573 }
2574 if (!CGF) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002575 auto *InitFunctionTy =
Alexey Bataev97720002014-11-11 04:05:39 +00002576 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002577 std::string Name = getName({"__omp_threadprivate_init_", ""});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002578 llvm::Function *InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Alexey Bataev18fa2322018-05-02 14:20:50 +00002579 InitFunctionTy, Name, CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002580 CodeGenFunction InitCGF(CGM);
2581 FunctionArgList ArgList;
2582 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2583 CGM.getTypes().arrangeNullaryFunction(), ArgList,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002584 Loc, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002585 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002586 InitCGF.FinishFunction();
2587 return InitFunction;
2588 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002589 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002590 }
2591 return nullptr;
2592}
2593
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002594/// Obtain information that uniquely identifies a target entry. This
Alexey Bataev34f8a702018-03-28 14:28:54 +00002595/// consists of the file and device IDs as well as line number associated with
2596/// the relevant entry source location.
2597static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
2598 unsigned &DeviceID, unsigned &FileID,
2599 unsigned &LineNum) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002600 SourceManager &SM = C.getSourceManager();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002601
2602 // The loc should be always valid and have a file ID (the user cannot use
2603 // #pragma directives in macros)
2604
2605 assert(Loc.isValid() && "Source location is expected to be always valid.");
Alexey Bataev34f8a702018-03-28 14:28:54 +00002606
2607 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
2608 assert(PLoc.isValid() && "Source location is expected to be always valid.");
2609
2610 llvm::sys::fs::UniqueID ID;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00002611 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
2612 SM.getDiagnostics().Report(diag::err_cannot_open_file)
2613 << PLoc.getFilename() << EC.message();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002614
2615 DeviceID = ID.getDevice();
2616 FileID = ID.getFile();
2617 LineNum = PLoc.getLine();
2618}
2619
2620bool CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD,
2621 llvm::GlobalVariable *Addr,
2622 bool PerformInit) {
2623 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002624 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002625 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link)
Alexey Bataevd01b7492018-08-15 19:45:12 +00002626 return CGM.getLangOpts().OpenMPIsDevice;
Alexey Bataev34f8a702018-03-28 14:28:54 +00002627 VD = VD->getDefinition(CGM.getContext());
2628 if (VD && !DeclareTargetWithDefinition.insert(VD).second)
2629 return CGM.getLangOpts().OpenMPIsDevice;
2630
2631 QualType ASTTy = VD->getType();
2632
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002633 SourceLocation Loc = VD->getCanonicalDecl()->getBeginLoc();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002634 // Produce the unique prefix to identify the new target regions. We use
2635 // the source location of the variable declaration which we know to not
2636 // conflict with any target region.
2637 unsigned DeviceID;
2638 unsigned FileID;
2639 unsigned Line;
2640 getTargetEntryUniqueInfo(CGM.getContext(), Loc, DeviceID, FileID, Line);
2641 SmallString<128> Buffer, Out;
2642 {
2643 llvm::raw_svector_ostream OS(Buffer);
2644 OS << "__omp_offloading_" << llvm::format("_%x", DeviceID)
2645 << llvm::format("_%x_", FileID) << VD->getName() << "_l" << Line;
2646 }
2647
2648 const Expr *Init = VD->getAnyInitializer();
2649 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2650 llvm::Constant *Ctor;
2651 llvm::Constant *ID;
2652 if (CGM.getLangOpts().OpenMPIsDevice) {
2653 // Generate function that re-emits the declaration's initializer into
2654 // the threadprivate copy of the variable VD
2655 CodeGenFunction CtorCGF(CGM);
2656
2657 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2658 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2659 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2660 FTy, Twine(Buffer, "_ctor"), FI, Loc);
2661 auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF);
2662 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2663 FunctionArgList(), Loc, Loc);
2664 auto AL = ApplyDebugLocation::CreateArtificial(CtorCGF);
2665 CtorCGF.EmitAnyExprToMem(Init,
2666 Address(Addr, CGM.getContext().getDeclAlign(VD)),
2667 Init->getType().getQualifiers(),
2668 /*IsInitializer=*/true);
2669 CtorCGF.FinishFunction();
2670 Ctor = Fn;
2671 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
Alexey Bataeve253f2f2018-05-09 14:15:18 +00002672 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ctor));
Alexey Bataev34f8a702018-03-28 14:28:54 +00002673 } else {
2674 Ctor = new llvm::GlobalVariable(
2675 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2676 llvm::GlobalValue::PrivateLinkage,
2677 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_ctor"));
2678 ID = Ctor;
2679 }
2680
2681 // Register the information for the entry associated with the constructor.
2682 Out.clear();
2683 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2684 DeviceID, FileID, Twine(Buffer, "_ctor").toStringRef(Out), Line, Ctor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002685 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryCtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002686 }
2687 if (VD->getType().isDestructedType() != QualType::DK_none) {
2688 llvm::Constant *Dtor;
2689 llvm::Constant *ID;
2690 if (CGM.getLangOpts().OpenMPIsDevice) {
2691 // Generate function that emits destructor call for the threadprivate
2692 // copy of the variable VD
2693 CodeGenFunction DtorCGF(CGM);
2694
2695 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2696 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2697 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2698 FTy, Twine(Buffer, "_dtor"), FI, Loc);
2699 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
2700 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2701 FunctionArgList(), Loc, Loc);
2702 // Create a scope with an artificial location for the body of this
2703 // function.
2704 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
2705 DtorCGF.emitDestroy(Address(Addr, CGM.getContext().getDeclAlign(VD)),
2706 ASTTy, DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2707 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2708 DtorCGF.FinishFunction();
2709 Dtor = Fn;
2710 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
Alexey Bataeve253f2f2018-05-09 14:15:18 +00002711 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Dtor));
Alexey Bataev34f8a702018-03-28 14:28:54 +00002712 } else {
2713 Dtor = new llvm::GlobalVariable(
2714 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2715 llvm::GlobalValue::PrivateLinkage,
2716 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_dtor"));
2717 ID = Dtor;
2718 }
2719 // Register the information for the entry associated with the destructor.
2720 Out.clear();
2721 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2722 DeviceID, FileID, Twine(Buffer, "_dtor").toStringRef(Out), Line, Dtor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002723 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryDtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002724 }
2725 return CGM.getLangOpts().OpenMPIsDevice;
2726}
2727
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002728Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2729 QualType VarType,
2730 StringRef Name) {
Alexey Bataev18fa2322018-05-02 14:20:50 +00002731 std::string Suffix = getName({"artificial", ""});
2732 std::string CacheSuffix = getName({"cache", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002733 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002734 llvm::Value *GAddr =
2735 getOrCreateInternalVariable(VarLVType, Twine(Name).concat(Suffix));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002736 llvm::Value *Args[] = {
2737 emitUpdateLocation(CGF, SourceLocation()),
2738 getThreadID(CGF, SourceLocation()),
2739 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2740 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2741 /*IsSigned=*/false),
Alexey Bataev18fa2322018-05-02 14:20:50 +00002742 getOrCreateInternalVariable(
2743 CGM.VoidPtrPtrTy, Twine(Name).concat(Suffix).concat(CacheSuffix))};
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002744 return Address(
2745 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2746 CGF.EmitRuntimeCall(
2747 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2748 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2749 CGM.getPointerAlign());
2750}
2751
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002752void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2753 const RegionCodeGenTy &ThenGen,
2754 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002755 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2756
2757 // If the condition constant folds and can be elided, try to avoid emitting
2758 // the condition and the dead arm of the if/else.
2759 bool CondConstant;
2760 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002761 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002762 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002763 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002764 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002765 return;
2766 }
2767
2768 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2769 // emit the conditional branch.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002770 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("omp_if.then");
2771 llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else");
2772 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("omp_if.end");
Alexey Bataev1d677132015-04-22 13:57:31 +00002773 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2774
2775 // Emit the 'then' code.
2776 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002777 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002778 CGF.EmitBranch(ContBlock);
2779 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002780 // There is no need to emit line number for unconditional branch.
2781 (void)ApplyDebugLocation::CreateEmpty(CGF);
2782 CGF.EmitBlock(ElseBlock);
2783 ElseGen(CGF);
2784 // There is no need to emit line number for unconditional branch.
2785 (void)ApplyDebugLocation::CreateEmpty(CGF);
2786 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002787 // Emit the continuation block for code after the if.
2788 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002789}
2790
Alexey Bataev1d677132015-04-22 13:57:31 +00002791void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2792 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002793 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002794 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002795 if (!CGF.HaveInsertPoint())
2796 return;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002797 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002798 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2799 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002800 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002801 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002802 llvm::Value *Args[] = {
2803 RTLoc,
2804 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002805 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002806 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2807 RealArgs.append(std::begin(Args), std::end(Args));
2808 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2809
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002810 llvm::Value *RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002811 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2812 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002813 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2814 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002815 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
2816 llvm::Value *ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00002817 // Build calls:
2818 // __kmpc_serialized_parallel(&Loc, GTid);
2819 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002820 CGF.EmitRuntimeCall(
2821 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002822
Alexey Bataev1d677132015-04-22 13:57:31 +00002823 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002824 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2825 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00002826 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00002827 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataev8521ff62018-07-25 20:03:01 +00002828 // ThreadId for serialized parallels is 0.
2829 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
Alexey Bataev2377fe92015-09-10 08:12:02 +00002830 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2831 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002832 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002833
Alexey Bataev1d677132015-04-22 13:57:31 +00002834 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002835 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00002836 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002837 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2838 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002839 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002840 if (IfCond) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002841 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002842 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002843 RegionCodeGenTy ThenRCG(ThenGen);
2844 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002845 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002846}
2847
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002848// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002849// thread-ID variable (it is passed in a first argument of the outlined function
2850// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2851// regular serial code region, get thread ID by calling kmp_int32
2852// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2853// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002854Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2855 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002856 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002857 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002858 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002859 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002860
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002861 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2862 QualType Int32Ty =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002863 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002864 Address ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
Alexey Bataevd74d0602014-10-13 06:02:40 +00002865 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002866 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002867
2868 return ThreadIDTemp;
2869}
2870
Alexey Bataev97720002014-11-11 04:05:39 +00002871llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002872CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002873 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002874 SmallString<256> Buffer;
2875 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002876 Out << Name;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002877 StringRef RuntimeName = Out.str();
Alexey Bataev43a919f2018-04-13 17:48:43 +00002878 auto &Elem = *InternalVars.try_emplace(RuntimeName, nullptr).first;
David Blaikie13156b62014-11-19 03:06:06 +00002879 if (Elem.second) {
2880 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002881 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002882 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002883 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002884
David Blaikie13156b62014-11-19 03:06:06 +00002885 return Elem.second = new llvm::GlobalVariable(
2886 CGM.getModule(), Ty, /*IsConstant*/ false,
2887 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2888 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002889}
2890
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002891llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev18fa2322018-05-02 14:20:50 +00002892 std::string Prefix = Twine("gomp_critical_user_", CriticalName).str();
2893 std::string Name = getName({Prefix, "var"});
2894 return getOrCreateInternalVariable(KmpCriticalNameTy, Name);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002895}
2896
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002897namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002898/// Common pre(post)-action for different OpenMP constructs.
2899class CommonActionTy final : public PrePostActionTy {
2900 llvm::Value *EnterCallee;
2901 ArrayRef<llvm::Value *> EnterArgs;
2902 llvm::Value *ExitCallee;
2903 ArrayRef<llvm::Value *> ExitArgs;
2904 bool Conditional;
2905 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002906
2907public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002908 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2909 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2910 bool Conditional = false)
2911 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2912 ExitArgs(ExitArgs), Conditional(Conditional) {}
2913 void Enter(CodeGenFunction &CGF) override {
2914 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2915 if (Conditional) {
2916 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2917 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2918 ContBlock = CGF.createBasicBlock("omp_if.end");
2919 // Generate the branch (If-stmt)
2920 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2921 CGF.EmitBlock(ThenBlock);
2922 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002923 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002924 void Done(CodeGenFunction &CGF) {
2925 // Emit the rest of blocks/branches
2926 CGF.EmitBranch(ContBlock);
2927 CGF.EmitBlock(ContBlock, true);
2928 }
2929 void Exit(CodeGenFunction &CGF) override {
2930 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002931 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002932};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002933} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002934
2935void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2936 StringRef CriticalName,
2937 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002938 SourceLocation Loc, const Expr *Hint) {
2939 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002940 // CriticalOpGen();
2941 // __kmpc_end_critical(ident_t *, gtid, Lock);
2942 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002943 if (!CGF.HaveInsertPoint())
2944 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002945 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2946 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002947 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2948 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002949 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002950 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2951 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2952 }
2953 CommonActionTy Action(
2954 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2955 : OMPRTL__kmpc_critical),
2956 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2957 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002958 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002959}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002960
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002961void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002962 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002963 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002964 if (!CGF.HaveInsertPoint())
2965 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002966 // if(__kmpc_master(ident_t *, gtid)) {
2967 // MasterOpGen();
2968 // __kmpc_end_master(ident_t *, gtid);
2969 // }
2970 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002971 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002972 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2973 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2974 /*Conditional=*/true);
2975 MasterOpGen.setAction(Action);
2976 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2977 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002978}
2979
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002980void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2981 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002982 if (!CGF.HaveInsertPoint())
2983 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00002984 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2985 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002986 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00002987 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002988 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002989 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2990 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00002991}
2992
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002993void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2994 const RegionCodeGenTy &TaskgroupOpGen,
2995 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002996 if (!CGF.HaveInsertPoint())
2997 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002998 // __kmpc_taskgroup(ident_t *, gtid);
2999 // TaskgroupOpGen();
3000 // __kmpc_end_taskgroup(ident_t *, gtid);
3001 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003002 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3003 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
3004 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
3005 Args);
3006 TaskgroupOpGen.setAction(Action);
3007 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003008}
3009
John McCall7f416cc2015-09-08 08:05:57 +00003010/// Given an array of pointers to variables, project the address of a
3011/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003012static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
3013 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00003014 // Pull out the pointer to the variable.
3015 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003016 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00003017 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
3018
3019 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003020 Addr = CGF.Builder.CreateElementBitCast(
3021 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00003022 return Addr;
3023}
3024
Alexey Bataeva63048e2015-03-23 06:18:07 +00003025static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00003026 CodeGenModule &CGM, llvm::Type *ArgsType,
3027 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003028 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps,
3029 SourceLocation Loc) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003030 ASTContext &C = CGM.getContext();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003031 // void copy_func(void *LHSArg, void *RHSArg);
3032 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003033 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3034 ImplicitParamDecl::Other);
3035 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3036 ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003037 Args.push_back(&LHSArg);
3038 Args.push_back(&RHSArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003039 const auto &CGFI =
3040 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003041 std::string Name =
3042 CGM.getOpenMPRuntime().getName({"omp", "copyprivate", "copy_func"});
3043 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
3044 llvm::GlobalValue::InternalLinkage, Name,
3045 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003046 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003047 Fn->setDoesNotRecurse();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003048 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003049 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00003050 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003051 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00003052 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3053 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
3054 ArgsType), CGF.getPointerAlign());
3055 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3056 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
3057 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00003058 // *(Type0*)Dst[0] = *(Type0*)Src[0];
3059 // *(Type1*)Dst[1] = *(Type1*)Src[1];
3060 // ...
3061 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00003062 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003063 const auto *DestVar =
3064 cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003065 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
3066
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003067 const auto *SrcVar =
3068 cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003069 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
3070
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003071 const auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003072 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00003073 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003074 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00003075 CGF.FinishFunction();
3076 return Fn;
3077}
3078
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003079void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003080 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00003081 SourceLocation Loc,
3082 ArrayRef<const Expr *> CopyprivateVars,
3083 ArrayRef<const Expr *> SrcExprs,
3084 ArrayRef<const Expr *> DstExprs,
3085 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003086 if (!CGF.HaveInsertPoint())
3087 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00003088 assert(CopyprivateVars.size() == SrcExprs.size() &&
3089 CopyprivateVars.size() == DstExprs.size() &&
3090 CopyprivateVars.size() == AssignmentOps.size());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003091 ASTContext &C = CGM.getContext();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003092 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003093 // if(__kmpc_single(ident_t *, gtid)) {
3094 // SingleOpGen();
3095 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003096 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003097 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00003098 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3099 // <copy_func>, did_it);
3100
John McCall7f416cc2015-09-08 08:05:57 +00003101 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003102 if (!CopyprivateVars.empty()) {
3103 // int32 did_it = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003104 QualType KmpInt32Ty =
3105 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003106 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00003107 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003108 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003109 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00003110 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003111 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
3112 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
3113 /*Conditional=*/true);
3114 SingleOpGen.setAction(Action);
3115 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
3116 if (DidIt.isValid()) {
3117 // did_it = 1;
3118 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
3119 }
3120 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003121 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3122 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00003123 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00003124 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003125 QualType CopyprivateArrayTy =
Alexey Bataeva63048e2015-03-23 06:18:07 +00003126 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3127 /*IndexTypeQuals=*/0);
3128 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00003129 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00003130 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
3131 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00003132 Address Elem = CGF.Builder.CreateConstArrayGEP(
3133 CopyprivateList, I, CGF.getPointerSize());
3134 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00003135 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003136 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
3137 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003138 }
3139 // Build function that copies private values from single region to all other
3140 // threads in the corresponding parallel region.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003141 llvm::Value *CpyFn = emitCopyprivateCopyFunction(
Alexey Bataeva63048e2015-03-23 06:18:07 +00003142 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003143 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps, Loc);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003144 llvm::Value *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00003145 Address CL =
3146 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
3147 CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003148 llvm::Value *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003149 llvm::Value *Args[] = {
3150 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
3151 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00003152 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00003153 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00003154 CpyFn, // void (*) (void *, void *) <copy_func>
3155 DidItVal // i32 did_it
3156 };
3157 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
3158 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003159}
3160
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003161void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
3162 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00003163 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003164 if (!CGF.HaveInsertPoint())
3165 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003166 // __kmpc_ordered(ident_t *, gtid);
3167 // OrderedOpGen();
3168 // __kmpc_end_ordered(ident_t *, gtid);
3169 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00003170 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003171 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003172 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
3173 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
3174 Args);
3175 OrderedOpGen.setAction(Action);
3176 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
3177 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003178 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003179 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003180}
3181
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003182void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00003183 OpenMPDirectiveKind Kind, bool EmitChecks,
3184 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003185 if (!CGF.HaveInsertPoint())
3186 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00003187 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003188 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003189 unsigned Flags;
3190 if (Kind == OMPD_for)
3191 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
3192 else if (Kind == OMPD_sections)
3193 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
3194 else if (Kind == OMPD_single)
3195 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
3196 else if (Kind == OMPD_barrier)
3197 Flags = OMP_IDENT_BARRIER_EXPL;
3198 else
3199 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003200 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
3201 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003202 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
3203 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003204 if (auto *OMPRegionInfo =
3205 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00003206 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003207 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003208 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00003209 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003210 // if (__kmpc_cancel_barrier()) {
3211 // exit from construct;
3212 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003213 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
3214 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
3215 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003216 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
3217 CGF.EmitBlock(ExitBB);
3218 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003219 CodeGenFunction::JumpDest CancelDestination =
Alexey Bataev25e5b442015-09-15 12:52:43 +00003220 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003221 CGF.EmitBranchThroughCleanup(CancelDestination);
3222 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
3223 }
3224 return;
3225 }
3226 }
3227 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00003228}
3229
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003230/// Map the OpenMP loop schedule to the runtime enumeration.
Alexander Musmanc6388682014-12-15 07:07:06 +00003231static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003232 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003233 switch (ScheduleKind) {
3234 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003235 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
3236 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00003237 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003238 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003239 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003240 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003241 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003242 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
3243 case OMPC_SCHEDULE_auto:
3244 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00003245 case OMPC_SCHEDULE_unknown:
3246 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003247 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00003248 }
3249 llvm_unreachable("Unexpected runtime schedule");
3250}
3251
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003252/// Map the OpenMP distribute schedule to the runtime enumeration.
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003253static OpenMPSchedType
3254getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
3255 // only static is allowed for dist_schedule
3256 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
3257}
3258
Alexander Musmanc6388682014-12-15 07:07:06 +00003259bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
3260 bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003261 OpenMPSchedType Schedule =
3262 getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00003263 return Schedule == OMP_sch_static;
3264}
3265
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003266bool CGOpenMPRuntime::isStaticNonchunked(
3267 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003268 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003269 return Schedule == OMP_dist_sch_static;
3270}
3271
3272
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003273bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003274 OpenMPSchedType Schedule =
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003275 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003276 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
3277 return Schedule != OMP_sch_static;
3278}
3279
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003280static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
3281 OpenMPScheduleClauseModifier M1,
3282 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00003283 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003284 switch (M1) {
3285 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003286 Modifier = OMP_sch_modifier_monotonic;
3287 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003288 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003289 Modifier = OMP_sch_modifier_nonmonotonic;
3290 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003291 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003292 if (Schedule == OMP_sch_static_chunked)
3293 Schedule = OMP_sch_static_balanced_chunked;
3294 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003295 case OMPC_SCHEDULE_MODIFIER_last:
3296 case OMPC_SCHEDULE_MODIFIER_unknown:
3297 break;
3298 }
3299 switch (M2) {
3300 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003301 Modifier = OMP_sch_modifier_monotonic;
3302 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003303 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003304 Modifier = OMP_sch_modifier_nonmonotonic;
3305 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003306 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003307 if (Schedule == OMP_sch_static_chunked)
3308 Schedule = OMP_sch_static_balanced_chunked;
3309 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003310 case OMPC_SCHEDULE_MODIFIER_last:
3311 case OMPC_SCHEDULE_MODIFIER_unknown:
3312 break;
3313 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00003314 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003315}
3316
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003317void CGOpenMPRuntime::emitForDispatchInit(
3318 CodeGenFunction &CGF, SourceLocation Loc,
3319 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
3320 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003321 if (!CGF.HaveInsertPoint())
3322 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003323 OpenMPSchedType Schedule = getRuntimeSchedule(
3324 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00003325 assert(Ordered ||
3326 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00003327 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
3328 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00003329 // Call __kmpc_dispatch_init(
3330 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
3331 // kmp_int[32|64] lower, kmp_int[32|64] upper,
3332 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00003333
John McCall7f416cc2015-09-08 08:05:57 +00003334 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003335 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
3336 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00003337 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003338 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3339 CGF.Builder.getInt32(addMonoNonMonoModifier(
3340 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003341 DispatchValues.LB, // Lower
3342 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003343 CGF.Builder.getIntN(IVSize, 1), // Stride
3344 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00003345 };
3346 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
3347}
3348
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003349static void emitForStaticInitCall(
3350 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
3351 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
3352 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003353 const CGOpenMPRuntime::StaticRTInput &Values) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003354 if (!CGF.HaveInsertPoint())
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003355 return;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003356
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003357 assert(!Values.Ordered);
3358 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
3359 Schedule == OMP_sch_static_balanced_chunked ||
3360 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
3361 Schedule == OMP_dist_sch_static ||
3362 Schedule == OMP_dist_sch_static_chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003363
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003364 // Call __kmpc_for_static_init(
3365 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
3366 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
3367 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
3368 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
3369 llvm::Value *Chunk = Values.Chunk;
3370 if (Chunk == nullptr) {
3371 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
3372 Schedule == OMP_dist_sch_static) &&
3373 "expected static non-chunked schedule");
3374 // If the Chunk was not specified in the clause - use default value 1.
3375 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3376 } else {
3377 assert((Schedule == OMP_sch_static_chunked ||
3378 Schedule == OMP_sch_static_balanced_chunked ||
3379 Schedule == OMP_ord_static_chunked ||
3380 Schedule == OMP_dist_sch_static_chunked) &&
3381 "expected static chunked schedule");
3382 }
3383 llvm::Value *Args[] = {
3384 UpdateLocation,
3385 ThreadId,
3386 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3387 M2)), // Schedule type
3388 Values.IL.getPointer(), // &isLastIter
3389 Values.LB.getPointer(), // &LB
3390 Values.UB.getPointer(), // &UB
3391 Values.ST.getPointer(), // &Stride
3392 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3393 Chunk // Chunk
3394 };
3395 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003396}
3397
John McCall7f416cc2015-09-08 08:05:57 +00003398void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3399 SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003400 OpenMPDirectiveKind DKind,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003401 const OpenMPScheduleTy &ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003402 const StaticRTInput &Values) {
3403 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3404 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3405 assert(isOpenMPWorksharingDirective(DKind) &&
3406 "Expected loop-based or sections-based directive.");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003407 llvm::Value *UpdatedLocation = emitUpdateLocation(CGF, Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003408 isOpenMPLoopDirective(DKind)
3409 ? OMP_IDENT_WORK_LOOP
3410 : OMP_IDENT_WORK_SECTIONS);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003411 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3412 llvm::Constant *StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003413 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003414 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003415 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003416}
John McCall7f416cc2015-09-08 08:05:57 +00003417
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003418void CGOpenMPRuntime::emitDistributeStaticInit(
3419 CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003420 OpenMPDistScheduleClauseKind SchedKind,
3421 const CGOpenMPRuntime::StaticRTInput &Values) {
3422 OpenMPSchedType ScheduleNum =
3423 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003424 llvm::Value *UpdatedLocation =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003425 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003426 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3427 llvm::Constant *StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003428 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003429 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3430 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003431 OMPC_SCHEDULE_MODIFIER_unknown, Values);
Alexander Musmanc6388682014-12-15 07:07:06 +00003432}
3433
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003434void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
Alexey Bataevf43f7142017-09-06 16:17:35 +00003435 SourceLocation Loc,
3436 OpenMPDirectiveKind DKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003437 if (!CGF.HaveInsertPoint())
3438 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003439 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataevf43f7142017-09-06 16:17:35 +00003440 llvm::Value *Args[] = {
3441 emitUpdateLocation(CGF, Loc,
3442 isOpenMPDistributeDirective(DKind)
3443 ? OMP_IDENT_WORK_DISTRIBUTE
3444 : isOpenMPLoopDirective(DKind)
3445 ? OMP_IDENT_WORK_LOOP
3446 : OMP_IDENT_WORK_SECTIONS),
3447 getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003448 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3449 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003450}
3451
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003452void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3453 SourceLocation Loc,
3454 unsigned IVSize,
3455 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003456 if (!CGF.HaveInsertPoint())
3457 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003458 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003459 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003460 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3461}
3462
Alexander Musman92bdaab2015-03-12 13:37:50 +00003463llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3464 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003465 bool IVSigned, Address IL,
3466 Address LB, Address UB,
3467 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003468 // Call __kmpc_dispatch_next(
3469 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3470 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3471 // kmp_int[32|64] *p_stride);
3472 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003473 emitUpdateLocation(CGF, Loc),
3474 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003475 IL.getPointer(), // &isLastIter
3476 LB.getPointer(), // &Lower
3477 UB.getPointer(), // &Upper
3478 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003479 };
3480 llvm::Value *Call =
3481 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3482 return CGF.EmitScalarConversion(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003483 Call, CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/1),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003484 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003485}
3486
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003487void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3488 llvm::Value *NumThreads,
3489 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003490 if (!CGF.HaveInsertPoint())
3491 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003492 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3493 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003494 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003495 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003496 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3497 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003498}
3499
Alexey Bataev7f210c62015-06-18 13:40:03 +00003500void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3501 OpenMPProcBindClauseKind ProcBind,
3502 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003503 if (!CGF.HaveInsertPoint())
3504 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003505 // Constants for proc bind value accepted by the runtime.
3506 enum ProcBindTy {
3507 ProcBindFalse = 0,
3508 ProcBindTrue,
3509 ProcBindMaster,
3510 ProcBindClose,
3511 ProcBindSpread,
3512 ProcBindIntel,
3513 ProcBindDefault
3514 } RuntimeProcBind;
3515 switch (ProcBind) {
3516 case OMPC_PROC_BIND_master:
3517 RuntimeProcBind = ProcBindMaster;
3518 break;
3519 case OMPC_PROC_BIND_close:
3520 RuntimeProcBind = ProcBindClose;
3521 break;
3522 case OMPC_PROC_BIND_spread:
3523 RuntimeProcBind = ProcBindSpread;
3524 break;
3525 case OMPC_PROC_BIND_unknown:
3526 llvm_unreachable("Unsupported proc_bind value.");
3527 }
3528 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3529 llvm::Value *Args[] = {
3530 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3531 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3532 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3533}
3534
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003535void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3536 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003537 if (!CGF.HaveInsertPoint())
3538 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003539 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003540 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3541 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003542}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003543
Alexey Bataev62b63b12015-03-10 07:28:44 +00003544namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003545/// Indexes of fields for type kmp_task_t.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003546enum KmpTaskTFields {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003547 /// List of shared variables.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003548 KmpTaskTShareds,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003549 /// Task routine.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003550 KmpTaskTRoutine,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003551 /// Partition id for the untied tasks.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003552 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003553 /// Function with call of destructors for private variables.
3554 Data1,
3555 /// Task priority.
3556 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003557 /// (Taskloops only) Lower bound.
3558 KmpTaskTLowerBound,
3559 /// (Taskloops only) Upper bound.
3560 KmpTaskTUpperBound,
3561 /// (Taskloops only) Stride.
3562 KmpTaskTStride,
3563 /// (Taskloops only) Is last iteration flag.
3564 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003565 /// (Taskloops only) Reduction data.
3566 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003567};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003568} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003569
Samuel Antaoee8fb302016-01-06 13:42:12 +00003570bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003571 return OffloadEntriesTargetRegion.empty() &&
3572 OffloadEntriesDeviceGlobalVar.empty();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003573}
3574
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003575/// Initialize target region entry.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003576void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3577 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3578 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003579 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003580 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3581 "only required for the device "
3582 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003583 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003584 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003585 OMPTargetRegionEntryTargetRegion);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003586 ++OffloadingEntriesNum;
3587}
3588
3589void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3590 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3591 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003592 llvm::Constant *Addr, llvm::Constant *ID,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003593 OMPTargetRegionEntryKind Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003594 // If we are emitting code for a target, the entry is already initialized,
3595 // only has to be registered.
3596 if (CGM.getLangOpts().OpenMPIsDevice) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00003597 if (!hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum)) {
3598 unsigned DiagID = CGM.getDiags().getCustomDiagID(
3599 DiagnosticsEngine::Error,
3600 "Unable to find target region on line '%0' in the device code.");
3601 CGM.getDiags().Report(DiagID) << LineNum;
3602 return;
3603 }
Samuel Antao2de62b02016-02-13 23:35:10 +00003604 auto &Entry =
3605 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003606 assert(Entry.isValid() && "Entry not initialized!");
3607 Entry.setAddress(Addr);
3608 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003609 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003610 } else {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003611 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003612 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00003613 ++OffloadingEntriesNum;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003614 }
3615}
3616
3617bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003618 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3619 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003620 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3621 if (PerDevice == OffloadEntriesTargetRegion.end())
3622 return false;
3623 auto PerFile = PerDevice->second.find(FileID);
3624 if (PerFile == PerDevice->second.end())
3625 return false;
3626 auto PerParentName = PerFile->second.find(ParentName);
3627 if (PerParentName == PerFile->second.end())
3628 return false;
3629 auto PerLine = PerParentName->second.find(LineNum);
3630 if (PerLine == PerParentName->second.end())
3631 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003632 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003633 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003634 return false;
3635 return true;
3636}
3637
3638void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3639 const OffloadTargetRegionEntryInfoActTy &Action) {
3640 // Scan all target region entries and perform the provided action.
Alexey Bataev03f270c2018-03-30 18:31:07 +00003641 for (const auto &D : OffloadEntriesTargetRegion)
3642 for (const auto &F : D.second)
3643 for (const auto &P : F.second)
3644 for (const auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003645 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003646}
3647
Alexey Bataev03f270c2018-03-30 18:31:07 +00003648void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3649 initializeDeviceGlobalVarEntryInfo(StringRef Name,
3650 OMPTargetGlobalVarEntryKind Flags,
3651 unsigned Order) {
3652 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3653 "only required for the device "
3654 "code generation.");
3655 OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags);
3656 ++OffloadingEntriesNum;
3657}
Samuel Antaoee8fb302016-01-06 13:42:12 +00003658
Alexey Bataev03f270c2018-03-30 18:31:07 +00003659void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3660 registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr,
3661 CharUnits VarSize,
3662 OMPTargetGlobalVarEntryKind Flags,
3663 llvm::GlobalValue::LinkageTypes Linkage) {
3664 if (CGM.getLangOpts().OpenMPIsDevice) {
3665 auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
3666 assert(Entry.isValid() && Entry.getFlags() == Flags &&
3667 "Entry not initialized!");
3668 assert((!Entry.getAddress() || Entry.getAddress() == Addr) &&
3669 "Resetting with the new address.");
3670 if (Entry.getAddress() && hasDeviceGlobalVarEntryInfo(VarName))
3671 return;
3672 Entry.setAddress(Addr);
3673 Entry.setVarSize(VarSize);
3674 Entry.setLinkage(Linkage);
3675 } else {
3676 if (hasDeviceGlobalVarEntryInfo(VarName))
3677 return;
3678 OffloadEntriesDeviceGlobalVar.try_emplace(
3679 VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage);
3680 ++OffloadingEntriesNum;
3681 }
3682}
3683
3684void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3685 actOnDeviceGlobalVarEntriesInfo(
3686 const OffloadDeviceGlobalVarEntryInfoActTy &Action) {
3687 // Scan all target region entries and perform the provided action.
3688 for (const auto &E : OffloadEntriesDeviceGlobalVar)
3689 Action(E.getKey(), E.getValue());
Samuel Antaoee8fb302016-01-06 13:42:12 +00003690}
3691
3692llvm::Function *
3693CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003694 // If we don't have entries or if we are emitting code for the device, we
3695 // don't need to do anything.
3696 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3697 return nullptr;
3698
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003699 llvm::Module &M = CGM.getModule();
3700 ASTContext &C = CGM.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003701
3702 // Get list of devices we care about
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003703 const std::vector<llvm::Triple> &Devices = CGM.getLangOpts().OMPTargetTriples;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003704
3705 // We should be creating an offloading descriptor only if there are devices
3706 // specified.
3707 assert(!Devices.empty() && "No OpenMP offloading devices??");
3708
3709 // Create the external variables that will point to the begin and end of the
3710 // host entries section. These will be defined by the linker.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003711 llvm::Type *OffloadEntryTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00003712 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
Alexey Bataev18fa2322018-05-02 14:20:50 +00003713 std::string EntriesBeginName = getName({"omp_offloading", "entries_begin"});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003714 auto *HostEntriesBegin = new llvm::GlobalVariable(
Samuel Antaoee8fb302016-01-06 13:42:12 +00003715 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003716 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003717 EntriesBeginName);
3718 std::string EntriesEndName = getName({"omp_offloading", "entries_end"});
3719 auto *HostEntriesEnd =
3720 new llvm::GlobalVariable(M, OffloadEntryTy, /*isConstant=*/true,
3721 llvm::GlobalValue::ExternalLinkage,
3722 /*Initializer=*/nullptr, EntriesEndName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003723
3724 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003725 auto *DeviceImageTy = cast<llvm::StructType>(
3726 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003727 ConstantInitBuilder DeviceImagesBuilder(CGM);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003728 ConstantArrayBuilder DeviceImagesEntries =
3729 DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003730
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003731 for (const llvm::Triple &Device : Devices) {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003732 StringRef T = Device.getTriple();
Alexey Bataev18fa2322018-05-02 14:20:50 +00003733 std::string BeginName = getName({"omp_offloading", "img_start", ""});
Samuel Antaoee8fb302016-01-06 13:42:12 +00003734 auto *ImgBegin = new llvm::GlobalVariable(
Alexey Bataev62a4cb02018-07-31 18:27:42 +00003735 M, CGM.Int8Ty, /*isConstant=*/true,
3736 llvm::GlobalValue::ExternalWeakLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003737 /*Initializer=*/nullptr, Twine(BeginName).concat(T));
3738 std::string EndName = getName({"omp_offloading", "img_end", ""});
Samuel Antaoee8fb302016-01-06 13:42:12 +00003739 auto *ImgEnd = new llvm::GlobalVariable(
Alexey Bataev62a4cb02018-07-31 18:27:42 +00003740 M, CGM.Int8Ty, /*isConstant=*/true,
3741 llvm::GlobalValue::ExternalWeakLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003742 /*Initializer=*/nullptr, Twine(EndName).concat(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003743
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003744 llvm::Constant *Data[] = {ImgBegin, ImgEnd, HostEntriesBegin,
3745 HostEntriesEnd};
3746 createConstantGlobalStructAndAddToParent(CGM, getTgtDeviceImageQTy(), Data,
3747 DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003748 }
3749
3750 // Create device images global array.
Alexey Bataev18fa2322018-05-02 14:20:50 +00003751 std::string ImagesName = getName({"omp_offloading", "device_images"});
John McCall6c9f1fdb2016-11-19 08:17:24 +00003752 llvm::GlobalVariable *DeviceImages =
Alexey Bataev18fa2322018-05-02 14:20:50 +00003753 DeviceImagesEntries.finishAndCreateGlobal(ImagesName,
3754 CGM.getPointerAlign(),
3755 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003756 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003757
3758 // This is a Zero array to be used in the creation of the constant expressions
3759 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3760 llvm::Constant::getNullValue(CGM.Int32Ty)};
3761
3762 // Create the target region descriptor.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003763 llvm::Constant *Data[] = {
3764 llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
3765 llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3766 DeviceImages, Index),
3767 HostEntriesBegin, HostEntriesEnd};
Alexey Bataev18fa2322018-05-02 14:20:50 +00003768 std::string Descriptor = getName({"omp_offloading", "descriptor"});
Mike Ricee1ca7b62018-08-29 15:45:11 +00003769 llvm::GlobalVariable *Desc = createGlobalStruct(
3770 CGM, getTgtBinaryDescriptorQTy(), /*IsConstant=*/true, Data, Descriptor);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003771
3772 // Emit code to register or unregister the descriptor at execution
3773 // startup or closing, respectively.
3774
Alexey Bataev03f270c2018-03-30 18:31:07 +00003775 llvm::Function *UnRegFn;
3776 {
3777 FunctionArgList Args;
3778 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
3779 Args.push_back(&DummyPtr);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003780
Alexey Bataev03f270c2018-03-30 18:31:07 +00003781 CodeGenFunction CGF(CGM);
3782 // Disable debug info for global (de-)initializer because they are not part
3783 // of some particular construct.
3784 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003785 const auto &FI =
3786 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3787 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003788 std::string UnregName = getName({"omp_offloading", "descriptor_unreg"});
3789 UnRegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, UnregName, FI);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003790 CGF.StartFunction(GlobalDecl(), C.VoidTy, UnRegFn, FI, Args);
3791 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3792 Desc);
3793 CGF.FinishFunction();
3794 }
3795 llvm::Function *RegFn;
3796 {
3797 CodeGenFunction CGF(CGM);
3798 // Disable debug info for global (de-)initializer because they are not part
3799 // of some particular construct.
3800 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003801 const auto &FI = CGM.getTypes().arrangeNullaryFunction();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003802 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Sergey Dmitrievbde9cf92018-08-03 20:19:28 +00003803
3804 // Encode offload target triples into the registration function name. It
3805 // will serve as a comdat key for the registration/unregistration code for
3806 // this particular combination of offloading targets.
3807 SmallVector<StringRef, 4U> RegFnNameParts(Devices.size() + 2U);
3808 RegFnNameParts[0] = "omp_offloading";
3809 RegFnNameParts[1] = "descriptor_reg";
3810 llvm::transform(Devices, std::next(RegFnNameParts.begin(), 2),
3811 [](const llvm::Triple &T) -> const std::string& {
3812 return T.getTriple();
3813 });
3814 llvm::sort(std::next(RegFnNameParts.begin(), 2), RegFnNameParts.end());
3815 std::string Descriptor = getName(RegFnNameParts);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003816 RegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, Descriptor, FI);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003817 CGF.StartFunction(GlobalDecl(), C.VoidTy, RegFn, FI, FunctionArgList());
3818 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib), Desc);
3819 // Create a variable to drive the registration and unregistration of the
3820 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3821 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(),
3822 SourceLocation(), nullptr, C.CharTy,
3823 ImplicitParamDecl::Other);
3824 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3825 CGF.FinishFunction();
3826 }
George Rokos29d0f002017-05-27 03:03:13 +00003827 if (CGM.supportsCOMDAT()) {
3828 // It is sufficient to call registration function only once, so create a
3829 // COMDAT group for registration/unregistration functions and associated
3830 // data. That would reduce startup time and code size. Registration
3831 // function serves as a COMDAT group key.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003832 llvm::Comdat *ComdatKey = M.getOrInsertComdat(RegFn->getName());
George Rokos29d0f002017-05-27 03:03:13 +00003833 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3834 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3835 RegFn->setComdat(ComdatKey);
3836 UnRegFn->setComdat(ComdatKey);
3837 DeviceImages->setComdat(ComdatKey);
3838 Desc->setComdat(ComdatKey);
3839 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003840 return RegFn;
3841}
3842
Alexey Bataev03f270c2018-03-30 18:31:07 +00003843void CGOpenMPRuntime::createOffloadEntry(
3844 llvm::Constant *ID, llvm::Constant *Addr, uint64_t Size, int32_t Flags,
3845 llvm::GlobalValue::LinkageTypes Linkage) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003846 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003847 llvm::Module &M = CGM.getModule();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003848 llvm::LLVMContext &C = M.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003849
3850 // Create constant string with the name.
3851 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3852
Alexey Bataev18fa2322018-05-02 14:20:50 +00003853 std::string StringName = getName({"omp_offloading", "entry_name"});
3854 auto *Str = new llvm::GlobalVariable(
3855 M, StrPtrInit->getType(), /*isConstant=*/true,
3856 llvm::GlobalValue::InternalLinkage, StrPtrInit, StringName);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003857 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003858
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003859 llvm::Constant *Data[] = {llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy),
3860 llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy),
3861 llvm::ConstantInt::get(CGM.SizeTy, Size),
3862 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
3863 llvm::ConstantInt::get(CGM.Int32Ty, 0)};
Alexey Bataev18fa2322018-05-02 14:20:50 +00003864 std::string EntryName = getName({"omp_offloading", "entry", ""});
Mike Ricee1ca7b62018-08-29 15:45:11 +00003865 llvm::GlobalVariable *Entry = createGlobalStruct(
3866 CGM, getTgtOffloadEntryQTy(), /*IsConstant=*/true, Data,
3867 Twine(EntryName).concat(Name), llvm::GlobalValue::WeakAnyLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003868
3869 // The entry has to be created in the section the linker expects it to be.
Alexey Bataev18fa2322018-05-02 14:20:50 +00003870 std::string Section = getName({"omp_offloading", "entries"});
3871 Entry->setSection(Section);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003872}
3873
3874void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3875 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003876 // can easily figure out what to emit. The produced metadata looks like
3877 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003878 //
3879 // !omp_offload.info = !{!1, ...}
3880 //
3881 // Right now we only generate metadata for function that contain target
3882 // regions.
3883
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003884 // If we do not have entries, we don't need to do anything.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003885 if (OffloadEntriesInfoManager.empty())
3886 return;
3887
3888 llvm::Module &M = CGM.getModule();
3889 llvm::LLVMContext &C = M.getContext();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003890 SmallVector<const OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
Samuel Antaoee8fb302016-01-06 13:42:12 +00003891 OrderedEntries(OffloadEntriesInfoManager.size());
3892
Simon Pilgrim2c518802017-03-30 14:13:19 +00003893 // Auxiliary methods to create metadata values and strings.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003894 auto &&GetMDInt = [this](unsigned V) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003895 return llvm::ConstantAsMetadata::get(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003896 llvm::ConstantInt::get(CGM.Int32Ty, V));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003897 };
3898
Alexey Bataev03f270c2018-03-30 18:31:07 +00003899 auto &&GetMDString = [&C](StringRef V) { return llvm::MDString::get(C, V); };
3900
3901 // Create the offloading info metadata node.
3902 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003903
3904 // Create function that emits metadata for each target region entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00003905 auto &&TargetRegionMetadataEmitter =
3906 [&C, MD, &OrderedEntries, &GetMDInt, &GetMDString](
3907 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3908 unsigned Line,
3909 const OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3910 // Generate metadata for target regions. Each entry of this metadata
3911 // contains:
3912 // - Entry 0 -> Kind of this type of metadata (0).
3913 // - Entry 1 -> Device ID of the file where the entry was identified.
3914 // - Entry 2 -> File ID of the file where the entry was identified.
3915 // - Entry 3 -> Mangled name of the function where the entry was
3916 // identified.
3917 // - Entry 4 -> Line in the file where the entry was identified.
3918 // - Entry 5 -> Order the entry was created.
3919 // The first element of the metadata node is the kind.
3920 llvm::Metadata *Ops[] = {GetMDInt(E.getKind()), GetMDInt(DeviceID),
3921 GetMDInt(FileID), GetMDString(ParentName),
3922 GetMDInt(Line), GetMDInt(E.getOrder())};
Samuel Antaoee8fb302016-01-06 13:42:12 +00003923
Alexey Bataev03f270c2018-03-30 18:31:07 +00003924 // Save this entry in the right position of the ordered entries array.
3925 OrderedEntries[E.getOrder()] = &E;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003926
Alexey Bataev03f270c2018-03-30 18:31:07 +00003927 // Add metadata to the named metadata node.
3928 MD->addOperand(llvm::MDNode::get(C, Ops));
3929 };
Samuel Antaoee8fb302016-01-06 13:42:12 +00003930
3931 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3932 TargetRegionMetadataEmitter);
3933
Alexey Bataev03f270c2018-03-30 18:31:07 +00003934 // Create function that emits metadata for each device global variable entry;
3935 auto &&DeviceGlobalVarMetadataEmitter =
3936 [&C, &OrderedEntries, &GetMDInt, &GetMDString,
3937 MD](StringRef MangledName,
3938 const OffloadEntriesInfoManagerTy::OffloadEntryInfoDeviceGlobalVar
3939 &E) {
3940 // Generate metadata for global variables. Each entry of this metadata
3941 // contains:
3942 // - Entry 0 -> Kind of this type of metadata (1).
3943 // - Entry 1 -> Mangled name of the variable.
3944 // - Entry 2 -> Declare target kind.
3945 // - Entry 3 -> Order the entry was created.
3946 // The first element of the metadata node is the kind.
3947 llvm::Metadata *Ops[] = {
3948 GetMDInt(E.getKind()), GetMDString(MangledName),
3949 GetMDInt(E.getFlags()), GetMDInt(E.getOrder())};
3950
3951 // Save this entry in the right position of the ordered entries array.
3952 OrderedEntries[E.getOrder()] = &E;
3953
3954 // Add metadata to the named metadata node.
3955 MD->addOperand(llvm::MDNode::get(C, Ops));
3956 };
3957
3958 OffloadEntriesInfoManager.actOnDeviceGlobalVarEntriesInfo(
3959 DeviceGlobalVarMetadataEmitter);
3960
3961 for (const auto *E : OrderedEntries) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003962 assert(E && "All ordered entries must exist!");
Alexey Bataev03f270c2018-03-30 18:31:07 +00003963 if (const auto *CE =
Samuel Antaoee8fb302016-01-06 13:42:12 +00003964 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3965 E)) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00003966 if (!CE->getID() || !CE->getAddress()) {
3967 unsigned DiagID = CGM.getDiags().getCustomDiagID(
3968 DiagnosticsEngine::Error,
Alexey Bataev7f01d202018-07-16 18:12:18 +00003969 "Offloading entry for target region is incorrect: either the "
Alexey Bataev64e62dc2018-04-30 16:26:57 +00003970 "address or the ID is invalid.");
3971 CGM.getDiags().Report(DiagID);
3972 continue;
3973 }
Alexey Bataev34f8a702018-03-28 14:28:54 +00003974 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0,
Alexey Bataev03f270c2018-03-30 18:31:07 +00003975 CE->getFlags(), llvm::GlobalValue::WeakAnyLinkage);
3976 } else if (const auto *CE =
3977 dyn_cast<OffloadEntriesInfoManagerTy::
3978 OffloadEntryInfoDeviceGlobalVar>(E)) {
Alexey Bataevc52f01d2018-07-16 20:05:25 +00003979 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags =
3980 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
3981 CE->getFlags());
3982 switch (Flags) {
3983 case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo: {
3984 if (!CE->getAddress()) {
3985 unsigned DiagID = CGM.getDiags().getCustomDiagID(
3986 DiagnosticsEngine::Error,
3987 "Offloading entry for declare target variable is incorrect: the "
3988 "address is invalid.");
3989 CGM.getDiags().Report(DiagID);
3990 continue;
3991 }
3992 break;
3993 }
3994 case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink:
3995 assert(((CGM.getLangOpts().OpenMPIsDevice && !CE->getAddress()) ||
3996 (!CGM.getLangOpts().OpenMPIsDevice && CE->getAddress())) &&
3997 "Declaret target link address is set.");
3998 if (CGM.getLangOpts().OpenMPIsDevice)
3999 continue;
4000 if (!CE->getAddress()) {
4001 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4002 DiagnosticsEngine::Error,
4003 "Offloading entry for declare target variable is incorrect: the "
4004 "address is invalid.");
4005 CGM.getDiags().Report(DiagID);
4006 continue;
4007 }
4008 break;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004009 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00004010 createOffloadEntry(CE->getAddress(), CE->getAddress(),
Alexey Bataevc52f01d2018-07-16 20:05:25 +00004011 CE->getVarSize().getQuantity(), Flags,
Alexey Bataev03f270c2018-03-30 18:31:07 +00004012 CE->getLinkage());
4013 } else {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004014 llvm_unreachable("Unsupported entry kind.");
Alexey Bataev03f270c2018-03-30 18:31:07 +00004015 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004016 }
4017}
4018
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004019/// Loads all the offload entries information from the host IR
Samuel Antaoee8fb302016-01-06 13:42:12 +00004020/// metadata.
4021void CGOpenMPRuntime::loadOffloadInfoMetadata() {
4022 // If we are in target mode, load the metadata from the host IR. This code has
4023 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
4024
4025 if (!CGM.getLangOpts().OpenMPIsDevice)
4026 return;
4027
4028 if (CGM.getLangOpts().OMPHostIRFile.empty())
4029 return;
4030
4031 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004032 if (auto EC = Buf.getError()) {
4033 CGM.getDiags().Report(diag::err_cannot_open_file)
4034 << CGM.getLangOpts().OMPHostIRFile << EC.message();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004035 return;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004036 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004037
4038 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00004039 auto ME = expectedToErrorOrAndEmitErrors(
4040 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004041
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004042 if (auto EC = ME.getError()) {
4043 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4044 DiagnosticsEngine::Error, "Unable to parse host IR file '%0':'%1'");
4045 CGM.getDiags().Report(DiagID)
4046 << CGM.getLangOpts().OMPHostIRFile << EC.message();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004047 return;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004048 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004049
4050 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
4051 if (!MD)
4052 return;
4053
George Burgess IV00f70bd2018-03-01 05:43:23 +00004054 for (llvm::MDNode *MN : MD->operands()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004055 auto &&GetMDInt = [MN](unsigned Idx) {
4056 auto *V = cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004057 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
4058 };
4059
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004060 auto &&GetMDString = [MN](unsigned Idx) {
4061 auto *V = cast<llvm::MDString>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004062 return V->getString();
4063 };
4064
Alexey Bataev03f270c2018-03-30 18:31:07 +00004065 switch (GetMDInt(0)) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004066 default:
4067 llvm_unreachable("Unexpected metadata!");
4068 break;
4069 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
Alexey Bataev34f8a702018-03-28 14:28:54 +00004070 OffloadingEntryInfoTargetRegion:
Samuel Antaoee8fb302016-01-06 13:42:12 +00004071 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
Alexey Bataev03f270c2018-03-30 18:31:07 +00004072 /*DeviceID=*/GetMDInt(1), /*FileID=*/GetMDInt(2),
4073 /*ParentName=*/GetMDString(3), /*Line=*/GetMDInt(4),
4074 /*Order=*/GetMDInt(5));
4075 break;
4076 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
4077 OffloadingEntryInfoDeviceGlobalVar:
4078 OffloadEntriesInfoManager.initializeDeviceGlobalVarEntryInfo(
4079 /*MangledName=*/GetMDString(1),
4080 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
4081 /*Flags=*/GetMDInt(2)),
4082 /*Order=*/GetMDInt(3));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004083 break;
4084 }
4085 }
4086}
4087
Alexey Bataev62b63b12015-03-10 07:28:44 +00004088void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
4089 if (!KmpRoutineEntryPtrTy) {
4090 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004091 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004092 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
4093 FunctionProtoType::ExtProtoInfo EPI;
4094 KmpRoutineEntryPtrQTy = C.getPointerType(
4095 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
4096 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
4097 }
4098}
4099
Samuel Antaoee8fb302016-01-06 13:42:12 +00004100QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004101 // Make sure the type of the entry is already created. This is the type we
4102 // have to create:
4103 // struct __tgt_offload_entry{
4104 // void *addr; // Pointer to the offload entry info.
4105 // // (function or global)
4106 // char *name; // Name of the function or global.
4107 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00004108 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
4109 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004110 // };
4111 if (TgtOffloadEntryQTy.isNull()) {
4112 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004113 RecordDecl *RD = C.buildImplicitRecord("__tgt_offload_entry");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004114 RD->startDefinition();
4115 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4116 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
4117 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00004118 addFieldToRecordDecl(
4119 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4120 addFieldToRecordDecl(
4121 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004122 RD->completeDefinition();
Jonas Hahnfeld5e4df282018-01-18 15:38:03 +00004123 RD->addAttr(PackedAttr::CreateImplicit(C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004124 TgtOffloadEntryQTy = C.getRecordType(RD);
4125 }
4126 return TgtOffloadEntryQTy;
4127}
4128
4129QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
4130 // These are the types we need to build:
4131 // struct __tgt_device_image{
4132 // void *ImageStart; // Pointer to the target code start.
4133 // void *ImageEnd; // Pointer to the target code end.
4134 // // We also add the host entries to the device image, as it may be useful
4135 // // for the target runtime to have access to that information.
4136 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
4137 // // the entries.
4138 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4139 // // entries (non inclusive).
4140 // };
4141 if (TgtDeviceImageQTy.isNull()) {
4142 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004143 RecordDecl *RD = C.buildImplicitRecord("__tgt_device_image");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004144 RD->startDefinition();
4145 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4146 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4147 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4148 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4149 RD->completeDefinition();
4150 TgtDeviceImageQTy = C.getRecordType(RD);
4151 }
4152 return TgtDeviceImageQTy;
4153}
4154
4155QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
4156 // struct __tgt_bin_desc{
4157 // int32_t NumDevices; // Number of devices supported.
4158 // __tgt_device_image *DeviceImages; // Arrays of device images
4159 // // (one per device).
4160 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
4161 // // entries.
4162 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4163 // // entries (non inclusive).
4164 // };
4165 if (TgtBinaryDescriptorQTy.isNull()) {
4166 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004167 RecordDecl *RD = C.buildImplicitRecord("__tgt_bin_desc");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004168 RD->startDefinition();
4169 addFieldToRecordDecl(
4170 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4171 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
4172 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4173 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4174 RD->completeDefinition();
4175 TgtBinaryDescriptorQTy = C.getRecordType(RD);
4176 }
4177 return TgtBinaryDescriptorQTy;
4178}
4179
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004180namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00004181struct PrivateHelpersTy {
4182 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
4183 const VarDecl *PrivateElemInit)
4184 : Original(Original), PrivateCopy(PrivateCopy),
4185 PrivateElemInit(PrivateElemInit) {}
4186 const VarDecl *Original;
4187 const VarDecl *PrivateCopy;
4188 const VarDecl *PrivateElemInit;
4189};
4190typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00004191} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004192
Alexey Bataev9e034042015-05-05 04:05:12 +00004193static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00004194createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004195 if (!Privates.empty()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004196 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004197 // Build struct .kmp_privates_t. {
4198 // /* private vars */
4199 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004200 RecordDecl *RD = C.buildImplicitRecord(".kmp_privates.t");
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004201 RD->startDefinition();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004202 for (const auto &Pair : Privates) {
4203 const VarDecl *VD = Pair.second.Original;
4204 QualType Type = VD->getType().getNonReferenceType();
4205 FieldDecl *FD = addFieldToRecordDecl(C, RD, Type);
Alexey Bataevc71a4092015-09-11 10:29:41 +00004206 if (VD->hasAttrs()) {
4207 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
4208 E(VD->getAttrs().end());
4209 I != E; ++I)
4210 FD->addAttr(*I);
4211 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004212 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004213 RD->completeDefinition();
4214 return RD;
4215 }
4216 return nullptr;
4217}
4218
Alexey Bataev9e034042015-05-05 04:05:12 +00004219static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00004220createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
4221 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004222 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004223 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004224 // Build struct kmp_task_t {
4225 // void * shareds;
4226 // kmp_routine_entry_t routine;
4227 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00004228 // kmp_cmplrdata_t data1;
4229 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00004230 // For taskloops additional fields:
4231 // kmp_uint64 lb;
4232 // kmp_uint64 ub;
4233 // kmp_int64 st;
4234 // kmp_int32 liter;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004235 // void * reductions;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004236 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004237 RecordDecl *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004238 UD->startDefinition();
4239 addFieldToRecordDecl(C, UD, KmpInt32Ty);
4240 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
4241 UD->completeDefinition();
4242 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004243 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t");
Alexey Bataev62b63b12015-03-10 07:28:44 +00004244 RD->startDefinition();
4245 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4246 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
4247 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004248 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
4249 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004250 if (isOpenMPTaskLoopDirective(Kind)) {
4251 QualType KmpUInt64Ty =
4252 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4253 QualType KmpInt64Ty =
4254 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4255 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4256 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4257 addFieldToRecordDecl(C, RD, KmpInt64Ty);
4258 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004259 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004260 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004261 RD->completeDefinition();
4262 return RD;
4263}
4264
4265static RecordDecl *
4266createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004267 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004268 ASTContext &C = CGM.getContext();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004269 // Build struct kmp_task_t_with_privates {
4270 // kmp_task_t task_data;
4271 // .kmp_privates_t. privates;
4272 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004273 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004274 RD->startDefinition();
4275 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004276 if (const RecordDecl *PrivateRD = createPrivatesRecordDecl(CGM, Privates))
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004277 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004278 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004279 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004280}
4281
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004282/// Emit a proxy function which accepts kmp_task_t as the second
Alexey Bataev62b63b12015-03-10 07:28:44 +00004283/// argument.
4284/// \code
4285/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004286/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00004287/// For taskloops:
4288/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004289/// tt->reductions, tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004290/// return 0;
4291/// }
4292/// \endcode
4293static llvm::Value *
4294emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00004295 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
4296 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004297 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004298 QualType SharedsPtrTy, llvm::Value *TaskFunction,
4299 llvm::Value *TaskPrivatesMap) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004300 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004301 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004302 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4303 ImplicitParamDecl::Other);
4304 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4305 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4306 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004307 Args.push_back(&GtidArg);
4308 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004309 const auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004310 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004311 llvm::FunctionType *TaskEntryTy =
4312 CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004313 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_entry", ""});
4314 auto *TaskEntry = llvm::Function::Create(
4315 TaskEntryTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004316 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskEntry, TaskEntryFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004317 TaskEntry->setDoesNotRecurse();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004318 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004319 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args,
4320 Loc, Loc);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004321
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004322 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00004323 // tt,
4324 // For taskloops:
4325 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
4326 // tt->task_data.shareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004327 llvm::Value *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00004328 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00004329 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4330 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4331 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004332 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004333 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004334 LValue Base =
4335 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004336 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004337 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004338 LValue PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
4339 llvm::Value *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004340
4341 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004342 LValue SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
4343 llvm::Value *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev1e491372018-01-23 18:44:14 +00004344 CGF.EmitLoadOfScalar(SharedsLVal, Loc),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004345 CGF.ConvertTypeForMem(SharedsPtrTy));
4346
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004347 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4348 llvm::Value *PrivatesParam;
4349 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004350 LValue PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004351 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004352 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004353 } else {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004354 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004355 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004356
Alexey Bataev7292c292016-04-25 12:22:29 +00004357 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
4358 TaskPrivatesMap,
4359 CGF.Builder
4360 .CreatePointerBitCastOrAddrSpaceCast(
4361 TDBase.getAddress(), CGF.VoidPtrTy)
4362 .getPointer()};
4363 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
4364 std::end(CommonArgs));
4365 if (isOpenMPTaskLoopDirective(Kind)) {
4366 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004367 LValue LBLVal = CGF.EmitLValueForField(Base, *LBFI);
4368 llvm::Value *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004369 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004370 LValue UBLVal = CGF.EmitLValueForField(Base, *UBFI);
4371 llvm::Value *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004372 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004373 LValue StLVal = CGF.EmitLValueForField(Base, *StFI);
4374 llvm::Value *StParam = CGF.EmitLoadOfScalar(StLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004375 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004376 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4377 llvm::Value *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004378 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004379 LValue RLVal = CGF.EmitLValueForField(Base, *RFI);
4380 llvm::Value *RParam = CGF.EmitLoadOfScalar(RLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004381 CallArgs.push_back(LBParam);
4382 CallArgs.push_back(UBParam);
4383 CallArgs.push_back(StParam);
4384 CallArgs.push_back(LIParam);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004385 CallArgs.push_back(RParam);
Alexey Bataev7292c292016-04-25 12:22:29 +00004386 }
4387 CallArgs.push_back(SharedsParam);
4388
Alexey Bataev3c595a62017-08-14 15:01:03 +00004389 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
4390 CallArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004391 CGF.EmitStoreThroughLValue(RValue::get(CGF.Builder.getInt32(/*C=*/0)),
4392 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004393 CGF.FinishFunction();
4394 return TaskEntry;
4395}
4396
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004397static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
4398 SourceLocation Loc,
4399 QualType KmpInt32Ty,
4400 QualType KmpTaskTWithPrivatesPtrQTy,
4401 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004402 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004403 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004404 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4405 ImplicitParamDecl::Other);
4406 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4407 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4408 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004409 Args.push_back(&GtidArg);
4410 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004411 const auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004412 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004413 llvm::FunctionType *DestructorFnTy =
4414 CGM.getTypes().GetFunctionType(DestructorFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004415 std::string Name =
4416 CGM.getOpenMPRuntime().getName({"omp_task_destructor", ""});
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004417 auto *DestructorFn =
4418 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00004419 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004420 CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004421 DestructorFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004422 DestructorFn->setDoesNotRecurse();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004423 CodeGenFunction CGF(CGM);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004424 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004425 Args, Loc, Loc);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004426
Alexey Bataev31300ed2016-02-04 11:27:03 +00004427 LValue Base = CGF.EmitLoadOfPointerLValue(
4428 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4429 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004430 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004431 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
4432 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004433 Base = CGF.EmitLValueForField(Base, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004434 for (const auto *Field :
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004435 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004436 if (QualType::DestructionKind DtorKind =
4437 Field->getType().isDestructedType()) {
4438 LValue FieldLValue = CGF.EmitLValueForField(Base, Field);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004439 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
4440 }
4441 }
4442 CGF.FinishFunction();
4443 return DestructorFn;
4444}
4445
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004446/// Emit a privates mapping function for correct handling of private and
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004447/// firstprivate variables.
4448/// \code
4449/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
4450/// **noalias priv1,..., <tyn> **noalias privn) {
4451/// *priv1 = &.privates.priv1;
4452/// ...;
4453/// *privn = &.privates.privn;
4454/// }
4455/// \endcode
4456static llvm::Value *
4457emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00004458 ArrayRef<const Expr *> PrivateVars,
4459 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004460 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004461 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004462 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004463 ASTContext &C = CGM.getContext();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004464 FunctionArgList Args;
4465 ImplicitParamDecl TaskPrivatesArg(
4466 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00004467 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
4468 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004469 Args.push_back(&TaskPrivatesArg);
4470 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
4471 unsigned Counter = 1;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004472 for (const Expr *E : PrivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004473 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004474 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4475 C.getPointerType(C.getPointerType(E->getType()))
4476 .withConst()
4477 .withRestrict(),
4478 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004479 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004480 PrivateVarsPos[VD] = Counter;
4481 ++Counter;
4482 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004483 for (const Expr *E : FirstprivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004484 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004485 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4486 C.getPointerType(C.getPointerType(E->getType()))
4487 .withConst()
4488 .withRestrict(),
4489 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004490 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004491 PrivateVarsPos[VD] = Counter;
4492 ++Counter;
4493 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004494 for (const Expr *E : LastprivateVars) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004495 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004496 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4497 C.getPointerType(C.getPointerType(E->getType()))
4498 .withConst()
4499 .withRestrict(),
4500 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004501 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004502 PrivateVarsPos[VD] = Counter;
4503 ++Counter;
4504 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004505 const auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004506 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004507 llvm::FunctionType *TaskPrivatesMapTy =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004508 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004509 std::string Name =
4510 CGM.getOpenMPRuntime().getName({"omp_task_privates_map", ""});
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004511 auto *TaskPrivatesMap = llvm::Function::Create(
Alexey Bataev18fa2322018-05-02 14:20:50 +00004512 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage, Name,
4513 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004514 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004515 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00004516 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00004517 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00004518 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004519 CodeGenFunction CGF(CGM);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004520 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004521 TaskPrivatesMapFnInfo, Args, Loc, Loc);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004522
4523 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00004524 LValue Base = CGF.EmitLoadOfPointerLValue(
4525 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4526 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004527 const auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004528 Counter = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004529 for (const FieldDecl *Field : PrivatesQTyRD->fields()) {
4530 LValue FieldLVal = CGF.EmitLValueForField(Base, Field);
4531 const VarDecl *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
4532 LValue RefLVal =
4533 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
4534 LValue RefLoadLVal = CGF.EmitLoadOfPointerLValue(
Alexey Bataev31300ed2016-02-04 11:27:03 +00004535 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00004536 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004537 ++Counter;
4538 }
4539 CGF.FinishFunction();
4540 return TaskPrivatesMap;
4541}
4542
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004543static bool stable_sort_comparator(const PrivateDataTy P1,
4544 const PrivateDataTy P2) {
4545 return P1.first > P2.first;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004546}
4547
Alexey Bataevf93095a2016-05-05 08:46:22 +00004548/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00004549static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004550 const OMPExecutableDirective &D,
4551 Address KmpTaskSharedsPtr, LValue TDBase,
4552 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4553 QualType SharedsTy, QualType SharedsPtrTy,
4554 const OMPTaskDataTy &Data,
4555 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004556 ASTContext &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004557 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4558 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004559 OpenMPDirectiveKind Kind = isOpenMPTaskLoopDirective(D.getDirectiveKind())
4560 ? OMPD_taskloop
4561 : OMPD_task;
4562 const CapturedStmt &CS = *D.getCapturedStmt(Kind);
4563 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004564 LValue SrcBase;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004565 bool IsTargetTask =
4566 isOpenMPTargetDataManagementDirective(D.getDirectiveKind()) ||
4567 isOpenMPTargetExecutionDirective(D.getDirectiveKind());
4568 // For target-based directives skip 3 firstprivate arrays BasePointersArray,
4569 // PointersArray and SizesArray. The original variables for these arrays are
4570 // not captured and we get their addresses explicitly.
4571 if ((!IsTargetTask && !Data.FirstprivateVars.empty()) ||
Alexey Bataev8451efa2018-01-15 19:06:12 +00004572 (IsTargetTask && KmpTaskSharedsPtr.isValid())) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004573 SrcBase = CGF.MakeAddrLValue(
4574 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4575 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4576 SharedsTy);
4577 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004578 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004579 for (const PrivateDataTy &Pair : Privates) {
4580 const VarDecl *VD = Pair.second.PrivateCopy;
4581 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004582 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4583 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004584 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004585 if (const VarDecl *Elem = Pair.second.PrivateElemInit) {
4586 const VarDecl *OriginalVD = Pair.second.Original;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004587 // Check if the variable is the target-based BasePointersArray,
4588 // PointersArray or SizesArray.
4589 LValue SharedRefLValue;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004590 QualType Type = OriginalVD->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004591 const FieldDecl *SharedField = CapturesInfo.lookup(OriginalVD);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004592 if (IsTargetTask && !SharedField) {
4593 assert(isa<ImplicitParamDecl>(OriginalVD) &&
4594 isa<CapturedDecl>(OriginalVD->getDeclContext()) &&
4595 cast<CapturedDecl>(OriginalVD->getDeclContext())
4596 ->getNumParams() == 0 &&
4597 isa<TranslationUnitDecl>(
4598 cast<CapturedDecl>(OriginalVD->getDeclContext())
4599 ->getDeclContext()) &&
4600 "Expected artificial target data variable.");
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004601 SharedRefLValue =
4602 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type);
4603 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004604 SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4605 SharedRefLValue = CGF.MakeAddrLValue(
4606 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
4607 SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl),
4608 SharedRefLValue.getTBAAInfo());
4609 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004610 if (Type->isArrayType()) {
4611 // Initialize firstprivate array.
4612 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4613 // Perform simple memcpy.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004614 CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004615 } else {
4616 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00004617 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00004618 CGF.EmitOMPAggregateAssign(
4619 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4620 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4621 Address SrcElement) {
4622 // Clean up any temporaries needed by the initialization.
4623 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4624 InitScope.addPrivate(
4625 Elem, [SrcElement]() -> Address { return SrcElement; });
4626 (void)InitScope.Privatize();
4627 // Emit initialization for single element.
4628 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4629 CGF, &CapturesInfo);
4630 CGF.EmitAnyExprToMem(Init, DestElement,
4631 Init->getType().getQualifiers(),
4632 /*IsInitializer=*/false);
4633 });
4634 }
4635 } else {
4636 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4637 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4638 return SharedRefLValue.getAddress();
4639 });
4640 (void)InitScope.Privatize();
4641 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4642 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4643 /*capturedByInit=*/false);
4644 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004645 } else {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004646 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004647 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004648 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004649 ++FI;
4650 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004651}
4652
4653/// Check if duplication function is required for taskloops.
4654static bool checkInitIsRequired(CodeGenFunction &CGF,
4655 ArrayRef<PrivateDataTy> Privates) {
4656 bool InitRequired = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004657 for (const PrivateDataTy &Pair : Privates) {
4658 const VarDecl *VD = Pair.second.PrivateCopy;
4659 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004660 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4661 !CGF.isTrivialInitializer(Init));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004662 if (InitRequired)
4663 break;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004664 }
4665 return InitRequired;
4666}
4667
4668
4669/// Emit task_dup function (for initialization of
4670/// private/firstprivate/lastprivate vars and last_iter flag)
4671/// \code
4672/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4673/// lastpriv) {
4674/// // setup lastprivate flag
4675/// task_dst->last = lastpriv;
4676/// // could be constructor calls here...
4677/// }
4678/// \endcode
4679static llvm::Value *
4680emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4681 const OMPExecutableDirective &D,
4682 QualType KmpTaskTWithPrivatesPtrQTy,
4683 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4684 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4685 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4686 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004687 ASTContext &C = CGM.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004688 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004689 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4690 KmpTaskTWithPrivatesPtrQTy,
4691 ImplicitParamDecl::Other);
4692 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4693 KmpTaskTWithPrivatesPtrQTy,
4694 ImplicitParamDecl::Other);
4695 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4696 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004697 Args.push_back(&DstArg);
4698 Args.push_back(&SrcArg);
4699 Args.push_back(&LastprivArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004700 const auto &TaskDupFnInfo =
Alexey Bataevf93095a2016-05-05 08:46:22 +00004701 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004702 llvm::FunctionType *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004703 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_dup", ""});
4704 auto *TaskDup = llvm::Function::Create(
4705 TaskDupTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004706 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskDup, TaskDupFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004707 TaskDup->setDoesNotRecurse();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004708 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004709 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args, Loc,
4710 Loc);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004711
4712 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4713 CGF.GetAddrOfLocalVar(&DstArg),
4714 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4715 // task_dst->liter = lastpriv;
4716 if (WithLastIter) {
4717 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4718 LValue Base = CGF.EmitLValueForField(
4719 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4720 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4721 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4722 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4723 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4724 }
4725
4726 // Emit initial values for private copies (if any).
4727 assert(!Privates.empty());
4728 Address KmpTaskSharedsPtr = Address::invalid();
4729 if (!Data.FirstprivateVars.empty()) {
4730 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4731 CGF.GetAddrOfLocalVar(&SrcArg),
4732 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4733 LValue Base = CGF.EmitLValueForField(
4734 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4735 KmpTaskSharedsPtr = Address(
4736 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4737 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4738 KmpTaskTShareds)),
4739 Loc),
4740 CGF.getNaturalTypeAlignment(SharedsTy));
4741 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004742 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4743 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004744 CGF.FinishFunction();
4745 return TaskDup;
4746}
4747
Alexey Bataev8a831592016-05-10 10:36:51 +00004748/// Checks if destructor function is required to be generated.
4749/// \return true if cleanups are required, false otherwise.
4750static bool
4751checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4752 bool NeedsCleanup = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004753 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4754 const auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4755 for (const FieldDecl *FD : PrivateRD->fields()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004756 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4757 if (NeedsCleanup)
4758 break;
4759 }
4760 return NeedsCleanup;
4761}
4762
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004763CGOpenMPRuntime::TaskResultTy
4764CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4765 const OMPExecutableDirective &D,
4766 llvm::Value *TaskFunction, QualType SharedsTy,
4767 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004768 ASTContext &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004769 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004770 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004771 auto I = Data.PrivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004772 for (const Expr *E : Data.PrivateVars) {
4773 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004774 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004775 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004776 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004777 /*PrivateElemInit=*/nullptr));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004778 ++I;
4779 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004780 I = Data.FirstprivateCopies.begin();
4781 auto IElemInitRef = Data.FirstprivateInits.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004782 for (const Expr *E : Data.FirstprivateVars) {
4783 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004784 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004785 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004786 PrivateHelpersTy(
4787 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004788 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl())));
Richard Trieucc3949d2016-02-18 22:34:54 +00004789 ++I;
4790 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004791 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004792 I = Data.LastprivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004793 for (const Expr *E : Data.LastprivateVars) {
4794 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004795 Privates.emplace_back(
Alexey Bataevf93095a2016-05-05 08:46:22 +00004796 C.getDeclAlign(VD),
4797 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004798 /*PrivateElemInit=*/nullptr));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004799 ++I;
4800 }
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004801 std::stable_sort(Privates.begin(), Privates.end(), stable_sort_comparator);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004802 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004803 // Build type kmp_routine_entry_t (if not built yet).
4804 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004805 // Build type kmp_task_t (if not built yet).
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004806 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
4807 if (SavedKmpTaskloopTQTy.isNull()) {
4808 SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4809 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4810 }
4811 KmpTaskTQTy = SavedKmpTaskloopTQTy;
Alexey Bataev3a03a7f2017-10-11 15:56:38 +00004812 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004813 assert((D.getDirectiveKind() == OMPD_task ||
4814 isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||
4815 isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) &&
4816 "Expected taskloop, task or target directive");
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004817 if (SavedKmpTaskTQTy.isNull()) {
4818 SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4819 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4820 }
4821 KmpTaskTQTy = SavedKmpTaskTQTy;
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004822 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004823 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004824 // Build particular struct kmp_task_t for the given task.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004825 const RecordDecl *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004826 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004827 QualType KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004828 QualType KmpTaskTWithPrivatesPtrQTy =
4829 C.getPointerType(KmpTaskTWithPrivatesQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004830 llvm::Type *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4831 llvm::Type *KmpTaskTWithPrivatesPtrTy =
4832 KmpTaskTWithPrivatesTy->getPointerTo();
4833 llvm::Value *KmpTaskTWithPrivatesTySize =
4834 CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004835 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4836
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004837 // Emit initial values for private copies (if any).
4838 llvm::Value *TaskPrivatesMap = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004839 llvm::Type *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00004840 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004841 if (!Privates.empty()) {
4842 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004843 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4844 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4845 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004846 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4847 TaskPrivatesMap, TaskPrivatesMapTy);
4848 } else {
4849 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4850 cast<llvm::PointerType>(TaskPrivatesMapTy));
4851 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004852 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4853 // kmp_task_t *tt);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004854 llvm::Value *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004855 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4856 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4857 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004858
4859 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4860 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4861 // kmp_routine_entry_t *task_entry);
4862 // Task flags. Format is taken from
4863 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4864 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004865 enum {
4866 TiedFlag = 0x1,
4867 FinalFlag = 0x2,
4868 DestructorsFlag = 0x8,
4869 PriorityFlag = 0x20
4870 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004871 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004872 bool NeedsCleanup = false;
4873 if (!Privates.empty()) {
4874 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4875 if (NeedsCleanup)
4876 Flags = Flags | DestructorsFlag;
4877 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004878 if (Data.Priority.getInt())
4879 Flags = Flags | PriorityFlag;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004880 llvm::Value *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004881 Data.Final.getPointer()
4882 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00004883 CGF.Builder.getInt32(FinalFlag),
4884 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004885 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004886 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004887 llvm::Value *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004888 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4889 getThreadID(CGF, Loc), TaskFlags,
4890 KmpTaskTWithPrivatesTySize, SharedsSize,
4891 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4892 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004893 llvm::Value *NewTask = CGF.EmitRuntimeCall(
Alexey Bataev62b63b12015-03-10 07:28:44 +00004894 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004895 llvm::Value *NewTaskNewTaskTTy =
4896 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4897 NewTask, KmpTaskTWithPrivatesPtrTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004898 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4899 KmpTaskTWithPrivatesQTy);
4900 LValue TDBase =
4901 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004902 // Fill the data in the resulting kmp_task_t record.
4903 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00004904 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004905 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00004906 KmpTaskSharedsPtr =
4907 Address(CGF.EmitLoadOfScalar(
4908 CGF.EmitLValueForField(
4909 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4910 KmpTaskTShareds)),
4911 Loc),
4912 CGF.getNaturalTypeAlignment(SharedsTy));
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004913 LValue Dest = CGF.MakeAddrLValue(KmpTaskSharedsPtr, SharedsTy);
4914 LValue Src = CGF.MakeAddrLValue(Shareds, SharedsTy);
Richard Smithe78fac52018-04-05 20:52:58 +00004915 CGF.EmitAggregateCopy(Dest, Src, SharedsTy, AggValueSlot::DoesNotOverlap);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004916 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004917 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00004918 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004919 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004920 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4921 SharedsTy, SharedsPtrTy, Data, Privates,
4922 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004923 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4924 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4925 Result.TaskDupFn = emitTaskDupFunction(
4926 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4927 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4928 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004929 }
4930 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00004931 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4932 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00004933 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00004934 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004935 const RecordDecl *KmpCmplrdataUD =
4936 (*FI)->getType()->getAsUnionType()->getDecl();
Alexey Bataevad537bb2016-05-30 09:06:50 +00004937 if (NeedsCleanup) {
4938 llvm::Value *DestructorFn = emitDestructorsFunction(
4939 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4940 KmpTaskTWithPrivatesQTy);
4941 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4942 LValue DestructorsLV = CGF.EmitLValueForField(
4943 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4944 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4945 DestructorFn, KmpRoutineEntryPtrTy),
4946 DestructorsLV);
4947 }
4948 // Set priority.
4949 if (Data.Priority.getInt()) {
4950 LValue Data2LV = CGF.EmitLValueForField(
4951 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
4952 LValue PriorityLV = CGF.EmitLValueForField(
4953 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
4954 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
4955 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004956 Result.NewTask = NewTask;
4957 Result.TaskEntry = TaskEntry;
4958 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
4959 Result.TDBase = TDBase;
4960 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
4961 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00004962}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004963
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004964void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
4965 const OMPExecutableDirective &D,
4966 llvm::Value *TaskFunction,
4967 QualType SharedsTy, Address Shareds,
4968 const Expr *IfCond,
4969 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004970 if (!CGF.HaveInsertPoint())
4971 return;
4972
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004973 TaskResultTy Result =
4974 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4975 llvm::Value *NewTask = Result.NewTask;
4976 llvm::Value *TaskEntry = Result.TaskEntry;
4977 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
4978 LValue TDBase = Result.TDBase;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004979 const RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
4980 ASTContext &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004981 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00004982 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004983 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00004984 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004985 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00004986 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004987 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
4988 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004989 QualType FlagsTy =
4990 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004991 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
4992 if (KmpDependInfoTy.isNull()) {
4993 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
4994 KmpDependInfoRD->startDefinition();
4995 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
4996 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
4997 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
4998 KmpDependInfoRD->completeDefinition();
4999 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005000 } else {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005001 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005002 }
John McCall7f416cc2015-09-08 08:05:57 +00005003 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005004 // Define type kmp_depend_info[<Dependences.size()>];
5005 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00005006 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005007 ArrayType::Normal, /*IndexTypeQuals=*/0);
5008 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00005009 DependenciesArray =
5010 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005011 for (unsigned I = 0; I < NumDependencies; ++I) {
5012 const Expr *E = Data.Dependences[I].second;
5013 LValue Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005014 llvm::Value *Size;
5015 QualType Ty = E->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005016 if (const auto *ASE =
5017 dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005018 LValue UpAddrLVal =
5019 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
5020 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00005021 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005022 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00005023 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005024 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
5025 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005026 } else {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005027 Size = CGF.getTypeSize(Ty);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005028 }
5029 LValue Base = CGF.MakeAddrLValue(
5030 CGF.Builder.CreateConstArrayGEP(DependenciesArray, I, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005031 KmpDependInfoTy);
5032 // deps[i].base_addr = &<Dependences[i].second>;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005033 LValue BaseAddrLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005034 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00005035 CGF.EmitStoreOfScalar(
5036 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
5037 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005038 // deps[i].len = sizeof(<Dependences[i].second>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005039 LValue LenLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005040 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
5041 CGF.EmitStoreOfScalar(Size, LenLVal);
5042 // deps[i].flags = <Dependences[i].first>;
5043 RTLDependenceKindTy DepKind;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005044 switch (Data.Dependences[I].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005045 case OMPC_DEPEND_in:
5046 DepKind = DepIn;
5047 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00005048 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005049 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005050 case OMPC_DEPEND_inout:
5051 DepKind = DepInOut;
5052 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00005053 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005054 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005055 case OMPC_DEPEND_unknown:
5056 llvm_unreachable("Unknown task dependence type");
5057 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005058 LValue FlagsLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005059 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
5060 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
5061 FlagsLVal);
5062 }
John McCall7f416cc2015-09-08 08:05:57 +00005063 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5064 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005065 CGF.VoidPtrTy);
5066 }
5067
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005068 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev62b63b12015-03-10 07:28:44 +00005069 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005070 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
5071 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
5072 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
5073 // list is not empty
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005074 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5075 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00005076 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
5077 llvm::Value *DepTaskArgs[7];
5078 if (NumDependencies) {
5079 DepTaskArgs[0] = UpLoc;
5080 DepTaskArgs[1] = ThreadID;
5081 DepTaskArgs[2] = NewTask;
5082 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
5083 DepTaskArgs[4] = DependenciesArray.getPointer();
5084 DepTaskArgs[5] = CGF.Builder.getInt32(0);
5085 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5086 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005087 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
5088 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005089 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005090 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005091 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005092 LValue PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005093 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
5094 }
John McCall7f416cc2015-09-08 08:05:57 +00005095 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005096 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00005097 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00005098 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005099 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00005100 TaskArgs);
5101 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00005102 // Check if parent region is untied and build return for untied task;
5103 if (auto *Region =
5104 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5105 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00005106 };
John McCall7f416cc2015-09-08 08:05:57 +00005107
5108 llvm::Value *DepWaitTaskArgs[6];
5109 if (NumDependencies) {
5110 DepWaitTaskArgs[0] = UpLoc;
5111 DepWaitTaskArgs[1] = ThreadID;
5112 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
5113 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
5114 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
5115 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5116 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005117 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00005118 NumDependencies, &DepWaitTaskArgs,
5119 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005120 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005121 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
5122 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
5123 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
5124 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
5125 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00005126 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005127 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005128 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005129 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00005130 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
5131 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005132 Action.Enter(CGF);
5133 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00005134 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00005135 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005136 };
5137
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005138 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
5139 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005140 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
5141 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005142 RegionCodeGenTy RCG(CodeGen);
5143 CommonActionTy Action(
5144 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
5145 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
5146 RCG.setAction(Action);
5147 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005148 };
John McCall7f416cc2015-09-08 08:05:57 +00005149
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005150 if (IfCond) {
Alexey Bataev1d677132015-04-22 13:57:31 +00005151 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005152 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005153 RegionCodeGenTy ThenRCG(ThenCodeGen);
5154 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00005155 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00005156}
5157
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005158void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
5159 const OMPLoopDirective &D,
5160 llvm::Value *TaskFunction,
5161 QualType SharedsTy, Address Shareds,
5162 const Expr *IfCond,
5163 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005164 if (!CGF.HaveInsertPoint())
5165 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005166 TaskResultTy Result =
5167 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005168 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev7292c292016-04-25 12:22:29 +00005169 // libcall.
5170 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
5171 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
5172 // sched, kmp_uint64 grainsize, void *task_dup);
5173 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5174 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
5175 llvm::Value *IfVal;
5176 if (IfCond) {
5177 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
5178 /*isSigned=*/true);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005179 } else {
Alexey Bataev7292c292016-04-25 12:22:29 +00005180 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005181 }
Alexey Bataev7292c292016-04-25 12:22:29 +00005182
5183 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005184 Result.TDBase,
5185 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005186 const auto *LBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005187 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
5188 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
5189 /*IsInitializer=*/true);
5190 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005191 Result.TDBase,
5192 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005193 const auto *UBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005194 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
5195 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
5196 /*IsInitializer=*/true);
5197 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005198 Result.TDBase,
5199 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005200 const auto *StVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005201 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
5202 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
5203 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005204 // Store reductions address.
5205 LValue RedLVal = CGF.EmitLValueForField(
5206 Result.TDBase,
5207 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005208 if (Data.Reductions) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005209 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005210 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005211 CGF.EmitNullInitialization(RedLVal.getAddress(),
5212 CGF.getContext().VoidPtrTy);
5213 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005214 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00005215 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00005216 UpLoc,
5217 ThreadID,
5218 Result.NewTask,
5219 IfVal,
5220 LBLVal.getPointer(),
5221 UBLVal.getPointer(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005222 CGF.EmitLoadOfScalar(StLVal, Loc),
Alexey Bataev33446032017-07-12 18:09:32 +00005223 llvm::ConstantInt::getNullValue(
5224 CGF.IntTy), // Always 0 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005225 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005226 CGF.IntTy, Data.Schedule.getPointer()
5227 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005228 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005229 Data.Schedule.getPointer()
5230 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005231 /*isSigned=*/false)
5232 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00005233 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5234 Result.TaskDupFn, CGF.VoidPtrTy)
5235 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00005236 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
5237}
5238
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005239/// Emit reduction operation for each element of array (required for
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005240/// array sections) LHS op = RHS.
5241/// \param Type Type of array.
5242/// \param LHSVar Variable on the left side of the reduction operation
5243/// (references element of array in original variable).
5244/// \param RHSVar Variable on the right side of the reduction operation
5245/// (references element of array in original variable).
5246/// \param RedOpGen Generator of reduction operation with use of LHSVar and
5247/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00005248static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005249 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
5250 const VarDecl *RHSVar,
5251 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
5252 const Expr *, const Expr *)> &RedOpGen,
5253 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
5254 const Expr *UpExpr = nullptr) {
5255 // Perform element-by-element initialization.
5256 QualType ElementTy;
5257 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
5258 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
5259
5260 // Drill down to the base element type on both arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005261 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
5262 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005263
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005264 llvm::Value *RHSBegin = RHSAddr.getPointer();
5265 llvm::Value *LHSBegin = LHSAddr.getPointer();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005266 // Cast from pointer to array type to pointer to single element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005267 llvm::Value *LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005268 // The basic structure here is a while-do loop.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005269 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
5270 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
5271 llvm::Value *IsEmpty =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005272 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
5273 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
5274
5275 // Enter the loop body, making that address the current address.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005276 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005277 CGF.EmitBlock(BodyBB);
5278
5279 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
5280
5281 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
5282 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
5283 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
5284 Address RHSElementCurrent =
5285 Address(RHSElementPHI,
5286 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5287
5288 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
5289 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
5290 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
5291 Address LHSElementCurrent =
5292 Address(LHSElementPHI,
5293 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5294
5295 // Emit copy.
5296 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005297 Scope.addPrivate(LHSVar, [=]() { return LHSElementCurrent; });
5298 Scope.addPrivate(RHSVar, [=]() { return RHSElementCurrent; });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005299 Scope.Privatize();
5300 RedOpGen(CGF, XExpr, EExpr, UpExpr);
5301 Scope.ForceCleanup();
5302
5303 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005304 llvm::Value *LHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005305 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005306 llvm::Value *RHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005307 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
5308 // Check whether we've reached the end.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005309 llvm::Value *Done =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005310 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
5311 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
5312 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
5313 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
5314
5315 // Done.
5316 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
5317}
5318
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005319/// Emit reduction combiner. If the combiner is a simple expression emit it as
5320/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
5321/// UDR combiner function.
5322static void emitReductionCombiner(CodeGenFunction &CGF,
5323 const Expr *ReductionOp) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005324 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
5325 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
5326 if (const auto *DRE =
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005327 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005328 if (const auto *DRD =
5329 dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005330 std::pair<llvm::Function *, llvm::Function *> Reduction =
5331 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
5332 RValue Func = RValue::get(Reduction.first);
5333 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
5334 CGF.EmitIgnoredExpr(ReductionOp);
5335 return;
5336 }
5337 CGF.EmitIgnoredExpr(ReductionOp);
5338}
5339
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005340llvm::Value *CGOpenMPRuntime::emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005341 CodeGenModule &CGM, SourceLocation Loc, llvm::Type *ArgsType,
5342 ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs,
5343 ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005344 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005345
5346 // void reduction_func(void *LHSArg, void *RHSArg);
5347 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005348 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5349 ImplicitParamDecl::Other);
5350 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5351 ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005352 Args.push_back(&LHSArg);
5353 Args.push_back(&RHSArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005354 const auto &CGFI =
5355 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005356 std::string Name = getName({"omp", "reduction", "reduction_func"});
5357 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
5358 llvm::GlobalValue::InternalLinkage, Name,
5359 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005360 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005361 Fn->setDoesNotRecurse();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005362 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005363 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005364
5365 // Dst = (void*[n])(LHSArg);
5366 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00005367 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5368 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
5369 ArgsType), CGF.getPointerAlign());
5370 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5371 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
5372 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005373
5374 // ...
5375 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
5376 // ...
5377 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005378 auto IPriv = Privates.begin();
5379 unsigned Idx = 0;
5380 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005381 const auto *RHSVar =
5382 cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
5383 Scope.addPrivate(RHSVar, [&CGF, RHS, Idx, RHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005384 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005385 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005386 const auto *LHSVar =
5387 cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
5388 Scope.addPrivate(LHSVar, [&CGF, LHS, Idx, LHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005389 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005390 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005391 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00005392 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005393 // Get array size and emit VLA type.
5394 ++Idx;
5395 Address Elem =
5396 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
5397 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005398 const VariableArrayType *VLA =
5399 CGF.getContext().getAsVariableArrayType(PrivTy);
5400 const auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005401 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00005402 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005403 CGF.EmitVariablyModifiedType(PrivTy);
5404 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005405 }
5406 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005407 IPriv = Privates.begin();
5408 auto ILHS = LHSExprs.begin();
5409 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005410 for (const Expr *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005411 if ((*IPriv)->getType()->isArrayType()) {
5412 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005413 const auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5414 const auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005415 EmitOMPAggregateReduction(
5416 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5417 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5418 emitReductionCombiner(CGF, E);
5419 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005420 } else {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005421 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005422 emitReductionCombiner(CGF, E);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005423 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005424 ++IPriv;
5425 ++ILHS;
5426 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005427 }
5428 Scope.ForceCleanup();
5429 CGF.FinishFunction();
5430 return Fn;
5431}
5432
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005433void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
5434 const Expr *ReductionOp,
5435 const Expr *PrivateRef,
5436 const DeclRefExpr *LHS,
5437 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005438 if (PrivateRef->getType()->isArrayType()) {
5439 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005440 const auto *LHSVar = cast<VarDecl>(LHS->getDecl());
5441 const auto *RHSVar = cast<VarDecl>(RHS->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005442 EmitOMPAggregateReduction(
5443 CGF, PrivateRef->getType(), LHSVar, RHSVar,
5444 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5445 emitReductionCombiner(CGF, ReductionOp);
5446 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005447 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005448 // Emit reduction for array subscript or single variable.
5449 emitReductionCombiner(CGF, ReductionOp);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005450 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005451}
5452
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005453void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005454 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005455 ArrayRef<const Expr *> LHSExprs,
5456 ArrayRef<const Expr *> RHSExprs,
5457 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005458 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005459 if (!CGF.HaveInsertPoint())
5460 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005461
5462 bool WithNowait = Options.WithNowait;
5463 bool SimpleReduction = Options.SimpleReduction;
5464
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005465 // Next code should be emitted for reduction:
5466 //
5467 // static kmp_critical_name lock = { 0 };
5468 //
5469 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
5470 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
5471 // ...
5472 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
5473 // *(Type<n>-1*)rhs[<n>-1]);
5474 // }
5475 //
5476 // ...
5477 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
5478 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5479 // RedList, reduce_func, &<lock>)) {
5480 // case 1:
5481 // ...
5482 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5483 // ...
5484 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5485 // break;
5486 // case 2:
5487 // ...
5488 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5489 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00005490 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005491 // break;
5492 // default:;
5493 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005494 //
5495 // if SimpleReduction is true, only the next code is generated:
5496 // ...
5497 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5498 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005499
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005500 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005501
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005502 if (SimpleReduction) {
5503 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005504 auto IPriv = Privates.begin();
5505 auto ILHS = LHSExprs.begin();
5506 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005507 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005508 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5509 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005510 ++IPriv;
5511 ++ILHS;
5512 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005513 }
5514 return;
5515 }
5516
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005517 // 1. Build a list of reduction variables.
5518 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005519 auto Size = RHSExprs.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005520 for (const Expr *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005521 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005522 // Reserve place for array size.
5523 ++Size;
5524 }
5525 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005526 QualType ReductionArrayTy =
5527 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
5528 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00005529 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005530 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005531 auto IPriv = Privates.begin();
5532 unsigned Idx = 0;
5533 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00005534 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005535 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00005536 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005537 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00005538 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
5539 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005540 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005541 // Store array size.
5542 ++Idx;
5543 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
5544 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00005545 llvm::Value *Size = CGF.Builder.CreateIntCast(
5546 CGF.getVLASize(
5547 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
Sander de Smalen891af03a2018-02-03 13:55:59 +00005548 .NumElts,
Alexey Bataev1189bd02016-01-26 12:20:39 +00005549 CGF.SizeTy, /*isSigned=*/false);
5550 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
5551 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005552 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005553 }
5554
5555 // 2. Emit reduce_func().
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005556 llvm::Value *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005557 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
5558 Privates, LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005559
5560 // 3. Create static kmp_critical_name lock = { 0 };
Alexey Bataev18fa2322018-05-02 14:20:50 +00005561 std::string Name = getName({"reduction"});
5562 llvm::Value *Lock = getCriticalRegionLock(Name);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005563
5564 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5565 // RedList, reduce_func, &<lock>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005566 llvm::Value *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
5567 llvm::Value *ThreadId = getThreadID(CGF, Loc);
5568 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
5569 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Samuel Antao4c8035b2016-12-12 18:00:20 +00005570 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005571 llvm::Value *Args[] = {
5572 IdentTLoc, // ident_t *<loc>
5573 ThreadId, // i32 <gtid>
5574 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5575 ReductionArrayTySize, // size_type sizeof(RedList)
5576 RL, // void *RedList
5577 ReductionFn, // void (*) (void *, void *) <reduce_func>
5578 Lock // kmp_critical_name *&<lock>
5579 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005580 llvm::Value *Res = CGF.EmitRuntimeCall(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005581 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5582 : OMPRTL__kmpc_reduce),
5583 Args);
5584
5585 // 5. Build switch(res)
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005586 llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5587 llvm::SwitchInst *SwInst =
5588 CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005589
5590 // 6. Build case 1:
5591 // ...
5592 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5593 // ...
5594 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5595 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005596 llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005597 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5598 CGF.EmitBlock(Case1BB);
5599
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005600 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5601 llvm::Value *EndArgs[] = {
5602 IdentTLoc, // ident_t *<loc>
5603 ThreadId, // i32 <gtid>
5604 Lock // kmp_critical_name *&<lock>
5605 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005606 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps](
5607 CodeGenFunction &CGF, PrePostActionTy &Action) {
5608 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005609 auto IPriv = Privates.begin();
5610 auto ILHS = LHSExprs.begin();
5611 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005612 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005613 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5614 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005615 ++IPriv;
5616 ++ILHS;
5617 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005618 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005619 };
5620 RegionCodeGenTy RCG(CodeGen);
5621 CommonActionTy Action(
5622 nullptr, llvm::None,
5623 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5624 : OMPRTL__kmpc_end_reduce),
5625 EndArgs);
5626 RCG.setAction(Action);
5627 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005628
5629 CGF.EmitBranch(DefaultBB);
5630
5631 // 7. Build case 2:
5632 // ...
5633 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5634 // ...
5635 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005636 llvm::BasicBlock *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005637 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5638 CGF.EmitBlock(Case2BB);
5639
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005640 auto &&AtomicCodeGen = [Loc, Privates, LHSExprs, RHSExprs, ReductionOps](
5641 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005642 auto ILHS = LHSExprs.begin();
5643 auto IRHS = RHSExprs.begin();
5644 auto IPriv = Privates.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005645 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005646 const Expr *XExpr = nullptr;
5647 const Expr *EExpr = nullptr;
5648 const Expr *UpExpr = nullptr;
5649 BinaryOperatorKind BO = BO_Comma;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005650 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005651 if (BO->getOpcode() == BO_Assign) {
5652 XExpr = BO->getLHS();
5653 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005654 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005655 }
5656 // Try to emit update expression as a simple atomic.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005657 const Expr *RHSExpr = UpExpr;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005658 if (RHSExpr) {
5659 // Analyze RHS part of the whole expression.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005660 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005661 RHSExpr->IgnoreParenImpCasts())) {
5662 // If this is a conditional operator, analyze its condition for
5663 // min/max reduction operator.
5664 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005665 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005666 if (const auto *BORHS =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005667 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5668 EExpr = BORHS->getRHS();
5669 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005670 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005671 }
5672 if (XExpr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005673 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005674 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005675 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5676 const Expr *EExpr, const Expr *UpExpr) {
5677 LValue X = CGF.EmitLValue(XExpr);
5678 RValue E;
5679 if (EExpr)
5680 E = CGF.EmitAnyExpr(EExpr);
5681 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005682 X, E, BO, /*IsXLHSInRHSPart=*/true,
5683 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005684 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005685 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5686 PrivateScope.addPrivate(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005687 VD, [&CGF, VD, XRValue, Loc]() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005688 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5689 CGF.emitOMPSimpleStore(
5690 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5691 VD->getType().getNonReferenceType(), Loc);
5692 return LHSTemp;
5693 });
5694 (void)PrivateScope.Privatize();
5695 return CGF.EmitAnyExpr(UpExpr);
5696 });
5697 };
5698 if ((*IPriv)->getType()->isArrayType()) {
5699 // Emit atomic reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005700 const auto *RHSVar =
5701 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005702 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5703 AtomicRedGen, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005704 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005705 // Emit atomic reduction for array subscript or single variable.
5706 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005707 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005708 } else {
5709 // Emit as a critical region.
5710 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005711 const Expr *, const Expr *) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005712 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005713 std::string Name = RT.getName({"atomic_reduction"});
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005714 RT.emitCriticalRegion(
Alexey Bataev18fa2322018-05-02 14:20:50 +00005715 CGF, Name,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005716 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5717 Action.Enter(CGF);
5718 emitReductionCombiner(CGF, E);
5719 },
5720 Loc);
5721 };
5722 if ((*IPriv)->getType()->isArrayType()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005723 const auto *LHSVar =
5724 cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5725 const auto *RHSVar =
5726 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005727 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5728 CritRedGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005729 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005730 CritRedGen(CGF, nullptr, nullptr, nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005731 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005732 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005733 ++ILHS;
5734 ++IRHS;
5735 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005736 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005737 };
5738 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5739 if (!WithNowait) {
5740 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5741 llvm::Value *EndArgs[] = {
5742 IdentTLoc, // ident_t *<loc>
5743 ThreadId, // i32 <gtid>
5744 Lock // kmp_critical_name *&<lock>
5745 };
5746 CommonActionTy Action(nullptr, llvm::None,
5747 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5748 EndArgs);
5749 AtomicRCG.setAction(Action);
5750 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005751 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005752 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005753 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005754
5755 CGF.EmitBranch(DefaultBB);
5756 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5757}
5758
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005759/// Generates unique name for artificial threadprivate variables.
Alexey Bataev1c44e152018-03-06 18:59:43 +00005760/// Format is: <Prefix> "." <Decl_mangled_name> "_" "<Decl_start_loc_raw_enc>"
5761static std::string generateUniqueName(CodeGenModule &CGM, StringRef Prefix,
5762 const Expr *Ref) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005763 SmallString<256> Buffer;
5764 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev1c44e152018-03-06 18:59:43 +00005765 const clang::DeclRefExpr *DE;
5766 const VarDecl *D = ::getBaseDecl(Ref, DE);
5767 if (!D)
5768 D = cast<VarDecl>(cast<DeclRefExpr>(Ref)->getDecl());
5769 D = D->getCanonicalDecl();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005770 std::string Name = CGM.getOpenMPRuntime().getName(
5771 {D->isLocalVarDeclOrParm() ? D->getName() : CGM.getMangledName(D)});
5772 Out << Prefix << Name << "_"
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005773 << D->getCanonicalDecl()->getBeginLoc().getRawEncoding();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005774 return Out.str();
5775}
5776
5777/// Emits reduction initializer function:
5778/// \code
5779/// void @.red_init(void* %arg) {
5780/// %0 = bitcast void* %arg to <type>*
5781/// store <type> <init>, <type>* %0
5782/// ret void
5783/// }
5784/// \endcode
5785static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5786 SourceLocation Loc,
5787 ReductionCodeGen &RCG, unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005788 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005789 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005790 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5791 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005792 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005793 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005794 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005795 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005796 std::string Name = CGM.getOpenMPRuntime().getName({"red_init", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005797 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005798 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005799 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005800 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005801 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005802 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005803 Address PrivateAddr = CGF.EmitLoadOfPointer(
5804 CGF.GetAddrOfLocalVar(&Param),
5805 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5806 llvm::Value *Size = nullptr;
5807 // If the size of the reduction item is non-constant, load it from global
5808 // threadprivate variable.
5809 if (RCG.getSizes(N).second) {
5810 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5811 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005812 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005813 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5814 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005815 }
5816 RCG.emitAggregateType(CGF, N, Size);
5817 LValue SharedLVal;
5818 // If initializer uses initializer from declare reduction construct, emit a
5819 // pointer to the address of the original reduction item (reuired by reduction
5820 // initializer)
5821 if (RCG.usesReductionInitializer(N)) {
5822 Address SharedAddr =
5823 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5824 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00005825 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataev21dab122018-03-09 15:20:30 +00005826 SharedAddr = CGF.EmitLoadOfPointer(
5827 SharedAddr,
5828 CGM.getContext().VoidPtrTy.castAs<PointerType>()->getTypePtr());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005829 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5830 } else {
5831 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5832 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5833 CGM.getContext().VoidPtrTy);
5834 }
5835 // Emit the initializer:
5836 // %0 = bitcast void* %arg to <type>*
5837 // store <type> <init>, <type>* %0
5838 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5839 [](CodeGenFunction &) { return false; });
5840 CGF.FinishFunction();
5841 return Fn;
5842}
5843
5844/// Emits reduction combiner function:
5845/// \code
5846/// void @.red_comb(void* %arg0, void* %arg1) {
5847/// %lhs = bitcast void* %arg0 to <type>*
5848/// %rhs = bitcast void* %arg1 to <type>*
5849/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5850/// store <type> %2, <type>* %lhs
5851/// ret void
5852/// }
5853/// \endcode
5854static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5855 SourceLocation Loc,
5856 ReductionCodeGen &RCG, unsigned N,
5857 const Expr *ReductionOp,
5858 const Expr *LHS, const Expr *RHS,
5859 const Expr *PrivateRef) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005860 ASTContext &C = CGM.getContext();
5861 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5862 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005863 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005864 ImplicitParamDecl ParamInOut(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
5865 C.VoidPtrTy, ImplicitParamDecl::Other);
5866 ImplicitParamDecl ParamIn(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5867 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005868 Args.emplace_back(&ParamInOut);
5869 Args.emplace_back(&ParamIn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005870 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005871 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005872 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005873 std::string Name = CGM.getOpenMPRuntime().getName({"red_comb", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005874 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005875 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005876 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005877 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005878 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005879 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005880 llvm::Value *Size = nullptr;
5881 // If the size of the reduction item is non-constant, load it from global
5882 // threadprivate variable.
5883 if (RCG.getSizes(N).second) {
5884 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5885 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005886 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005887 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5888 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005889 }
5890 RCG.emitAggregateType(CGF, N, Size);
5891 // Remap lhs and rhs variables to the addresses of the function arguments.
5892 // %lhs = bitcast void* %arg0 to <type>*
5893 // %rhs = bitcast void* %arg1 to <type>*
5894 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005895 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005896 // Pull out the pointer to the variable.
5897 Address PtrAddr = CGF.EmitLoadOfPointer(
5898 CGF.GetAddrOfLocalVar(&ParamInOut),
5899 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5900 return CGF.Builder.CreateElementBitCast(
5901 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
5902 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005903 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005904 // Pull out the pointer to the variable.
5905 Address PtrAddr = CGF.EmitLoadOfPointer(
5906 CGF.GetAddrOfLocalVar(&ParamIn),
5907 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5908 return CGF.Builder.CreateElementBitCast(
5909 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
5910 });
5911 PrivateScope.Privatize();
5912 // Emit the combiner body:
5913 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
5914 // store <type> %2, <type>* %lhs
5915 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
5916 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
5917 cast<DeclRefExpr>(RHS));
5918 CGF.FinishFunction();
5919 return Fn;
5920}
5921
5922/// Emits reduction finalizer function:
5923/// \code
5924/// void @.red_fini(void* %arg) {
5925/// %0 = bitcast void* %arg to <type>*
5926/// <destroy>(<type>* %0)
5927/// ret void
5928/// }
5929/// \endcode
5930static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
5931 SourceLocation Loc,
5932 ReductionCodeGen &RCG, unsigned N) {
5933 if (!RCG.needCleanups(N))
5934 return nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005935 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005936 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005937 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5938 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005939 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005940 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005941 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005942 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005943 std::string Name = CGM.getOpenMPRuntime().getName({"red_fini", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005944 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005945 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005946 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005947 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005948 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005949 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005950 Address PrivateAddr = CGF.EmitLoadOfPointer(
5951 CGF.GetAddrOfLocalVar(&Param),
5952 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5953 llvm::Value *Size = nullptr;
5954 // If the size of the reduction item is non-constant, load it from global
5955 // threadprivate variable.
5956 if (RCG.getSizes(N).second) {
5957 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5958 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005959 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005960 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5961 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005962 }
5963 RCG.emitAggregateType(CGF, N, Size);
5964 // Emit the finalizer body:
5965 // <destroy>(<type>* %0)
5966 RCG.emitCleanups(CGF, N, PrivateAddr);
5967 CGF.FinishFunction();
5968 return Fn;
5969}
5970
5971llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
5972 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
5973 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
5974 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
5975 return nullptr;
5976
5977 // Build typedef struct:
5978 // kmp_task_red_input {
5979 // void *reduce_shar; // shared reduction item
5980 // size_t reduce_size; // size of data item
5981 // void *reduce_init; // data initialization routine
5982 // void *reduce_fini; // data finalization routine
5983 // void *reduce_comb; // data combiner routine
5984 // kmp_task_red_flags_t flags; // flags for additional info from compiler
5985 // } kmp_task_red_input_t;
5986 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005987 RecordDecl *RD = C.buildImplicitRecord("kmp_task_red_input_t");
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005988 RD->startDefinition();
5989 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5990 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
5991 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5992 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5993 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5994 const FieldDecl *FlagsFD = addFieldToRecordDecl(
5995 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
5996 RD->completeDefinition();
5997 QualType RDType = C.getRecordType(RD);
5998 unsigned Size = Data.ReductionVars.size();
5999 llvm::APInt ArraySize(/*numBits=*/64, Size);
6000 QualType ArrayRDType = C.getConstantArrayType(
6001 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
6002 // kmp_task_red_input_t .rd_input.[Size];
6003 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
6004 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
6005 Data.ReductionOps);
6006 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
6007 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
6008 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
6009 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
6010 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
6011 TaskRedInput.getPointer(), Idxs,
6012 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
6013 ".rd_input.gep.");
6014 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
6015 // ElemLVal.reduce_shar = &Shareds[Cnt];
6016 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
6017 RCG.emitSharedLValue(CGF, Cnt);
6018 llvm::Value *CastedShared =
6019 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
6020 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
6021 RCG.emitAggregateType(CGF, Cnt);
6022 llvm::Value *SizeValInChars;
6023 llvm::Value *SizeVal;
6024 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
6025 // We use delayed creation/initialization for VLAs, array sections and
6026 // custom reduction initializations. It is required because runtime does not
6027 // provide the way to pass the sizes of VLAs/array sections to
6028 // initializer/combiner/finalizer functions and does not pass the pointer to
6029 // original reduction item to the initializer. Instead threadprivate global
6030 // variables are used to store these values and use them in the functions.
6031 bool DelayedCreation = !!SizeVal;
6032 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
6033 /*isSigned=*/false);
6034 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
6035 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
6036 // ElemLVal.reduce_init = init;
6037 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
6038 llvm::Value *InitAddr =
6039 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
6040 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
6041 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
6042 // ElemLVal.reduce_fini = fini;
6043 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
6044 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
6045 llvm::Value *FiniAddr = Fini
6046 ? CGF.EmitCastToVoidPtr(Fini)
6047 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
6048 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
6049 // ElemLVal.reduce_comb = comb;
6050 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
6051 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
6052 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
6053 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
6054 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
6055 // ElemLVal.flags = 0;
6056 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
6057 if (DelayedCreation) {
6058 CGF.EmitStoreOfScalar(
6059 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
6060 FlagsLVal);
6061 } else
6062 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
6063 }
6064 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
6065 // *data);
6066 llvm::Value *Args[] = {
6067 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6068 /*isSigned=*/true),
6069 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
6070 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
6071 CGM.VoidPtrTy)};
6072 return CGF.EmitRuntimeCall(
6073 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
6074}
6075
6076void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
6077 SourceLocation Loc,
6078 ReductionCodeGen &RCG,
6079 unsigned N) {
6080 auto Sizes = RCG.getSizes(N);
6081 // Emit threadprivate global variable if the type is non-constant
6082 // (Sizes.second = nullptr).
6083 if (Sizes.second) {
6084 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
6085 /*isSigned=*/false);
6086 Address SizeAddr = getAddrOfArtificialThreadPrivate(
6087 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00006088 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006089 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
6090 }
6091 // Store address of the original reduction item if custom initializer is used.
6092 if (RCG.usesReductionInitializer(N)) {
6093 Address SharedAddr = getAddrOfArtificialThreadPrivate(
6094 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00006095 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006096 CGF.Builder.CreateStore(
6097 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6098 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
6099 SharedAddr, /*IsVolatile=*/false);
6100 }
6101}
6102
6103Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
6104 SourceLocation Loc,
6105 llvm::Value *ReductionsPtr,
6106 LValue SharedLVal) {
6107 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
6108 // *d);
6109 llvm::Value *Args[] = {
6110 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6111 /*isSigned=*/true),
6112 ReductionsPtr,
6113 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
6114 CGM.VoidPtrTy)};
6115 return Address(
6116 CGF.EmitRuntimeCall(
6117 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
6118 SharedLVal.getAlignment());
6119}
6120
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006121void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
6122 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006123 if (!CGF.HaveInsertPoint())
6124 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006125 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
6126 // global_tid);
6127 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
6128 // Ignore return result until untied tasks are supported.
6129 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00006130 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
6131 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006132}
6133
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006134void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006135 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006136 const RegionCodeGenTy &CodeGen,
6137 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006138 if (!CGF.HaveInsertPoint())
6139 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00006140 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006141 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00006142}
6143
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006144namespace {
6145enum RTCancelKind {
6146 CancelNoreq = 0,
6147 CancelParallel = 1,
6148 CancelLoop = 2,
6149 CancelSections = 3,
6150 CancelTaskgroup = 4
6151};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00006152} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006153
6154static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
6155 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00006156 if (CancelRegion == OMPD_parallel)
6157 CancelKind = CancelParallel;
6158 else if (CancelRegion == OMPD_for)
6159 CancelKind = CancelLoop;
6160 else if (CancelRegion == OMPD_sections)
6161 CancelKind = CancelSections;
6162 else {
6163 assert(CancelRegion == OMPD_taskgroup);
6164 CancelKind = CancelTaskgroup;
6165 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006166 return CancelKind;
6167}
6168
6169void CGOpenMPRuntime::emitCancellationPointCall(
6170 CodeGenFunction &CGF, SourceLocation Loc,
6171 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006172 if (!CGF.HaveInsertPoint())
6173 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006174 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
6175 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006176 if (auto *OMPRegionInfo =
6177 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00006178 // For 'cancellation point taskgroup', the task region info may not have a
6179 // cancel. This may instead happen in another adjacent task.
6180 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006181 llvm::Value *Args[] = {
6182 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
6183 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006184 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006185 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006186 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
6187 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006188 // exit from construct;
6189 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006190 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6191 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6192 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006193 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6194 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006195 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006196 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev25e5b442015-09-15 12:52:43 +00006197 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006198 CGF.EmitBranchThroughCleanup(CancelDest);
6199 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6200 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006201 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006202}
6203
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006204void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00006205 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006206 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006207 if (!CGF.HaveInsertPoint())
6208 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006209 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
6210 // kmp_int32 cncl_kind);
6211 if (auto *OMPRegionInfo =
6212 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006213 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
6214 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006215 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00006216 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006217 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00006218 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
6219 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006220 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006221 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00006222 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00006223 // exit from construct;
6224 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006225 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6226 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6227 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev87933c72015-09-18 08:07:34 +00006228 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6229 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00006230 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006231 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev87933c72015-09-18 08:07:34 +00006232 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
6233 CGF.EmitBranchThroughCleanup(CancelDest);
6234 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6235 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006236 if (IfCond) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006237 emitOMPIfClause(CGF, IfCond, ThenGen,
6238 [](CodeGenFunction &, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006239 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006240 RegionCodeGenTy ThenRCG(ThenGen);
6241 ThenRCG(CGF);
6242 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006243 }
6244}
Samuel Antaobed3c462015-10-02 16:14:20 +00006245
Samuel Antaoee8fb302016-01-06 13:42:12 +00006246void CGOpenMPRuntime::emitTargetOutlinedFunction(
6247 const OMPExecutableDirective &D, StringRef ParentName,
6248 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006249 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00006250 assert(!ParentName.empty() && "Invalid target region parent name!");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006251 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
6252 IsOffloadEntry, CodeGen);
6253}
6254
6255void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
6256 const OMPExecutableDirective &D, StringRef ParentName,
6257 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
6258 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00006259 // Create a unique name for the entry function using the source location
6260 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00006261 //
Samuel Antao2de62b02016-02-13 23:35:10 +00006262 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00006263 //
6264 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00006265 // mangled name of the function that encloses the target region and BB is the
6266 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00006267
6268 unsigned DeviceID;
6269 unsigned FileID;
6270 unsigned Line;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006271 getTargetEntryUniqueInfo(CGM.getContext(), D.getBeginLoc(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00006272 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006273 SmallString<64> EntryFnName;
6274 {
6275 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00006276 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
6277 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00006278 }
6279
Alexey Bataev475a7442018-01-12 19:39:11 +00006280 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006281
Samuel Antaobed3c462015-10-02 16:14:20 +00006282 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006283 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00006284 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006285
Samuel Antao6d004262016-06-16 18:39:34 +00006286 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006287
6288 // If this target outline function is not an offload entry, we don't need to
6289 // register it.
6290 if (!IsOffloadEntry)
6291 return;
6292
6293 // The target region ID is used by the runtime library to identify the current
6294 // target region, so it only has to be unique and not necessarily point to
6295 // anything. It could be the pointer to the outlined function that implements
6296 // the target region, but we aren't using that so that the compiler doesn't
6297 // need to keep that, and could therefore inline the host function if proven
6298 // worthwhile during optimization. In the other hand, if emitting code for the
6299 // device, the ID has to be the function address so that it can retrieved from
6300 // the offloading entry and launched by the runtime library. We also mark the
6301 // outlined function to have external linkage in case we are emitting code for
6302 // the device, because these functions will be entry points to the device.
6303
6304 if (CGM.getLangOpts().OpenMPIsDevice) {
6305 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
Alexey Bataev9a700172018-05-08 14:16:57 +00006306 OutlinedFn->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Rafael Espindolacbca4872018-01-11 22:15:12 +00006307 OutlinedFn->setDSOLocal(false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006308 } else {
Alexey Bataevc15ea702018-05-09 18:02:37 +00006309 std::string Name = getName({EntryFnName, "region_id"});
Samuel Antaoee8fb302016-01-06 13:42:12 +00006310 OutlinedFnID = new llvm::GlobalVariable(
6311 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
Alexey Bataev9a700172018-05-08 14:16:57 +00006312 llvm::GlobalValue::WeakAnyLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00006313 llvm::Constant::getNullValue(CGM.Int8Ty), Name);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006314 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00006315
6316 // Register the information for the entry associated with this target region.
6317 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00006318 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
Alexey Bataev03f270c2018-03-30 18:31:07 +00006319 OffloadEntriesInfoManagerTy::OMPTargetRegionEntryTargetRegion);
Samuel Antaobed3c462015-10-02 16:14:20 +00006320}
6321
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006322/// discard all CompoundStmts intervening between two constructs
6323static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006324 while (const auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006325 Body = CS->body_front();
6326
6327 return Body;
6328}
6329
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006330/// Emit the number of teams for a target directive. Inspect the num_teams
6331/// clause associated with a teams construct combined or closely nested
6332/// with the target directive.
6333///
6334/// Emit a team of size one for directives such as 'target parallel' that
6335/// have no associated teams construct.
6336///
6337/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006338static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006339emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6340 CodeGenFunction &CGF,
6341 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006342 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6343 "teams directive expected to be "
6344 "emitted only for the host!");
6345
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006346 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006347
6348 // If the target directive is combined with a teams directive:
6349 // Return the value in the num_teams clause, if any.
6350 // Otherwise, return 0 to denote the runtime default.
6351 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
6352 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
6353 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006354 llvm::Value *NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
6355 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006356 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6357 /*IsSigned=*/true);
6358 }
6359
6360 // The default value is 0.
6361 return Bld.getInt32(0);
6362 }
6363
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006364 // If the target directive is combined with a parallel directive but not a
6365 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006366 if (isOpenMPParallelDirective(D.getDirectiveKind()))
6367 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006368
6369 // If the current target region has a teams region enclosed, we need to get
6370 // the number of teams to pass to the runtime function call. This is done
6371 // by generating the expression in a inlined region. This is required because
6372 // the expression is captured in the enclosing target environment when the
6373 // teams directive is not combined with target.
6374
Alexey Bataev475a7442018-01-12 19:39:11 +00006375 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006376
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006377 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006378 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006379 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006380 if (const auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006381 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6382 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6383 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
6384 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6385 /*IsSigned=*/true);
6386 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006387
Alexey Bataev50a1c782017-12-01 21:31:08 +00006388 // If we have an enclosed teams directive but no num_teams clause we use
6389 // the default value 0.
6390 return Bld.getInt32(0);
6391 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006392 }
6393
6394 // No teams associated with the directive.
6395 return nullptr;
6396}
6397
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006398/// Emit the number of threads for a target directive. Inspect the
6399/// thread_limit clause associated with a teams construct combined or closely
6400/// nested with the target directive.
6401///
6402/// Emit the num_threads clause for directives such as 'target parallel' that
6403/// have no associated teams construct.
6404///
6405/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006406static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006407emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6408 CodeGenFunction &CGF,
6409 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006410 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6411 "teams directive expected to be "
6412 "emitted only for the host!");
6413
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006414 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006415
6416 //
6417 // If the target directive is combined with a teams directive:
6418 // Return the value in the thread_limit clause, if any.
6419 //
6420 // If the target directive is combined with a parallel directive:
6421 // Return the value in the num_threads clause, if any.
6422 //
6423 // If both clauses are set, select the minimum of the two.
6424 //
6425 // If neither teams or parallel combined directives set the number of threads
6426 // in a team, return 0 to denote the runtime default.
6427 //
6428 // If this is not a teams directive return nullptr.
6429
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006430 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
6431 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006432 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
6433 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006434 llvm::Value *ThreadLimitVal = nullptr;
6435
6436 if (const auto *ThreadLimitClause =
6437 D.getSingleClause<OMPThreadLimitClause>()) {
6438 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006439 llvm::Value *ThreadLimit =
6440 CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
6441 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006442 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6443 /*IsSigned=*/true);
6444 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006445
6446 if (const auto *NumThreadsClause =
6447 D.getSingleClause<OMPNumThreadsClause>()) {
6448 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
6449 llvm::Value *NumThreads =
6450 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
6451 /*IgnoreResultAssign*/ true);
6452 NumThreadsVal =
6453 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
6454 }
6455
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006456 // Select the lesser of thread_limit and num_threads.
6457 if (NumThreadsVal)
6458 ThreadLimitVal = ThreadLimitVal
6459 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
6460 ThreadLimitVal),
6461 NumThreadsVal, ThreadLimitVal)
6462 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00006463
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006464 // Set default value passed to the runtime if either teams or a target
6465 // parallel type directive is found but no clause is specified.
6466 if (!ThreadLimitVal)
6467 ThreadLimitVal = DefaultThreadLimitVal;
6468
6469 return ThreadLimitVal;
6470 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00006471
Samuel Antaob68e2db2016-03-03 16:20:23 +00006472 // If the current target region has a teams region enclosed, we need to get
6473 // the thread limit to pass to the runtime function call. This is done
6474 // by generating the expression in a inlined region. This is required because
6475 // the expression is captured in the enclosing target environment when the
6476 // teams directive is not combined with target.
6477
Alexey Bataev475a7442018-01-12 19:39:11 +00006478 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006479
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006480 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006481 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006482 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006483 if (const auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006484 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6485 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6486 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
6487 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6488 /*IsSigned=*/true);
6489 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006490
Alexey Bataev50a1c782017-12-01 21:31:08 +00006491 // If we have an enclosed teams directive but no thread_limit clause we
6492 // use the default value 0.
6493 return CGF.Builder.getInt32(0);
6494 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006495 }
6496
6497 // No teams associated with the directive.
6498 return nullptr;
6499}
6500
Samuel Antao86ace552016-04-27 22:40:57 +00006501namespace {
Alexey Bataevb3638132018-07-19 16:34:13 +00006502LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
6503
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006504// Utility to handle information from clauses associated with a given
Samuel Antao86ace552016-04-27 22:40:57 +00006505// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
6506// It provides a convenient interface to obtain the information and generate
6507// code for that information.
6508class MappableExprsHandler {
6509public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006510 /// Values for bit flags used to specify the mapping type for
Samuel Antao86ace552016-04-27 22:40:57 +00006511 /// offloading.
Alexey Bataevb3638132018-07-19 16:34:13 +00006512 enum OpenMPOffloadMappingFlags : uint64_t {
6513 /// No flags
6514 OMP_MAP_NONE = 0x0,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006515 /// Allocate memory on the device and move data from host to device.
Samuel Antao86ace552016-04-27 22:40:57 +00006516 OMP_MAP_TO = 0x01,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006517 /// Allocate memory on the device and move data from device to host.
Samuel Antao86ace552016-04-27 22:40:57 +00006518 OMP_MAP_FROM = 0x02,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006519 /// Always perform the requested mapping action on the element, even
Samuel Antao86ace552016-04-27 22:40:57 +00006520 /// if it was already mapped before.
6521 OMP_MAP_ALWAYS = 0x04,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006522 /// Delete the element from the device environment, ignoring the
Samuel Antao86ace552016-04-27 22:40:57 +00006523 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00006524 OMP_MAP_DELETE = 0x08,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006525 /// The element being mapped is a pointer-pointee pair; both the
George Rokos065755d2017-11-07 18:27:04 +00006526 /// pointer and the pointee should be mapped.
6527 OMP_MAP_PTR_AND_OBJ = 0x10,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006528 /// This flags signals that the base address of an entry should be
George Rokos065755d2017-11-07 18:27:04 +00006529 /// passed to the target kernel as an argument.
6530 OMP_MAP_TARGET_PARAM = 0x20,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006531 /// Signal that the runtime library has to return the device pointer
George Rokos065755d2017-11-07 18:27:04 +00006532 /// in the current position for the data being mapped. Used when we have the
6533 /// use_device_ptr clause.
6534 OMP_MAP_RETURN_PARAM = 0x40,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006535 /// This flag signals that the reference being passed is a pointer to
Samuel Antaod486f842016-05-26 16:53:38 +00006536 /// private data.
George Rokos065755d2017-11-07 18:27:04 +00006537 OMP_MAP_PRIVATE = 0x80,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006538 /// Pass the element to the device by value.
George Rokos065755d2017-11-07 18:27:04 +00006539 OMP_MAP_LITERAL = 0x100,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006540 /// Implicit map
6541 OMP_MAP_IMPLICIT = 0x200,
Alexey Bataevb3638132018-07-19 16:34:13 +00006542 /// The 16 MSBs of the flags indicate whether the entry is member of some
6543 /// struct/class.
6544 OMP_MAP_MEMBER_OF = 0xffff000000000000,
6545 LLVM_MARK_AS_BITMASK_ENUM(/* LargestFlag = */ OMP_MAP_MEMBER_OF),
Samuel Antao86ace552016-04-27 22:40:57 +00006546 };
6547
Samuel Antaocc10b852016-07-28 14:23:26 +00006548 /// Class that associates information with a base pointer to be passed to the
6549 /// runtime library.
6550 class BasePointerInfo {
6551 /// The base pointer.
6552 llvm::Value *Ptr = nullptr;
6553 /// The base declaration that refers to this device pointer, or null if
6554 /// there is none.
6555 const ValueDecl *DevPtrDecl = nullptr;
6556
6557 public:
6558 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
6559 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
6560 llvm::Value *operator*() const { return Ptr; }
6561 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
6562 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
6563 };
6564
Alexey Bataevb3638132018-07-19 16:34:13 +00006565 using MapBaseValuesArrayTy = SmallVector<BasePointerInfo, 4>;
6566 using MapValuesArrayTy = SmallVector<llvm::Value *, 4>;
6567 using MapFlagsArrayTy = SmallVector<OpenMPOffloadMappingFlags, 4>;
6568
6569 /// Map between a struct and the its lowest & highest elements which have been
6570 /// mapped.
6571 /// [ValueDecl *] --> {LE(FieldIndex, Pointer),
6572 /// HE(FieldIndex, Pointer)}
6573 struct StructRangeInfoTy {
6574 std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> LowestElem = {
6575 0, Address::invalid()};
6576 std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> HighestElem = {
6577 0, Address::invalid()};
6578 Address Base = Address::invalid();
6579 };
Samuel Antao86ace552016-04-27 22:40:57 +00006580
6581private:
Alexey Bataevb3638132018-07-19 16:34:13 +00006582 /// Kind that defines how a device pointer has to be returned.
6583 struct MapInfo {
6584 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
6585 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
6586 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown;
6587 bool ReturnDevicePointer = false;
6588 bool IsImplicit = false;
6589
6590 MapInfo() = default;
6591 MapInfo(
6592 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
6593 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6594 bool ReturnDevicePointer, bool IsImplicit)
6595 : Components(Components), MapType(MapType),
6596 MapTypeModifier(MapTypeModifier),
6597 ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
6598 };
6599
6600 /// If use_device_ptr is used on a pointer which is a struct member and there
6601 /// is no map information about it, then emission of that entry is deferred
6602 /// until the whole struct has been processed.
6603 struct DeferredDevicePtrEntryTy {
6604 const Expr *IE = nullptr;
6605 const ValueDecl *VD = nullptr;
6606
6607 DeferredDevicePtrEntryTy(const Expr *IE, const ValueDecl *VD)
6608 : IE(IE), VD(VD) {}
6609 };
6610
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006611 /// Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00006612 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00006613
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006614 /// Function the directive is being generated for.
Samuel Antao86ace552016-04-27 22:40:57 +00006615 CodeGenFunction &CGF;
6616
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006617 /// Set of all first private variables in the current directive.
Samuel Antaod486f842016-05-26 16:53:38 +00006618 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
6619
Samuel Antao6890b092016-07-28 14:25:09 +00006620 /// Map between device pointer declarations and their expression components.
6621 /// The key value for declarations in 'this' is null.
6622 llvm::DenseMap<
6623 const ValueDecl *,
6624 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6625 DevPointersMap;
6626
Samuel Antao86ace552016-04-27 22:40:57 +00006627 llvm::Value *getExprTypeSize(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006628 QualType ExprTy = E->getType().getCanonicalType();
Samuel Antao86ace552016-04-27 22:40:57 +00006629
6630 // Reference types are ignored for mapping purposes.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006631 if (const auto *RefTy = ExprTy->getAs<ReferenceType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006632 ExprTy = RefTy->getPointeeType().getCanonicalType();
6633
6634 // Given that an array section is considered a built-in type, we need to
6635 // do the calculation based on the length of the section instead of relying
6636 // on CGF.getTypeSize(E->getType()).
6637 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6638 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6639 OAE->getBase()->IgnoreParenImpCasts())
6640 .getCanonicalType();
6641
6642 // If there is no length associated with the expression, that means we
6643 // are using the whole length of the base.
6644 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6645 return CGF.getTypeSize(BaseTy);
6646
6647 llvm::Value *ElemSize;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006648 if (const auto *PTy = BaseTy->getAs<PointerType>()) {
Samuel Antao86ace552016-04-27 22:40:57 +00006649 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006650 } else {
6651 const auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
Samuel Antao86ace552016-04-27 22:40:57 +00006652 assert(ATy && "Expecting array type if not a pointer type.");
6653 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6654 }
6655
6656 // If we don't have a length at this point, that is because we have an
6657 // array section with a single element.
6658 if (!OAE->getLength())
6659 return ElemSize;
6660
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006661 llvm::Value *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
Samuel Antao86ace552016-04-27 22:40:57 +00006662 LengthVal =
6663 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6664 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6665 }
6666 return CGF.getTypeSize(ExprTy);
6667 }
6668
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006669 /// Return the corresponding bits for a given map clause modifier. Add
Samuel Antao86ace552016-04-27 22:40:57 +00006670 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006671 /// map as the first one of a series of maps that relate to the same map
6672 /// expression.
Alexey Bataevb3638132018-07-19 16:34:13 +00006673 OpenMPOffloadMappingFlags getMapTypeBits(OpenMPMapClauseKind MapType,
6674 OpenMPMapClauseKind MapTypeModifier,
6675 bool IsImplicit, bool AddPtrFlag,
6676 bool AddIsTargetParamFlag) const {
6677 OpenMPOffloadMappingFlags Bits =
6678 IsImplicit ? OMP_MAP_IMPLICIT : OMP_MAP_NONE;
Samuel Antao86ace552016-04-27 22:40:57 +00006679 switch (MapType) {
6680 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006681 case OMPC_MAP_release:
6682 // alloc and release is the default behavior in the runtime library, i.e.
6683 // if we don't pass any bits alloc/release that is what the runtime is
6684 // going to do. Therefore, we don't need to signal anything for these two
6685 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006686 break;
6687 case OMPC_MAP_to:
Alexey Bataevb3638132018-07-19 16:34:13 +00006688 Bits |= OMP_MAP_TO;
Samuel Antao86ace552016-04-27 22:40:57 +00006689 break;
6690 case OMPC_MAP_from:
Alexey Bataevb3638132018-07-19 16:34:13 +00006691 Bits |= OMP_MAP_FROM;
Samuel Antao86ace552016-04-27 22:40:57 +00006692 break;
6693 case OMPC_MAP_tofrom:
Alexey Bataevb3638132018-07-19 16:34:13 +00006694 Bits |= OMP_MAP_TO | OMP_MAP_FROM;
Samuel Antao86ace552016-04-27 22:40:57 +00006695 break;
6696 case OMPC_MAP_delete:
Alexey Bataevb3638132018-07-19 16:34:13 +00006697 Bits |= OMP_MAP_DELETE;
Samuel Antao86ace552016-04-27 22:40:57 +00006698 break;
Alexey Bataevb3638132018-07-19 16:34:13 +00006699 case OMPC_MAP_always:
6700 case OMPC_MAP_unknown:
Samuel Antao86ace552016-04-27 22:40:57 +00006701 llvm_unreachable("Unexpected map type!");
Samuel Antao86ace552016-04-27 22:40:57 +00006702 }
6703 if (AddPtrFlag)
George Rokos065755d2017-11-07 18:27:04 +00006704 Bits |= OMP_MAP_PTR_AND_OBJ;
6705 if (AddIsTargetParamFlag)
6706 Bits |= OMP_MAP_TARGET_PARAM;
Samuel Antao86ace552016-04-27 22:40:57 +00006707 if (MapTypeModifier == OMPC_MAP_always)
6708 Bits |= OMP_MAP_ALWAYS;
6709 return Bits;
6710 }
6711
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006712 /// Return true if the provided expression is a final array section. A
Samuel Antao86ace552016-04-27 22:40:57 +00006713 /// final array section, is one whose length can't be proved to be one.
6714 bool isFinalArraySectionExpression(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006715 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antao86ace552016-04-27 22:40:57 +00006716
6717 // It is not an array section and therefore not a unity-size one.
6718 if (!OASE)
6719 return false;
6720
6721 // An array section with no colon always refer to a single element.
6722 if (OASE->getColonLoc().isInvalid())
6723 return false;
6724
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006725 const Expr *Length = OASE->getLength();
Samuel Antao86ace552016-04-27 22:40:57 +00006726
6727 // If we don't have a length we have to check if the array has size 1
6728 // for this dimension. Also, we should always expect a length if the
6729 // base type is pointer.
6730 if (!Length) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006731 QualType BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6732 OASE->getBase()->IgnoreParenImpCasts())
6733 .getCanonicalType();
6734 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antao86ace552016-04-27 22:40:57 +00006735 return ATy->getSize().getSExtValue() != 1;
6736 // If we don't have a constant dimension length, we have to consider
6737 // the current section as having any size, so it is not necessarily
6738 // unitary. If it happen to be unity size, that's user fault.
6739 return true;
6740 }
6741
6742 // Check if the length evaluates to 1.
6743 llvm::APSInt ConstLength;
6744 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
6745 return true; // Can have more that size 1.
6746
6747 return ConstLength.getSExtValue() != 1;
6748 }
6749
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006750 /// Generate the base pointers, section pointers, sizes and map type
Samuel Antao86ace552016-04-27 22:40:57 +00006751 /// bits for the provided map type, map modifier, and expression components.
6752 /// \a IsFirstComponent should be set to true if the provided set of
6753 /// components is the first associated with a capture.
6754 void generateInfoForComponentList(
6755 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6756 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006757 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006758 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
Alexey Bataevb3638132018-07-19 16:34:13 +00006759 StructRangeInfoTy &PartialStruct, bool IsFirstComponentList,
6760 bool IsImplicit) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006761 // The following summarizes what has to be generated for each map and the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006762 // types below. The generated information is expressed in this order:
Samuel Antao86ace552016-04-27 22:40:57 +00006763 // base pointer, section pointer, size, flags
6764 // (to add to the ones that come from the map type and modifier).
6765 //
6766 // double d;
6767 // int i[100];
6768 // float *p;
6769 //
6770 // struct S1 {
6771 // int i;
6772 // float f[50];
6773 // }
6774 // struct S2 {
6775 // int i;
6776 // float f[50];
6777 // S1 s;
6778 // double *p;
6779 // struct S2 *ps;
6780 // }
6781 // S2 s;
6782 // S2 *ps;
6783 //
6784 // map(d)
Alexey Bataevb3638132018-07-19 16:34:13 +00006785 // &d, &d, sizeof(double), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006786 //
6787 // map(i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006788 // &i, &i, 100*sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006789 //
6790 // map(i[1:23])
Alexey Bataevb3638132018-07-19 16:34:13 +00006791 // &i(=&i[0]), &i[1], 23*sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006792 //
6793 // map(p)
Alexey Bataevb3638132018-07-19 16:34:13 +00006794 // &p, &p, sizeof(float*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006795 //
6796 // map(p[1:24])
Alexey Bataevb3638132018-07-19 16:34:13 +00006797 // p, &p[1], 24*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006798 //
6799 // map(s)
Alexey Bataevb3638132018-07-19 16:34:13 +00006800 // &s, &s, sizeof(S2), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006801 //
6802 // map(s.i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006803 // &s, &(s.i), sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006804 //
6805 // map(s.s.f)
Alexey Bataevb3638132018-07-19 16:34:13 +00006806 // &s, &(s.s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006807 //
6808 // map(s.p)
Alexey Bataevb3638132018-07-19 16:34:13 +00006809 // &s, &(s.p), sizeof(double*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006810 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006811 // map(to: s.p[:22])
6812 // &s, &(s.p), sizeof(double*), TARGET_PARAM (*)
6813 // &s, &(s.p), sizeof(double*), MEMBER_OF(1) (**)
6814 // &(s.p), &(s.p[0]), 22*sizeof(double),
6815 // MEMBER_OF(1) | PTR_AND_OBJ | TO (***)
6816 // (*) alloc space for struct members, only this is a target parameter
6817 // (**) map the pointer (nothing to be mapped in this example) (the compiler
6818 // optimizes this entry out, same in the examples below)
6819 // (***) map the pointee (map: to)
Samuel Antao86ace552016-04-27 22:40:57 +00006820 //
6821 // map(s.ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006822 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006823 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006824 // map(from: s.ps->s.i)
6825 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6826 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6827 // &(s.ps), &(s.ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006828 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006829 // map(to: s.ps->ps)
6830 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6831 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6832 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006833 //
6834 // map(s.ps->ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006835 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6836 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6837 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6838 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006839 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006840 // map(to: s.ps->ps->s.f[:22])
6841 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6842 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6843 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6844 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006845 //
6846 // map(ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006847 // &ps, &ps, sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006848 //
6849 // map(ps->i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006850 // ps, &(ps->i), sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006851 //
6852 // map(ps->s.f)
Alexey Bataevb3638132018-07-19 16:34:13 +00006853 // ps, &(ps->s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006854 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006855 // map(from: ps->p)
6856 // ps, &(ps->p), sizeof(double*), TARGET_PARAM | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006857 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006858 // map(to: ps->p[:22])
6859 // ps, &(ps->p), sizeof(double*), TARGET_PARAM
6860 // ps, &(ps->p), sizeof(double*), MEMBER_OF(1)
6861 // &(ps->p), &(ps->p[0]), 22*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006862 //
6863 // map(ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006864 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006865 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006866 // map(from: ps->ps->s.i)
6867 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6868 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6869 // &(ps->ps), &(ps->ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006870 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006871 // map(from: ps->ps->ps)
6872 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6873 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6874 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006875 //
6876 // map(ps->ps->ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006877 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6878 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6879 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6880 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006881 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006882 // map(to: ps->ps->ps->s.f[:22])
6883 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6884 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6885 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6886 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO
6887 //
6888 // map(to: s.f[:22]) map(from: s.p[:33])
6889 // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1) +
6890 // sizeof(double*) (**), TARGET_PARAM
6891 // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | TO
6892 // &s, &(s.p), sizeof(double*), MEMBER_OF(1)
6893 // &(s.p), &(s.p[0]), 33*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | FROM
6894 // (*) allocate contiguous space needed to fit all mapped members even if
6895 // we allocate space for members not mapped (in this example,
6896 // s.f[22..49] and s.s are not mapped, yet we must allocate space for
6897 // them as well because they fall between &s.f[0] and &s.p)
6898 //
6899 // map(from: s.f[:22]) map(to: ps->p[:33])
6900 // &s, &(s.f[0]), 22*sizeof(float), TARGET_PARAM | FROM
6901 // ps, &(ps->p), sizeof(S2*), TARGET_PARAM
6902 // ps, &(ps->p), sizeof(double*), MEMBER_OF(2) (*)
6903 // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(2) | PTR_AND_OBJ | TO
6904 // (*) the struct this entry pertains to is the 2nd element in the list of
6905 // arguments, hence MEMBER_OF(2)
6906 //
6907 // map(from: s.f[:22], s.s) map(to: ps->p[:33])
6908 // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1), TARGET_PARAM
6909 // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | FROM
6910 // &s, &(s.s), sizeof(struct S1), MEMBER_OF(1) | FROM
6911 // ps, &(ps->p), sizeof(S2*), TARGET_PARAM
6912 // ps, &(ps->p), sizeof(double*), MEMBER_OF(4) (*)
6913 // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(4) | PTR_AND_OBJ | TO
6914 // (*) the struct this entry pertains to is the 4th element in the list
6915 // of arguments, hence MEMBER_OF(4)
Samuel Antao86ace552016-04-27 22:40:57 +00006916
6917 // Track if the map information being generated is the first for a capture.
6918 bool IsCaptureFirstInfo = IsFirstComponentList;
Alexey Bataev92327c52018-03-26 16:40:55 +00006919 bool IsLink = false; // Is this variable a "declare target link"?
Samuel Antao86ace552016-04-27 22:40:57 +00006920
6921 // Scan the components from the base to the complete expression.
6922 auto CI = Components.rbegin();
6923 auto CE = Components.rend();
6924 auto I = CI;
6925
6926 // Track if the map information being generated is the first for a list of
6927 // components.
6928 bool IsExpressionFirstInfo = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00006929 Address BP = Address::invalid();
Samuel Antao86ace552016-04-27 22:40:57 +00006930
Erich Keanee69755a2018-07-19 17:19:16 +00006931 if (isa<MemberExpr>(I->getAssociatedExpression())) {
Samuel Antao86ace552016-04-27 22:40:57 +00006932 // The base is the 'this' pointer. The content of the pointer is going
6933 // to be the base of the field being mapped.
Alexey Bataevb3638132018-07-19 16:34:13 +00006934 BP = CGF.LoadCXXThisAddress();
Samuel Antao86ace552016-04-27 22:40:57 +00006935 } else {
6936 // The base is the reference to the variable.
6937 // BP = &Var.
Alexey Bataevb3638132018-07-19 16:34:13 +00006938 BP = CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getAddress();
Alexey Bataev92327c52018-03-26 16:40:55 +00006939 if (const auto *VD =
6940 dyn_cast_or_null<VarDecl>(I->getAssociatedDeclaration())) {
6941 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00006942 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataev2c1dffe2018-04-16 20:34:41 +00006943 if (*Res == OMPDeclareTargetDeclAttr::MT_Link) {
6944 IsLink = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00006945 BP = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
Alexey Bataev2c1dffe2018-04-16 20:34:41 +00006946 }
Alexey Bataev92327c52018-03-26 16:40:55 +00006947 }
Samuel Antao86ace552016-04-27 22:40:57 +00006948
6949 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00006950 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00006951 // reference. References are ignored for mapping purposes.
6952 QualType Ty =
6953 I->getAssociatedDeclaration()->getType().getNonReferenceType();
6954 if (Ty->isAnyPointerType() && std::next(I) != CE) {
Alexey Bataevb3638132018-07-19 16:34:13 +00006955 BP = CGF.EmitLoadOfPointer(BP, Ty->castAs<PointerType>());
Samuel Antao86ace552016-04-27 22:40:57 +00006956
6957 // We do not need to generate individual map information for the
6958 // pointer, it can be associated with the combined storage.
6959 ++I;
6960 }
6961 }
6962
Alexey Bataevb3638132018-07-19 16:34:13 +00006963 // Track whether a component of the list should be marked as MEMBER_OF some
6964 // combined entry (for partial structs). Only the first PTR_AND_OBJ entry
6965 // in a component list should be marked as MEMBER_OF, all subsequent entries
6966 // do not belong to the base struct. E.g.
6967 // struct S2 s;
6968 // s.ps->ps->ps->f[:]
6969 // (1) (2) (3) (4)
6970 // ps(1) is a member pointer, ps(2) is a pointee of ps(1), so it is a
6971 // PTR_AND_OBJ entry; the PTR is ps(1), so MEMBER_OF the base struct. ps(3)
6972 // is the pointee of ps(2) which is not member of struct s, so it should not
6973 // be marked as such (it is still PTR_AND_OBJ).
6974 // The variable is initialized to false so that PTR_AND_OBJ entries which
6975 // are not struct members are not considered (e.g. array of pointers to
6976 // data).
6977 bool ShouldBeMemberOf = false;
6978
6979 // Variable keeping track of whether or not we have encountered a component
6980 // in the component list which is a member expression. Useful when we have a
6981 // pointer or a final array section, in which case it is the previous
6982 // component in the list which tells us whether we have a member expression.
6983 // E.g. X.f[:]
6984 // While processing the final array section "[:]" it is "f" which tells us
6985 // whether we are dealing with a member of a declared struct.
6986 const MemberExpr *EncounteredME = nullptr;
6987
Samuel Antao86ace552016-04-27 22:40:57 +00006988 for (; I != CE; ++I) {
Alexey Bataevb3638132018-07-19 16:34:13 +00006989 // If the current component is member of a struct (parent struct) mark it.
6990 if (!EncounteredME) {
6991 EncounteredME = dyn_cast<MemberExpr>(I->getAssociatedExpression());
6992 // If we encounter a PTR_AND_OBJ entry from now on it should be marked
6993 // as MEMBER_OF the parent struct.
6994 if (EncounteredME)
6995 ShouldBeMemberOf = true;
6996 }
6997
Samuel Antao86ace552016-04-27 22:40:57 +00006998 auto Next = std::next(I);
6999
7000 // We need to generate the addresses and sizes if this is the last
7001 // component, if the component is a pointer or if it is an array section
7002 // whose length can't be proved to be one. If this is a pointer, it
7003 // becomes the base address for the following components.
7004
7005 // A final array section, is one whose length can't be proved to be one.
7006 bool IsFinalArraySection =
7007 isFinalArraySectionExpression(I->getAssociatedExpression());
7008
7009 // Get information on whether the element is a pointer. Have to do a
7010 // special treatment for array sections given that they are built-in
7011 // types.
7012 const auto *OASE =
7013 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
7014 bool IsPointer =
Alexey Bataevb3638132018-07-19 16:34:13 +00007015 (OASE && OMPArraySectionExpr::getBaseOriginalType(OASE)
7016 .getCanonicalType()
7017 ->isAnyPointerType()) ||
Samuel Antao86ace552016-04-27 22:40:57 +00007018 I->getAssociatedExpression()->getType()->isAnyPointerType();
7019
7020 if (Next == CE || IsPointer || IsFinalArraySection) {
Samuel Antao86ace552016-04-27 22:40:57 +00007021 // If this is not the last component, we expect the pointer to be
7022 // associated with an array expression or member expression.
7023 assert((Next == CE ||
7024 isa<MemberExpr>(Next->getAssociatedExpression()) ||
7025 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
7026 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
7027 "Unexpected expression");
7028
Alexey Bataevb3638132018-07-19 16:34:13 +00007029 Address LB =
7030 CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getAddress();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007031 llvm::Value *Size = getExprTypeSize(I->getAssociatedExpression());
Samuel Antao86ace552016-04-27 22:40:57 +00007032
Alexey Bataevb3638132018-07-19 16:34:13 +00007033 // If this component is a pointer inside the base struct then we don't
7034 // need to create any entry for it - it will be combined with the object
7035 // it is pointing to into a single PTR_AND_OBJ entry.
7036 bool IsMemberPointer =
7037 IsPointer && EncounteredME &&
7038 (dyn_cast<MemberExpr>(I->getAssociatedExpression()) ==
7039 EncounteredME);
7040 if (!IsMemberPointer) {
7041 BasePointers.push_back(BP.getPointer());
7042 Pointers.push_back(LB.getPointer());
7043 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00007044
Alexey Bataevb3638132018-07-19 16:34:13 +00007045 // We need to add a pointer flag for each map that comes from the
7046 // same expression except for the first one. We also need to signal
7047 // this map is the first one that relates with the current capture
7048 // (there is a set of entries for each capture).
7049 OpenMPOffloadMappingFlags Flags = getMapTypeBits(
7050 MapType, MapTypeModifier, IsImplicit,
7051 !IsExpressionFirstInfo || IsLink, IsCaptureFirstInfo && !IsLink);
7052
7053 if (!IsExpressionFirstInfo) {
7054 // If we have a PTR_AND_OBJ pair where the OBJ is a pointer as well,
7055 // then we reset the TO/FROM/ALWAYS/DELETE flags.
7056 if (IsPointer)
7057 Flags &= ~(OMP_MAP_TO | OMP_MAP_FROM | OMP_MAP_ALWAYS |
7058 OMP_MAP_DELETE);
7059
7060 if (ShouldBeMemberOf) {
7061 // Set placeholder value MEMBER_OF=FFFF to indicate that the flag
7062 // should be later updated with the correct value of MEMBER_OF.
7063 Flags |= OMP_MAP_MEMBER_OF;
7064 // From now on, all subsequent PTR_AND_OBJ entries should not be
7065 // marked as MEMBER_OF.
7066 ShouldBeMemberOf = false;
7067 }
7068 }
7069
7070 Types.push_back(Flags);
Samuel Antao03a3cec2016-07-27 22:52:16 +00007071 }
7072
Alexey Bataevb3638132018-07-19 16:34:13 +00007073 // If we have encountered a member expression so far, keep track of the
7074 // mapped member. If the parent is "*this", then the value declaration
7075 // is nullptr.
7076 if (EncounteredME) {
7077 const auto *FD = dyn_cast<FieldDecl>(EncounteredME->getMemberDecl());
7078 unsigned FieldIndex = FD->getFieldIndex();
Samuel Antao03a3cec2016-07-27 22:52:16 +00007079
Alexey Bataevb3638132018-07-19 16:34:13 +00007080 // Update info about the lowest and highest elements for this struct
7081 if (!PartialStruct.Base.isValid()) {
7082 PartialStruct.LowestElem = {FieldIndex, LB};
7083 PartialStruct.HighestElem = {FieldIndex, LB};
7084 PartialStruct.Base = BP;
7085 } else if (FieldIndex < PartialStruct.LowestElem.first) {
7086 PartialStruct.LowestElem = {FieldIndex, LB};
7087 } else if (FieldIndex > PartialStruct.HighestElem.first) {
7088 PartialStruct.HighestElem = {FieldIndex, LB};
7089 }
7090 }
Samuel Antao86ace552016-04-27 22:40:57 +00007091
7092 // If we have a final array section, we are done with this expression.
7093 if (IsFinalArraySection)
7094 break;
7095
7096 // The pointer becomes the base for the next element.
7097 if (Next != CE)
7098 BP = LB;
7099
7100 IsExpressionFirstInfo = false;
7101 IsCaptureFirstInfo = false;
Samuel Antao86ace552016-04-27 22:40:57 +00007102 }
7103 }
7104 }
7105
Alexey Bataevb3638132018-07-19 16:34:13 +00007106 /// Return the adjusted map modifiers if the declaration a capture refers to
7107 /// appears in a first-private clause. This is expected to be used only with
7108 /// directives that start with 'target'.
7109 MappableExprsHandler::OpenMPOffloadMappingFlags
7110 getMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap) const {
7111 assert(Cap.capturesVariable() && "Expected capture by reference only!");
7112
7113 // A first private variable captured by reference will use only the
7114 // 'private ptr' and 'map to' flag. Return the right flags if the captured
7115 // declaration is known as first-private in this handler.
7116 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
7117 return MappableExprsHandler::OMP_MAP_PRIVATE |
7118 MappableExprsHandler::OMP_MAP_TO;
7119 return MappableExprsHandler::OMP_MAP_TO |
7120 MappableExprsHandler::OMP_MAP_FROM;
7121 }
7122
7123 static OpenMPOffloadMappingFlags getMemberOfFlag(unsigned Position) {
7124 // Member of is given by the 16 MSB of the flag, so rotate by 48 bits.
7125 return static_cast<OpenMPOffloadMappingFlags>(((uint64_t)Position + 1)
7126 << 48);
7127 }
7128
7129 static void setCorrectMemberOfFlag(OpenMPOffloadMappingFlags &Flags,
7130 OpenMPOffloadMappingFlags MemberOfFlag) {
7131 // If the entry is PTR_AND_OBJ but has not been marked with the special
7132 // placeholder value 0xFFFF in the MEMBER_OF field, then it should not be
7133 // marked as MEMBER_OF.
7134 if ((Flags & OMP_MAP_PTR_AND_OBJ) &&
7135 ((Flags & OMP_MAP_MEMBER_OF) != OMP_MAP_MEMBER_OF))
7136 return;
7137
7138 // Reset the placeholder value to prepare the flag for the assignment of the
7139 // proper MEMBER_OF value.
7140 Flags &= ~OMP_MAP_MEMBER_OF;
7141 Flags |= MemberOfFlag;
7142 }
7143
7144public:
7145 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
7146 : CurDir(Dir), CGF(CGF) {
7147 // Extract firstprivate clause information.
7148 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
7149 for (const auto *D : C->varlists())
7150 FirstPrivateDecls.insert(
7151 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
7152 // Extract device pointer clause information.
7153 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
7154 for (auto L : C->component_lists())
7155 DevPointersMap[L.first].push_back(L.second);
7156 }
7157
7158 /// Generate code for the combined entry if we have a partially mapped struct
7159 /// and take care of the mapping flags of the arguments corresponding to
7160 /// individual struct members.
7161 void emitCombinedEntry(MapBaseValuesArrayTy &BasePointers,
7162 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7163 MapFlagsArrayTy &Types, MapFlagsArrayTy &CurTypes,
7164 const StructRangeInfoTy &PartialStruct) const {
7165 // Base is the base of the struct
7166 BasePointers.push_back(PartialStruct.Base.getPointer());
7167 // Pointer is the address of the lowest element
7168 llvm::Value *LB = PartialStruct.LowestElem.second.getPointer();
7169 Pointers.push_back(LB);
7170 // Size is (addr of {highest+1} element) - (addr of lowest element)
7171 llvm::Value *HB = PartialStruct.HighestElem.second.getPointer();
7172 llvm::Value *HAddr = CGF.Builder.CreateConstGEP1_32(HB, /*Idx0=*/1);
7173 llvm::Value *CLAddr = CGF.Builder.CreatePointerCast(LB, CGF.VoidPtrTy);
7174 llvm::Value *CHAddr = CGF.Builder.CreatePointerCast(HAddr, CGF.VoidPtrTy);
7175 llvm::Value *Diff = CGF.Builder.CreatePtrDiff(CHAddr, CLAddr);
7176 llvm::Value *Size = CGF.Builder.CreateIntCast(Diff, CGF.SizeTy,
7177 /*isSinged=*/false);
7178 Sizes.push_back(Size);
7179 // Map type is always TARGET_PARAM
7180 Types.push_back(OMP_MAP_TARGET_PARAM);
7181 // Remove TARGET_PARAM flag from the first element
7182 (*CurTypes.begin()) &= ~OMP_MAP_TARGET_PARAM;
7183
7184 // All other current entries will be MEMBER_OF the combined entry
7185 // (except for PTR_AND_OBJ entries which do not have a placeholder value
7186 // 0xFFFF in the MEMBER_OF field).
7187 OpenMPOffloadMappingFlags MemberOfFlag =
7188 getMemberOfFlag(BasePointers.size() - 1);
7189 for (auto &M : CurTypes)
7190 setCorrectMemberOfFlag(M, MemberOfFlag);
7191 }
7192
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007193 /// Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00007194 /// types for the extracted mappable expressions. Also, for each item that
7195 /// relates with a device pointer, a pair of the relevant declaration and
7196 /// index where it occurs is appended to the device pointers info array.
7197 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007198 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7199 MapFlagsArrayTy &Types) const {
Samuel Antao86ace552016-04-27 22:40:57 +00007200 // We have to process the component lists that relate with the same
7201 // declaration in a single chunk so that we can generate the map flags
7202 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00007203 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00007204
7205 // Helper function to fill the information map for the different supported
7206 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00007207 auto &&InfoGen = [&Info](
7208 const ValueDecl *D,
7209 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
7210 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Alexey Bataevb3638132018-07-19 16:34:13 +00007211 bool ReturnDevicePointer, bool IsImplicit) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007212 const ValueDecl *VD =
7213 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007214 Info[VD].emplace_back(L, MapType, MapModifier, ReturnDevicePointer,
7215 IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007216 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00007217
Paul Robinson78fb1322016-08-01 22:12:46 +00007218 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007219 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
7220 for (const auto &L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00007221 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
Alexey Bataevb3638132018-07-19 16:34:13 +00007222 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007223 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007224 for (const auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
7225 for (const auto &L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00007226 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
Alexey Bataevb3638132018-07-19 16:34:13 +00007227 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007228 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007229 for (const auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
7230 for (const auto &L : C->component_lists()) {
Samuel Antaocf3f83e2016-07-28 14:47:35 +00007231 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
Alexey Bataevb3638132018-07-19 16:34:13 +00007232 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007233 }
Samuel Antao86ace552016-04-27 22:40:57 +00007234
Samuel Antaocc10b852016-07-28 14:23:26 +00007235 // Look at the use_device_ptr clause information and mark the existing map
7236 // entries as such. If there is no map information for an entry in the
7237 // use_device_ptr list, we create one with map type 'alloc' and zero size
Alexey Bataevb3638132018-07-19 16:34:13 +00007238 // section. It is the user fault if that was not mapped before. If there is
7239 // no map information and the pointer is a struct member, then we defer the
7240 // emission of that entry until the whole struct has been processed.
7241 llvm::MapVector<const ValueDecl *, SmallVector<DeferredDevicePtrEntryTy, 4>>
7242 DeferredInfo;
7243
Paul Robinson78fb1322016-08-01 22:12:46 +00007244 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataevb3638132018-07-19 16:34:13 +00007245 for (const auto *C :
7246 this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007247 for (const auto &L : C->component_lists()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007248 assert(!L.second.empty() && "Not expecting empty list of components!");
7249 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
7250 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007251 const Expr *IE = L.second.back().getAssociatedExpression();
Samuel Antaocc10b852016-07-28 14:23:26 +00007252 // If the first component is a member expression, we have to look into
7253 // 'this', which maps to null in the map of map information. Otherwise
7254 // look directly for the information.
7255 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
7256
7257 // We potentially have map information for this declaration already.
7258 // Look for the first set of components that refer to it.
7259 if (It != Info.end()) {
7260 auto CI = std::find_if(
7261 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
7262 return MI.Components.back().getAssociatedDeclaration() == VD;
7263 });
7264 // If we found a map entry, signal that the pointer has to be returned
7265 // and move on to the next declaration.
7266 if (CI != It->second.end()) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007267 CI->ReturnDevicePointer = true;
Samuel Antaocc10b852016-07-28 14:23:26 +00007268 continue;
7269 }
7270 }
7271
7272 // We didn't find any match in our map information - generate a zero
Alexey Bataevb3638132018-07-19 16:34:13 +00007273 // size array section - if the pointer is a struct member we defer this
7274 // action until the whole struct has been processed.
Paul Robinson78fb1322016-08-01 22:12:46 +00007275 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Alexey Bataevb3638132018-07-19 16:34:13 +00007276 if (isa<MemberExpr>(IE)) {
7277 // Insert the pointer into Info to be processed by
7278 // generateInfoForComponentList. Because it is a member pointer
7279 // without a pointee, no entry will be generated for it, therefore
7280 // we need to generate one after the whole struct has been processed.
7281 // Nonetheless, generateInfoForComponentList must be called to take
7282 // the pointer into account for the calculation of the range of the
7283 // partial struct.
7284 InfoGen(nullptr, L.second, OMPC_MAP_unknown, OMPC_MAP_unknown,
7285 /*ReturnDevicePointer=*/false, C->isImplicit());
7286 DeferredInfo[nullptr].emplace_back(IE, VD);
7287 } else {
7288 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(
7289 this->CGF.EmitLValue(IE), IE->getExprLoc());
7290 BasePointers.emplace_back(Ptr, VD);
7291 Pointers.push_back(Ptr);
7292 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
7293 Types.push_back(OMP_MAP_RETURN_PARAM | OMP_MAP_TARGET_PARAM);
7294 }
Samuel Antaocc10b852016-07-28 14:23:26 +00007295 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007296 }
Samuel Antaocc10b852016-07-28 14:23:26 +00007297
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007298 for (const auto &M : Info) {
Samuel Antao86ace552016-04-27 22:40:57 +00007299 // We need to know when we generate information for the first component
7300 // associated with a capture, because the mapping flags depend on it.
7301 bool IsFirstComponentList = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00007302
7303 // Temporary versions of arrays
7304 MapBaseValuesArrayTy CurBasePointers;
7305 MapValuesArrayTy CurPointers;
7306 MapValuesArrayTy CurSizes;
7307 MapFlagsArrayTy CurTypes;
7308 StructRangeInfoTy PartialStruct;
7309
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007310 for (const MapInfo &L : M.second) {
Samuel Antao86ace552016-04-27 22:40:57 +00007311 assert(!L.Components.empty() &&
7312 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00007313
7314 // Remember the current base pointer index.
Alexey Bataevb3638132018-07-19 16:34:13 +00007315 unsigned CurrentBasePointersIdx = CurBasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00007316 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007317 this->generateInfoForComponentList(
Alexey Bataevb3638132018-07-19 16:34:13 +00007318 L.MapType, L.MapTypeModifier, L.Components, CurBasePointers,
7319 CurPointers, CurSizes, CurTypes, PartialStruct,
7320 IsFirstComponentList, L.IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007321
7322 // If this entry relates with a device pointer, set the relevant
7323 // declaration and add the 'return pointer' flag.
Alexey Bataevb3638132018-07-19 16:34:13 +00007324 if (L.ReturnDevicePointer) {
7325 assert(CurBasePointers.size() > CurrentBasePointersIdx &&
Samuel Antaocc10b852016-07-28 14:23:26 +00007326 "Unexpected number of mapped base pointers.");
7327
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007328 const ValueDecl *RelevantVD =
7329 L.Components.back().getAssociatedDeclaration();
Samuel Antaocc10b852016-07-28 14:23:26 +00007330 assert(RelevantVD &&
7331 "No relevant declaration related with device pointer??");
7332
Alexey Bataevb3638132018-07-19 16:34:13 +00007333 CurBasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
7334 CurTypes[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PARAM;
Samuel Antaocc10b852016-07-28 14:23:26 +00007335 }
Samuel Antao86ace552016-04-27 22:40:57 +00007336 IsFirstComponentList = false;
7337 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007338
7339 // Append any pending zero-length pointers which are struct members and
7340 // used with use_device_ptr.
7341 auto CI = DeferredInfo.find(M.first);
7342 if (CI != DeferredInfo.end()) {
7343 for (const DeferredDevicePtrEntryTy &L : CI->second) {
7344 llvm::Value *BasePtr = this->CGF.EmitLValue(L.IE).getPointer();
7345 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(
7346 this->CGF.EmitLValue(L.IE), L.IE->getExprLoc());
7347 CurBasePointers.emplace_back(BasePtr, L.VD);
7348 CurPointers.push_back(Ptr);
7349 CurSizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
7350 // Entry is PTR_AND_OBJ and RETURN_PARAM. Also, set the placeholder
7351 // value MEMBER_OF=FFFF so that the entry is later updated with the
7352 // correct value of MEMBER_OF.
7353 CurTypes.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_RETURN_PARAM |
7354 OMP_MAP_MEMBER_OF);
7355 }
7356 }
7357
7358 // If there is an entry in PartialStruct it means we have a struct with
7359 // individual members mapped. Emit an extra combined entry.
7360 if (PartialStruct.Base.isValid())
7361 emitCombinedEntry(BasePointers, Pointers, Sizes, Types, CurTypes,
7362 PartialStruct);
7363
7364 // We need to append the results of this capture to what we already have.
7365 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
7366 Pointers.append(CurPointers.begin(), CurPointers.end());
7367 Sizes.append(CurSizes.begin(), CurSizes.end());
7368 Types.append(CurTypes.begin(), CurTypes.end());
Samuel Antao86ace552016-04-27 22:40:57 +00007369 }
7370 }
7371
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007372 /// Generate the base pointers, section pointers, sizes and map types
Samuel Antao86ace552016-04-27 22:40:57 +00007373 /// associated to a given capture.
7374 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00007375 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007376 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007377 MapValuesArrayTy &Pointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007378 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
7379 StructRangeInfoTy &PartialStruct) const {
Samuel Antao86ace552016-04-27 22:40:57 +00007380 assert(!Cap->capturesVariableArrayType() &&
7381 "Not expecting to generate map info for a variable array type!");
7382
Samuel Antao6890b092016-07-28 14:25:09 +00007383 // We need to know when we generating information for the first component
7384 // associated with a capture, because the mapping flags depend on it.
7385 bool IsFirstComponentList = true;
7386
Alexey Bataevb3638132018-07-19 16:34:13 +00007387 const ValueDecl *VD = Cap->capturesThis()
7388 ? nullptr
7389 : Cap->getCapturedVar()->getCanonicalDecl();
Samuel Antao86ace552016-04-27 22:40:57 +00007390
Samuel Antao6890b092016-07-28 14:25:09 +00007391 // If this declaration appears in a is_device_ptr clause we just have to
7392 // pass the pointer by value. If it is a reference to a declaration, we just
Alexey Bataevb3638132018-07-19 16:34:13 +00007393 // pass its value.
7394 if (DevPointersMap.count(VD)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007395 BasePointers.emplace_back(Arg, VD);
Samuel Antao6890b092016-07-28 14:25:09 +00007396 Pointers.push_back(Arg);
7397 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
George Rokos065755d2017-11-07 18:27:04 +00007398 Types.push_back(OMP_MAP_LITERAL | OMP_MAP_TARGET_PARAM);
Samuel Antao6890b092016-07-28 14:25:09 +00007399 return;
7400 }
7401
Paul Robinson78fb1322016-08-01 22:12:46 +00007402 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007403 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
7404 for (const auto &L : C->decl_component_lists(VD)) {
Samuel Antao86ace552016-04-27 22:40:57 +00007405 assert(L.first == VD &&
7406 "We got information for the wrong declaration??");
7407 assert(!L.second.empty() &&
7408 "Not expecting declaration with no component lists.");
Alexey Bataevb3638132018-07-19 16:34:13 +00007409 generateInfoForComponentList(C->getMapType(), C->getMapTypeModifier(),
7410 L.second, BasePointers, Pointers, Sizes,
7411 Types, PartialStruct, IsFirstComponentList,
7412 C->isImplicit());
Samuel Antao86ace552016-04-27 22:40:57 +00007413 IsFirstComponentList = false;
7414 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007415 }
Samuel Antao86ace552016-04-27 22:40:57 +00007416
Alexey Bataevb3638132018-07-19 16:34:13 +00007417 /// Generate the base pointers, section pointers, sizes and map types
7418 /// associated with the declare target link variables.
7419 void generateInfoForDeclareTargetLink(MapBaseValuesArrayTy &BasePointers,
7420 MapValuesArrayTy &Pointers,
7421 MapValuesArrayTy &Sizes,
7422 MapFlagsArrayTy &Types) const {
7423 // Map other list items in the map clause which are not captured variables
7424 // but "declare target link" global variables.,
7425 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) {
7426 for (const auto &L : C->component_lists()) {
7427 if (!L.first)
7428 continue;
7429 const auto *VD = dyn_cast<VarDecl>(L.first);
7430 if (!VD)
7431 continue;
7432 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00007433 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataevb3638132018-07-19 16:34:13 +00007434 if (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link)
7435 continue;
7436 StructRangeInfoTy PartialStruct;
7437 generateInfoForComponentList(
7438 C->getMapType(), C->getMapTypeModifier(), L.second, BasePointers,
7439 Pointers, Sizes, Types, PartialStruct,
7440 /*IsFirstComponentList=*/true, C->isImplicit());
7441 assert(!PartialStruct.Base.isValid() &&
7442 "No partial structs for declare target link expected.");
7443 }
7444 }
Samuel Antao86ace552016-04-27 22:40:57 +00007445 }
Samuel Antaod486f842016-05-26 16:53:38 +00007446
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007447 /// Generate the default map information for a given capture \a CI,
Samuel Antaod486f842016-05-26 16:53:38 +00007448 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00007449 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
7450 const FieldDecl &RI, llvm::Value *CV,
7451 MapBaseValuesArrayTy &CurBasePointers,
7452 MapValuesArrayTy &CurPointers,
7453 MapValuesArrayTy &CurSizes,
Alexey Bataevb3638132018-07-19 16:34:13 +00007454 MapFlagsArrayTy &CurMapTypes) const {
Samuel Antaod486f842016-05-26 16:53:38 +00007455 // Do the default mapping.
7456 if (CI.capturesThis()) {
7457 CurBasePointers.push_back(CV);
7458 CurPointers.push_back(CV);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007459 const auto *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007460 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
7461 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00007462 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00007463 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007464 CurBasePointers.push_back(CV);
7465 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00007466 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007467 // We have to signal to the runtime captures passed by value that are
7468 // not pointers.
George Rokos065755d2017-11-07 18:27:04 +00007469 CurMapTypes.push_back(OMP_MAP_LITERAL);
Samuel Antaod486f842016-05-26 16:53:38 +00007470 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
7471 } else {
7472 // Pointers are implicitly mapped with a zero size and no flags
7473 // (other than first map that is added for all implicit maps).
Alexey Bataevb3638132018-07-19 16:34:13 +00007474 CurMapTypes.push_back(OMP_MAP_NONE);
Samuel Antaod486f842016-05-26 16:53:38 +00007475 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
7476 }
7477 } else {
7478 assert(CI.capturesVariable() && "Expected captured reference.");
7479 CurBasePointers.push_back(CV);
7480 CurPointers.push_back(CV);
7481
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007482 const auto *PtrTy = cast<ReferenceType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007483 QualType ElementType = PtrTy->getPointeeType();
7484 CurSizes.push_back(CGF.getTypeSize(ElementType));
7485 // The default map type for a scalar/complex type is 'to' because by
7486 // default the value doesn't have to be retrieved. For an aggregate
7487 // type, the default is 'tofrom'.
Alexey Bataevb3638132018-07-19 16:34:13 +00007488 CurMapTypes.push_back(getMapModifiersForPrivateClauses(CI));
Samuel Antaod486f842016-05-26 16:53:38 +00007489 }
George Rokos065755d2017-11-07 18:27:04 +00007490 // Every default map produces a single argument which is a target parameter.
7491 CurMapTypes.back() |= OMP_MAP_TARGET_PARAM;
Alexey Bataevb3638132018-07-19 16:34:13 +00007492
7493 // Add flag stating this is an implicit map.
7494 CurMapTypes.back() |= OMP_MAP_IMPLICIT;
Samuel Antaod486f842016-05-26 16:53:38 +00007495 }
Samuel Antao86ace552016-04-27 22:40:57 +00007496};
Samuel Antaodf158d52016-04-27 22:58:19 +00007497
7498enum OpenMPOffloadingReservedDeviceIDs {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007499 /// Device ID if the device was not defined, runtime should get it
Samuel Antaodf158d52016-04-27 22:58:19 +00007500 /// from environment variables in the spec.
7501 OMP_DEVICEID_UNDEF = -1,
7502};
7503} // anonymous namespace
7504
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007505/// Emit the arrays used to pass the captures and map information to the
Samuel Antaodf158d52016-04-27 22:58:19 +00007506/// offloading runtime library. If there is no map or capture information,
7507/// return nullptr by reference.
7508static void
Samuel Antaocc10b852016-07-28 14:23:26 +00007509emitOffloadingArrays(CodeGenFunction &CGF,
7510 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00007511 MappableExprsHandler::MapValuesArrayTy &Pointers,
7512 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00007513 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
7514 CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007515 CodeGenModule &CGM = CGF.CGM;
7516 ASTContext &Ctx = CGF.getContext();
Samuel Antaodf158d52016-04-27 22:58:19 +00007517
Samuel Antaocc10b852016-07-28 14:23:26 +00007518 // Reset the array information.
7519 Info.clearArrayInfo();
7520 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00007521
Samuel Antaocc10b852016-07-28 14:23:26 +00007522 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007523 // Detect if we have any capture size requiring runtime evaluation of the
7524 // size so that a constant array could be eventually used.
7525 bool hasRuntimeEvaluationCaptureSize = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007526 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00007527 if (!isa<llvm::Constant>(S)) {
7528 hasRuntimeEvaluationCaptureSize = true;
7529 break;
7530 }
7531
Samuel Antaocc10b852016-07-28 14:23:26 +00007532 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00007533 QualType PointerArrayType =
7534 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
7535 /*IndexTypeQuals=*/0);
7536
Samuel Antaocc10b852016-07-28 14:23:26 +00007537 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007538 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00007539 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007540 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
7541
7542 // If we don't have any VLA types or other types that require runtime
7543 // evaluation, we can use a constant array for the map sizes, otherwise we
7544 // need to fill up the arrays as we do for the pointers.
7545 if (hasRuntimeEvaluationCaptureSize) {
7546 QualType SizeArrayType = Ctx.getConstantArrayType(
7547 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
7548 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00007549 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007550 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
7551 } else {
7552 // We expect all the sizes to be constant, so we collect them to create
7553 // a constant array.
7554 SmallVector<llvm::Constant *, 16> ConstSizes;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007555 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00007556 ConstSizes.push_back(cast<llvm::Constant>(S));
7557
7558 auto *SizesArrayInit = llvm::ConstantArray::get(
7559 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
Alexey Bataev18fa2322018-05-02 14:20:50 +00007560 std::string Name = CGM.getOpenMPRuntime().getName({"offload_sizes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00007561 auto *SizesArrayGbl = new llvm::GlobalVariable(
7562 CGM.getModule(), SizesArrayInit->getType(),
7563 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00007564 SizesArrayInit, Name);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00007565 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00007566 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00007567 }
7568
7569 // The map types are always constant so we don't need to generate code to
7570 // fill arrays. Instead, we create an array constant.
Alexey Bataevb3638132018-07-19 16:34:13 +00007571 SmallVector<uint64_t, 4> Mapping(MapTypes.size(), 0);
7572 llvm::copy(MapTypes, Mapping.begin());
Samuel Antaodf158d52016-04-27 22:58:19 +00007573 llvm::Constant *MapTypesArrayInit =
Alexey Bataevb3638132018-07-19 16:34:13 +00007574 llvm::ConstantDataArray::get(CGF.Builder.getContext(), Mapping);
Alexey Bataev18fa2322018-05-02 14:20:50 +00007575 std::string MaptypesName =
7576 CGM.getOpenMPRuntime().getName({"offload_maptypes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00007577 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
7578 CGM.getModule(), MapTypesArrayInit->getType(),
7579 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00007580 MapTypesArrayInit, MaptypesName);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00007581 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00007582 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00007583
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007584 for (unsigned I = 0; I < Info.NumberOfPtrs; ++I) {
7585 llvm::Value *BPVal = *BasePointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00007586 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007587 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007588 Info.BasePointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00007589 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7590 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00007591 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
7592 CGF.Builder.CreateStore(BPVal, BPAddr);
7593
Samuel Antaocc10b852016-07-28 14:23:26 +00007594 if (Info.requiresDevicePointerInfo())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007595 if (const ValueDecl *DevVD = BasePointers[I].getDevicePtrDecl())
Alexey Bataev43a919f2018-04-13 17:48:43 +00007596 Info.CaptureDeviceAddrMap.try_emplace(DevVD, BPAddr);
Samuel Antaocc10b852016-07-28 14:23:26 +00007597
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007598 llvm::Value *PVal = Pointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00007599 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007600 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007601 Info.PointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00007602 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7603 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00007604 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
7605 CGF.Builder.CreateStore(PVal, PAddr);
7606
7607 if (hasRuntimeEvaluationCaptureSize) {
7608 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007609 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
7610 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007611 /*Idx0=*/0,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007612 /*Idx1=*/I);
Samuel Antaodf158d52016-04-27 22:58:19 +00007613 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
7614 CGF.Builder.CreateStore(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007615 CGF.Builder.CreateIntCast(Sizes[I], CGM.SizeTy, /*isSigned=*/true),
Samuel Antaodf158d52016-04-27 22:58:19 +00007616 SAddr);
7617 }
7618 }
7619 }
7620}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007621/// Emit the arguments to be passed to the runtime library based on the
Samuel Antaodf158d52016-04-27 22:58:19 +00007622/// arrays of pointers, sizes and map types.
7623static void emitOffloadingArraysArgument(
7624 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
7625 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007626 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007627 CodeGenModule &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00007628 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007629 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007630 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
7631 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007632 /*Idx0=*/0, /*Idx1=*/0);
7633 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007634 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
7635 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007636 /*Idx0=*/0,
7637 /*Idx1=*/0);
7638 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00007639 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007640 /*Idx0=*/0, /*Idx1=*/0);
7641 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
George Rokos63bc9d62017-11-21 18:25:12 +00007642 llvm::ArrayType::get(CGM.Int64Ty, Info.NumberOfPtrs),
Samuel Antaocc10b852016-07-28 14:23:26 +00007643 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00007644 /*Idx0=*/0,
7645 /*Idx1=*/0);
7646 } else {
7647 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
7648 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
7649 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
7650 MapTypesArrayArg =
George Rokos63bc9d62017-11-21 18:25:12 +00007651 llvm::ConstantPointerNull::get(CGM.Int64Ty->getPointerTo());
Samuel Antaodf158d52016-04-27 22:58:19 +00007652 }
Samuel Antao86ace552016-04-27 22:40:57 +00007653}
7654
Samuel Antaobed3c462015-10-02 16:14:20 +00007655void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
7656 const OMPExecutableDirective &D,
7657 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00007658 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00007659 const Expr *IfCond, const Expr *Device) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00007660 if (!CGF.HaveInsertPoint())
7661 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00007662
Samuel Antaoee8fb302016-01-06 13:42:12 +00007663 assert(OutlinedFn && "Invalid outlined function!");
7664
Alexey Bataev8451efa2018-01-15 19:06:12 +00007665 const bool RequiresOuterTask = D.hasClausesOfKind<OMPDependClause>();
7666 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Alexey Bataev475a7442018-01-12 19:39:11 +00007667 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Alexey Bataev8451efa2018-01-15 19:06:12 +00007668 auto &&ArgsCodegen = [&CS, &CapturedVars](CodeGenFunction &CGF,
7669 PrePostActionTy &) {
7670 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7671 };
7672 emitInlinedDirective(CGF, OMPD_unknown, ArgsCodegen);
Samuel Antao86ace552016-04-27 22:40:57 +00007673
Alexey Bataev8451efa2018-01-15 19:06:12 +00007674 CodeGenFunction::OMPTargetDataInfo InputInfo;
7675 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00007676 // Fill up the pointer arrays and transfer execution to the device.
Alexey Bataev8451efa2018-01-15 19:06:12 +00007677 auto &&ThenGen = [this, Device, OutlinedFn, OutlinedFnID, &D, &InputInfo,
7678 &MapTypesArray, &CS, RequiresOuterTask,
7679 &CapturedVars](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobed3c462015-10-02 16:14:20 +00007680 // On top of the arrays that were filled up, the target offloading call
7681 // takes as arguments the device id as well as the host pointer. The host
7682 // pointer is used by the runtime library to identify the current target
7683 // region, so it only has to be unique and not necessarily point to
7684 // anything. It could be the pointer to the outlined function that
7685 // implements the target region, but we aren't using that so that the
7686 // compiler doesn't need to keep that, and could therefore inline the host
7687 // function if proven worthwhile during optimization.
7688
Samuel Antaoee8fb302016-01-06 13:42:12 +00007689 // From this point on, we need to have an ID of the target region defined.
7690 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00007691
7692 // Emit device ID if any.
7693 llvm::Value *DeviceID;
George Rokos63bc9d62017-11-21 18:25:12 +00007694 if (Device) {
Samuel Antaobed3c462015-10-02 16:14:20 +00007695 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00007696 CGF.Int64Ty, /*isSigned=*/true);
7697 } else {
7698 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
7699 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007700
Samuel Antaodf158d52016-04-27 22:58:19 +00007701 // Emit the number of elements in the offloading arrays.
Alexey Bataev8451efa2018-01-15 19:06:12 +00007702 llvm::Value *PointerNum =
7703 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaodf158d52016-04-27 22:58:19 +00007704
Samuel Antaob68e2db2016-03-03 16:20:23 +00007705 // Return value of the runtime offloading call.
7706 llvm::Value *Return;
7707
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007708 llvm::Value *NumTeams = emitNumTeamsForTargetDirective(*this, CGF, D);
7709 llvm::Value *NumThreads = emitNumThreadsForTargetDirective(*this, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007710
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007711 bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007712 // The target region is an outlined function launched by the runtime
7713 // via calls __tgt_target() or __tgt_target_teams().
7714 //
7715 // __tgt_target() launches a target region with one team and one thread,
7716 // executing a serial region. This master thread may in turn launch
7717 // more threads within its team upon encountering a parallel region,
7718 // however, no additional teams can be launched on the device.
7719 //
7720 // __tgt_target_teams() launches a target region with one or more teams,
7721 // each with one or more threads. This call is required for target
7722 // constructs such as:
7723 // 'target teams'
7724 // 'target' / 'teams'
7725 // 'target teams distribute parallel for'
7726 // 'target parallel'
7727 // and so on.
7728 //
7729 // Note that on the host and CPU targets, the runtime implementation of
7730 // these calls simply call the outlined function without forking threads.
7731 // The outlined functions themselves have runtime calls to
7732 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
7733 // the compiler in emitTeamsCall() and emitParallelCall().
7734 //
7735 // In contrast, on the NVPTX target, the implementation of
7736 // __tgt_target_teams() launches a GPU kernel with the requested number
7737 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00007738 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007739 // If we have NumTeams defined this means that we have an enclosed teams
7740 // region. Therefore we also expect to have NumThreads defined. These two
7741 // values should be defined in the presence of a teams directive,
7742 // regardless of having any clauses associated. If the user is using teams
7743 // but no clauses, these two values will be the default that should be
7744 // passed to the runtime library - a 32-bit integer with the value zero.
7745 assert(NumThreads && "Thread limit expression should be available along "
7746 "with number of teams.");
Alexey Bataev8451efa2018-01-15 19:06:12 +00007747 llvm::Value *OffloadingArgs[] = {DeviceID,
7748 OutlinedFnID,
7749 PointerNum,
7750 InputInfo.BasePointersArray.getPointer(),
7751 InputInfo.PointersArray.getPointer(),
7752 InputInfo.SizesArray.getPointer(),
7753 MapTypesArray,
7754 NumTeams,
7755 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00007756 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00007757 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_teams_nowait
7758 : OMPRTL__tgt_target_teams),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007759 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007760 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00007761 llvm::Value *OffloadingArgs[] = {DeviceID,
7762 OutlinedFnID,
7763 PointerNum,
7764 InputInfo.BasePointersArray.getPointer(),
7765 InputInfo.PointersArray.getPointer(),
7766 InputInfo.SizesArray.getPointer(),
7767 MapTypesArray};
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007768 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00007769 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_nowait
7770 : OMPRTL__tgt_target),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00007771 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007772 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007773
Alexey Bataev2a007e02017-10-02 14:20:58 +00007774 // Check the error code and execute the host version if required.
7775 llvm::BasicBlock *OffloadFailedBlock =
7776 CGF.createBasicBlock("omp_offload.failed");
7777 llvm::BasicBlock *OffloadContBlock =
7778 CGF.createBasicBlock("omp_offload.cont");
7779 llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
7780 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
7781
7782 CGF.EmitBlock(OffloadFailedBlock);
Alexey Bataev8451efa2018-01-15 19:06:12 +00007783 if (RequiresOuterTask) {
7784 CapturedVars.clear();
7785 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7786 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007787 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars);
Alexey Bataev2a007e02017-10-02 14:20:58 +00007788 CGF.EmitBranch(OffloadContBlock);
7789
7790 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00007791 };
7792
Samuel Antaoee8fb302016-01-06 13:42:12 +00007793 // Notify that the host version must be executed.
Alexey Bataev8451efa2018-01-15 19:06:12 +00007794 auto &&ElseGen = [this, &D, OutlinedFn, &CS, &CapturedVars,
7795 RequiresOuterTask](CodeGenFunction &CGF,
7796 PrePostActionTy &) {
7797 if (RequiresOuterTask) {
7798 CapturedVars.clear();
7799 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
7800 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007801 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars);
Alexey Bataev8451efa2018-01-15 19:06:12 +00007802 };
7803
7804 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray,
7805 &CapturedVars, RequiresOuterTask,
7806 &CS](CodeGenFunction &CGF, PrePostActionTy &) {
7807 // Fill up the arrays with all the captured variables.
7808 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
7809 MappableExprsHandler::MapValuesArrayTy Pointers;
7810 MappableExprsHandler::MapValuesArrayTy Sizes;
7811 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7812
Alexey Bataev8451efa2018-01-15 19:06:12 +00007813 // Get mappable expression information.
7814 MappableExprsHandler MEHandler(D, CGF);
7815
7816 auto RI = CS.getCapturedRecordDecl()->field_begin();
7817 auto CV = CapturedVars.begin();
7818 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
7819 CE = CS.capture_end();
7820 CI != CE; ++CI, ++RI, ++CV) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007821 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
7822 MappableExprsHandler::MapValuesArrayTy CurPointers;
7823 MappableExprsHandler::MapValuesArrayTy CurSizes;
7824 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
7825 MappableExprsHandler::StructRangeInfoTy PartialStruct;
Alexey Bataev8451efa2018-01-15 19:06:12 +00007826
7827 // VLA sizes are passed to the outlined region by copy and do not have map
7828 // information associated.
7829 if (CI->capturesVariableArrayType()) {
7830 CurBasePointers.push_back(*CV);
7831 CurPointers.push_back(*CV);
7832 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
7833 // Copy to the device as an argument. No need to retrieve it.
7834 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_LITERAL |
7835 MappableExprsHandler::OMP_MAP_TARGET_PARAM);
7836 } else {
7837 // If we have any information in the map clause, we use it, otherwise we
7838 // just do a default mapping.
7839 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007840 CurSizes, CurMapTypes, PartialStruct);
Alexey Bataev8451efa2018-01-15 19:06:12 +00007841 if (CurBasePointers.empty())
7842 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
7843 CurPointers, CurSizes, CurMapTypes);
7844 }
7845 // We expect to have at least an element of information for this capture.
7846 assert(!CurBasePointers.empty() &&
7847 "Non-existing map pointer for capture!");
7848 assert(CurBasePointers.size() == CurPointers.size() &&
7849 CurBasePointers.size() == CurSizes.size() &&
7850 CurBasePointers.size() == CurMapTypes.size() &&
7851 "Inconsistent map information sizes!");
7852
Alexey Bataevb3638132018-07-19 16:34:13 +00007853 // If there is an entry in PartialStruct it means we have a struct with
7854 // individual members mapped. Emit an extra combined entry.
7855 if (PartialStruct.Base.isValid())
7856 MEHandler.emitCombinedEntry(BasePointers, Pointers, Sizes, MapTypes,
7857 CurMapTypes, PartialStruct);
7858
Alexey Bataev8451efa2018-01-15 19:06:12 +00007859 // We need to append the results of this capture to what we already have.
7860 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
7861 Pointers.append(CurPointers.begin(), CurPointers.end());
7862 Sizes.append(CurSizes.begin(), CurSizes.end());
7863 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
7864 }
Alexey Bataev92327c52018-03-26 16:40:55 +00007865 // Map other list items in the map clause which are not captured variables
7866 // but "declare target link" global variables.
Alexey Bataevb3638132018-07-19 16:34:13 +00007867 MEHandler.generateInfoForDeclareTargetLink(BasePointers, Pointers, Sizes,
7868 MapTypes);
Alexey Bataev8451efa2018-01-15 19:06:12 +00007869
7870 TargetDataInfo Info;
7871 // Fill up the arrays and create the arguments.
7872 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
7873 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
7874 Info.PointersArray, Info.SizesArray,
7875 Info.MapTypesArray, Info);
7876 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
7877 InputInfo.BasePointersArray =
7878 Address(Info.BasePointersArray, CGM.getPointerAlign());
7879 InputInfo.PointersArray =
7880 Address(Info.PointersArray, CGM.getPointerAlign());
7881 InputInfo.SizesArray = Address(Info.SizesArray, CGM.getPointerAlign());
7882 MapTypesArray = Info.MapTypesArray;
7883 if (RequiresOuterTask)
7884 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
7885 else
7886 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
7887 };
7888
7889 auto &&TargetElseGen = [this, &ElseGen, &D, RequiresOuterTask](
7890 CodeGenFunction &CGF, PrePostActionTy &) {
7891 if (RequiresOuterTask) {
7892 CodeGenFunction::OMPTargetDataInfo InputInfo;
7893 CGF.EmitOMPTargetTaskBasedDirective(D, ElseGen, InputInfo);
7894 } else {
7895 emitInlinedDirective(CGF, D.getDirectiveKind(), ElseGen);
7896 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00007897 };
7898
7899 // If we have a target function ID it means that we need to support
7900 // offloading, otherwise, just execute on the host. We need to execute on host
7901 // regardless of the conditional in the if clause if, e.g., the user do not
7902 // specify target triples.
7903 if (OutlinedFnID) {
Alexey Bataev8451efa2018-01-15 19:06:12 +00007904 if (IfCond) {
7905 emitOMPIfClause(CGF, IfCond, TargetThenGen, TargetElseGen);
7906 } else {
7907 RegionCodeGenTy ThenRCG(TargetThenGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007908 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007909 }
7910 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00007911 RegionCodeGenTy ElseRCG(TargetElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007912 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007913 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007914}
Samuel Antaoee8fb302016-01-06 13:42:12 +00007915
7916void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
7917 StringRef ParentName) {
7918 if (!S)
7919 return;
7920
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007921 // Codegen OMP target directives that offload compute to the device.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007922 bool RequiresDeviceCodegen =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007923 isa<OMPExecutableDirective>(S) &&
7924 isOpenMPTargetExecutionDirective(
7925 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00007926
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007927 if (RequiresDeviceCodegen) {
7928 const auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007929 unsigned DeviceID;
7930 unsigned FileID;
7931 unsigned Line;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007932 getTargetEntryUniqueInfo(CGM.getContext(), E.getBeginLoc(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00007933 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007934
7935 // Is this a target region that should not be emitted as an entry point? If
7936 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00007937 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
7938 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007939 return;
7940
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007941 switch (E.getDirectiveKind()) {
7942 case OMPD_target:
7943 CodeGenFunction::EmitOMPTargetDeviceFunction(CGM, ParentName,
7944 cast<OMPTargetDirective>(E));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007945 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007946 case OMPD_target_parallel:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00007947 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007948 CGM, ParentName, cast<OMPTargetParallelDirective>(E));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00007949 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007950 case OMPD_target_teams:
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00007951 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007952 CGM, ParentName, cast<OMPTargetTeamsDirective>(E));
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00007953 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007954 case OMPD_target_teams_distribute:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007955 CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007956 CGM, ParentName, cast<OMPTargetTeamsDistributeDirective>(E));
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007957 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007958 case OMPD_target_teams_distribute_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007959 CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007960 CGM, ParentName, cast<OMPTargetTeamsDistributeSimdDirective>(E));
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007961 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007962 case OMPD_target_parallel_for:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007963 CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007964 CGM, ParentName, cast<OMPTargetParallelForDirective>(E));
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007965 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007966 case OMPD_target_parallel_for_simd:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007967 CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007968 CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(E));
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007969 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007970 case OMPD_target_simd:
Alexey Bataevf8365372017-11-17 17:57:25 +00007971 CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007972 CGM, ParentName, cast<OMPTargetSimdDirective>(E));
Alexey Bataevf8365372017-11-17 17:57:25 +00007973 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007974 case OMPD_target_teams_distribute_parallel_for:
Carlo Bertolli52978c32018-01-03 21:12:44 +00007975 CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
7976 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007977 cast<OMPTargetTeamsDistributeParallelForDirective>(E));
Carlo Bertolli52978c32018-01-03 21:12:44 +00007978 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007979 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00007980 CodeGenFunction::
7981 EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
7982 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007983 cast<OMPTargetTeamsDistributeParallelForSimdDirective>(E));
Alexey Bataev647dd842018-01-15 20:59:40 +00007984 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007985 case OMPD_parallel:
7986 case OMPD_for:
7987 case OMPD_parallel_for:
7988 case OMPD_parallel_sections:
7989 case OMPD_for_simd:
7990 case OMPD_parallel_for_simd:
7991 case OMPD_cancel:
7992 case OMPD_cancellation_point:
7993 case OMPD_ordered:
7994 case OMPD_threadprivate:
7995 case OMPD_task:
7996 case OMPD_simd:
7997 case OMPD_sections:
7998 case OMPD_section:
7999 case OMPD_single:
8000 case OMPD_master:
8001 case OMPD_critical:
8002 case OMPD_taskyield:
8003 case OMPD_barrier:
8004 case OMPD_taskwait:
8005 case OMPD_taskgroup:
8006 case OMPD_atomic:
8007 case OMPD_flush:
8008 case OMPD_teams:
8009 case OMPD_target_data:
8010 case OMPD_target_exit_data:
8011 case OMPD_target_enter_data:
8012 case OMPD_distribute:
8013 case OMPD_distribute_simd:
8014 case OMPD_distribute_parallel_for:
8015 case OMPD_distribute_parallel_for_simd:
8016 case OMPD_teams_distribute:
8017 case OMPD_teams_distribute_simd:
8018 case OMPD_teams_distribute_parallel_for:
8019 case OMPD_teams_distribute_parallel_for_simd:
8020 case OMPD_target_update:
8021 case OMPD_declare_simd:
8022 case OMPD_declare_target:
8023 case OMPD_end_declare_target:
8024 case OMPD_declare_reduction:
8025 case OMPD_taskloop:
8026 case OMPD_taskloop_simd:
8027 case OMPD_unknown:
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008028 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
8029 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00008030 return;
8031 }
8032
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008033 if (const auto *E = dyn_cast<OMPExecutableDirective>(S)) {
Alexey Bataev475a7442018-01-12 19:39:11 +00008034 if (!E->hasAssociatedStmt() || !E->getAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00008035 return;
8036
8037 scanForTargetRegionsFunctions(
Alexey Bataev475a7442018-01-12 19:39:11 +00008038 E->getInnermostCapturedStmt()->getCapturedStmt(), ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008039 return;
8040 }
8041
8042 // If this is a lambda function, look into its body.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008043 if (const auto *L = dyn_cast<LambdaExpr>(S))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008044 S = L->getBody();
8045
8046 // Keep looking for target regions recursively.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008047 for (const Stmt *II : S->children())
Samuel Antaoee8fb302016-01-06 13:42:12 +00008048 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008049}
8050
8051bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008052 const auto *FD = cast<FunctionDecl>(GD.getDecl());
Samuel Antaoee8fb302016-01-06 13:42:12 +00008053
8054 // If emitting code for the host, we do not process FD here. Instead we do
8055 // the normal code generation.
8056 if (!CGM.getLangOpts().OpenMPIsDevice)
8057 return false;
8058
8059 // Try to detect target regions in the function.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008060 scanForTargetRegionsFunctions(FD->getBody(), CGM.getMangledName(GD));
Samuel Antaoee8fb302016-01-06 13:42:12 +00008061
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008062 // Do not to emit function if it is not marked as declare target.
Alexey Bataev97b72212018-08-14 18:31:20 +00008063 return !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD) &&
Alexey Bataevfb388282018-05-01 14:09:46 +00008064 AlreadyEmittedTargetFunctions.count(FD->getCanonicalDecl()) == 0;
Samuel Antaoee8fb302016-01-06 13:42:12 +00008065}
8066
8067bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
8068 if (!CGM.getLangOpts().OpenMPIsDevice)
8069 return false;
8070
8071 // Check if there are Ctors/Dtors in this declaration and look for target
8072 // regions in it. We use the complete variant to produce the kernel name
8073 // mangling.
8074 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008075 if (const auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
8076 for (const CXXConstructorDecl *Ctor : RD->ctors()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008077 StringRef ParentName =
8078 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
8079 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
8080 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008081 if (const CXXDestructorDecl *Dtor = RD->getDestructor()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008082 StringRef ParentName =
8083 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
8084 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
8085 }
8086 }
8087
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008088 // Do not to emit variable if it is not marked as declare target.
Alexey Bataev92327c52018-03-26 16:40:55 +00008089 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00008090 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
8091 cast<VarDecl>(GD.getDecl()));
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008092 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Alexey Bataevd01b7492018-08-15 19:45:12 +00008093 DeferredGlobalVariables.insert(cast<VarDecl>(GD.getDecl()));
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008094 return true;
8095 }
8096 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00008097}
8098
Alexey Bataev03f270c2018-03-30 18:31:07 +00008099void CGOpenMPRuntime::registerTargetGlobalVariable(const VarDecl *VD,
8100 llvm::Constant *Addr) {
8101 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00008102 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
Alexey Bataev03f270c2018-03-30 18:31:07 +00008103 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags;
8104 StringRef VarName;
8105 CharUnits VarSize;
8106 llvm::GlobalValue::LinkageTypes Linkage;
8107 switch (*Res) {
8108 case OMPDeclareTargetDeclAttr::MT_To:
8109 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo;
8110 VarName = CGM.getMangledName(VD);
8111 VarSize = CGM.getContext().getTypeSizeInChars(VD->getType());
8112 Linkage = CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false);
Alexey Bataev38235142018-07-31 16:40:15 +00008113 // Temp solution to prevent optimizations of the internal variables.
8114 if (CGM.getLangOpts().OpenMPIsDevice && !VD->isExternallyVisible()) {
8115 std::string RefName = getName({VarName, "ref"});
8116 if (!CGM.GetGlobalValue(RefName)) {
8117 llvm::Constant *AddrRef =
8118 getOrCreateInternalVariable(Addr->getType(), RefName);
8119 auto *GVAddrRef = cast<llvm::GlobalVariable>(AddrRef);
8120 GVAddrRef->setConstant(/*Val=*/true);
8121 GVAddrRef->setLinkage(llvm::GlobalValue::InternalLinkage);
8122 GVAddrRef->setInitializer(Addr);
8123 CGM.addCompilerUsedGlobal(GVAddrRef);
8124 }
8125 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00008126 break;
8127 case OMPDeclareTargetDeclAttr::MT_Link:
Alexey Bataevc52f01d2018-07-16 20:05:25 +00008128 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink;
8129 if (CGM.getLangOpts().OpenMPIsDevice) {
8130 VarName = Addr->getName();
8131 Addr = nullptr;
8132 } else {
8133 VarName = getAddrOfDeclareTargetLink(VD).getName();
Alexey Bataev03f270c2018-03-30 18:31:07 +00008134 Addr =
8135 cast<llvm::Constant>(getAddrOfDeclareTargetLink(VD).getPointer());
8136 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00008137 VarSize = CGM.getPointerSize();
8138 Linkage = llvm::GlobalValue::WeakAnyLinkage;
8139 break;
8140 }
8141 OffloadEntriesInfoManager.registerDeviceGlobalVarEntryInfo(
8142 VarName, Addr, VarSize, Flags, Linkage);
8143 }
8144}
8145
Samuel Antaoee8fb302016-01-06 13:42:12 +00008146bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008147 if (isa<FunctionDecl>(GD.getDecl()))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008148 return emitTargetFunctions(GD);
8149
8150 return emitTargetGlobalVariable(GD);
8151}
8152
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008153void CGOpenMPRuntime::emitDeferredTargetDecls() const {
8154 for (const VarDecl *VD : DeferredGlobalVariables) {
8155 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00008156 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataevd01b7492018-08-15 19:45:12 +00008157 if (!Res)
8158 continue;
8159 if (*Res == OMPDeclareTargetDeclAttr::MT_To) {
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008160 CGM.EmitGlobal(VD);
Alexey Bataevd01b7492018-08-15 19:45:12 +00008161 } else {
8162 assert(*Res == OMPDeclareTargetDeclAttr::MT_Link &&
8163 "Expected to or link clauses.");
8164 (void)CGM.getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008165 }
8166 }
8167}
8168
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008169CGOpenMPRuntime::DisableAutoDeclareTargetRAII::DisableAutoDeclareTargetRAII(
8170 CodeGenModule &CGM)
8171 : CGM(CGM) {
8172 if (CGM.getLangOpts().OpenMPIsDevice) {
8173 SavedShouldMarkAsGlobal = CGM.getOpenMPRuntime().ShouldMarkAsGlobal;
8174 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = false;
8175 }
8176}
8177
8178CGOpenMPRuntime::DisableAutoDeclareTargetRAII::~DisableAutoDeclareTargetRAII() {
8179 if (CGM.getLangOpts().OpenMPIsDevice)
8180 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = SavedShouldMarkAsGlobal;
8181}
8182
Alexey Bataev6d944102018-05-02 15:45:28 +00008183bool CGOpenMPRuntime::markAsGlobalTarget(GlobalDecl GD) {
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008184 if (!CGM.getLangOpts().OpenMPIsDevice || !ShouldMarkAsGlobal)
8185 return true;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008186
Alexey Bataev6d944102018-05-02 15:45:28 +00008187 const auto *D = cast<FunctionDecl>(GD.getDecl());
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008188 const FunctionDecl *FD = D->getCanonicalDecl();
Alexey Bataev34f8a702018-03-28 14:28:54 +00008189 // Do not to emit function if it is marked as declare target as it was already
8190 // emitted.
Alexey Bataev97b72212018-08-14 18:31:20 +00008191 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(D)) {
Alexey Bataev34f8a702018-03-28 14:28:54 +00008192 if (D->hasBody() && AlreadyEmittedTargetFunctions.count(FD) == 0) {
8193 if (auto *F = dyn_cast_or_null<llvm::Function>(
Alexey Bataev6d944102018-05-02 15:45:28 +00008194 CGM.GetGlobalValue(CGM.getMangledName(GD))))
Alexey Bataev34f8a702018-03-28 14:28:54 +00008195 return !F->isDeclaration();
8196 return false;
8197 }
8198 return true;
8199 }
8200
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008201 return !AlreadyEmittedTargetFunctions.insert(FD).second;
8202}
8203
Samuel Antaoee8fb302016-01-06 13:42:12 +00008204llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
8205 // If we have offloading in the current module, we need to emit the entries
8206 // now and register the offloading descriptor.
8207 createOffloadEntriesAndInfoMetadata();
8208
8209 // Create and register the offloading binary descriptors. This is the main
8210 // entity that captures all the information about offloading in the current
8211 // compilation unit.
8212 return createOffloadingBinaryDescriptorRegistration();
8213}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008214
8215void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
8216 const OMPExecutableDirective &D,
8217 SourceLocation Loc,
8218 llvm::Value *OutlinedFn,
8219 ArrayRef<llvm::Value *> CapturedVars) {
8220 if (!CGF.HaveInsertPoint())
8221 return;
8222
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008223 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008224 CodeGenFunction::RunCleanupsScope Scope(CGF);
8225
8226 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
8227 llvm::Value *Args[] = {
8228 RTLoc,
8229 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
8230 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
8231 llvm::SmallVector<llvm::Value *, 16> RealArgs;
8232 RealArgs.append(std::begin(Args), std::end(Args));
8233 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
8234
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008235 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008236 CGF.EmitRuntimeCall(RTLFn, RealArgs);
8237}
8238
8239void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00008240 const Expr *NumTeams,
8241 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008242 SourceLocation Loc) {
8243 if (!CGF.HaveInsertPoint())
8244 return;
8245
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008246 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008247
Carlo Bertollic6872252016-04-04 15:55:02 +00008248 llvm::Value *NumTeamsVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008249 NumTeams
Carlo Bertollic6872252016-04-04 15:55:02 +00008250 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
8251 CGF.CGM.Int32Ty, /* isSigned = */ true)
8252 : CGF.Builder.getInt32(0);
8253
8254 llvm::Value *ThreadLimitVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008255 ThreadLimit
Carlo Bertollic6872252016-04-04 15:55:02 +00008256 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
8257 CGF.CGM.Int32Ty, /* isSigned = */ true)
8258 : CGF.Builder.getInt32(0);
8259
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008260 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00008261 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
8262 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008263 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
8264 PushNumTeamsArgs);
8265}
Samuel Antaodf158d52016-04-27 22:58:19 +00008266
Samuel Antaocc10b852016-07-28 14:23:26 +00008267void CGOpenMPRuntime::emitTargetDataCalls(
8268 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8269 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008270 if (!CGF.HaveInsertPoint())
8271 return;
8272
Samuel Antaocc10b852016-07-28 14:23:26 +00008273 // Action used to replace the default codegen action and turn privatization
8274 // off.
8275 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00008276
8277 // Generate the code for the opening of the data environment. Capture all the
8278 // arguments of the runtime call by reference because they are used in the
8279 // closing of the region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008280 auto &&BeginThenGen = [this, &D, Device, &Info,
8281 &CodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008282 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00008283 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00008284 MappableExprsHandler::MapValuesArrayTy Pointers;
8285 MappableExprsHandler::MapValuesArrayTy Sizes;
8286 MappableExprsHandler::MapFlagsArrayTy MapTypes;
8287
8288 // Get map clause information.
8289 MappableExprsHandler MCHandler(D, CGF);
8290 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00008291
8292 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00008293 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008294
8295 llvm::Value *BasePointersArrayArg = nullptr;
8296 llvm::Value *PointersArrayArg = nullptr;
8297 llvm::Value *SizesArrayArg = nullptr;
8298 llvm::Value *MapTypesArrayArg = nullptr;
8299 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008300 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008301
8302 // Emit device ID if any.
8303 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008304 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008305 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008306 CGF.Int64Ty, /*isSigned=*/true);
8307 } else {
8308 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8309 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008310
8311 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008312 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00008313
8314 llvm::Value *OffloadingArgs[] = {
8315 DeviceID, PointerNum, BasePointersArrayArg,
8316 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008317 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_begin),
Samuel Antaodf158d52016-04-27 22:58:19 +00008318 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00008319
8320 // If device pointer privatization is required, emit the body of the region
8321 // here. It will have to be duplicated: with and without privatization.
8322 if (!Info.CaptureDeviceAddrMap.empty())
8323 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008324 };
8325
8326 // Generate code for the closing of the data region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008327 auto &&EndThenGen = [this, Device, &Info](CodeGenFunction &CGF,
8328 PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008329 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00008330
8331 llvm::Value *BasePointersArrayArg = nullptr;
8332 llvm::Value *PointersArrayArg = nullptr;
8333 llvm::Value *SizesArrayArg = nullptr;
8334 llvm::Value *MapTypesArrayArg = nullptr;
8335 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008336 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008337
8338 // Emit device ID if any.
8339 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008340 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008341 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008342 CGF.Int64Ty, /*isSigned=*/true);
8343 } else {
8344 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8345 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008346
8347 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008348 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00008349
8350 llvm::Value *OffloadingArgs[] = {
8351 DeviceID, PointerNum, BasePointersArrayArg,
8352 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008353 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_end),
Samuel Antaodf158d52016-04-27 22:58:19 +00008354 OffloadingArgs);
8355 };
8356
Samuel Antaocc10b852016-07-28 14:23:26 +00008357 // If we need device pointer privatization, we need to emit the body of the
8358 // region with no privatization in the 'else' branch of the conditional.
8359 // Otherwise, we don't have to do anything.
8360 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
8361 PrePostActionTy &) {
8362 if (!Info.CaptureDeviceAddrMap.empty()) {
8363 CodeGen.setAction(NoPrivAction);
8364 CodeGen(CGF);
8365 }
8366 };
8367
8368 // We don't have to do anything to close the region if the if clause evaluates
8369 // to false.
8370 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00008371
8372 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008373 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00008374 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00008375 RegionCodeGenTy RCG(BeginThenGen);
8376 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008377 }
8378
Samuel Antaocc10b852016-07-28 14:23:26 +00008379 // If we don't require privatization of device pointers, we emit the body in
8380 // between the runtime calls. This avoids duplicating the body code.
8381 if (Info.CaptureDeviceAddrMap.empty()) {
8382 CodeGen.setAction(NoPrivAction);
8383 CodeGen(CGF);
8384 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008385
8386 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008387 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00008388 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00008389 RegionCodeGenTy RCG(EndThenGen);
8390 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008391 }
8392}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008393
Samuel Antao8d2d7302016-05-26 18:30:22 +00008394void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00008395 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8396 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008397 if (!CGF.HaveInsertPoint())
8398 return;
8399
Samuel Antao8dd66282016-04-27 23:14:30 +00008400 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00008401 isa<OMPTargetExitDataDirective>(D) ||
8402 isa<OMPTargetUpdateDirective>(D)) &&
8403 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00008404
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008405 CodeGenFunction::OMPTargetDataInfo InputInfo;
8406 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008407 // Generate the code for the opening of the data environment.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008408 auto &&ThenGen = [this, &D, Device, &InputInfo,
8409 &MapTypesArray](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008410 // Emit device ID if any.
8411 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008412 if (Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008413 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008414 CGF.Int64Ty, /*isSigned=*/true);
8415 } else {
8416 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8417 }
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008418
8419 // Emit the number of elements in the offloading arrays.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008420 llvm::Constant *PointerNum =
8421 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008422
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008423 llvm::Value *OffloadingArgs[] = {DeviceID,
8424 PointerNum,
8425 InputInfo.BasePointersArray.getPointer(),
8426 InputInfo.PointersArray.getPointer(),
8427 InputInfo.SizesArray.getPointer(),
8428 MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00008429
Samuel Antao8d2d7302016-05-26 18:30:22 +00008430 // Select the right runtime function call for each expected standalone
8431 // directive.
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008432 const bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Samuel Antao8d2d7302016-05-26 18:30:22 +00008433 OpenMPRTLFunction RTLFn;
8434 switch (D.getDirectiveKind()) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00008435 case OMPD_target_enter_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008436 RTLFn = HasNowait ? OMPRTL__tgt_target_data_begin_nowait
8437 : OMPRTL__tgt_target_data_begin;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008438 break;
8439 case OMPD_target_exit_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008440 RTLFn = HasNowait ? OMPRTL__tgt_target_data_end_nowait
8441 : OMPRTL__tgt_target_data_end;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008442 break;
8443 case OMPD_target_update:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00008444 RTLFn = HasNowait ? OMPRTL__tgt_target_data_update_nowait
8445 : OMPRTL__tgt_target_data_update;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008446 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008447 case OMPD_parallel:
8448 case OMPD_for:
8449 case OMPD_parallel_for:
8450 case OMPD_parallel_sections:
8451 case OMPD_for_simd:
8452 case OMPD_parallel_for_simd:
8453 case OMPD_cancel:
8454 case OMPD_cancellation_point:
8455 case OMPD_ordered:
8456 case OMPD_threadprivate:
8457 case OMPD_task:
8458 case OMPD_simd:
8459 case OMPD_sections:
8460 case OMPD_section:
8461 case OMPD_single:
8462 case OMPD_master:
8463 case OMPD_critical:
8464 case OMPD_taskyield:
8465 case OMPD_barrier:
8466 case OMPD_taskwait:
8467 case OMPD_taskgroup:
8468 case OMPD_atomic:
8469 case OMPD_flush:
8470 case OMPD_teams:
8471 case OMPD_target_data:
8472 case OMPD_distribute:
8473 case OMPD_distribute_simd:
8474 case OMPD_distribute_parallel_for:
8475 case OMPD_distribute_parallel_for_simd:
8476 case OMPD_teams_distribute:
8477 case OMPD_teams_distribute_simd:
8478 case OMPD_teams_distribute_parallel_for:
8479 case OMPD_teams_distribute_parallel_for_simd:
8480 case OMPD_declare_simd:
8481 case OMPD_declare_target:
8482 case OMPD_end_declare_target:
8483 case OMPD_declare_reduction:
8484 case OMPD_taskloop:
8485 case OMPD_taskloop_simd:
8486 case OMPD_target:
8487 case OMPD_target_simd:
8488 case OMPD_target_teams_distribute:
8489 case OMPD_target_teams_distribute_simd:
8490 case OMPD_target_teams_distribute_parallel_for:
8491 case OMPD_target_teams_distribute_parallel_for_simd:
8492 case OMPD_target_teams:
8493 case OMPD_target_parallel:
8494 case OMPD_target_parallel_for:
8495 case OMPD_target_parallel_for_simd:
8496 case OMPD_unknown:
8497 llvm_unreachable("Unexpected standalone target data directive.");
8498 break;
Samuel Antao8d2d7302016-05-26 18:30:22 +00008499 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008500 CGF.EmitRuntimeCall(createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008501 };
8502
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008503 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray](
8504 CodeGenFunction &CGF, PrePostActionTy &) {
8505 // Fill up the arrays with all the mapped variables.
8506 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
8507 MappableExprsHandler::MapValuesArrayTy Pointers;
8508 MappableExprsHandler::MapValuesArrayTy Sizes;
8509 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008510
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008511 // Get map clause information.
8512 MappableExprsHandler MEHandler(D, CGF);
8513 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
8514
8515 TargetDataInfo Info;
8516 // Fill up the arrays and create the arguments.
8517 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
8518 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
8519 Info.PointersArray, Info.SizesArray,
8520 Info.MapTypesArray, Info);
8521 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
8522 InputInfo.BasePointersArray =
8523 Address(Info.BasePointersArray, CGM.getPointerAlign());
8524 InputInfo.PointersArray =
8525 Address(Info.PointersArray, CGM.getPointerAlign());
8526 InputInfo.SizesArray =
8527 Address(Info.SizesArray, CGM.getPointerAlign());
8528 MapTypesArray = Info.MapTypesArray;
8529 if (D.hasClausesOfKind<OMPDependClause>())
8530 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
8531 else
Alexey Bataev768f1f22018-01-09 19:59:25 +00008532 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008533 };
8534
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008535 if (IfCond) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008536 emitOMPIfClause(CGF, IfCond, TargetThenGen,
8537 [](CodeGenFunction &CGF, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008538 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008539 RegionCodeGenTy ThenRCG(TargetThenGen);
8540 ThenRCG(CGF);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00008541 }
8542}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008543
8544namespace {
8545 /// Kind of parameter in a function with 'declare simd' directive.
8546 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
8547 /// Attribute set of the parameter.
8548 struct ParamAttrTy {
8549 ParamKindTy Kind = Vector;
8550 llvm::APSInt StrideOrArg;
8551 llvm::APSInt Alignment;
8552 };
8553} // namespace
8554
8555static unsigned evaluateCDTSize(const FunctionDecl *FD,
8556 ArrayRef<ParamAttrTy> ParamAttrs) {
8557 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
8558 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
8559 // of that clause. The VLEN value must be power of 2.
8560 // In other case the notion of the function`s "characteristic data type" (CDT)
8561 // is used to compute the vector length.
8562 // CDT is defined in the following order:
8563 // a) For non-void function, the CDT is the return type.
8564 // b) If the function has any non-uniform, non-linear parameters, then the
8565 // CDT is the type of the first such parameter.
8566 // c) If the CDT determined by a) or b) above is struct, union, or class
8567 // type which is pass-by-value (except for the type that maps to the
8568 // built-in complex data type), the characteristic data type is int.
8569 // d) If none of the above three cases is applicable, the CDT is int.
8570 // The VLEN is then determined based on the CDT and the size of vector
8571 // register of that ISA for which current vector version is generated. The
8572 // VLEN is computed using the formula below:
8573 // VLEN = sizeof(vector_register) / sizeof(CDT),
8574 // where vector register size specified in section 3.2.1 Registers and the
8575 // Stack Frame of original AMD64 ABI document.
8576 QualType RetType = FD->getReturnType();
8577 if (RetType.isNull())
8578 return 0;
8579 ASTContext &C = FD->getASTContext();
8580 QualType CDT;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008581 if (!RetType.isNull() && !RetType->isVoidType()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008582 CDT = RetType;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008583 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008584 unsigned Offset = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008585 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008586 if (ParamAttrs[Offset].Kind == Vector)
8587 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
8588 ++Offset;
8589 }
8590 if (CDT.isNull()) {
8591 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
8592 if (ParamAttrs[I + Offset].Kind == Vector) {
8593 CDT = FD->getParamDecl(I)->getType();
8594 break;
8595 }
8596 }
8597 }
8598 }
8599 if (CDT.isNull())
8600 CDT = C.IntTy;
8601 CDT = CDT->getCanonicalTypeUnqualified();
8602 if (CDT->isRecordType() || CDT->isUnionType())
8603 CDT = C.IntTy;
8604 return C.getTypeSize(CDT);
8605}
8606
8607static void
8608emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00008609 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008610 ArrayRef<ParamAttrTy> ParamAttrs,
8611 OMPDeclareSimdDeclAttr::BranchStateTy State) {
8612 struct ISADataTy {
8613 char ISA;
8614 unsigned VecRegSize;
8615 };
8616 ISADataTy ISAData[] = {
8617 {
8618 'b', 128
8619 }, // SSE
8620 {
8621 'c', 256
8622 }, // AVX
8623 {
8624 'd', 256
8625 }, // AVX2
8626 {
8627 'e', 512
8628 }, // AVX512
8629 };
8630 llvm::SmallVector<char, 2> Masked;
8631 switch (State) {
8632 case OMPDeclareSimdDeclAttr::BS_Undefined:
8633 Masked.push_back('N');
8634 Masked.push_back('M');
8635 break;
8636 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
8637 Masked.push_back('N');
8638 break;
8639 case OMPDeclareSimdDeclAttr::BS_Inbranch:
8640 Masked.push_back('M');
8641 break;
8642 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008643 for (char Mask : Masked) {
8644 for (const ISADataTy &Data : ISAData) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008645 SmallString<256> Buffer;
8646 llvm::raw_svector_ostream Out(Buffer);
8647 Out << "_ZGV" << Data.ISA << Mask;
8648 if (!VLENVal) {
8649 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
8650 evaluateCDTSize(FD, ParamAttrs));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008651 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008652 Out << VLENVal;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008653 }
8654 for (const ParamAttrTy &ParamAttr : ParamAttrs) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008655 switch (ParamAttr.Kind){
8656 case LinearWithVarStride:
8657 Out << 's' << ParamAttr.StrideOrArg;
8658 break;
8659 case Linear:
8660 Out << 'l';
8661 if (!!ParamAttr.StrideOrArg)
8662 Out << ParamAttr.StrideOrArg;
8663 break;
8664 case Uniform:
8665 Out << 'u';
8666 break;
8667 case Vector:
8668 Out << 'v';
8669 break;
8670 }
8671 if (!!ParamAttr.Alignment)
8672 Out << 'a' << ParamAttr.Alignment;
8673 }
8674 Out << '_' << Fn->getName();
8675 Fn->addFnAttr(Out.str());
8676 }
8677 }
8678}
8679
8680void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
8681 llvm::Function *Fn) {
8682 ASTContext &C = CGM.getContext();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008683 FD = FD->getMostRecentDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008684 // Map params to their positions in function decl.
8685 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
8686 if (isa<CXXMethodDecl>(FD))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008687 ParamPositions.try_emplace(FD, 0);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008688 unsigned ParamPos = ParamPositions.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008689 for (const ParmVarDecl *P : FD->parameters()) {
8690 ParamPositions.try_emplace(P->getCanonicalDecl(), ParamPos);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008691 ++ParamPos;
8692 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008693 while (FD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008694 for (const auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008695 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
8696 // Mark uniform parameters.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008697 for (const Expr *E : Attr->uniforms()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008698 E = E->IgnoreParenImpCasts();
8699 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008700 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008701 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008702 } else {
8703 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
8704 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008705 Pos = ParamPositions[PVD];
8706 }
8707 ParamAttrs[Pos].Kind = Uniform;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008708 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008709 // Get alignment info.
8710 auto NI = Attr->alignments_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008711 for (const Expr *E : Attr->aligneds()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008712 E = E->IgnoreParenImpCasts();
8713 unsigned Pos;
8714 QualType ParmTy;
8715 if (isa<CXXThisExpr>(E)) {
8716 Pos = ParamPositions[FD];
8717 ParmTy = E->getType();
8718 } else {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008719 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
8720 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008721 Pos = ParamPositions[PVD];
8722 ParmTy = PVD->getType();
8723 }
8724 ParamAttrs[Pos].Alignment =
8725 (*NI)
8726 ? (*NI)->EvaluateKnownConstInt(C)
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008727 : llvm::APSInt::getUnsigned(
8728 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
8729 .getQuantity());
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008730 ++NI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008731 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008732 // Mark linear parameters.
8733 auto SI = Attr->steps_begin();
8734 auto MI = Attr->modifiers_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008735 for (const Expr *E : Attr->linears()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008736 E = E->IgnoreParenImpCasts();
8737 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008738 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008739 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008740 } else {
8741 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
8742 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008743 Pos = ParamPositions[PVD];
8744 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008745 ParamAttrTy &ParamAttr = ParamAttrs[Pos];
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008746 ParamAttr.Kind = Linear;
8747 if (*SI) {
8748 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
8749 Expr::SE_AllowSideEffects)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008750 if (const auto *DRE =
8751 cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
8752 if (const auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008753 ParamAttr.Kind = LinearWithVarStride;
8754 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
8755 ParamPositions[StridePVD->getCanonicalDecl()]);
8756 }
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008757 }
8758 }
8759 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008760 ++SI;
8761 ++MI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008762 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008763 llvm::APSInt VLENVal;
8764 if (const Expr *VLEN = Attr->getSimdlen())
8765 VLENVal = VLEN->EvaluateKnownConstInt(C);
8766 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
8767 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
8768 CGM.getTriple().getArch() == llvm::Triple::x86_64)
8769 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008770 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00008771 FD = FD->getPreviousDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00008772 }
8773}
Alexey Bataev8b427062016-05-25 12:36:08 +00008774
8775namespace {
8776/// Cleanup action for doacross support.
8777class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
8778public:
8779 static const int DoacrossFinArgs = 2;
8780
8781private:
8782 llvm::Value *RTLFn;
8783 llvm::Value *Args[DoacrossFinArgs];
8784
8785public:
8786 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
8787 : RTLFn(RTLFn) {
8788 assert(CallArgs.size() == DoacrossFinArgs);
8789 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
8790 }
8791 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
8792 if (!CGF.HaveInsertPoint())
8793 return;
8794 CGF.EmitRuntimeCall(RTLFn, Args);
8795 }
8796};
8797} // namespace
8798
8799void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
Alexey Bataevf138fda2018-08-13 19:04:24 +00008800 const OMPLoopDirective &D,
8801 ArrayRef<Expr *> NumIterations) {
Alexey Bataev8b427062016-05-25 12:36:08 +00008802 if (!CGF.HaveInsertPoint())
8803 return;
8804
8805 ASTContext &C = CGM.getContext();
8806 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
8807 RecordDecl *RD;
8808 if (KmpDimTy.isNull()) {
8809 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
8810 // kmp_int64 lo; // lower
8811 // kmp_int64 up; // upper
8812 // kmp_int64 st; // stride
8813 // };
8814 RD = C.buildImplicitRecord("kmp_dim");
8815 RD->startDefinition();
8816 addFieldToRecordDecl(C, RD, Int64Ty);
8817 addFieldToRecordDecl(C, RD, Int64Ty);
8818 addFieldToRecordDecl(C, RD, Int64Ty);
8819 RD->completeDefinition();
8820 KmpDimTy = C.getRecordType(RD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008821 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00008822 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008823 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00008824 llvm::APInt Size(/*numBits=*/32, NumIterations.size());
8825 QualType ArrayTy =
8826 C.getConstantArrayType(KmpDimTy, Size, ArrayType::Normal, 0);
Alexey Bataev8b427062016-05-25 12:36:08 +00008827
Alexey Bataevf138fda2018-08-13 19:04:24 +00008828 Address DimsAddr = CGF.CreateMemTemp(ArrayTy, "dims");
8829 CGF.EmitNullInitialization(DimsAddr, ArrayTy);
Alexey Bataev8b427062016-05-25 12:36:08 +00008830 enum { LowerFD = 0, UpperFD, StrideFD };
8831 // Fill dims with data.
Alexey Bataevf138fda2018-08-13 19:04:24 +00008832 for (unsigned I = 0, E = NumIterations.size(); I < E; ++I) {
8833 LValue DimsLVal =
8834 CGF.MakeAddrLValue(CGF.Builder.CreateConstArrayGEP(
8835 DimsAddr, I, C.getTypeSizeInChars(KmpDimTy)),
8836 KmpDimTy);
8837 // dims.upper = num_iterations;
8838 LValue UpperLVal = CGF.EmitLValueForField(
8839 DimsLVal, *std::next(RD->field_begin(), UpperFD));
8840 llvm::Value *NumIterVal =
8841 CGF.EmitScalarConversion(CGF.EmitScalarExpr(NumIterations[I]),
8842 D.getNumIterations()->getType(), Int64Ty,
8843 D.getNumIterations()->getExprLoc());
8844 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
8845 // dims.stride = 1;
8846 LValue StrideLVal = CGF.EmitLValueForField(
8847 DimsLVal, *std::next(RD->field_begin(), StrideFD));
8848 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
8849 StrideLVal);
8850 }
Alexey Bataev8b427062016-05-25 12:36:08 +00008851
8852 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
8853 // kmp_int32 num_dims, struct kmp_dim * dims);
Alexey Bataevf138fda2018-08-13 19:04:24 +00008854 llvm::Value *Args[] = {
8855 emitUpdateLocation(CGF, D.getBeginLoc()),
8856 getThreadID(CGF, D.getBeginLoc()),
8857 llvm::ConstantInt::getSigned(CGM.Int32Ty, NumIterations.size()),
8858 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
8859 CGF.Builder
8860 .CreateConstArrayGEP(DimsAddr, 0, C.getTypeSizeInChars(KmpDimTy))
8861 .getPointer(),
8862 CGM.VoidPtrTy)};
Alexey Bataev8b427062016-05-25 12:36:08 +00008863
8864 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
8865 CGF.EmitRuntimeCall(RTLFn, Args);
8866 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008867 emitUpdateLocation(CGF, D.getEndLoc()), getThreadID(CGF, D.getEndLoc())};
Alexey Bataev8b427062016-05-25 12:36:08 +00008868 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
8869 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
8870 llvm::makeArrayRef(FiniArgs));
8871}
8872
8873void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
8874 const OMPDependClause *C) {
8875 QualType Int64Ty =
8876 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
Alexey Bataevf138fda2018-08-13 19:04:24 +00008877 llvm::APInt Size(/*numBits=*/32, C->getNumLoops());
8878 QualType ArrayTy = CGM.getContext().getConstantArrayType(
8879 Int64Ty, Size, ArrayType::Normal, 0);
8880 Address CntAddr = CGF.CreateMemTemp(ArrayTy, ".cnt.addr");
8881 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I) {
8882 const Expr *CounterVal = C->getLoopData(I);
8883 assert(CounterVal);
8884 llvm::Value *CntVal = CGF.EmitScalarConversion(
8885 CGF.EmitScalarExpr(CounterVal), CounterVal->getType(), Int64Ty,
8886 CounterVal->getExprLoc());
8887 CGF.EmitStoreOfScalar(
8888 CntVal,
8889 CGF.Builder.CreateConstArrayGEP(
8890 CntAddr, I, CGM.getContext().getTypeSizeInChars(Int64Ty)),
8891 /*Volatile=*/false, Int64Ty);
8892 }
8893 llvm::Value *Args[] = {
8894 emitUpdateLocation(CGF, C->getBeginLoc()),
8895 getThreadID(CGF, C->getBeginLoc()),
8896 CGF.Builder
8897 .CreateConstArrayGEP(CntAddr, 0,
8898 CGM.getContext().getTypeSizeInChars(Int64Ty))
8899 .getPointer()};
Alexey Bataev8b427062016-05-25 12:36:08 +00008900 llvm::Value *RTLFn;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008901 if (C->getDependencyKind() == OMPC_DEPEND_source) {
Alexey Bataev8b427062016-05-25 12:36:08 +00008902 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008903 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00008904 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
8905 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
8906 }
8907 CGF.EmitRuntimeCall(RTLFn, Args);
8908}
8909
Alexey Bataev7ef47a62018-02-22 18:33:31 +00008910void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, SourceLocation Loc,
8911 llvm::Value *Callee,
8912 ArrayRef<llvm::Value *> Args) const {
8913 assert(Loc.isValid() && "Outlined function call location must be valid.");
Alexey Bataev3c595a62017-08-14 15:01:03 +00008914 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
8915
8916 if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008917 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00008918 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008919 return;
8920 }
8921 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00008922 CGF.EmitRuntimeCall(Callee, Args);
8923}
8924
8925void CGOpenMPRuntime::emitOutlinedFunctionCall(
8926 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
8927 ArrayRef<llvm::Value *> Args) const {
Alexey Bataev7ef47a62018-02-22 18:33:31 +00008928 emitCall(CGF, Loc, OutlinedFn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00008929}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00008930
8931Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
8932 const VarDecl *NativeParam,
8933 const VarDecl *TargetParam) const {
8934 return CGF.GetAddrOfLocalVar(NativeParam);
8935}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00008936
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00008937Address CGOpenMPRuntime::getAddressOfLocalVariable(CodeGenFunction &CGF,
8938 const VarDecl *VD) {
8939 return Address::invalid();
8940}
8941
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00008942llvm::Value *CGOpenMPSIMDRuntime::emitParallelOutlinedFunction(
8943 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8944 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
8945 llvm_unreachable("Not supported in SIMD-only mode");
8946}
8947
8948llvm::Value *CGOpenMPSIMDRuntime::emitTeamsOutlinedFunction(
8949 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8950 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
8951 llvm_unreachable("Not supported in SIMD-only mode");
8952}
8953
8954llvm::Value *CGOpenMPSIMDRuntime::emitTaskOutlinedFunction(
8955 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
8956 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
8957 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
8958 bool Tied, unsigned &NumberOfParts) {
8959 llvm_unreachable("Not supported in SIMD-only mode");
8960}
8961
8962void CGOpenMPSIMDRuntime::emitParallelCall(CodeGenFunction &CGF,
8963 SourceLocation Loc,
8964 llvm::Value *OutlinedFn,
8965 ArrayRef<llvm::Value *> CapturedVars,
8966 const Expr *IfCond) {
8967 llvm_unreachable("Not supported in SIMD-only mode");
8968}
8969
8970void CGOpenMPSIMDRuntime::emitCriticalRegion(
8971 CodeGenFunction &CGF, StringRef CriticalName,
8972 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
8973 const Expr *Hint) {
8974 llvm_unreachable("Not supported in SIMD-only mode");
8975}
8976
8977void CGOpenMPSIMDRuntime::emitMasterRegion(CodeGenFunction &CGF,
8978 const RegionCodeGenTy &MasterOpGen,
8979 SourceLocation Loc) {
8980 llvm_unreachable("Not supported in SIMD-only mode");
8981}
8982
8983void CGOpenMPSIMDRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
8984 SourceLocation Loc) {
8985 llvm_unreachable("Not supported in SIMD-only mode");
8986}
8987
8988void CGOpenMPSIMDRuntime::emitTaskgroupRegion(
8989 CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen,
8990 SourceLocation Loc) {
8991 llvm_unreachable("Not supported in SIMD-only mode");
8992}
8993
8994void CGOpenMPSIMDRuntime::emitSingleRegion(
8995 CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen,
8996 SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars,
8997 ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs,
8998 ArrayRef<const Expr *> AssignmentOps) {
8999 llvm_unreachable("Not supported in SIMD-only mode");
9000}
9001
9002void CGOpenMPSIMDRuntime::emitOrderedRegion(CodeGenFunction &CGF,
9003 const RegionCodeGenTy &OrderedOpGen,
9004 SourceLocation Loc,
9005 bool IsThreads) {
9006 llvm_unreachable("Not supported in SIMD-only mode");
9007}
9008
9009void CGOpenMPSIMDRuntime::emitBarrierCall(CodeGenFunction &CGF,
9010 SourceLocation Loc,
9011 OpenMPDirectiveKind Kind,
9012 bool EmitChecks,
9013 bool ForceSimpleCall) {
9014 llvm_unreachable("Not supported in SIMD-only mode");
9015}
9016
9017void CGOpenMPSIMDRuntime::emitForDispatchInit(
9018 CodeGenFunction &CGF, SourceLocation Loc,
9019 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
9020 bool Ordered, const DispatchRTInput &DispatchValues) {
9021 llvm_unreachable("Not supported in SIMD-only mode");
9022}
9023
9024void CGOpenMPSIMDRuntime::emitForStaticInit(
9025 CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind,
9026 const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values) {
9027 llvm_unreachable("Not supported in SIMD-only mode");
9028}
9029
9030void CGOpenMPSIMDRuntime::emitDistributeStaticInit(
9031 CodeGenFunction &CGF, SourceLocation Loc,
9032 OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values) {
9033 llvm_unreachable("Not supported in SIMD-only mode");
9034}
9035
9036void CGOpenMPSIMDRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
9037 SourceLocation Loc,
9038 unsigned IVSize,
9039 bool IVSigned) {
9040 llvm_unreachable("Not supported in SIMD-only mode");
9041}
9042
9043void CGOpenMPSIMDRuntime::emitForStaticFinish(CodeGenFunction &CGF,
9044 SourceLocation Loc,
9045 OpenMPDirectiveKind DKind) {
9046 llvm_unreachable("Not supported in SIMD-only mode");
9047}
9048
9049llvm::Value *CGOpenMPSIMDRuntime::emitForNext(CodeGenFunction &CGF,
9050 SourceLocation Loc,
9051 unsigned IVSize, bool IVSigned,
9052 Address IL, Address LB,
9053 Address UB, Address ST) {
9054 llvm_unreachable("Not supported in SIMD-only mode");
9055}
9056
9057void CGOpenMPSIMDRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
9058 llvm::Value *NumThreads,
9059 SourceLocation Loc) {
9060 llvm_unreachable("Not supported in SIMD-only mode");
9061}
9062
9063void CGOpenMPSIMDRuntime::emitProcBindClause(CodeGenFunction &CGF,
9064 OpenMPProcBindClauseKind ProcBind,
9065 SourceLocation Loc) {
9066 llvm_unreachable("Not supported in SIMD-only mode");
9067}
9068
9069Address CGOpenMPSIMDRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
9070 const VarDecl *VD,
9071 Address VDAddr,
9072 SourceLocation Loc) {
9073 llvm_unreachable("Not supported in SIMD-only mode");
9074}
9075
9076llvm::Function *CGOpenMPSIMDRuntime::emitThreadPrivateVarDefinition(
9077 const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit,
9078 CodeGenFunction *CGF) {
9079 llvm_unreachable("Not supported in SIMD-only mode");
9080}
9081
9082Address CGOpenMPSIMDRuntime::getAddrOfArtificialThreadPrivate(
9083 CodeGenFunction &CGF, QualType VarType, StringRef Name) {
9084 llvm_unreachable("Not supported in SIMD-only mode");
9085}
9086
9087void CGOpenMPSIMDRuntime::emitFlush(CodeGenFunction &CGF,
9088 ArrayRef<const Expr *> Vars,
9089 SourceLocation Loc) {
9090 llvm_unreachable("Not supported in SIMD-only mode");
9091}
9092
9093void CGOpenMPSIMDRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
9094 const OMPExecutableDirective &D,
9095 llvm::Value *TaskFunction,
9096 QualType SharedsTy, Address Shareds,
9097 const Expr *IfCond,
9098 const OMPTaskDataTy &Data) {
9099 llvm_unreachable("Not supported in SIMD-only mode");
9100}
9101
9102void CGOpenMPSIMDRuntime::emitTaskLoopCall(
9103 CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D,
9104 llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
9105 const Expr *IfCond, const OMPTaskDataTy &Data) {
9106 llvm_unreachable("Not supported in SIMD-only mode");
9107}
9108
9109void CGOpenMPSIMDRuntime::emitReduction(
9110 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
9111 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
9112 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
9113 assert(Options.SimpleReduction && "Only simple reduction is expected.");
9114 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
9115 ReductionOps, Options);
9116}
9117
9118llvm::Value *CGOpenMPSIMDRuntime::emitTaskReductionInit(
9119 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
9120 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
9121 llvm_unreachable("Not supported in SIMD-only mode");
9122}
9123
9124void CGOpenMPSIMDRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
9125 SourceLocation Loc,
9126 ReductionCodeGen &RCG,
9127 unsigned N) {
9128 llvm_unreachable("Not supported in SIMD-only mode");
9129}
9130
9131Address CGOpenMPSIMDRuntime::getTaskReductionItem(CodeGenFunction &CGF,
9132 SourceLocation Loc,
9133 llvm::Value *ReductionsPtr,
9134 LValue SharedLVal) {
9135 llvm_unreachable("Not supported in SIMD-only mode");
9136}
9137
9138void CGOpenMPSIMDRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
9139 SourceLocation Loc) {
9140 llvm_unreachable("Not supported in SIMD-only mode");
9141}
9142
9143void CGOpenMPSIMDRuntime::emitCancellationPointCall(
9144 CodeGenFunction &CGF, SourceLocation Loc,
9145 OpenMPDirectiveKind CancelRegion) {
9146 llvm_unreachable("Not supported in SIMD-only mode");
9147}
9148
9149void CGOpenMPSIMDRuntime::emitCancelCall(CodeGenFunction &CGF,
9150 SourceLocation Loc, const Expr *IfCond,
9151 OpenMPDirectiveKind CancelRegion) {
9152 llvm_unreachable("Not supported in SIMD-only mode");
9153}
9154
9155void CGOpenMPSIMDRuntime::emitTargetOutlinedFunction(
9156 const OMPExecutableDirective &D, StringRef ParentName,
9157 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
9158 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
9159 llvm_unreachable("Not supported in SIMD-only mode");
9160}
9161
9162void CGOpenMPSIMDRuntime::emitTargetCall(CodeGenFunction &CGF,
9163 const OMPExecutableDirective &D,
9164 llvm::Value *OutlinedFn,
9165 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00009166 const Expr *IfCond, const Expr *Device) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009167 llvm_unreachable("Not supported in SIMD-only mode");
9168}
9169
9170bool CGOpenMPSIMDRuntime::emitTargetFunctions(GlobalDecl GD) {
9171 llvm_unreachable("Not supported in SIMD-only mode");
9172}
9173
9174bool CGOpenMPSIMDRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
9175 llvm_unreachable("Not supported in SIMD-only mode");
9176}
9177
9178bool CGOpenMPSIMDRuntime::emitTargetGlobal(GlobalDecl GD) {
9179 return false;
9180}
9181
9182llvm::Function *CGOpenMPSIMDRuntime::emitRegistrationFunction() {
9183 return nullptr;
9184}
9185
9186void CGOpenMPSIMDRuntime::emitTeamsCall(CodeGenFunction &CGF,
9187 const OMPExecutableDirective &D,
9188 SourceLocation Loc,
9189 llvm::Value *OutlinedFn,
9190 ArrayRef<llvm::Value *> CapturedVars) {
9191 llvm_unreachable("Not supported in SIMD-only mode");
9192}
9193
9194void CGOpenMPSIMDRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
9195 const Expr *NumTeams,
9196 const Expr *ThreadLimit,
9197 SourceLocation Loc) {
9198 llvm_unreachable("Not supported in SIMD-only mode");
9199}
9200
9201void CGOpenMPSIMDRuntime::emitTargetDataCalls(
9202 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
9203 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
9204 llvm_unreachable("Not supported in SIMD-only mode");
9205}
9206
9207void CGOpenMPSIMDRuntime::emitTargetDataStandAloneCall(
9208 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
9209 const Expr *Device) {
9210 llvm_unreachable("Not supported in SIMD-only mode");
9211}
9212
9213void CGOpenMPSIMDRuntime::emitDoacrossInit(CodeGenFunction &CGF,
Alexey Bataevf138fda2018-08-13 19:04:24 +00009214 const OMPLoopDirective &D,
9215 ArrayRef<Expr *> NumIterations) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009216 llvm_unreachable("Not supported in SIMD-only mode");
9217}
9218
9219void CGOpenMPSIMDRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
9220 const OMPDependClause *C) {
9221 llvm_unreachable("Not supported in SIMD-only mode");
9222}
9223
9224const VarDecl *
9225CGOpenMPSIMDRuntime::translateParameter(const FieldDecl *FD,
9226 const VarDecl *NativeParam) const {
9227 llvm_unreachable("Not supported in SIMD-only mode");
9228}
9229
9230Address
9231CGOpenMPSIMDRuntime::getParameterAddress(CodeGenFunction &CGF,
9232 const VarDecl *NativeParam,
9233 const VarDecl *TargetParam) const {
9234 llvm_unreachable("Not supported in SIMD-only mode");
9235}
9236