blob: 0beb134b66a72b93c9e3c9a4fa97b350540c3558 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===----- CGOpenMPRuntime.cpp - Interface to OpenMP Runtimes -------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Alexey Bataev9959db52014-05-06 10:08:46 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This provides a class for OpenMP runtime code generation.
10//
11//===----------------------------------------------------------------------===//
12
Samuel Antaoee8fb302016-01-06 13:42:12 +000013#include "CGCXXABI.h"
14#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000015#include "CGOpenMPRuntime.h"
Alexey Bataeva4fa0b82018-04-16 17:59:34 +000016#include "CGRecordLayout.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000017#include "CodeGenFunction.h"
John McCall5ad74072017-03-02 20:04:19 +000018#include "clang/CodeGen/ConstantInitBuilder.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000019#include "clang/AST/Decl.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000020#include "clang/AST/StmtOpenMP.h"
Richard Smithbf5bcf22018-06-26 23:20:26 +000021#include "clang/Basic/BitmaskEnum.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000022#include "llvm/ADT/ArrayRef.h"
Teresa Johnsonffc4e242016-11-11 05:35:12 +000023#include "llvm/Bitcode/BitcodeReader.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000024#include "llvm/IR/DerivedTypes.h"
25#include "llvm/IR/GlobalValue.h"
26#include "llvm/IR/Value.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000027#include "llvm/Support/Format.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000028#include "llvm/Support/raw_ostream.h"
Alexey Bataev23b69422014-06-18 07:08:49 +000029#include <cassert>
Alexey Bataev9959db52014-05-06 10:08:46 +000030
31using namespace clang;
32using namespace CodeGen;
33
Benjamin Kramerc52193f2014-10-10 13:57:57 +000034namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000035/// Base class for handling code generation inside OpenMP regions.
Alexey Bataev18095712014-10-10 12:19:54 +000036class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
37public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000038 /// Kinds of OpenMP regions used in codegen.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000039 enum CGOpenMPRegionKind {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000040 /// Region with outlined function for standalone 'parallel'
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000041 /// directive.
42 ParallelOutlinedRegion,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000043 /// Region with outlined function for standalone 'task' directive.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000044 TaskOutlinedRegion,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000045 /// Region for constructs that do not require function outlining,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000046 /// like 'for', 'sections', 'atomic' etc. directives.
47 InlinedRegion,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000048 /// Region with outlined function for standalone 'target' directive.
Samuel Antaobed3c462015-10-02 16:14:20 +000049 TargetRegion,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000050 };
Alexey Bataev18095712014-10-10 12:19:54 +000051
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000052 CGOpenMPRegionInfo(const CapturedStmt &CS,
53 const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000054 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
55 bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000056 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
Alexey Bataev25e5b442015-09-15 12:52:43 +000057 CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000058
59 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000060 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
61 bool HasCancel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +000062 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
Alexey Bataev25e5b442015-09-15 12:52:43 +000063 Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000064
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000065 /// Get a variable or parameter for storing global thread id
Alexey Bataev18095712014-10-10 12:19:54 +000066 /// inside OpenMP construct.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000067 virtual const VarDecl *getThreadIDVariable() const = 0;
Alexey Bataev18095712014-10-10 12:19:54 +000068
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000069 /// Emit the captured statement body.
Hans Wennborg7eb54642015-09-10 17:07:54 +000070 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000071
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000072 /// Get an LValue for the current ThreadID variable.
Alexey Bataev62b63b12015-03-10 07:28:44 +000073 /// \return LValue for thread id variable. This LValue always has type int32*.
74 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
Alexey Bataev18095712014-10-10 12:19:54 +000075
Alexey Bataev48591dd2016-04-20 04:01:36 +000076 virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {}
77
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000078 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000079
Alexey Bataev81c7ea02015-07-03 09:56:58 +000080 OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
81
Alexey Bataev25e5b442015-09-15 12:52:43 +000082 bool hasCancel() const { return HasCancel; }
83
Alexey Bataev18095712014-10-10 12:19:54 +000084 static bool classof(const CGCapturedStmtInfo *Info) {
85 return Info->getKind() == CR_OpenMP;
86 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000087
Alexey Bataev48591dd2016-04-20 04:01:36 +000088 ~CGOpenMPRegionInfo() override = default;
89
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000090protected:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000091 CGOpenMPRegionKind RegionKind;
Hans Wennborg45c74392016-01-12 20:54:36 +000092 RegionCodeGenTy CodeGen;
Alexey Bataev81c7ea02015-07-03 09:56:58 +000093 OpenMPDirectiveKind Kind;
Alexey Bataev25e5b442015-09-15 12:52:43 +000094 bool HasCancel;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000095};
Alexey Bataev18095712014-10-10 12:19:54 +000096
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000097/// API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +000098class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000099public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000100 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000101 const RegionCodeGenTy &CodeGen,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000102 OpenMPDirectiveKind Kind, bool HasCancel,
103 StringRef HelperName)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000104 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
105 HasCancel),
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000106 ThreadIDVar(ThreadIDVar), HelperName(HelperName) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000107 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
108 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000109
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000110 /// Get a variable or parameter for storing global thread id
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000111 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000112 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000113
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000114 /// Get the name of the capture helper.
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000115 StringRef getHelperName() const override { return HelperName; }
Alexey Bataev18095712014-10-10 12:19:54 +0000116
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000117 static bool classof(const CGCapturedStmtInfo *Info) {
118 return CGOpenMPRegionInfo::classof(Info) &&
119 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
120 ParallelOutlinedRegion;
121 }
122
Alexey Bataev18095712014-10-10 12:19:54 +0000123private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000124 /// A variable or parameter storing global thread id for OpenMP
Alexey Bataev18095712014-10-10 12:19:54 +0000125 /// constructs.
126 const VarDecl *ThreadIDVar;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000127 StringRef HelperName;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000128};
129
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000130/// API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000131class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000132public:
Alexey Bataev48591dd2016-04-20 04:01:36 +0000133 class UntiedTaskActionTy final : public PrePostActionTy {
134 bool Untied;
135 const VarDecl *PartIDVar;
136 const RegionCodeGenTy UntiedCodeGen;
137 llvm::SwitchInst *UntiedSwitch = nullptr;
138
139 public:
140 UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
141 const RegionCodeGenTy &UntiedCodeGen)
142 : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
143 void Enter(CodeGenFunction &CGF) override {
144 if (Untied) {
145 // Emit task switching point.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000146 LValue PartIdLVal = CGF.EmitLoadOfPointerLValue(
Alexey Bataev48591dd2016-04-20 04:01:36 +0000147 CGF.GetAddrOfLocalVar(PartIDVar),
148 PartIDVar->getType()->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000149 llvm::Value *Res =
150 CGF.EmitLoadOfScalar(PartIdLVal, PartIDVar->getLocation());
151 llvm::BasicBlock *DoneBB = CGF.createBasicBlock(".untied.done.");
Alexey Bataev48591dd2016-04-20 04:01:36 +0000152 UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
153 CGF.EmitBlock(DoneBB);
154 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
155 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
156 UntiedSwitch->addCase(CGF.Builder.getInt32(0),
157 CGF.Builder.GetInsertBlock());
158 emitUntiedSwitch(CGF);
159 }
160 }
161 void emitUntiedSwitch(CodeGenFunction &CGF) const {
162 if (Untied) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000163 LValue PartIdLVal = CGF.EmitLoadOfPointerLValue(
Alexey Bataev48591dd2016-04-20 04:01:36 +0000164 CGF.GetAddrOfLocalVar(PartIDVar),
165 PartIDVar->getType()->castAs<PointerType>());
166 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
167 PartIdLVal);
168 UntiedCodeGen(CGF);
169 CodeGenFunction::JumpDest CurPoint =
170 CGF.getJumpDestInCurrentScope(".untied.next.");
171 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
172 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
173 UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
174 CGF.Builder.GetInsertBlock());
175 CGF.EmitBranchThroughCleanup(CurPoint);
176 CGF.EmitBlock(CurPoint.getBlock());
177 }
178 }
179 unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
180 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000181 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000182 const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000183 const RegionCodeGenTy &CodeGen,
Alexey Bataev48591dd2016-04-20 04:01:36 +0000184 OpenMPDirectiveKind Kind, bool HasCancel,
185 const UntiedTaskActionTy &Action)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000186 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
Alexey Bataev48591dd2016-04-20 04:01:36 +0000187 ThreadIDVar(ThreadIDVar), Action(Action) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000188 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
189 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000190
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000191 /// Get a variable or parameter for storing global thread id
Alexey Bataev62b63b12015-03-10 07:28:44 +0000192 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000193 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000194
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000195 /// Get an LValue for the current ThreadID variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000196 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000197
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000198 /// Get the name of the capture helper.
Alexey Bataev62b63b12015-03-10 07:28:44 +0000199 StringRef getHelperName() const override { return ".omp_outlined."; }
200
Alexey Bataev48591dd2016-04-20 04:01:36 +0000201 void emitUntiedSwitch(CodeGenFunction &CGF) override {
202 Action.emitUntiedSwitch(CGF);
203 }
204
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000205 static bool classof(const CGCapturedStmtInfo *Info) {
206 return CGOpenMPRegionInfo::classof(Info) &&
207 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
208 TaskOutlinedRegion;
209 }
210
Alexey Bataev62b63b12015-03-10 07:28:44 +0000211private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000212 /// A variable or parameter storing global thread id for OpenMP
Alexey Bataev62b63b12015-03-10 07:28:44 +0000213 /// constructs.
214 const VarDecl *ThreadIDVar;
Alexey Bataev48591dd2016-04-20 04:01:36 +0000215 /// Action for emitting code for untied tasks.
216 const UntiedTaskActionTy &Action;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000217};
218
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000219/// API for inlined captured statement code generation in OpenMP
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000220/// constructs.
221class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
222public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000223 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000224 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000225 OpenMPDirectiveKind Kind, bool HasCancel)
226 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
227 OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000228 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000229
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000230 // Retrieve the value of the context parameter.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000231 llvm::Value *getContextValue() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000232 if (OuterRegionInfo)
233 return OuterRegionInfo->getContextValue();
234 llvm_unreachable("No context value for inlined OpenMP region");
235 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000236
Hans Wennborg7eb54642015-09-10 17:07:54 +0000237 void setContextValue(llvm::Value *V) override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000238 if (OuterRegionInfo) {
239 OuterRegionInfo->setContextValue(V);
240 return;
241 }
242 llvm_unreachable("No context value for inlined OpenMP region");
243 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000244
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000245 /// Lookup the captured field decl for a variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000246 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000247 if (OuterRegionInfo)
248 return OuterRegionInfo->lookup(VD);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000249 // If there is no outer outlined region,no need to lookup in a list of
250 // captured variables, we can use the original one.
251 return nullptr;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000252 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000253
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000254 FieldDecl *getThisFieldDecl() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000255 if (OuterRegionInfo)
256 return OuterRegionInfo->getThisFieldDecl();
257 return nullptr;
258 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000259
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000260 /// Get a variable or parameter for storing global thread id
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000261 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000262 const VarDecl *getThreadIDVariable() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000263 if (OuterRegionInfo)
264 return OuterRegionInfo->getThreadIDVariable();
265 return nullptr;
266 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000267
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000268 /// Get an LValue for the current ThreadID variable.
Alexey Bataev311a9282017-10-12 13:51:32 +0000269 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override {
270 if (OuterRegionInfo)
271 return OuterRegionInfo->getThreadIDVariableLValue(CGF);
272 llvm_unreachable("No LValue for inlined OpenMP construct");
273 }
274
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000275 /// Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000276 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000277 if (auto *OuterRegionInfo = getOldCSI())
278 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000279 llvm_unreachable("No helper name for inlined OpenMP construct");
280 }
281
Alexey Bataev48591dd2016-04-20 04:01:36 +0000282 void emitUntiedSwitch(CodeGenFunction &CGF) override {
283 if (OuterRegionInfo)
284 OuterRegionInfo->emitUntiedSwitch(CGF);
285 }
286
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000287 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
288
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000289 static bool classof(const CGCapturedStmtInfo *Info) {
290 return CGOpenMPRegionInfo::classof(Info) &&
291 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
292 }
293
Alexey Bataev48591dd2016-04-20 04:01:36 +0000294 ~CGOpenMPInlinedRegionInfo() override = default;
295
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000296private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000297 /// CodeGen info about outer OpenMP region.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000298 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
299 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000300};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000301
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000302/// API for captured statement code generation in OpenMP target
Samuel Antaobed3c462015-10-02 16:14:20 +0000303/// constructs. For this captures, implicit parameters are used instead of the
Samuel Antaoee8fb302016-01-06 13:42:12 +0000304/// captured fields. The name of the target region has to be unique in a given
305/// application so it is provided by the client, because only the client has
306/// the information to generate that.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000307class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
Samuel Antaobed3c462015-10-02 16:14:20 +0000308public:
309 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000310 const RegionCodeGenTy &CodeGen, StringRef HelperName)
Samuel Antaobed3c462015-10-02 16:14:20 +0000311 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000312 /*HasCancel=*/false),
313 HelperName(HelperName) {}
Samuel Antaobed3c462015-10-02 16:14:20 +0000314
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000315 /// This is unused for target regions because each starts executing
Samuel Antaobed3c462015-10-02 16:14:20 +0000316 /// with a single thread.
317 const VarDecl *getThreadIDVariable() const override { return nullptr; }
318
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000319 /// Get the name of the capture helper.
Samuel Antaoee8fb302016-01-06 13:42:12 +0000320 StringRef getHelperName() const override { return HelperName; }
Samuel Antaobed3c462015-10-02 16:14:20 +0000321
322 static bool classof(const CGCapturedStmtInfo *Info) {
323 return CGOpenMPRegionInfo::classof(Info) &&
324 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
325 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000326
327private:
328 StringRef HelperName;
Samuel Antaobed3c462015-10-02 16:14:20 +0000329};
330
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000331static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000332 llvm_unreachable("No codegen for expressions");
333}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000334/// API for generation of expressions captured in a innermost OpenMP
Samuel Antaob68e2db2016-03-03 16:20:23 +0000335/// region.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000336class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000337public:
338 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
339 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
340 OMPD_unknown,
341 /*HasCancel=*/false),
342 PrivScope(CGF) {
343 // Make sure the globals captured in the provided statement are local by
344 // using the privatization logic. We assume the same variable is not
345 // captured more than once.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000346 for (const auto &C : CS.captures()) {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000347 if (!C.capturesVariable() && !C.capturesVariableByCopy())
348 continue;
349
350 const VarDecl *VD = C.getCapturedVar();
351 if (VD->isLocalVarDeclOrParm())
352 continue;
353
Bruno Ricci5fc4db72018-12-21 14:10:18 +0000354 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(VD),
Samuel Antaob68e2db2016-03-03 16:20:23 +0000355 /*RefersToEnclosingVariableOrCapture=*/false,
356 VD->getType().getNonReferenceType(), VK_LValue,
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000357 C.getLocation());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000358 PrivScope.addPrivate(
359 VD, [&CGF, &DRE]() { return CGF.EmitLValue(&DRE).getAddress(); });
Samuel Antaob68e2db2016-03-03 16:20:23 +0000360 }
361 (void)PrivScope.Privatize();
362 }
363
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000364 /// Lookup the captured field decl for a variable.
Samuel Antaob68e2db2016-03-03 16:20:23 +0000365 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000366 if (const FieldDecl *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
Samuel Antaob68e2db2016-03-03 16:20:23 +0000367 return FD;
368 return nullptr;
369 }
370
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000371 /// Emit the captured statement body.
Samuel Antaob68e2db2016-03-03 16:20:23 +0000372 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
373 llvm_unreachable("No body for expressions");
374 }
375
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000376 /// Get a variable or parameter for storing global thread id
Samuel Antaob68e2db2016-03-03 16:20:23 +0000377 /// inside OpenMP construct.
378 const VarDecl *getThreadIDVariable() const override {
379 llvm_unreachable("No thread id for expressions");
380 }
381
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000382 /// Get the name of the capture helper.
Samuel Antaob68e2db2016-03-03 16:20:23 +0000383 StringRef getHelperName() const override {
384 llvm_unreachable("No helper name for expressions");
385 }
386
387 static bool classof(const CGCapturedStmtInfo *Info) { return false; }
388
389private:
390 /// Private scope to capture global variables.
391 CodeGenFunction::OMPPrivateScope PrivScope;
392};
393
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000394/// RAII for emitting code of OpenMP constructs.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000395class InlinedOpenMPRegionRAII {
396 CodeGenFunction &CGF;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000397 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
398 FieldDecl *LambdaThisCaptureField = nullptr;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000399 const CodeGen::CGBlockInfo *BlockInfo = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000400
401public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000402 /// Constructs region for combined constructs.
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000403 /// \param CodeGen Code generation sequence for combined directives. Includes
404 /// a list of functions used for code generation of implicitly inlined
405 /// regions.
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000406 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000407 OpenMPDirectiveKind Kind, bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000408 : CGF(CGF) {
409 // Start emission for the construct.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000410 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
411 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000412 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
413 LambdaThisCaptureField = CGF.LambdaThisCaptureField;
414 CGF.LambdaThisCaptureField = nullptr;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000415 BlockInfo = CGF.BlockInfo;
416 CGF.BlockInfo = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000417 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000418
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000419 ~InlinedOpenMPRegionRAII() {
420 // Restore original CapturedStmtInfo only if we're done with code emission.
421 auto *OldCSI =
422 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
423 delete CGF.CapturedStmtInfo;
424 CGF.CapturedStmtInfo = OldCSI;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000425 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
426 CGF.LambdaThisCaptureField = LambdaThisCaptureField;
Alexey Bataeva8a9153a2017-12-29 18:07:07 +0000427 CGF.BlockInfo = BlockInfo;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000428 }
429};
430
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000431/// Values for bit flags used in the ident_t to describe the fields.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000432/// All enumeric elements are named and described in accordance with the code
James Y Knight5d71fc52019-01-29 16:37:27 +0000433/// from https://github.com/llvm/llvm-project/blob/master/openmp/runtime/src/kmp.h
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000434enum OpenMPLocationFlags : unsigned {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000435 /// Use trampoline for internal microtask.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000436 OMP_IDENT_IMD = 0x01,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000437 /// Use c-style ident structure.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000438 OMP_IDENT_KMPC = 0x02,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000439 /// Atomic reduction option for kmpc_reduce.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000440 OMP_ATOMIC_REDUCE = 0x10,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000441 /// Explicit 'barrier' directive.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000442 OMP_IDENT_BARRIER_EXPL = 0x20,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000443 /// Implicit barrier in code.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000444 OMP_IDENT_BARRIER_IMPL = 0x40,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000445 /// Implicit barrier in 'for' directive.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000446 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000447 /// Implicit barrier in 'sections' directive.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000448 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000449 /// Implicit barrier in 'single' directive.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000450 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140,
451 /// Call of __kmp_for_static_init for static loop.
452 OMP_IDENT_WORK_LOOP = 0x200,
453 /// Call of __kmp_for_static_init for sections.
454 OMP_IDENT_WORK_SECTIONS = 0x400,
455 /// Call of __kmp_for_static_init for distribute.
456 OMP_IDENT_WORK_DISTRIBUTE = 0x800,
457 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_IDENT_WORK_DISTRIBUTE)
Alexey Bataev50b3c952016-02-19 10:38:26 +0000458};
459
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000460/// Describes ident structure that describes a source location.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000461/// All descriptions are taken from
James Y Knight5d71fc52019-01-29 16:37:27 +0000462/// https://github.com/llvm/llvm-project/blob/master/openmp/runtime/src/kmp.h
Alexey Bataev50b3c952016-02-19 10:38:26 +0000463/// Original structure:
464/// typedef struct ident {
465/// kmp_int32 reserved_1; /**< might be used in Fortran;
466/// see above */
467/// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
468/// KMP_IDENT_KMPC identifies this union
469/// member */
470/// kmp_int32 reserved_2; /**< not really used in Fortran any more;
471/// see above */
472///#if USE_ITT_BUILD
473/// /* but currently used for storing
474/// region-specific ITT */
475/// /* contextual information. */
476///#endif /* USE_ITT_BUILD */
477/// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
478/// C++ */
479/// char const *psource; /**< String describing the source location.
480/// The string is composed of semi-colon separated
481// fields which describe the source file,
482/// the function and a pair of line numbers that
483/// delimit the construct.
484/// */
485/// } ident_t;
486enum IdentFieldIndex {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000487 /// might be used in Fortran
Alexey Bataev50b3c952016-02-19 10:38:26 +0000488 IdentField_Reserved_1,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000489 /// OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000490 IdentField_Flags,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000491 /// Not really used in Fortran any more
Alexey Bataev50b3c952016-02-19 10:38:26 +0000492 IdentField_Reserved_2,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000493 /// Source[4] in Fortran, do not use for C++
Alexey Bataev50b3c952016-02-19 10:38:26 +0000494 IdentField_Reserved_3,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000495 /// String describing the source location. The string is composed of
Alexey Bataev50b3c952016-02-19 10:38:26 +0000496 /// semi-colon separated fields which describe the source file, the function
497 /// and a pair of line numbers that delimit the construct.
498 IdentField_PSource
499};
500
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000501/// Schedule types for 'omp for' loops (these enumerators are taken from
Alexey Bataev50b3c952016-02-19 10:38:26 +0000502/// the enum sched_type in kmp.h).
503enum OpenMPSchedType {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000504 /// Lower bound for default (unordered) versions.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000505 OMP_sch_lower = 32,
506 OMP_sch_static_chunked = 33,
507 OMP_sch_static = 34,
508 OMP_sch_dynamic_chunked = 35,
509 OMP_sch_guided_chunked = 36,
510 OMP_sch_runtime = 37,
511 OMP_sch_auto = 38,
Alexey Bataev6cff6242016-05-30 13:05:14 +0000512 /// static with chunk adjustment (e.g., simd)
Samuel Antao4c8035b2016-12-12 18:00:20 +0000513 OMP_sch_static_balanced_chunked = 45,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000514 /// Lower bound for 'ordered' versions.
Alexey Bataev50b3c952016-02-19 10:38:26 +0000515 OMP_ord_lower = 64,
516 OMP_ord_static_chunked = 65,
517 OMP_ord_static = 66,
518 OMP_ord_dynamic_chunked = 67,
519 OMP_ord_guided_chunked = 68,
520 OMP_ord_runtime = 69,
521 OMP_ord_auto = 70,
522 OMP_sch_default = OMP_sch_static,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000523 /// dist_schedule types
Carlo Bertollifc35ad22016-03-07 16:04:49 +0000524 OMP_dist_sch_static_chunked = 91,
525 OMP_dist_sch_static = 92,
Alexey Bataev9ebd7422016-05-10 09:57:36 +0000526 /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
527 /// Set if the monotonic schedule modifier was present.
528 OMP_sch_modifier_monotonic = (1 << 29),
529 /// Set if the nonmonotonic schedule modifier was present.
530 OMP_sch_modifier_nonmonotonic = (1 << 30),
Alexey Bataev50b3c952016-02-19 10:38:26 +0000531};
532
533enum OpenMPRTLFunction {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000534 /// Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000535 /// kmpc_micro microtask, ...);
536 OMPRTL__kmpc_fork_call,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000537 /// Call to void *__kmpc_threadprivate_cached(ident_t *loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000538 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
539 OMPRTL__kmpc_threadprivate_cached,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000540 /// Call to void __kmpc_threadprivate_register( ident_t *,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000541 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
542 OMPRTL__kmpc_threadprivate_register,
543 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
544 OMPRTL__kmpc_global_thread_num,
545 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
546 // kmp_critical_name *crit);
547 OMPRTL__kmpc_critical,
548 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
549 // global_tid, kmp_critical_name *crit, uintptr_t hint);
550 OMPRTL__kmpc_critical_with_hint,
551 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
552 // kmp_critical_name *crit);
553 OMPRTL__kmpc_end_critical,
554 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
555 // global_tid);
556 OMPRTL__kmpc_cancel_barrier,
557 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
558 OMPRTL__kmpc_barrier,
559 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
560 OMPRTL__kmpc_for_static_fini,
561 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
562 // global_tid);
563 OMPRTL__kmpc_serialized_parallel,
564 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
565 // global_tid);
566 OMPRTL__kmpc_end_serialized_parallel,
567 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
568 // kmp_int32 num_threads);
569 OMPRTL__kmpc_push_num_threads,
570 // Call to void __kmpc_flush(ident_t *loc);
571 OMPRTL__kmpc_flush,
572 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
573 OMPRTL__kmpc_master,
574 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
575 OMPRTL__kmpc_end_master,
576 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
577 // int end_part);
578 OMPRTL__kmpc_omp_taskyield,
579 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
580 OMPRTL__kmpc_single,
581 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
582 OMPRTL__kmpc_end_single,
583 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
584 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
585 // kmp_routine_entry_t *task_entry);
586 OMPRTL__kmpc_omp_task_alloc,
587 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
588 // new_task);
589 OMPRTL__kmpc_omp_task,
590 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
591 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
592 // kmp_int32 didit);
593 OMPRTL__kmpc_copyprivate,
594 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
595 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
596 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
597 OMPRTL__kmpc_reduce,
598 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
599 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
600 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
601 // *lck);
602 OMPRTL__kmpc_reduce_nowait,
603 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
604 // kmp_critical_name *lck);
605 OMPRTL__kmpc_end_reduce,
606 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
607 // kmp_critical_name *lck);
608 OMPRTL__kmpc_end_reduce_nowait,
609 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
610 // kmp_task_t * new_task);
611 OMPRTL__kmpc_omp_task_begin_if0,
612 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
613 // kmp_task_t * new_task);
614 OMPRTL__kmpc_omp_task_complete_if0,
615 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
616 OMPRTL__kmpc_ordered,
617 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
618 OMPRTL__kmpc_end_ordered,
619 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
620 // global_tid);
621 OMPRTL__kmpc_omp_taskwait,
622 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
623 OMPRTL__kmpc_taskgroup,
624 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
625 OMPRTL__kmpc_end_taskgroup,
626 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
627 // int proc_bind);
628 OMPRTL__kmpc_push_proc_bind,
629 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
630 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
631 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
632 OMPRTL__kmpc_omp_task_with_deps,
633 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
634 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
635 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
636 OMPRTL__kmpc_omp_wait_deps,
637 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
638 // global_tid, kmp_int32 cncl_kind);
639 OMPRTL__kmpc_cancellationpoint,
640 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
641 // kmp_int32 cncl_kind);
642 OMPRTL__kmpc_cancel,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000643 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
644 // kmp_int32 num_teams, kmp_int32 thread_limit);
645 OMPRTL__kmpc_push_num_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000646 // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
647 // microtask, ...);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000648 OMPRTL__kmpc_fork_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000649 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
650 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
651 // sched, kmp_uint64 grainsize, void *task_dup);
652 OMPRTL__kmpc_taskloop,
Alexey Bataev8b427062016-05-25 12:36:08 +0000653 // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
654 // num_dims, struct kmp_dim *dims);
655 OMPRTL__kmpc_doacross_init,
656 // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
657 OMPRTL__kmpc_doacross_fini,
658 // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
659 // *vec);
660 OMPRTL__kmpc_doacross_post,
661 // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
662 // *vec);
663 OMPRTL__kmpc_doacross_wait,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000664 // Call to void *__kmpc_task_reduction_init(int gtid, int num_data, void
665 // *data);
666 OMPRTL__kmpc_task_reduction_init,
667 // Call to void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
668 // *d);
669 OMPRTL__kmpc_task_reduction_get_th_data,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000670
671 //
672 // Offloading related calls
673 //
Alexey Bataev7bb33532019-01-07 21:30:43 +0000674 // Call to void __kmpc_push_target_tripcount(int64_t device_id, kmp_uint64
675 // size);
676 OMPRTL__kmpc_push_target_tripcount,
George Rokos63bc9d62017-11-21 18:25:12 +0000677 // Call to int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
678 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Alexey Bataev50b3c952016-02-19 10:38:26 +0000679 // *arg_types);
680 OMPRTL__tgt_target,
Alexey Bataeva9f77c62017-12-13 21:04:20 +0000681 // Call to int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
682 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
683 // *arg_types);
684 OMPRTL__tgt_target_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000685 // Call to int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
686 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
687 // *arg_types, int32_t num_teams, int32_t thread_limit);
Samuel Antaob68e2db2016-03-03 16:20:23 +0000688 OMPRTL__tgt_target_teams,
Alexey Bataeva9f77c62017-12-13 21:04:20 +0000689 // Call to int32_t __tgt_target_teams_nowait(int64_t device_id, void
690 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
691 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
692 OMPRTL__tgt_target_teams_nowait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000693 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
694 OMPRTL__tgt_register_lib,
695 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
696 OMPRTL__tgt_unregister_lib,
George Rokos63bc9d62017-11-21 18:25:12 +0000697 // Call to void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
698 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antaodf158d52016-04-27 22:58:19 +0000699 OMPRTL__tgt_target_data_begin,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000700 // Call to void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
701 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
702 // *arg_types);
703 OMPRTL__tgt_target_data_begin_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000704 // Call to void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
705 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antaodf158d52016-04-27 22:58:19 +0000706 OMPRTL__tgt_target_data_end,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000707 // Call to void __tgt_target_data_end_nowait(int64_t device_id, int32_t
708 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
709 // *arg_types);
710 OMPRTL__tgt_target_data_end_nowait,
George Rokos63bc9d62017-11-21 18:25:12 +0000711 // Call to void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
712 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
Samuel Antao8d2d7302016-05-26 18:30:22 +0000713 OMPRTL__tgt_target_data_update,
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +0000714 // Call to void __tgt_target_data_update_nowait(int64_t device_id, int32_t
715 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
716 // *arg_types);
717 OMPRTL__tgt_target_data_update_nowait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000718};
719
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000720/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
721/// region.
722class CleanupTy final : public EHScopeStack::Cleanup {
723 PrePostActionTy *Action;
724
725public:
726 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
727 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
728 if (!CGF.HaveInsertPoint())
729 return;
730 Action->Exit(CGF);
731 }
732};
733
Hans Wennborg7eb54642015-09-10 17:07:54 +0000734} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000735
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000736void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
737 CodeGenFunction::RunCleanupsScope Scope(CGF);
738 if (PrePostAction) {
739 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
740 Callback(CodeGen, CGF, *PrePostAction);
741 } else {
742 PrePostActionTy Action;
743 Callback(CodeGen, CGF, Action);
744 }
745}
746
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000747/// Check if the combiner is a call to UDR combiner and if it is so return the
748/// UDR decl used for reduction.
749static const OMPDeclareReductionDecl *
750getReductionInit(const Expr *ReductionOp) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000751 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
752 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
753 if (const auto *DRE =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000754 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000755 if (const auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000756 return DRD;
757 return nullptr;
758}
759
760static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
761 const OMPDeclareReductionDecl *DRD,
762 const Expr *InitOp,
763 Address Private, Address Original,
764 QualType Ty) {
765 if (DRD->getInitializer()) {
766 std::pair<llvm::Function *, llvm::Function *> Reduction =
767 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000768 const auto *CE = cast<CallExpr>(InitOp);
769 const auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000770 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
771 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000772 const auto *LHSDRE =
773 cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
774 const auto *RHSDRE =
775 cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000776 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
777 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000778 [=]() { return Private; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000779 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000780 [=]() { return Original; });
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000781 (void)PrivateScope.Privatize();
782 RValue Func = RValue::get(Reduction.second);
783 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
784 CGF.EmitIgnoredExpr(InitOp);
785 } else {
786 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
Alexey Bataev18fa2322018-05-02 14:20:50 +0000787 std::string Name = CGF.CGM.getOpenMPRuntime().getName({"init"});
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000788 auto *GV = new llvm::GlobalVariable(
789 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
Alexey Bataev18fa2322018-05-02 14:20:50 +0000790 llvm::GlobalValue::PrivateLinkage, Init, Name);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000791 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
792 RValue InitRVal;
793 switch (CGF.getEvaluationKind(Ty)) {
794 case TEK_Scalar:
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000795 InitRVal = CGF.EmitLoadOfLValue(LV, DRD->getLocation());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000796 break;
797 case TEK_Complex:
798 InitRVal =
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000799 RValue::getComplex(CGF.EmitLoadOfComplex(LV, DRD->getLocation()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000800 break;
801 case TEK_Aggregate:
802 InitRVal = RValue::getAggregate(LV.getAddress());
803 break;
804 }
Alexey Bataeva9b9cc02018-01-23 18:12:38 +0000805 OpaqueValueExpr OVE(DRD->getLocation(), Ty, VK_RValue);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000806 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
807 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
808 /*IsInitializer=*/false);
809 }
810}
811
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000812/// Emit initialization of arrays of complex types.
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000813/// \param DestAddr Address of the array.
814/// \param Type Type of array.
815/// \param Init Initial expression of array.
816/// \param SrcAddr Address of the original array.
817static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
Alexey Bataeva7b19152017-10-12 20:03:39 +0000818 QualType Type, bool EmitDeclareReductionInit,
819 const Expr *Init,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000820 const OMPDeclareReductionDecl *DRD,
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000821 Address SrcAddr = Address::invalid()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000822 // Perform element-by-element initialization.
823 QualType ElementTy;
824
825 // Drill down to the base element type on both arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000826 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
827 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000828 DestAddr =
829 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
830 if (DRD)
831 SrcAddr =
832 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
833
834 llvm::Value *SrcBegin = nullptr;
835 if (DRD)
836 SrcBegin = SrcAddr.getPointer();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000837 llvm::Value *DestBegin = DestAddr.getPointer();
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000838 // Cast from pointer to array type to pointer to single element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000839 llvm::Value *DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000840 // The basic structure here is a while-do loop.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000841 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
842 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
843 llvm::Value *IsEmpty =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000844 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
845 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
846
847 // Enter the loop body, making that address the current address.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000848 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000849 CGF.EmitBlock(BodyBB);
850
851 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
852
853 llvm::PHINode *SrcElementPHI = nullptr;
854 Address SrcElementCurrent = Address::invalid();
855 if (DRD) {
856 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
857 "omp.arraycpy.srcElementPast");
858 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
859 SrcElementCurrent =
860 Address(SrcElementPHI,
861 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
862 }
863 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
864 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
865 DestElementPHI->addIncoming(DestBegin, EntryBB);
866 Address DestElementCurrent =
867 Address(DestElementPHI,
868 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
869
870 // Emit copy.
871 {
872 CodeGenFunction::RunCleanupsScope InitScope(CGF);
Alexey Bataeva7b19152017-10-12 20:03:39 +0000873 if (EmitDeclareReductionInit) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000874 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
875 SrcElementCurrent, ElementTy);
876 } else
877 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
878 /*IsInitializer=*/false);
879 }
880
881 if (DRD) {
882 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000883 llvm::Value *SrcElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000884 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
885 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
886 }
887
888 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000889 llvm::Value *DestElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000890 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
891 // Check whether we've reached the end.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000892 llvm::Value *Done =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000893 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
894 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
895 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
896
897 // Done.
898 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
899}
900
901LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +0000902 return CGF.EmitOMPSharedLValue(E);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000903}
904
905LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
906 const Expr *E) {
907 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
908 return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
909 return LValue();
910}
911
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000912void ReductionCodeGen::emitAggregateInitialization(
913 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
914 const OMPDeclareReductionDecl *DRD) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000915 // Emit VarDecl with copy init for arrays.
916 // Get the address of the original variable captured in current
917 // captured region.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000918 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000919 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva7b19152017-10-12 20:03:39 +0000920 bool EmitDeclareReductionInit =
921 DRD && (DRD->getInitializer() || !PrivateVD->hasInit());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000922 EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
Alexey Bataeva7b19152017-10-12 20:03:39 +0000923 EmitDeclareReductionInit,
924 EmitDeclareReductionInit ? ClausesData[N].ReductionOp
925 : PrivateVD->getInit(),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000926 DRD, SharedLVal.getAddress());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000927}
928
929ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
930 ArrayRef<const Expr *> Privates,
931 ArrayRef<const Expr *> ReductionOps) {
932 ClausesData.reserve(Shareds.size());
933 SharedAddresses.reserve(Shareds.size());
934 Sizes.reserve(Shareds.size());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000935 BaseDecls.reserve(Shareds.size());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000936 auto IPriv = Privates.begin();
937 auto IRed = ReductionOps.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000938 for (const Expr *Ref : Shareds) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000939 ClausesData.emplace_back(Ref, *IPriv, *IRed);
940 std::advance(IPriv, 1);
941 std::advance(IRed, 1);
942 }
943}
944
945void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
946 assert(SharedAddresses.size() == N &&
947 "Number of generated lvalues must be exactly N.");
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000948 LValue First = emitSharedLValue(CGF, ClausesData[N].Ref);
949 LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Ref);
950 SharedAddresses.emplace_back(First, Second);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000951}
952
953void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000954 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000955 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
956 QualType PrivateType = PrivateVD->getType();
957 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000958 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000959 Sizes.emplace_back(
960 CGF.getTypeSize(
961 SharedAddresses[N].first.getType().getNonReferenceType()),
962 nullptr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000963 return;
964 }
965 llvm::Value *Size;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000966 llvm::Value *SizeInChars;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000967 auto *ElemType =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000968 cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
969 ->getElementType();
970 auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000971 if (AsArraySection) {
972 Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
973 SharedAddresses[N].first.getPointer());
974 Size = CGF.Builder.CreateNUWAdd(
975 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000976 SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000977 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000978 SizeInChars = CGF.getTypeSize(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000979 SharedAddresses[N].first.getType().getNonReferenceType());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000980 Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000981 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000982 Sizes.emplace_back(SizeInChars, Size);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000983 CodeGenFunction::OpaqueValueMapping OpaqueMap(
984 CGF,
985 cast<OpaqueValueExpr>(
986 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
987 RValue::get(Size));
988 CGF.EmitVariablyModifiedType(PrivateType);
989}
990
991void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
992 llvm::Value *Size) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +0000993 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000994 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
995 QualType PrivateType = PrivateVD->getType();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000996 if (!PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000997 assert(!Size && !Sizes[N].second &&
Jonas Hahnfeld4525c822017-10-23 19:01:35 +0000998 "Size should be nullptr for non-variably modified reduction "
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000999 "items.");
1000 return;
1001 }
1002 CodeGenFunction::OpaqueValueMapping OpaqueMap(
1003 CGF,
1004 cast<OpaqueValueExpr>(
1005 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
1006 RValue::get(Size));
1007 CGF.EmitVariablyModifiedType(PrivateType);
1008}
1009
1010void ReductionCodeGen::emitInitialization(
1011 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
1012 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
1013 assert(SharedAddresses.size() > N && "No variable was generated");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001014 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001015 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001016 const OMPDeclareReductionDecl *DRD =
1017 getReductionInit(ClausesData[N].ReductionOp);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001018 QualType PrivateType = PrivateVD->getType();
1019 PrivateAddr = CGF.Builder.CreateElementBitCast(
1020 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1021 QualType SharedType = SharedAddresses[N].first.getType();
1022 SharedLVal = CGF.MakeAddrLValue(
1023 CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
1024 CGF.ConvertTypeForMem(SharedType)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001025 SharedType, SharedAddresses[N].first.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001026 CGF.CGM.getTBAAInfoForSubobject(SharedAddresses[N].first, SharedType));
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00001027 if (CGF.getContext().getAsArrayType(PrivateVD->getType())) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001028 emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001029 } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
1030 emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
1031 PrivateAddr, SharedLVal.getAddress(),
1032 SharedLVal.getType());
1033 } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
1034 !CGF.isTrivialInitializer(PrivateVD->getInit())) {
1035 CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
1036 PrivateVD->getType().getQualifiers(),
1037 /*IsInitializer=*/false);
1038 }
1039}
1040
1041bool ReductionCodeGen::needCleanups(unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001042 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001043 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1044 QualType PrivateType = PrivateVD->getType();
1045 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1046 return DTorKind != QualType::DK_none;
1047}
1048
1049void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
1050 Address PrivateAddr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001051 const auto *PrivateVD =
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001052 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1053 QualType PrivateType = PrivateVD->getType();
1054 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1055 if (needCleanups(N)) {
1056 PrivateAddr = CGF.Builder.CreateElementBitCast(
1057 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1058 CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
1059 }
1060}
1061
1062static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1063 LValue BaseLV) {
1064 BaseTy = BaseTy.getNonReferenceType();
1065 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1066 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001067 if (const auto *PtrTy = BaseTy->getAs<PointerType>()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001068 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001069 } else {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00001070 LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(), BaseTy);
1071 BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001072 }
1073 BaseTy = BaseTy->getPointeeType();
1074 }
1075 return CGF.MakeAddrLValue(
1076 CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
1077 CGF.ConvertTypeForMem(ElTy)),
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00001078 BaseLV.getType(), BaseLV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00001079 CGF.CGM.getTBAAInfoForSubobject(BaseLV, BaseLV.getType()));
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001080}
1081
1082static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1083 llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
1084 llvm::Value *Addr) {
1085 Address Tmp = Address::invalid();
1086 Address TopTmp = Address::invalid();
1087 Address MostTopTmp = Address::invalid();
1088 BaseTy = BaseTy.getNonReferenceType();
1089 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1090 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1091 Tmp = CGF.CreateMemTemp(BaseTy);
1092 if (TopTmp.isValid())
1093 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
1094 else
1095 MostTopTmp = Tmp;
1096 TopTmp = Tmp;
1097 BaseTy = BaseTy->getPointeeType();
1098 }
1099 llvm::Type *Ty = BaseLVType;
1100 if (Tmp.isValid())
1101 Ty = Tmp.getElementType();
1102 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
1103 if (Tmp.isValid()) {
1104 CGF.Builder.CreateStore(Addr, Tmp);
1105 return MostTopTmp;
1106 }
1107 return Address(Addr, BaseLVAlignment);
1108}
1109
Alexey Bataev1c44e152018-03-06 18:59:43 +00001110static const VarDecl *getBaseDecl(const Expr *Ref, const DeclRefExpr *&DE) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001111 const VarDecl *OrigVD = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001112 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(Ref)) {
1113 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
1114 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001115 Base = TempOASE->getBase()->IgnoreParenImpCasts();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001116 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001117 Base = TempASE->getBase()->IgnoreParenImpCasts();
1118 DE = cast<DeclRefExpr>(Base);
1119 OrigVD = cast<VarDecl>(DE->getDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001120 } else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Ref)) {
1121 const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
1122 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001123 Base = TempASE->getBase()->IgnoreParenImpCasts();
1124 DE = cast<DeclRefExpr>(Base);
1125 OrigVD = cast<VarDecl>(DE->getDecl());
1126 }
Alexey Bataev1c44e152018-03-06 18:59:43 +00001127 return OrigVD;
1128}
1129
1130Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
1131 Address PrivateAddr) {
1132 const DeclRefExpr *DE;
1133 if (const VarDecl *OrigVD = ::getBaseDecl(ClausesData[N].Ref, DE)) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001134 BaseDecls.emplace_back(OrigVD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001135 LValue OriginalBaseLValue = CGF.EmitLValue(DE);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001136 LValue BaseLValue =
1137 loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1138 OriginalBaseLValue);
1139 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1140 BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001141 llvm::Value *PrivatePointer =
1142 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1143 PrivateAddr.getPointer(),
1144 SharedAddresses[N].first.getAddress().getType());
1145 llvm::Value *Ptr = CGF.Builder.CreateGEP(PrivatePointer, Adjustment);
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001146 return castToBase(CGF, OrigVD->getType(),
1147 SharedAddresses[N].first.getType(),
Jonas Hahnfeld273d2612017-12-06 19:15:28 +00001148 OriginalBaseLValue.getAddress().getType(),
Alexey Bataev5c40bec2017-07-13 13:36:14 +00001149 OriginalBaseLValue.getAlignment(), Ptr);
1150 }
1151 BaseDecls.emplace_back(
1152 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1153 return PrivateAddr;
1154}
1155
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001156bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001157 const OMPDeclareReductionDecl *DRD =
1158 getReductionInit(ClausesData[N].ReductionOp);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001159 return DRD && DRD->getInitializer();
1160}
1161
Alexey Bataev18095712014-10-10 12:19:54 +00001162LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00001163 return CGF.EmitLoadOfPointerLValue(
1164 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1165 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +00001166}
1167
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001168void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001169 if (!CGF.HaveInsertPoint())
1170 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001171 // 1.2.2 OpenMP Language Terminology
1172 // Structured block - An executable statement with a single entry at the
1173 // top and a single exit at the bottom.
1174 // The point of exit cannot be a branch out of the structured block.
1175 // longjmp() and throw() must not violate the entry/exit criteria.
1176 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001177 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001178 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001179}
1180
Alexey Bataev62b63b12015-03-10 07:28:44 +00001181LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1182 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001183 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1184 getThreadIDVariable()->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00001185 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001186}
1187
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001188static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
1189 QualType FieldTy) {
1190 auto *Field = FieldDecl::Create(
1191 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
1192 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
1193 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
1194 Field->setAccess(AS_public);
1195 DC->addDecl(Field);
1196 return Field;
1197}
1198
Alexey Bataev18fa2322018-05-02 14:20:50 +00001199CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM, StringRef FirstSeparator,
1200 StringRef Separator)
1201 : CGM(CGM), FirstSeparator(FirstSeparator), Separator(Separator),
1202 OffloadEntriesInfoManager(CGM) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001203 ASTContext &C = CGM.getContext();
1204 RecordDecl *RD = C.buildImplicitRecord("ident_t");
1205 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
1206 RD->startDefinition();
1207 // reserved_1
1208 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1209 // flags
1210 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1211 // reserved_2
1212 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1213 // reserved_3
1214 addFieldToRecordDecl(C, RD, KmpInt32Ty);
1215 // psource
1216 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
1217 RD->completeDefinition();
1218 IdentQTy = C.getRecordType(RD);
1219 IdentTy = CGM.getTypes().ConvertRecordDeclType(RD);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001220 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +00001221
1222 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +00001223}
1224
Alexey Bataev91797552015-03-18 04:13:55 +00001225void CGOpenMPRuntime::clear() {
1226 InternalVars.clear();
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00001227 // Clean non-target variable declarations possibly used only in debug info.
1228 for (const auto &Data : EmittedNonTargetVariables) {
1229 if (!Data.getValue().pointsToAliveValue())
1230 continue;
1231 auto *GV = dyn_cast<llvm::GlobalVariable>(Data.getValue());
1232 if (!GV)
1233 continue;
1234 if (!GV->isDeclaration() || GV->getNumUses() > 0)
1235 continue;
1236 GV->eraseFromParent();
1237 }
Alexey Bataev91797552015-03-18 04:13:55 +00001238}
1239
Alexey Bataev18fa2322018-05-02 14:20:50 +00001240std::string CGOpenMPRuntime::getName(ArrayRef<StringRef> Parts) const {
1241 SmallString<128> Buffer;
1242 llvm::raw_svector_ostream OS(Buffer);
1243 StringRef Sep = FirstSeparator;
1244 for (StringRef Part : Parts) {
1245 OS << Sep << Part;
1246 Sep = Separator;
1247 }
1248 return OS.str();
1249}
1250
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001251static llvm::Function *
1252emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1253 const Expr *CombinerInitializer, const VarDecl *In,
1254 const VarDecl *Out, bool IsCombiner) {
1255 // void .omp_combiner.(Ty *in, Ty *out);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001256 ASTContext &C = CGM.getContext();
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001257 QualType PtrTy = C.getPointerType(Ty).withRestrict();
1258 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001259 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001260 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001261 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001262 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001263 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001264 Args.push_back(&OmpInParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001265 const CGFunctionInfo &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001266 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001267 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00001268 std::string Name = CGM.getOpenMPRuntime().getName(
1269 {IsCombiner ? "omp_combiner" : "omp_initializer", ""});
1270 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
1271 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00001272 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001273 Fn->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001274 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001275 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001276 CodeGenFunction CGF(CGM);
1277 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1278 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
Alexey Bataev7cae94e2018-01-04 19:45:16 +00001279 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, In->getLocation(),
1280 Out->getLocation());
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001281 CodeGenFunction::OMPPrivateScope Scope(CGF);
1282 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001283 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001284 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1285 .getAddress();
1286 });
1287 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001288 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001289 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1290 .getAddress();
1291 });
1292 (void)Scope.Privatize();
Alexey Bataev070f43a2017-09-06 14:49:58 +00001293 if (!IsCombiner && Out->hasInit() &&
1294 !CGF.isTrivialInitializer(Out->getInit())) {
1295 CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
1296 Out->getType().getQualifiers(),
1297 /*IsInitializer=*/true);
1298 }
1299 if (CombinerInitializer)
1300 CGF.EmitIgnoredExpr(CombinerInitializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001301 Scope.ForceCleanup();
1302 CGF.FinishFunction();
1303 return Fn;
1304}
1305
1306void CGOpenMPRuntime::emitUserDefinedReduction(
1307 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1308 if (UDRMap.count(D) > 0)
1309 return;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001310 llvm::Function *Combiner = emitCombinerOrInitializer(
Alexey Bataeve6aa4692018-09-13 16:54:05 +00001311 CGM, D->getType(), D->getCombiner(),
1312 cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerIn())->getDecl()),
1313 cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerOut())->getDecl()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001314 /*IsCombiner=*/true);
1315 llvm::Function *Initializer = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001316 if (const Expr *Init = D->getInitializer()) {
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001317 Initializer = emitCombinerOrInitializer(
Alexey Bataev070f43a2017-09-06 14:49:58 +00001318 CGM, D->getType(),
1319 D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init
1320 : nullptr,
Alexey Bataeve6aa4692018-09-13 16:54:05 +00001321 cast<VarDecl>(cast<DeclRefExpr>(D->getInitOrig())->getDecl()),
1322 cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl()),
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001323 /*IsCombiner=*/false);
1324 }
Alexey Bataev43a919f2018-04-13 17:48:43 +00001325 UDRMap.try_emplace(D, Combiner, Initializer);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001326 if (CGF) {
1327 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1328 Decls.second.push_back(D);
1329 }
1330}
1331
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001332std::pair<llvm::Function *, llvm::Function *>
1333CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1334 auto I = UDRMap.find(D);
1335 if (I != UDRMap.end())
1336 return I->second;
1337 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1338 return UDRMap.lookup(D);
1339}
1340
James Y Knight9871db02019-02-05 16:42:33 +00001341static llvm::Function *emitParallelOrTeamsOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001342 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1343 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1344 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001345 assert(ThreadIDVar->getType()->isPointerType() &&
1346 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +00001347 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00001348 bool HasCancel = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001349 if (const auto *OPD = dyn_cast<OMPParallelDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001350 HasCancel = OPD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001351 else if (const auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001352 HasCancel = OPSD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001353 else if (const auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
Alexey Bataev25e5b442015-09-15 12:52:43 +00001354 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001355 else if (const auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D))
Alexey Bataev2139ed62017-11-16 18:20:21 +00001356 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001357 else if (const auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&D))
Alexey Bataev10a54312017-11-27 16:54:08 +00001358 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001359 else if (const auto *OPFD =
1360 dyn_cast<OMPTeamsDistributeParallelForDirective>(&D))
Alexey Bataev10a54312017-11-27 16:54:08 +00001361 HasCancel = OPFD->hasCancel();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001362 else if (const auto *OPFD =
Alexey Bataev10a54312017-11-27 16:54:08 +00001363 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D))
1364 HasCancel = OPFD->hasCancel();
Alexey Bataev25e5b442015-09-15 12:52:43 +00001365 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001366 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +00001367 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001368 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +00001369}
1370
James Y Knight9871db02019-02-05 16:42:33 +00001371llvm::Function *CGOpenMPRuntime::emitParallelOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001372 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1373 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1374 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1375 return emitParallelOrTeamsOutlinedFunction(
1376 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1377}
1378
James Y Knight9871db02019-02-05 16:42:33 +00001379llvm::Function *CGOpenMPRuntime::emitTeamsOutlinedFunction(
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001380 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1381 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1382 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1383 return emitParallelOrTeamsOutlinedFunction(
1384 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1385}
1386
James Y Knight9871db02019-02-05 16:42:33 +00001387llvm::Function *CGOpenMPRuntime::emitTaskOutlinedFunction(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001388 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +00001389 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1390 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1391 bool Tied, unsigned &NumberOfParts) {
1392 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1393 PrePostActionTy &) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001394 llvm::Value *ThreadID = getThreadID(CGF, D.getBeginLoc());
1395 llvm::Value *UpLoc = emitUpdateLocation(CGF, D.getBeginLoc());
Alexey Bataev48591dd2016-04-20 04:01:36 +00001396 llvm::Value *TaskArgs[] = {
1397 UpLoc, ThreadID,
1398 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1399 TaskTVar->getType()->castAs<PointerType>())
1400 .getPointer()};
1401 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1402 };
1403 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1404 UntiedCodeGen);
1405 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001406 assert(!ThreadIDVar->getType()->isPointerType() &&
1407 "thread id variable must be of type kmp_int32 for tasks");
Alexey Bataev475a7442018-01-12 19:39:11 +00001408 const OpenMPDirectiveKind Region =
1409 isOpenMPTaskLoopDirective(D.getDirectiveKind()) ? OMPD_taskloop
1410 : OMPD_task;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001411 const CapturedStmt *CS = D.getCapturedStmt(Region);
1412 const auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001413 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +00001414 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1415 InnermostKind,
1416 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +00001417 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
James Y Knight9871db02019-02-05 16:42:33 +00001418 llvm::Function *Res = CGF.GenerateCapturedStmtFunction(*CS);
Alexey Bataev48591dd2016-04-20 04:01:36 +00001419 if (!Tied)
1420 NumberOfParts = Action.getNumberOfParts();
1421 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001422}
1423
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001424static void buildStructValue(ConstantStructBuilder &Fields, CodeGenModule &CGM,
1425 const RecordDecl *RD, const CGRecordLayout &RL,
1426 ArrayRef<llvm::Constant *> Data) {
1427 llvm::StructType *StructTy = RL.getLLVMType();
1428 unsigned PrevIdx = 0;
1429 ConstantInitBuilder CIBuilder(CGM);
1430 auto DI = Data.begin();
1431 for (const FieldDecl *FD : RD->fields()) {
1432 unsigned Idx = RL.getLLVMFieldNo(FD);
1433 // Fill the alignment.
1434 for (unsigned I = PrevIdx; I < Idx; ++I)
1435 Fields.add(llvm::Constant::getNullValue(StructTy->getElementType(I)));
1436 PrevIdx = Idx + 1;
1437 Fields.add(*DI);
1438 ++DI;
1439 }
1440}
1441
1442template <class... As>
1443static llvm::GlobalVariable *
Mike Ricee1ca7b62018-08-29 15:45:11 +00001444createGlobalStruct(CodeGenModule &CGM, QualType Ty, bool IsConstant,
1445 ArrayRef<llvm::Constant *> Data, const Twine &Name,
1446 As &&... Args) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001447 const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1448 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1449 ConstantInitBuilder CIBuilder(CGM);
1450 ConstantStructBuilder Fields = CIBuilder.beginStruct(RL.getLLVMType());
1451 buildStructValue(Fields, CGM, RD, RL, Data);
1452 return Fields.finishAndCreateGlobal(
Mike Ricee1ca7b62018-08-29 15:45:11 +00001453 Name, CGM.getContext().getAlignOfGlobalVarInChars(Ty), IsConstant,
1454 std::forward<As>(Args)...);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001455}
1456
1457template <typename T>
Benjamin Kramer651d0bf2018-05-15 21:26:47 +00001458static void
1459createConstantGlobalStructAndAddToParent(CodeGenModule &CGM, QualType Ty,
1460 ArrayRef<llvm::Constant *> Data,
1461 T &Parent) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001462 const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1463 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1464 ConstantStructBuilder Fields = Parent.beginStruct(RL.getLLVMType());
1465 buildStructValue(Fields, CGM, RD, RL, Data);
1466 Fields.finishAndAddTo(Parent);
1467}
1468
Alexey Bataev50b3c952016-02-19 10:38:26 +00001469Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001470 CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
Alexey Bataevceeaa482018-11-21 21:04:34 +00001471 unsigned Reserved2Flags = getDefaultLocationReserved2Flags();
1472 FlagsTy FlagsKey(Flags, Reserved2Flags);
1473 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(FlagsKey);
Alexey Bataev9959db52014-05-06 10:08:46 +00001474 if (!Entry) {
1475 if (!DefaultOpenMPPSource) {
1476 // Initialize default location for psource field of ident_t structure of
1477 // all ident_t objects. Format is ";file;function;line;column;;".
1478 // Taken from
James Y Knight5d71fc52019-01-29 16:37:27 +00001479 // https://github.com/llvm/llvm-project/blob/master/openmp/runtime/src/kmp_str.cpp
Alexey Bataev9959db52014-05-06 10:08:46 +00001480 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +00001481 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001482 DefaultOpenMPPSource =
1483 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1484 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001485
Alexey Bataevceeaa482018-11-21 21:04:34 +00001486 llvm::Constant *Data[] = {
1487 llvm::ConstantInt::getNullValue(CGM.Int32Ty),
1488 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
1489 llvm::ConstantInt::get(CGM.Int32Ty, Reserved2Flags),
1490 llvm::ConstantInt::getNullValue(CGM.Int32Ty), DefaultOpenMPPSource};
Mike Ricee1ca7b62018-08-29 15:45:11 +00001491 llvm::GlobalValue *DefaultOpenMPLocation =
Alexey Bataevceeaa482018-11-21 21:04:34 +00001492 createGlobalStruct(CGM, IdentQTy, isDefaultLocationConstant(), Data, "",
Mike Ricee1ca7b62018-08-29 15:45:11 +00001493 llvm::GlobalValue::PrivateLinkage);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001494 DefaultOpenMPLocation->setUnnamedAddr(
1495 llvm::GlobalValue::UnnamedAddr::Global);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001496
Alexey Bataevceeaa482018-11-21 21:04:34 +00001497 OpenMPDefaultLocMap[FlagsKey] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +00001498 }
John McCall7f416cc2015-09-08 08:05:57 +00001499 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +00001500}
1501
Alexey Bataevfd006c42018-10-05 15:08:53 +00001502void CGOpenMPRuntime::setLocThreadIdInsertPt(CodeGenFunction &CGF,
1503 bool AtCurrentPoint) {
1504 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1505 assert(!Elem.second.ServiceInsertPt && "Insert point is set already.");
1506
1507 llvm::Value *Undef = llvm::UndefValue::get(CGF.Int32Ty);
1508 if (AtCurrentPoint) {
1509 Elem.second.ServiceInsertPt = new llvm::BitCastInst(
1510 Undef, CGF.Int32Ty, "svcpt", CGF.Builder.GetInsertBlock());
1511 } else {
1512 Elem.second.ServiceInsertPt =
1513 new llvm::BitCastInst(Undef, CGF.Int32Ty, "svcpt");
1514 Elem.second.ServiceInsertPt->insertAfter(CGF.AllocaInsertPt);
1515 }
1516}
1517
1518void CGOpenMPRuntime::clearLocThreadIdInsertPt(CodeGenFunction &CGF) {
1519 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1520 if (Elem.second.ServiceInsertPt) {
1521 llvm::Instruction *Ptr = Elem.second.ServiceInsertPt;
1522 Elem.second.ServiceInsertPt = nullptr;
1523 Ptr->eraseFromParent();
1524 }
1525}
1526
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001527llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1528 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001529 unsigned Flags) {
1530 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +00001531 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001532 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +00001533 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +00001534 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001535
1536 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1537
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001538 CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy);
John McCall7f416cc2015-09-08 08:05:57 +00001539 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001540 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1541 if (I != OpenMPLocThreadIDMap.end())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001542 LocValue = Address(I->second.DebugLoc, Align);
John McCall7f416cc2015-09-08 08:05:57 +00001543
Alexander Musmanc6388682014-12-15 07:07:06 +00001544 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1545 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +00001546 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +00001547 // Generate "ident_t .kmpc_loc.addr;"
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001548 Address AI = CGF.CreateMemTemp(IdentQTy, ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +00001549 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +00001550 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001551 LocValue = AI;
1552
Alexey Bataevfd006c42018-10-05 15:08:53 +00001553 if (!Elem.second.ServiceInsertPt)
1554 setLocThreadIdInsertPt(CGF);
Alexey Bataev9959db52014-05-06 10:08:46 +00001555 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001556 CGF.Builder.SetInsertPoint(Elem.second.ServiceInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001557 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001558 CGF.getTypeSize(IdentQTy));
Alexey Bataev9959db52014-05-06 10:08:46 +00001559 }
1560
1561 // char **psource = &.kmpc_loc_<flags>.addr.psource;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001562 LValue Base = CGF.MakeAddrLValue(LocValue, IdentQTy);
1563 auto Fields = cast<RecordDecl>(IdentQTy->getAsTagDecl())->field_begin();
1564 LValue PSource =
1565 CGF.EmitLValueForField(Base, *std::next(Fields, IdentField_PSource));
Alexey Bataev9959db52014-05-06 10:08:46 +00001566
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001567 llvm::Value *OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
Alexey Bataevf002aca2014-05-30 05:48:40 +00001568 if (OMPDebugLoc == nullptr) {
1569 SmallString<128> Buffer2;
1570 llvm::raw_svector_ostream OS2(Buffer2);
1571 // Build debug location
1572 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1573 OS2 << ";" << PLoc.getFilename() << ";";
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001574 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl))
Alexey Bataevf002aca2014-05-30 05:48:40 +00001575 OS2 << FD->getQualifiedNameAsString();
Alexey Bataevf002aca2014-05-30 05:48:40 +00001576 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1577 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1578 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +00001579 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001580 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001581 CGF.EmitStoreOfScalar(OMPDebugLoc, PSource);
Alexey Bataevf002aca2014-05-30 05:48:40 +00001582
John McCall7f416cc2015-09-08 08:05:57 +00001583 // Our callers always pass this to a runtime function, so for
1584 // convenience, go ahead and return a naked pointer.
1585 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001586}
1587
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001588llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1589 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001590 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1591
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001592 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001593 // Check whether we've already cached a load of the thread id in this
1594 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001595 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001596 if (I != OpenMPLocThreadIDMap.end()) {
1597 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001598 if (ThreadID != nullptr)
1599 return ThreadID;
1600 }
Alexey Bataevaee18552017-08-16 14:01:00 +00001601 // If exceptions are enabled, do not use parameter to avoid possible crash.
Alexey Bataev5d2c9a42017-11-02 18:55:05 +00001602 if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions ||
1603 !CGF.getLangOpts().CXXExceptions ||
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001604 CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
Alexey Bataevaee18552017-08-16 14:01:00 +00001605 if (auto *OMPRegionInfo =
1606 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1607 if (OMPRegionInfo->getThreadIDVariable()) {
1608 // Check if this an outlined function with thread id passed as argument.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001609 LValue LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev1e491372018-01-23 18:44:14 +00001610 ThreadID = CGF.EmitLoadOfScalar(LVal, Loc);
Alexey Bataevaee18552017-08-16 14:01:00 +00001611 // If value loaded in entry block, cache it and use it everywhere in
1612 // function.
1613 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1614 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1615 Elem.second.ThreadID = ThreadID;
1616 }
1617 return ThreadID;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001618 }
Alexey Bataevd6c57552014-07-25 07:55:17 +00001619 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001620 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001621
1622 // This is not an outlined function region - need to call __kmpc_int32
1623 // kmpc_global_thread_num(ident_t *loc).
1624 // Generate thread id value and cache this value for use across the
1625 // function.
Alexey Bataevfd006c42018-10-05 15:08:53 +00001626 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1627 if (!Elem.second.ServiceInsertPt)
1628 setLocThreadIdInsertPt(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001629 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001630 CGF.Builder.SetInsertPoint(Elem.second.ServiceInsertPt);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001631 llvm::CallInst *Call = CGF.Builder.CreateCall(
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001632 createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1633 emitUpdateLocation(CGF, Loc));
1634 Call->setCallingConv(CGF.getRuntimeCC());
Alexey Bataev0e1b4582017-11-02 14:25:34 +00001635 Elem.second.ThreadID = Call;
1636 return Call;
Alexey Bataev9959db52014-05-06 10:08:46 +00001637}
1638
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001639void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001640 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataevfd006c42018-10-05 15:08:53 +00001641 if (OpenMPLocThreadIDMap.count(CGF.CurFn)) {
1642 clearLocThreadIdInsertPt(CGF);
Alexey Bataev03b340a2014-10-21 03:16:40 +00001643 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevfd006c42018-10-05 15:08:53 +00001644 }
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001645 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001646 for(auto *D : FunctionUDRMap[CGF.CurFn])
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001647 UDRMap.erase(D);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001648 FunctionUDRMap.erase(CGF.CurFn);
1649 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001650}
1651
1652llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001653 return IdentTy->getPointerTo();
Alexey Bataev9959db52014-05-06 10:08:46 +00001654}
1655
1656llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001657 if (!Kmpc_MicroTy) {
1658 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1659 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1660 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1661 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1662 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001663 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1664}
1665
James Y Knight9871db02019-02-05 16:42:33 +00001666llvm::FunctionCallee CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
1667 llvm::FunctionCallee RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001668 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001669 case OMPRTL__kmpc_fork_call: {
1670 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1671 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001672 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1673 getKmpc_MicroPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001674 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001675 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001676 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
James Y Knight9871db02019-02-05 16:42:33 +00001677 if (auto *F = dyn_cast<llvm::Function>(RTLFn.getCallee())) {
Johannes Doerfertac991bb2019-01-19 05:36:54 +00001678 if (!F->hasMetadata(llvm::LLVMContext::MD_callback)) {
1679 llvm::LLVMContext &Ctx = F->getContext();
1680 llvm::MDBuilder MDB(Ctx);
1681 // Annotate the callback behavior of the __kmpc_fork_call:
1682 // - The callback callee is argument number 2 (microtask).
1683 // - The first two arguments of the callback callee are unknown (-1).
1684 // - All variadic arguments to the __kmpc_fork_call are passed to the
1685 // callback callee.
1686 F->addMetadata(
1687 llvm::LLVMContext::MD_callback,
1688 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
1689 2, {-1, -1},
1690 /* VarArgsArePassed */ true)}));
1691 }
1692 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001693 break;
1694 }
1695 case OMPRTL__kmpc_global_thread_num: {
1696 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001697 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001698 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001699 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001700 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1701 break;
1702 }
Alexey Bataev97720002014-11-11 04:05:39 +00001703 case OMPRTL__kmpc_threadprivate_cached: {
1704 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1705 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1706 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1707 CGM.VoidPtrTy, CGM.SizeTy,
1708 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001709 auto *FnTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001710 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1711 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1712 break;
1713 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001714 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001715 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1716 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001717 llvm::Type *TypeParams[] = {
1718 getIdentTyPointerTy(), CGM.Int32Ty,
1719 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001720 auto *FnTy =
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001721 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1722 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1723 break;
1724 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001725 case OMPRTL__kmpc_critical_with_hint: {
1726 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1727 // kmp_critical_name *crit, uintptr_t hint);
1728 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1729 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1730 CGM.IntPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001731 auto *FnTy =
Alexey Bataevfc57d162015-12-15 10:55:09 +00001732 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1733 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1734 break;
1735 }
Alexey Bataev97720002014-11-11 04:05:39 +00001736 case OMPRTL__kmpc_threadprivate_register: {
1737 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1738 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1739 // typedef void *(*kmpc_ctor)(void *);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001740 auto *KmpcCtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001741 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1742 /*isVarArg*/ false)->getPointerTo();
1743 // typedef void *(*kmpc_cctor)(void *, void *);
1744 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001745 auto *KmpcCopyCtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001746 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001747 /*isVarArg*/ false)
1748 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00001749 // typedef void (*kmpc_dtor)(void *);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001750 auto *KmpcDtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001751 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1752 ->getPointerTo();
1753 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1754 KmpcCopyCtorTy, KmpcDtorTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001755 auto *FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
Alexey Bataev97720002014-11-11 04:05:39 +00001756 /*isVarArg*/ false);
1757 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1758 break;
1759 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001760 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001761 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1762 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001763 llvm::Type *TypeParams[] = {
1764 getIdentTyPointerTy(), CGM.Int32Ty,
1765 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001766 auto *FnTy =
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001767 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1768 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1769 break;
1770 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001771 case OMPRTL__kmpc_cancel_barrier: {
1772 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1773 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001774 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001775 auto *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001776 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1777 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001778 break;
1779 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001780 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001781 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001782 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001783 auto *FnTy =
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001784 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1785 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1786 break;
1787 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001788 case OMPRTL__kmpc_for_static_fini: {
1789 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1790 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001791 auto *FnTy =
Alexander Musmanc6388682014-12-15 07:07:06 +00001792 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1793 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1794 break;
1795 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001796 case OMPRTL__kmpc_push_num_threads: {
1797 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1798 // kmp_int32 num_threads)
1799 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1800 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001801 auto *FnTy =
Alexey Bataevb2059782014-10-13 08:23:51 +00001802 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1803 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1804 break;
1805 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001806 case OMPRTL__kmpc_serialized_parallel: {
1807 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1808 // global_tid);
1809 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001810 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001811 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1812 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1813 break;
1814 }
1815 case OMPRTL__kmpc_end_serialized_parallel: {
1816 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1817 // global_tid);
1818 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001819 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001820 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1821 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1822 break;
1823 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001824 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001825 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001826 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001827 auto *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001828 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001829 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1830 break;
1831 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001832 case OMPRTL__kmpc_master: {
1833 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1834 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001835 auto *FnTy =
Alexey Bataev8d690652014-12-04 07:23:53 +00001836 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1837 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1838 break;
1839 }
1840 case OMPRTL__kmpc_end_master: {
1841 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1842 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001843 auto *FnTy =
Alexey Bataev8d690652014-12-04 07:23:53 +00001844 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1845 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1846 break;
1847 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001848 case OMPRTL__kmpc_omp_taskyield: {
1849 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1850 // int end_part);
1851 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001852 auto *FnTy =
Alexey Bataev9f797f32015-02-05 05:57:51 +00001853 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1854 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1855 break;
1856 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001857 case OMPRTL__kmpc_single: {
1858 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1859 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001860 auto *FnTy =
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001861 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1862 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1863 break;
1864 }
1865 case OMPRTL__kmpc_end_single: {
1866 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1867 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001868 auto *FnTy =
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001869 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1870 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1871 break;
1872 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001873 case OMPRTL__kmpc_omp_task_alloc: {
1874 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1875 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1876 // kmp_routine_entry_t *task_entry);
1877 assert(KmpRoutineEntryPtrTy != nullptr &&
1878 "Type kmp_routine_entry_t must be created.");
1879 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1880 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1881 // Return void * and then cast to particular kmp_task_t type.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001882 auto *FnTy =
Alexey Bataev62b63b12015-03-10 07:28:44 +00001883 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1884 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1885 break;
1886 }
1887 case OMPRTL__kmpc_omp_task: {
1888 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1889 // *new_task);
1890 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1891 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001892 auto *FnTy =
Alexey Bataev62b63b12015-03-10 07:28:44 +00001893 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1894 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1895 break;
1896 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001897 case OMPRTL__kmpc_copyprivate: {
1898 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001899 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001900 // kmp_int32 didit);
1901 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1902 auto *CpyFnTy =
1903 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001904 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001905 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1906 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001907 auto *FnTy =
Alexey Bataeva63048e2015-03-23 06:18:07 +00001908 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1909 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1910 break;
1911 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001912 case OMPRTL__kmpc_reduce: {
1913 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1914 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1915 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1916 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1917 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1918 /*isVarArg=*/false);
1919 llvm::Type *TypeParams[] = {
1920 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1921 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1922 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001923 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001924 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1925 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1926 break;
1927 }
1928 case OMPRTL__kmpc_reduce_nowait: {
1929 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1930 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1931 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1932 // *lck);
1933 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1934 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1935 /*isVarArg=*/false);
1936 llvm::Type *TypeParams[] = {
1937 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1938 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1939 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001940 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001941 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1942 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1943 break;
1944 }
1945 case OMPRTL__kmpc_end_reduce: {
1946 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1947 // kmp_critical_name *lck);
1948 llvm::Type *TypeParams[] = {
1949 getIdentTyPointerTy(), CGM.Int32Ty,
1950 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001951 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001952 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1953 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1954 break;
1955 }
1956 case OMPRTL__kmpc_end_reduce_nowait: {
1957 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1958 // kmp_critical_name *lck);
1959 llvm::Type *TypeParams[] = {
1960 getIdentTyPointerTy(), CGM.Int32Ty,
1961 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001962 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001963 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1964 RTLFn =
1965 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1966 break;
1967 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001968 case OMPRTL__kmpc_omp_task_begin_if0: {
1969 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1970 // *new_task);
1971 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1972 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001973 auto *FnTy =
Alexey Bataev1d677132015-04-22 13:57:31 +00001974 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1975 RTLFn =
1976 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1977 break;
1978 }
1979 case OMPRTL__kmpc_omp_task_complete_if0: {
1980 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1981 // *new_task);
1982 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1983 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001984 auto *FnTy =
Alexey Bataev1d677132015-04-22 13:57:31 +00001985 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1986 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1987 /*Name=*/"__kmpc_omp_task_complete_if0");
1988 break;
1989 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001990 case OMPRTL__kmpc_ordered: {
1991 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1992 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001993 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001994 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1995 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1996 break;
1997 }
1998 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001999 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002000 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002001 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002002 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2003 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
2004 break;
2005 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002006 case OMPRTL__kmpc_omp_taskwait: {
2007 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
2008 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002009 auto *FnTy =
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002010 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
2011 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
2012 break;
2013 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002014 case OMPRTL__kmpc_taskgroup: {
2015 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
2016 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002017 auto *FnTy =
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002018 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2019 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
2020 break;
2021 }
2022 case OMPRTL__kmpc_end_taskgroup: {
2023 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
2024 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002025 auto *FnTy =
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002026 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2027 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
2028 break;
2029 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00002030 case OMPRTL__kmpc_push_proc_bind: {
2031 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
2032 // int proc_bind)
2033 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002034 auto *FnTy =
Alexey Bataev7f210c62015-06-18 13:40:03 +00002035 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2036 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
2037 break;
2038 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002039 case OMPRTL__kmpc_omp_task_with_deps: {
2040 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
2041 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
2042 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
2043 llvm::Type *TypeParams[] = {
2044 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
2045 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002046 auto *FnTy =
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002047 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
2048 RTLFn =
2049 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
2050 break;
2051 }
2052 case OMPRTL__kmpc_omp_wait_deps: {
2053 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
2054 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
2055 // kmp_depend_info_t *noalias_dep_list);
2056 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2057 CGM.Int32Ty, CGM.VoidPtrTy,
2058 CGM.Int32Ty, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002059 auto *FnTy =
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002060 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2061 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
2062 break;
2063 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00002064 case OMPRTL__kmpc_cancellationpoint: {
2065 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
2066 // global_tid, kmp_int32 cncl_kind)
2067 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002068 auto *FnTy =
Alexey Bataev0f34da12015-07-02 04:17:07 +00002069 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2070 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
2071 break;
2072 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002073 case OMPRTL__kmpc_cancel: {
2074 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
2075 // kmp_int32 cncl_kind)
2076 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002077 auto *FnTy =
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002078 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2079 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
2080 break;
2081 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002082 case OMPRTL__kmpc_push_num_teams: {
2083 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
2084 // kmp_int32 num_teams, kmp_int32 num_threads)
2085 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
2086 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002087 auto *FnTy =
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002088 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2089 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
2090 break;
2091 }
2092 case OMPRTL__kmpc_fork_teams: {
2093 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
2094 // microtask, ...);
2095 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2096 getKmpc_MicroPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002097 auto *FnTy =
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002098 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
2099 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
James Y Knight9871db02019-02-05 16:42:33 +00002100 if (auto *F = dyn_cast<llvm::Function>(RTLFn.getCallee())) {
Johannes Doerfertac991bb2019-01-19 05:36:54 +00002101 if (!F->hasMetadata(llvm::LLVMContext::MD_callback)) {
2102 llvm::LLVMContext &Ctx = F->getContext();
2103 llvm::MDBuilder MDB(Ctx);
2104 // Annotate the callback behavior of the __kmpc_fork_teams:
2105 // - The callback callee is argument number 2 (microtask).
2106 // - The first two arguments of the callback callee are unknown (-1).
2107 // - All variadic arguments to the __kmpc_fork_teams are passed to the
2108 // callback callee.
2109 F->addMetadata(
2110 llvm::LLVMContext::MD_callback,
2111 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
2112 2, {-1, -1},
2113 /* VarArgsArePassed */ true)}));
2114 }
2115 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002116 break;
2117 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002118 case OMPRTL__kmpc_taskloop: {
2119 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
2120 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
2121 // sched, kmp_uint64 grainsize, void *task_dup);
2122 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2123 CGM.IntTy,
2124 CGM.VoidPtrTy,
2125 CGM.IntTy,
2126 CGM.Int64Ty->getPointerTo(),
2127 CGM.Int64Ty->getPointerTo(),
2128 CGM.Int64Ty,
2129 CGM.IntTy,
2130 CGM.IntTy,
2131 CGM.Int64Ty,
2132 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002133 auto *FnTy =
Alexey Bataev7292c292016-04-25 12:22:29 +00002134 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2135 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
2136 break;
2137 }
Alexey Bataev8b427062016-05-25 12:36:08 +00002138 case OMPRTL__kmpc_doacross_init: {
2139 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
2140 // num_dims, struct kmp_dim *dims);
2141 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2142 CGM.Int32Ty,
2143 CGM.Int32Ty,
2144 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002145 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002146 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2147 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
2148 break;
2149 }
2150 case OMPRTL__kmpc_doacross_fini: {
2151 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
2152 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002153 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002154 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2155 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
2156 break;
2157 }
2158 case OMPRTL__kmpc_doacross_post: {
2159 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
2160 // *vec);
2161 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2162 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002163 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002164 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2165 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
2166 break;
2167 }
2168 case OMPRTL__kmpc_doacross_wait: {
2169 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
2170 // *vec);
2171 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2172 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002173 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002174 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2175 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
2176 break;
2177 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002178 case OMPRTL__kmpc_task_reduction_init: {
2179 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
2180 // *data);
2181 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002182 auto *FnTy =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002183 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2184 RTLFn =
2185 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
2186 break;
2187 }
2188 case OMPRTL__kmpc_task_reduction_get_th_data: {
2189 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
2190 // *d);
2191 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002192 auto *FnTy =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002193 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2194 RTLFn = CGM.CreateRuntimeFunction(
2195 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2196 break;
2197 }
Alexey Bataev7bb33532019-01-07 21:30:43 +00002198 case OMPRTL__kmpc_push_target_tripcount: {
2199 // Build void __kmpc_push_target_tripcount(int64_t device_id, kmp_uint64
2200 // size);
2201 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int64Ty};
2202 llvm::FunctionType *FnTy =
2203 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2204 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_target_tripcount");
2205 break;
2206 }
Samuel Antaobed3c462015-10-02 16:14:20 +00002207 case OMPRTL__tgt_target: {
George Rokos63bc9d62017-11-21 18:25:12 +00002208 // Build int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
2209 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Samuel Antaobed3c462015-10-02 16:14:20 +00002210 // *arg_types);
George Rokos63bc9d62017-11-21 18:25:12 +00002211 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaobed3c462015-10-02 16:14:20 +00002212 CGM.VoidPtrTy,
2213 CGM.Int32Ty,
2214 CGM.VoidPtrPtrTy,
2215 CGM.VoidPtrPtrTy,
2216 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002217 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002218 auto *FnTy =
Samuel Antaobed3c462015-10-02 16:14:20 +00002219 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2220 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2221 break;
2222 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002223 case OMPRTL__tgt_target_nowait: {
2224 // Build int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
2225 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2226 // int64_t *arg_types);
2227 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2228 CGM.VoidPtrTy,
2229 CGM.Int32Ty,
2230 CGM.VoidPtrPtrTy,
2231 CGM.VoidPtrPtrTy,
2232 CGM.SizeTy->getPointerTo(),
2233 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002234 auto *FnTy =
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002235 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2236 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_nowait");
2237 break;
2238 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00002239 case OMPRTL__tgt_target_teams: {
George Rokos63bc9d62017-11-21 18:25:12 +00002240 // Build int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002241 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
George Rokos63bc9d62017-11-21 18:25:12 +00002242 // int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2243 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002244 CGM.VoidPtrTy,
2245 CGM.Int32Ty,
2246 CGM.VoidPtrPtrTy,
2247 CGM.VoidPtrPtrTy,
2248 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002249 CGM.Int64Ty->getPointerTo(),
Samuel Antaob68e2db2016-03-03 16:20:23 +00002250 CGM.Int32Ty,
2251 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002252 auto *FnTy =
Samuel Antaob68e2db2016-03-03 16:20:23 +00002253 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2254 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2255 break;
2256 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002257 case OMPRTL__tgt_target_teams_nowait: {
2258 // Build int32_t __tgt_target_teams_nowait(int64_t device_id, void
2259 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
2260 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2261 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2262 CGM.VoidPtrTy,
2263 CGM.Int32Ty,
2264 CGM.VoidPtrPtrTy,
2265 CGM.VoidPtrPtrTy,
2266 CGM.SizeTy->getPointerTo(),
2267 CGM.Int64Ty->getPointerTo(),
2268 CGM.Int32Ty,
2269 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002270 auto *FnTy =
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002271 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2272 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams_nowait");
2273 break;
2274 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002275 case OMPRTL__tgt_register_lib: {
2276 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2277 QualType ParamTy =
2278 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2279 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002280 auto *FnTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002281 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2282 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2283 break;
2284 }
2285 case OMPRTL__tgt_unregister_lib: {
2286 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2287 QualType ParamTy =
2288 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2289 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002290 auto *FnTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002291 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2292 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2293 break;
2294 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002295 case OMPRTL__tgt_target_data_begin: {
George Rokos63bc9d62017-11-21 18:25:12 +00002296 // Build void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
2297 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2298 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002299 CGM.Int32Ty,
2300 CGM.VoidPtrPtrTy,
2301 CGM.VoidPtrPtrTy,
2302 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002303 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002304 auto *FnTy =
Samuel Antaodf158d52016-04-27 22:58:19 +00002305 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2306 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2307 break;
2308 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002309 case OMPRTL__tgt_target_data_begin_nowait: {
2310 // Build void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
2311 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2312 // *arg_types);
2313 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2314 CGM.Int32Ty,
2315 CGM.VoidPtrPtrTy,
2316 CGM.VoidPtrPtrTy,
2317 CGM.SizeTy->getPointerTo(),
2318 CGM.Int64Ty->getPointerTo()};
2319 auto *FnTy =
2320 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2321 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin_nowait");
2322 break;
2323 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002324 case OMPRTL__tgt_target_data_end: {
George Rokos63bc9d62017-11-21 18:25:12 +00002325 // Build void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
2326 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2327 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002328 CGM.Int32Ty,
2329 CGM.VoidPtrPtrTy,
2330 CGM.VoidPtrPtrTy,
2331 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002332 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002333 auto *FnTy =
Samuel Antaodf158d52016-04-27 22:58:19 +00002334 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2335 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2336 break;
2337 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002338 case OMPRTL__tgt_target_data_end_nowait: {
2339 // Build void __tgt_target_data_end_nowait(int64_t device_id, int32_t
2340 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2341 // *arg_types);
2342 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2343 CGM.Int32Ty,
2344 CGM.VoidPtrPtrTy,
2345 CGM.VoidPtrPtrTy,
2346 CGM.SizeTy->getPointerTo(),
2347 CGM.Int64Ty->getPointerTo()};
2348 auto *FnTy =
2349 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2350 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end_nowait");
2351 break;
2352 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002353 case OMPRTL__tgt_target_data_update: {
George Rokos63bc9d62017-11-21 18:25:12 +00002354 // Build void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
2355 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2356 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antao8d2d7302016-05-26 18:30:22 +00002357 CGM.Int32Ty,
2358 CGM.VoidPtrPtrTy,
2359 CGM.VoidPtrPtrTy,
2360 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002361 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002362 auto *FnTy =
Samuel Antao8d2d7302016-05-26 18:30:22 +00002363 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2364 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2365 break;
2366 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002367 case OMPRTL__tgt_target_data_update_nowait: {
2368 // Build void __tgt_target_data_update_nowait(int64_t device_id, int32_t
2369 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2370 // *arg_types);
2371 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2372 CGM.Int32Ty,
2373 CGM.VoidPtrPtrTy,
2374 CGM.VoidPtrPtrTy,
2375 CGM.SizeTy->getPointerTo(),
2376 CGM.Int64Ty->getPointerTo()};
2377 auto *FnTy =
2378 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2379 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update_nowait");
2380 break;
2381 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002382 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002383 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002384 return RTLFn;
2385}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002386
James Y Knight9871db02019-02-05 16:42:33 +00002387llvm::FunctionCallee
2388CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize, bool IVSigned) {
Alexander Musman21212e42015-03-13 10:38:23 +00002389 assert((IVSize == 32 || IVSize == 64) &&
2390 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002391 StringRef Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2392 : "__kmpc_for_static_init_4u")
2393 : (IVSigned ? "__kmpc_for_static_init_8"
2394 : "__kmpc_for_static_init_8u");
2395 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2396 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
Alexander Musman21212e42015-03-13 10:38:23 +00002397 llvm::Type *TypeParams[] = {
2398 getIdentTyPointerTy(), // loc
2399 CGM.Int32Ty, // tid
2400 CGM.Int32Ty, // schedtype
2401 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2402 PtrTy, // p_lower
2403 PtrTy, // p_upper
2404 PtrTy, // p_stride
2405 ITy, // incr
2406 ITy // chunk
2407 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002408 auto *FnTy =
Alexander Musman21212e42015-03-13 10:38:23 +00002409 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2410 return CGM.CreateRuntimeFunction(FnTy, Name);
2411}
2412
James Y Knight9871db02019-02-05 16:42:33 +00002413llvm::FunctionCallee
2414CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize, bool IVSigned) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00002415 assert((IVSize == 32 || IVSize == 64) &&
2416 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002417 StringRef Name =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002418 IVSize == 32
2419 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2420 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002421 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
Alexander Musman92bdaab2015-03-12 13:37:50 +00002422 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2423 CGM.Int32Ty, // tid
2424 CGM.Int32Ty, // schedtype
2425 ITy, // lower
2426 ITy, // upper
2427 ITy, // stride
2428 ITy // chunk
2429 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002430 auto *FnTy =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002431 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2432 return CGM.CreateRuntimeFunction(FnTy, Name);
2433}
2434
James Y Knight9871db02019-02-05 16:42:33 +00002435llvm::FunctionCallee
2436CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize, bool IVSigned) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002437 assert((IVSize == 32 || IVSize == 64) &&
2438 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002439 StringRef Name =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002440 IVSize == 32
2441 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2442 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2443 llvm::Type *TypeParams[] = {
2444 getIdentTyPointerTy(), // loc
2445 CGM.Int32Ty, // tid
2446 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002447 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002448 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2449 return CGM.CreateRuntimeFunction(FnTy, Name);
2450}
2451
James Y Knight9871db02019-02-05 16:42:33 +00002452llvm::FunctionCallee
2453CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize, bool IVSigned) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00002454 assert((IVSize == 32 || IVSize == 64) &&
2455 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002456 StringRef Name =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002457 IVSize == 32
2458 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2459 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002460 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2461 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002462 llvm::Type *TypeParams[] = {
2463 getIdentTyPointerTy(), // loc
2464 CGM.Int32Ty, // tid
2465 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2466 PtrTy, // p_lower
2467 PtrTy, // p_upper
2468 PtrTy // p_stride
2469 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002470 auto *FnTy =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002471 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2472 return CGM.CreateRuntimeFunction(FnTy, Name);
2473}
2474
Alexey Bataev03f270c2018-03-30 18:31:07 +00002475Address CGOpenMPRuntime::getAddrOfDeclareTargetLink(const VarDecl *VD) {
2476 if (CGM.getLangOpts().OpenMPSimd)
2477 return Address::invalid();
Alexey Bataev92327c52018-03-26 16:40:55 +00002478 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002479 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00002480 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2481 SmallString<64> PtrName;
2482 {
2483 llvm::raw_svector_ostream OS(PtrName);
2484 OS << CGM.getMangledName(GlobalDecl(VD)) << "_decl_tgt_link_ptr";
2485 }
2486 llvm::Value *Ptr = CGM.getModule().getNamedValue(PtrName);
2487 if (!Ptr) {
2488 QualType PtrTy = CGM.getContext().getPointerType(VD->getType());
2489 Ptr = getOrCreateInternalVariable(CGM.getTypes().ConvertTypeForMem(PtrTy),
2490 PtrName);
Alexey Bataev03f270c2018-03-30 18:31:07 +00002491 if (!CGM.getLangOpts().OpenMPIsDevice) {
2492 auto *GV = cast<llvm::GlobalVariable>(Ptr);
2493 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2494 GV->setInitializer(CGM.GetAddrOfGlobal(VD));
2495 }
2496 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ptr));
2497 registerTargetGlobalVariable(VD, cast<llvm::Constant>(Ptr));
Alexey Bataev92327c52018-03-26 16:40:55 +00002498 }
2499 return Address(Ptr, CGM.getContext().getDeclAlign(VD));
2500 }
2501 return Address::invalid();
2502}
2503
Alexey Bataev97720002014-11-11 04:05:39 +00002504llvm::Constant *
2505CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002506 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2507 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002508 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev18fa2322018-05-02 14:20:50 +00002509 std::string Suffix = getName({"cache", ""});
2510 return getOrCreateInternalVariable(
2511 CGM.Int8PtrPtrTy, Twine(CGM.getMangledName(VD)).concat(Suffix));
Alexey Bataev97720002014-11-11 04:05:39 +00002512}
2513
John McCall7f416cc2015-09-08 08:05:57 +00002514Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2515 const VarDecl *VD,
2516 Address VDAddr,
2517 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002518 if (CGM.getLangOpts().OpenMPUseTLS &&
2519 CGM.getContext().getTargetInfo().isTLSSupported())
2520 return VDAddr;
2521
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002522 llvm::Type *VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002523 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002524 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2525 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002526 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2527 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002528 return Address(CGF.EmitRuntimeCall(
2529 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2530 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002531}
2532
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002533void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002534 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002535 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2536 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2537 // library.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002538 llvm::Value *OMPLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002539 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002540 OMPLoc);
2541 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2542 // to register constructor/destructor for variable.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002543 llvm::Value *Args[] = {
2544 OMPLoc, CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.VoidPtrTy),
2545 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002546 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002547 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002548}
2549
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002550llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002551 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002552 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002553 if (CGM.getLangOpts().OpenMPUseTLS &&
2554 CGM.getContext().getTargetInfo().isTLSSupported())
2555 return nullptr;
2556
Alexey Bataev97720002014-11-11 04:05:39 +00002557 VD = VD->getDefinition(CGM.getContext());
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00002558 if (VD && ThreadPrivateWithDefinition.insert(CGM.getMangledName(VD)).second) {
Alexey Bataev97720002014-11-11 04:05:39 +00002559 QualType ASTTy = VD->getType();
2560
2561 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002562 const Expr *Init = VD->getAnyInitializer();
Alexey Bataev97720002014-11-11 04:05:39 +00002563 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2564 // Generate function that re-emits the declaration's initializer into the
2565 // threadprivate copy of the variable VD
2566 CodeGenFunction CtorCGF(CGM);
2567 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002568 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2569 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002570 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002571 Args.push_back(&Dst);
2572
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002573 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
John McCallc56a8b32016-03-11 04:30:31 +00002574 CGM.getContext().VoidPtrTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002575 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002576 std::string Name = getName({"__kmpc_global_ctor_", ""});
2577 llvm::Function *Fn =
2578 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002579 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002580 Args, Loc, Loc);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002581 llvm::Value *ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002582 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002583 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002584 Address Arg = Address(ArgVal, VDAddr.getAlignment());
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002585 Arg = CtorCGF.Builder.CreateElementBitCast(
2586 Arg, CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002587 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2588 /*IsInitializer=*/true);
2589 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002590 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002591 CGM.getContext().VoidPtrTy, Dst.getLocation());
2592 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2593 CtorCGF.FinishFunction();
2594 Ctor = Fn;
2595 }
2596 if (VD->getType().isDestructedType() != QualType::DK_none) {
2597 // Generate function that emits destructor call for the threadprivate copy
2598 // of the variable VD
2599 CodeGenFunction DtorCGF(CGM);
2600 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002601 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2602 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002603 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002604 Args.push_back(&Dst);
2605
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002606 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
John McCallc56a8b32016-03-11 04:30:31 +00002607 CGM.getContext().VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002608 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002609 std::string Name = getName({"__kmpc_global_dtor_", ""});
2610 llvm::Function *Fn =
2611 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002612 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002613 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002614 Loc, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002615 // Create a scope with an artificial location for the body of this function.
2616 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002617 llvm::Value *ArgVal = DtorCGF.EmitLoadOfScalar(
Alexey Bataev97720002014-11-11 04:05:39 +00002618 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002619 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2620 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002621 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2622 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2623 DtorCGF.FinishFunction();
2624 Dtor = Fn;
2625 }
2626 // Do not emit init function if it is not required.
2627 if (!Ctor && !Dtor)
2628 return nullptr;
2629
2630 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002631 auto *CopyCtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2632 /*isVarArg=*/false)
2633 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002634 // Copying constructor for the threadprivate variable.
2635 // Must be NULL - reserved by runtime, but currently it requires that this
2636 // parameter is always NULL. Otherwise it fires assertion.
2637 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2638 if (Ctor == nullptr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002639 auto *CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2640 /*isVarArg=*/false)
2641 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002642 Ctor = llvm::Constant::getNullValue(CtorTy);
2643 }
2644 if (Dtor == nullptr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002645 auto *DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2646 /*isVarArg=*/false)
2647 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002648 Dtor = llvm::Constant::getNullValue(DtorTy);
2649 }
2650 if (!CGF) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002651 auto *InitFunctionTy =
Alexey Bataev97720002014-11-11 04:05:39 +00002652 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002653 std::string Name = getName({"__omp_threadprivate_init_", ""});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002654 llvm::Function *InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Alexey Bataev18fa2322018-05-02 14:20:50 +00002655 InitFunctionTy, Name, CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002656 CodeGenFunction InitCGF(CGM);
2657 FunctionArgList ArgList;
2658 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2659 CGM.getTypes().arrangeNullaryFunction(), ArgList,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002660 Loc, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002661 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002662 InitCGF.FinishFunction();
2663 return InitFunction;
2664 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002665 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002666 }
2667 return nullptr;
2668}
2669
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002670/// Obtain information that uniquely identifies a target entry. This
Alexey Bataev34f8a702018-03-28 14:28:54 +00002671/// consists of the file and device IDs as well as line number associated with
2672/// the relevant entry source location.
2673static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
2674 unsigned &DeviceID, unsigned &FileID,
2675 unsigned &LineNum) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002676 SourceManager &SM = C.getSourceManager();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002677
2678 // The loc should be always valid and have a file ID (the user cannot use
2679 // #pragma directives in macros)
2680
2681 assert(Loc.isValid() && "Source location is expected to be always valid.");
Alexey Bataev34f8a702018-03-28 14:28:54 +00002682
2683 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
2684 assert(PLoc.isValid() && "Source location is expected to be always valid.");
2685
2686 llvm::sys::fs::UniqueID ID;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00002687 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
2688 SM.getDiagnostics().Report(diag::err_cannot_open_file)
2689 << PLoc.getFilename() << EC.message();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002690
2691 DeviceID = ID.getDevice();
2692 FileID = ID.getFile();
2693 LineNum = PLoc.getLine();
2694}
2695
2696bool CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD,
2697 llvm::GlobalVariable *Addr,
2698 bool PerformInit) {
2699 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002700 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002701 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link)
Alexey Bataevd01b7492018-08-15 19:45:12 +00002702 return CGM.getLangOpts().OpenMPIsDevice;
Alexey Bataev34f8a702018-03-28 14:28:54 +00002703 VD = VD->getDefinition(CGM.getContext());
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00002704 if (VD && !DeclareTargetWithDefinition.insert(CGM.getMangledName(VD)).second)
Alexey Bataev34f8a702018-03-28 14:28:54 +00002705 return CGM.getLangOpts().OpenMPIsDevice;
2706
2707 QualType ASTTy = VD->getType();
2708
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002709 SourceLocation Loc = VD->getCanonicalDecl()->getBeginLoc();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002710 // Produce the unique prefix to identify the new target regions. We use
2711 // the source location of the variable declaration which we know to not
2712 // conflict with any target region.
2713 unsigned DeviceID;
2714 unsigned FileID;
2715 unsigned Line;
2716 getTargetEntryUniqueInfo(CGM.getContext(), Loc, DeviceID, FileID, Line);
2717 SmallString<128> Buffer, Out;
2718 {
2719 llvm::raw_svector_ostream OS(Buffer);
2720 OS << "__omp_offloading_" << llvm::format("_%x", DeviceID)
2721 << llvm::format("_%x_", FileID) << VD->getName() << "_l" << Line;
2722 }
2723
2724 const Expr *Init = VD->getAnyInitializer();
2725 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2726 llvm::Constant *Ctor;
2727 llvm::Constant *ID;
2728 if (CGM.getLangOpts().OpenMPIsDevice) {
2729 // Generate function that re-emits the declaration's initializer into
2730 // the threadprivate copy of the variable VD
2731 CodeGenFunction CtorCGF(CGM);
2732
2733 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2734 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2735 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2736 FTy, Twine(Buffer, "_ctor"), FI, Loc);
2737 auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF);
2738 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2739 FunctionArgList(), Loc, Loc);
2740 auto AL = ApplyDebugLocation::CreateArtificial(CtorCGF);
2741 CtorCGF.EmitAnyExprToMem(Init,
2742 Address(Addr, CGM.getContext().getDeclAlign(VD)),
2743 Init->getType().getQualifiers(),
2744 /*IsInitializer=*/true);
2745 CtorCGF.FinishFunction();
2746 Ctor = Fn;
2747 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
Alexey Bataeve253f2f2018-05-09 14:15:18 +00002748 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ctor));
Alexey Bataev34f8a702018-03-28 14:28:54 +00002749 } else {
2750 Ctor = new llvm::GlobalVariable(
2751 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2752 llvm::GlobalValue::PrivateLinkage,
2753 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_ctor"));
2754 ID = Ctor;
2755 }
2756
2757 // Register the information for the entry associated with the constructor.
2758 Out.clear();
2759 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2760 DeviceID, FileID, Twine(Buffer, "_ctor").toStringRef(Out), Line, Ctor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002761 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryCtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002762 }
2763 if (VD->getType().isDestructedType() != QualType::DK_none) {
2764 llvm::Constant *Dtor;
2765 llvm::Constant *ID;
2766 if (CGM.getLangOpts().OpenMPIsDevice) {
2767 // Generate function that emits destructor call for the threadprivate
2768 // copy of the variable VD
2769 CodeGenFunction DtorCGF(CGM);
2770
2771 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2772 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2773 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2774 FTy, Twine(Buffer, "_dtor"), FI, Loc);
2775 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
2776 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2777 FunctionArgList(), Loc, Loc);
2778 // Create a scope with an artificial location for the body of this
2779 // function.
2780 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
2781 DtorCGF.emitDestroy(Address(Addr, CGM.getContext().getDeclAlign(VD)),
2782 ASTTy, DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2783 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2784 DtorCGF.FinishFunction();
2785 Dtor = Fn;
2786 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
Alexey Bataeve253f2f2018-05-09 14:15:18 +00002787 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Dtor));
Alexey Bataev34f8a702018-03-28 14:28:54 +00002788 } else {
2789 Dtor = new llvm::GlobalVariable(
2790 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2791 llvm::GlobalValue::PrivateLinkage,
2792 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_dtor"));
2793 ID = Dtor;
2794 }
2795 // Register the information for the entry associated with the destructor.
2796 Out.clear();
2797 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2798 DeviceID, FileID, Twine(Buffer, "_dtor").toStringRef(Out), Line, Dtor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002799 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryDtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002800 }
2801 return CGM.getLangOpts().OpenMPIsDevice;
2802}
2803
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002804Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2805 QualType VarType,
2806 StringRef Name) {
Alexey Bataev18fa2322018-05-02 14:20:50 +00002807 std::string Suffix = getName({"artificial", ""});
2808 std::string CacheSuffix = getName({"cache", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002809 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002810 llvm::Value *GAddr =
2811 getOrCreateInternalVariable(VarLVType, Twine(Name).concat(Suffix));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002812 llvm::Value *Args[] = {
2813 emitUpdateLocation(CGF, SourceLocation()),
2814 getThreadID(CGF, SourceLocation()),
2815 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2816 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2817 /*IsSigned=*/false),
Alexey Bataev18fa2322018-05-02 14:20:50 +00002818 getOrCreateInternalVariable(
2819 CGM.VoidPtrPtrTy, Twine(Name).concat(Suffix).concat(CacheSuffix))};
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002820 return Address(
2821 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2822 CGF.EmitRuntimeCall(
2823 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2824 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2825 CGM.getPointerAlign());
2826}
2827
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002828void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2829 const RegionCodeGenTy &ThenGen,
2830 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002831 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2832
2833 // If the condition constant folds and can be elided, try to avoid emitting
2834 // the condition and the dead arm of the if/else.
2835 bool CondConstant;
2836 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002837 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002838 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002839 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002840 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002841 return;
2842 }
2843
2844 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2845 // emit the conditional branch.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002846 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("omp_if.then");
2847 llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else");
2848 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("omp_if.end");
Alexey Bataev1d677132015-04-22 13:57:31 +00002849 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2850
2851 // Emit the 'then' code.
2852 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002853 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002854 CGF.EmitBranch(ContBlock);
2855 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002856 // There is no need to emit line number for unconditional branch.
2857 (void)ApplyDebugLocation::CreateEmpty(CGF);
2858 CGF.EmitBlock(ElseBlock);
2859 ElseGen(CGF);
2860 // There is no need to emit line number for unconditional branch.
2861 (void)ApplyDebugLocation::CreateEmpty(CGF);
2862 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002863 // Emit the continuation block for code after the if.
2864 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002865}
2866
Alexey Bataev1d677132015-04-22 13:57:31 +00002867void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
James Y Knight9871db02019-02-05 16:42:33 +00002868 llvm::Function *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002869 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002870 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002871 if (!CGF.HaveInsertPoint())
2872 return;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002873 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002874 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2875 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002876 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002877 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002878 llvm::Value *Args[] = {
2879 RTLoc,
2880 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002881 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002882 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2883 RealArgs.append(std::begin(Args), std::end(Args));
2884 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2885
James Y Knight9871db02019-02-05 16:42:33 +00002886 llvm::FunctionCallee RTLFn =
2887 RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002888 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2889 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002890 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2891 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002892 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
2893 llvm::Value *ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00002894 // Build calls:
2895 // __kmpc_serialized_parallel(&Loc, GTid);
2896 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002897 CGF.EmitRuntimeCall(
2898 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002899
Alexey Bataev1d677132015-04-22 13:57:31 +00002900 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002901 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2902 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00002903 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00002904 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
Alexey Bataev8521ff62018-07-25 20:03:01 +00002905 // ThreadId for serialized parallels is 0.
2906 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
Alexey Bataev2377fe92015-09-10 08:12:02 +00002907 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2908 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002909 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002910
Alexey Bataev1d677132015-04-22 13:57:31 +00002911 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002912 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00002913 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002914 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2915 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002916 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002917 if (IfCond) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002918 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002919 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002920 RegionCodeGenTy ThenRCG(ThenGen);
2921 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002922 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002923}
2924
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002925// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002926// thread-ID variable (it is passed in a first argument of the outlined function
2927// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2928// regular serial code region, get thread ID by calling kmp_int32
2929// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2930// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002931Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2932 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002933 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002934 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002935 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002936 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002937
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002938 llvm::Value *ThreadID = getThreadID(CGF, Loc);
2939 QualType Int32Ty =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002940 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002941 Address ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
Alexey Bataevd74d0602014-10-13 06:02:40 +00002942 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002943 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002944
2945 return ThreadIDTemp;
2946}
2947
Alexey Bataev1af5bd52019-03-05 17:47:18 +00002948llvm::Constant *CGOpenMPRuntime::getOrCreateInternalVariable(
2949 llvm::Type *Ty, const llvm::Twine &Name, unsigned AddressSpace) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002950 SmallString<256> Buffer;
2951 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002952 Out << Name;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002953 StringRef RuntimeName = Out.str();
Alexey Bataev43a919f2018-04-13 17:48:43 +00002954 auto &Elem = *InternalVars.try_emplace(RuntimeName, nullptr).first;
David Blaikie13156b62014-11-19 03:06:06 +00002955 if (Elem.second) {
2956 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002957 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002958 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002959 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002960
David Blaikie13156b62014-11-19 03:06:06 +00002961 return Elem.second = new llvm::GlobalVariable(
2962 CGM.getModule(), Ty, /*IsConstant*/ false,
2963 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
Alexey Bataev1af5bd52019-03-05 17:47:18 +00002964 Elem.first(), /*InsertBefore=*/nullptr,
2965 llvm::GlobalValue::NotThreadLocal, AddressSpace);
Alexey Bataev97720002014-11-11 04:05:39 +00002966}
2967
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002968llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev18fa2322018-05-02 14:20:50 +00002969 std::string Prefix = Twine("gomp_critical_user_", CriticalName).str();
2970 std::string Name = getName({Prefix, "var"});
2971 return getOrCreateInternalVariable(KmpCriticalNameTy, Name);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002972}
2973
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002974namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002975/// Common pre(post)-action for different OpenMP constructs.
2976class CommonActionTy final : public PrePostActionTy {
James Y Knight9871db02019-02-05 16:42:33 +00002977 llvm::FunctionCallee EnterCallee;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002978 ArrayRef<llvm::Value *> EnterArgs;
James Y Knight9871db02019-02-05 16:42:33 +00002979 llvm::FunctionCallee ExitCallee;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002980 ArrayRef<llvm::Value *> ExitArgs;
2981 bool Conditional;
2982 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002983
2984public:
James Y Knight9871db02019-02-05 16:42:33 +00002985 CommonActionTy(llvm::FunctionCallee EnterCallee,
2986 ArrayRef<llvm::Value *> EnterArgs,
2987 llvm::FunctionCallee ExitCallee,
2988 ArrayRef<llvm::Value *> ExitArgs, bool Conditional = false)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002989 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2990 ExitArgs(ExitArgs), Conditional(Conditional) {}
2991 void Enter(CodeGenFunction &CGF) override {
2992 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2993 if (Conditional) {
2994 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2995 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2996 ContBlock = CGF.createBasicBlock("omp_if.end");
2997 // Generate the branch (If-stmt)
2998 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2999 CGF.EmitBlock(ThenBlock);
3000 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00003001 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003002 void Done(CodeGenFunction &CGF) {
3003 // Emit the rest of blocks/branches
3004 CGF.EmitBranch(ContBlock);
3005 CGF.EmitBlock(ContBlock, true);
3006 }
3007 void Exit(CodeGenFunction &CGF) override {
3008 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00003009 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003010};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003011} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003012
3013void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
3014 StringRef CriticalName,
3015 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00003016 SourceLocation Loc, const Expr *Hint) {
3017 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00003018 // CriticalOpGen();
3019 // __kmpc_end_critical(ident_t *, gtid, Lock);
3020 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00003021 if (!CGF.HaveInsertPoint())
3022 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00003023 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3024 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003025 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
3026 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00003027 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003028 EnterArgs.push_back(CGF.Builder.CreateIntCast(
3029 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
3030 }
3031 CommonActionTy Action(
3032 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
3033 : OMPRTL__kmpc_critical),
3034 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
3035 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00003036 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00003037}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00003038
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003039void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003040 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003041 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003042 if (!CGF.HaveInsertPoint())
3043 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00003044 // if(__kmpc_master(ident_t *, gtid)) {
3045 // MasterOpGen();
3046 // __kmpc_end_master(ident_t *, gtid);
3047 // }
3048 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00003049 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003050 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
3051 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
3052 /*Conditional=*/true);
3053 MasterOpGen.setAction(Action);
3054 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
3055 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00003056}
3057
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003058void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
3059 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003060 if (!CGF.HaveInsertPoint())
3061 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00003062 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
3063 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003064 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00003065 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003066 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003067 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
3068 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00003069}
3070
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003071void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
3072 const RegionCodeGenTy &TaskgroupOpGen,
3073 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003074 if (!CGF.HaveInsertPoint())
3075 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003076 // __kmpc_taskgroup(ident_t *, gtid);
3077 // TaskgroupOpGen();
3078 // __kmpc_end_taskgroup(ident_t *, gtid);
3079 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003080 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3081 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
3082 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
3083 Args);
3084 TaskgroupOpGen.setAction(Action);
3085 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003086}
3087
John McCall7f416cc2015-09-08 08:05:57 +00003088/// Given an array of pointers to variables, project the address of a
3089/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003090static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
3091 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00003092 // Pull out the pointer to the variable.
James Y Knight751fe282019-02-09 22:22:28 +00003093 Address PtrAddr = CGF.Builder.CreateConstArrayGEP(Array, Index);
John McCall7f416cc2015-09-08 08:05:57 +00003094 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
3095
3096 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003097 Addr = CGF.Builder.CreateElementBitCast(
3098 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00003099 return Addr;
3100}
3101
Alexey Bataeva63048e2015-03-23 06:18:07 +00003102static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00003103 CodeGenModule &CGM, llvm::Type *ArgsType,
3104 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003105 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps,
3106 SourceLocation Loc) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003107 ASTContext &C = CGM.getContext();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003108 // void copy_func(void *LHSArg, void *RHSArg);
3109 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003110 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3111 ImplicitParamDecl::Other);
3112 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
3113 ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003114 Args.push_back(&LHSArg);
3115 Args.push_back(&RHSArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003116 const auto &CGFI =
3117 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003118 std::string Name =
3119 CGM.getOpenMPRuntime().getName({"omp", "copyprivate", "copy_func"});
3120 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
3121 llvm::GlobalValue::InternalLinkage, Name,
3122 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003123 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003124 Fn->setDoesNotRecurse();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003125 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003126 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev420d45b2015-04-14 05:11:24 +00003127 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003128 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00003129 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3130 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
3131 ArgsType), CGF.getPointerAlign());
3132 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3133 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
3134 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00003135 // *(Type0*)Dst[0] = *(Type0*)Src[0];
3136 // *(Type1*)Dst[1] = *(Type1*)Src[1];
3137 // ...
3138 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00003139 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003140 const auto *DestVar =
3141 cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003142 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
3143
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003144 const auto *SrcVar =
3145 cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003146 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
3147
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003148 const auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003149 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00003150 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003151 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00003152 CGF.FinishFunction();
3153 return Fn;
3154}
3155
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003156void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003157 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00003158 SourceLocation Loc,
3159 ArrayRef<const Expr *> CopyprivateVars,
3160 ArrayRef<const Expr *> SrcExprs,
3161 ArrayRef<const Expr *> DstExprs,
3162 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003163 if (!CGF.HaveInsertPoint())
3164 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00003165 assert(CopyprivateVars.size() == SrcExprs.size() &&
3166 CopyprivateVars.size() == DstExprs.size() &&
3167 CopyprivateVars.size() == AssignmentOps.size());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003168 ASTContext &C = CGM.getContext();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003169 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003170 // if(__kmpc_single(ident_t *, gtid)) {
3171 // SingleOpGen();
3172 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003173 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003174 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00003175 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3176 // <copy_func>, did_it);
3177
John McCall7f416cc2015-09-08 08:05:57 +00003178 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00003179 if (!CopyprivateVars.empty()) {
3180 // int32 did_it = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003181 QualType KmpInt32Ty =
3182 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003183 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00003184 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003185 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003186 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00003187 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003188 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
3189 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
3190 /*Conditional=*/true);
3191 SingleOpGen.setAction(Action);
3192 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
3193 if (DidIt.isValid()) {
3194 // did_it = 1;
3195 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
3196 }
3197 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003198 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
3199 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00003200 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00003201 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003202 QualType CopyprivateArrayTy =
Alexey Bataeva63048e2015-03-23 06:18:07 +00003203 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
3204 /*IndexTypeQuals=*/0);
3205 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00003206 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00003207 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
3208 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
James Y Knight751fe282019-02-09 22:22:28 +00003209 Address Elem = CGF.Builder.CreateConstArrayGEP(CopyprivateList, I);
John McCall7f416cc2015-09-08 08:05:57 +00003210 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00003211 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003212 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
3213 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003214 }
3215 // Build function that copies private values from single region to all other
3216 // threads in the corresponding parallel region.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003217 llvm::Value *CpyFn = emitCopyprivateCopyFunction(
Alexey Bataeva63048e2015-03-23 06:18:07 +00003218 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003219 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps, Loc);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003220 llvm::Value *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00003221 Address CL =
3222 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
3223 CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003224 llvm::Value *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003225 llvm::Value *Args[] = {
3226 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
3227 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00003228 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00003229 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00003230 CpyFn, // void (*) (void *, void *) <copy_func>
3231 DidItVal // i32 did_it
3232 };
3233 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
3234 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003235}
3236
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003237void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
3238 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00003239 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003240 if (!CGF.HaveInsertPoint())
3241 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003242 // __kmpc_ordered(ident_t *, gtid);
3243 // OrderedOpGen();
3244 // __kmpc_end_ordered(ident_t *, gtid);
3245 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00003246 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003247 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003248 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
3249 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
3250 Args);
3251 OrderedOpGen.setAction(Action);
3252 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
3253 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003254 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003255 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003256}
3257
Alexey Bataevc3028ca2018-12-04 15:03:25 +00003258unsigned CGOpenMPRuntime::getDefaultFlagsForBarriers(OpenMPDirectiveKind Kind) {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003259 unsigned Flags;
3260 if (Kind == OMPD_for)
3261 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
3262 else if (Kind == OMPD_sections)
3263 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
3264 else if (Kind == OMPD_single)
3265 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
3266 else if (Kind == OMPD_barrier)
3267 Flags = OMP_IDENT_BARRIER_EXPL;
3268 else
3269 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataevc3028ca2018-12-04 15:03:25 +00003270 return Flags;
3271}
3272
3273void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
3274 OpenMPDirectiveKind Kind, bool EmitChecks,
3275 bool ForceSimpleCall) {
3276 if (!CGF.HaveInsertPoint())
3277 return;
3278 // Build call __kmpc_cancel_barrier(loc, thread_id);
3279 // Build call __kmpc_barrier(loc, thread_id);
3280 unsigned Flags = getDefaultFlagsForBarriers(Kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003281 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
3282 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003283 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
3284 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003285 if (auto *OMPRegionInfo =
3286 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00003287 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003288 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003289 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00003290 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003291 // if (__kmpc_cancel_barrier()) {
3292 // exit from construct;
3293 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003294 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
3295 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
3296 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003297 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
3298 CGF.EmitBlock(ExitBB);
3299 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003300 CodeGenFunction::JumpDest CancelDestination =
Alexey Bataev25e5b442015-09-15 12:52:43 +00003301 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003302 CGF.EmitBranchThroughCleanup(CancelDestination);
3303 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
3304 }
3305 return;
3306 }
3307 }
3308 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00003309}
3310
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003311/// Map the OpenMP loop schedule to the runtime enumeration.
Alexander Musmanc6388682014-12-15 07:07:06 +00003312static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003313 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003314 switch (ScheduleKind) {
3315 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003316 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
3317 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00003318 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003319 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003320 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003321 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003322 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003323 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
3324 case OMPC_SCHEDULE_auto:
3325 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00003326 case OMPC_SCHEDULE_unknown:
3327 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003328 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00003329 }
3330 llvm_unreachable("Unexpected runtime schedule");
3331}
3332
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003333/// Map the OpenMP distribute schedule to the runtime enumeration.
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003334static OpenMPSchedType
3335getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
3336 // only static is allowed for dist_schedule
3337 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
3338}
3339
Alexander Musmanc6388682014-12-15 07:07:06 +00003340bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
3341 bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003342 OpenMPSchedType Schedule =
3343 getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00003344 return Schedule == OMP_sch_static;
3345}
3346
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003347bool CGOpenMPRuntime::isStaticNonchunked(
3348 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003349 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003350 return Schedule == OMP_dist_sch_static;
3351}
3352
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003353bool CGOpenMPRuntime::isStaticChunked(OpenMPScheduleClauseKind ScheduleKind,
3354 bool Chunked) const {
3355 OpenMPSchedType Schedule =
3356 getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
3357 return Schedule == OMP_sch_static_chunked;
3358}
3359
3360bool CGOpenMPRuntime::isStaticChunked(
3361 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
3362 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
3363 return Schedule == OMP_dist_sch_static_chunked;
3364}
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003365
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003366bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003367 OpenMPSchedType Schedule =
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003368 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003369 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
3370 return Schedule != OMP_sch_static;
3371}
3372
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003373static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
3374 OpenMPScheduleClauseModifier M1,
3375 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00003376 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003377 switch (M1) {
3378 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003379 Modifier = OMP_sch_modifier_monotonic;
3380 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003381 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003382 Modifier = OMP_sch_modifier_nonmonotonic;
3383 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003384 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003385 if (Schedule == OMP_sch_static_chunked)
3386 Schedule = OMP_sch_static_balanced_chunked;
3387 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003388 case OMPC_SCHEDULE_MODIFIER_last:
3389 case OMPC_SCHEDULE_MODIFIER_unknown:
3390 break;
3391 }
3392 switch (M2) {
3393 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003394 Modifier = OMP_sch_modifier_monotonic;
3395 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003396 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003397 Modifier = OMP_sch_modifier_nonmonotonic;
3398 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003399 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003400 if (Schedule == OMP_sch_static_chunked)
3401 Schedule = OMP_sch_static_balanced_chunked;
3402 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003403 case OMPC_SCHEDULE_MODIFIER_last:
3404 case OMPC_SCHEDULE_MODIFIER_unknown:
3405 break;
3406 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00003407 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003408}
3409
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003410void CGOpenMPRuntime::emitForDispatchInit(
3411 CodeGenFunction &CGF, SourceLocation Loc,
3412 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
3413 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003414 if (!CGF.HaveInsertPoint())
3415 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003416 OpenMPSchedType Schedule = getRuntimeSchedule(
3417 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00003418 assert(Ordered ||
3419 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00003420 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
3421 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00003422 // Call __kmpc_dispatch_init(
3423 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
3424 // kmp_int[32|64] lower, kmp_int[32|64] upper,
3425 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00003426
John McCall7f416cc2015-09-08 08:05:57 +00003427 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003428 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
3429 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00003430 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003431 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3432 CGF.Builder.getInt32(addMonoNonMonoModifier(
3433 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003434 DispatchValues.LB, // Lower
3435 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003436 CGF.Builder.getIntN(IVSize, 1), // Stride
3437 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00003438 };
3439 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
3440}
3441
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003442static void emitForStaticInitCall(
3443 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
James Y Knight9871db02019-02-05 16:42:33 +00003444 llvm::FunctionCallee ForStaticInitFunction, OpenMPSchedType Schedule,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003445 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003446 const CGOpenMPRuntime::StaticRTInput &Values) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003447 if (!CGF.HaveInsertPoint())
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003448 return;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003449
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003450 assert(!Values.Ordered);
3451 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
3452 Schedule == OMP_sch_static_balanced_chunked ||
3453 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
3454 Schedule == OMP_dist_sch_static ||
3455 Schedule == OMP_dist_sch_static_chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003456
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003457 // Call __kmpc_for_static_init(
3458 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
3459 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
3460 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
3461 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
3462 llvm::Value *Chunk = Values.Chunk;
3463 if (Chunk == nullptr) {
3464 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
3465 Schedule == OMP_dist_sch_static) &&
3466 "expected static non-chunked schedule");
3467 // If the Chunk was not specified in the clause - use default value 1.
3468 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3469 } else {
3470 assert((Schedule == OMP_sch_static_chunked ||
3471 Schedule == OMP_sch_static_balanced_chunked ||
3472 Schedule == OMP_ord_static_chunked ||
3473 Schedule == OMP_dist_sch_static_chunked) &&
3474 "expected static chunked schedule");
3475 }
3476 llvm::Value *Args[] = {
3477 UpdateLocation,
3478 ThreadId,
3479 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3480 M2)), // Schedule type
3481 Values.IL.getPointer(), // &isLastIter
3482 Values.LB.getPointer(), // &LB
3483 Values.UB.getPointer(), // &UB
3484 Values.ST.getPointer(), // &Stride
3485 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3486 Chunk // Chunk
3487 };
3488 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003489}
3490
John McCall7f416cc2015-09-08 08:05:57 +00003491void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3492 SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003493 OpenMPDirectiveKind DKind,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003494 const OpenMPScheduleTy &ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003495 const StaticRTInput &Values) {
3496 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3497 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3498 assert(isOpenMPWorksharingDirective(DKind) &&
3499 "Expected loop-based or sections-based directive.");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003500 llvm::Value *UpdatedLocation = emitUpdateLocation(CGF, Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003501 isOpenMPLoopDirective(DKind)
3502 ? OMP_IDENT_WORK_LOOP
3503 : OMP_IDENT_WORK_SECTIONS);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003504 llvm::Value *ThreadId = getThreadID(CGF, Loc);
James Y Knight9871db02019-02-05 16:42:33 +00003505 llvm::FunctionCallee StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003506 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003507 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003508 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003509}
John McCall7f416cc2015-09-08 08:05:57 +00003510
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003511void CGOpenMPRuntime::emitDistributeStaticInit(
3512 CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003513 OpenMPDistScheduleClauseKind SchedKind,
3514 const CGOpenMPRuntime::StaticRTInput &Values) {
3515 OpenMPSchedType ScheduleNum =
3516 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003517 llvm::Value *UpdatedLocation =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003518 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003519 llvm::Value *ThreadId = getThreadID(CGF, Loc);
James Y Knight9871db02019-02-05 16:42:33 +00003520 llvm::FunctionCallee StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003521 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003522 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3523 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003524 OMPC_SCHEDULE_MODIFIER_unknown, Values);
Alexander Musmanc6388682014-12-15 07:07:06 +00003525}
3526
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003527void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
Alexey Bataevf43f7142017-09-06 16:17:35 +00003528 SourceLocation Loc,
3529 OpenMPDirectiveKind DKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003530 if (!CGF.HaveInsertPoint())
3531 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003532 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataevf43f7142017-09-06 16:17:35 +00003533 llvm::Value *Args[] = {
3534 emitUpdateLocation(CGF, Loc,
3535 isOpenMPDistributeDirective(DKind)
3536 ? OMP_IDENT_WORK_DISTRIBUTE
3537 : isOpenMPLoopDirective(DKind)
3538 ? OMP_IDENT_WORK_LOOP
3539 : OMP_IDENT_WORK_SECTIONS),
3540 getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003541 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3542 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003543}
3544
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003545void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3546 SourceLocation Loc,
3547 unsigned IVSize,
3548 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003549 if (!CGF.HaveInsertPoint())
3550 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003551 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003552 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003553 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3554}
3555
Alexander Musman92bdaab2015-03-12 13:37:50 +00003556llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3557 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003558 bool IVSigned, Address IL,
3559 Address LB, Address UB,
3560 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003561 // Call __kmpc_dispatch_next(
3562 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3563 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3564 // kmp_int[32|64] *p_stride);
3565 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003566 emitUpdateLocation(CGF, Loc),
3567 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003568 IL.getPointer(), // &isLastIter
3569 LB.getPointer(), // &Lower
3570 UB.getPointer(), // &Upper
3571 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003572 };
3573 llvm::Value *Call =
3574 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3575 return CGF.EmitScalarConversion(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003576 Call, CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/1),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003577 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003578}
3579
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003580void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3581 llvm::Value *NumThreads,
3582 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003583 if (!CGF.HaveInsertPoint())
3584 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003585 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3586 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003587 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003588 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003589 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3590 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003591}
3592
Alexey Bataev7f210c62015-06-18 13:40:03 +00003593void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3594 OpenMPProcBindClauseKind ProcBind,
3595 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003596 if (!CGF.HaveInsertPoint())
3597 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003598 // Constants for proc bind value accepted by the runtime.
3599 enum ProcBindTy {
3600 ProcBindFalse = 0,
3601 ProcBindTrue,
3602 ProcBindMaster,
3603 ProcBindClose,
3604 ProcBindSpread,
3605 ProcBindIntel,
3606 ProcBindDefault
3607 } RuntimeProcBind;
3608 switch (ProcBind) {
3609 case OMPC_PROC_BIND_master:
3610 RuntimeProcBind = ProcBindMaster;
3611 break;
3612 case OMPC_PROC_BIND_close:
3613 RuntimeProcBind = ProcBindClose;
3614 break;
3615 case OMPC_PROC_BIND_spread:
3616 RuntimeProcBind = ProcBindSpread;
3617 break;
3618 case OMPC_PROC_BIND_unknown:
3619 llvm_unreachable("Unsupported proc_bind value.");
3620 }
3621 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3622 llvm::Value *Args[] = {
3623 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3624 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3625 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3626}
3627
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003628void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3629 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003630 if (!CGF.HaveInsertPoint())
3631 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003632 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003633 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3634 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003635}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003636
Alexey Bataev62b63b12015-03-10 07:28:44 +00003637namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003638/// Indexes of fields for type kmp_task_t.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003639enum KmpTaskTFields {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003640 /// List of shared variables.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003641 KmpTaskTShareds,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003642 /// Task routine.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003643 KmpTaskTRoutine,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003644 /// Partition id for the untied tasks.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003645 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003646 /// Function with call of destructors for private variables.
3647 Data1,
3648 /// Task priority.
3649 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003650 /// (Taskloops only) Lower bound.
3651 KmpTaskTLowerBound,
3652 /// (Taskloops only) Upper bound.
3653 KmpTaskTUpperBound,
3654 /// (Taskloops only) Stride.
3655 KmpTaskTStride,
3656 /// (Taskloops only) Is last iteration flag.
3657 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003658 /// (Taskloops only) Reduction data.
3659 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003660};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003661} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003662
Samuel Antaoee8fb302016-01-06 13:42:12 +00003663bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003664 return OffloadEntriesTargetRegion.empty() &&
3665 OffloadEntriesDeviceGlobalVar.empty();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003666}
3667
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003668/// Initialize target region entry.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003669void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3670 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3671 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003672 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003673 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3674 "only required for the device "
3675 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003676 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003677 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003678 OMPTargetRegionEntryTargetRegion);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003679 ++OffloadingEntriesNum;
3680}
3681
3682void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3683 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3684 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003685 llvm::Constant *Addr, llvm::Constant *ID,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003686 OMPTargetRegionEntryKind Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003687 // If we are emitting code for a target, the entry is already initialized,
3688 // only has to be registered.
3689 if (CGM.getLangOpts().OpenMPIsDevice) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00003690 if (!hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum)) {
3691 unsigned DiagID = CGM.getDiags().getCustomDiagID(
3692 DiagnosticsEngine::Error,
3693 "Unable to find target region on line '%0' in the device code.");
3694 CGM.getDiags().Report(DiagID) << LineNum;
3695 return;
3696 }
Samuel Antao2de62b02016-02-13 23:35:10 +00003697 auto &Entry =
3698 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003699 assert(Entry.isValid() && "Entry not initialized!");
3700 Entry.setAddress(Addr);
3701 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003702 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003703 } else {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003704 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003705 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00003706 ++OffloadingEntriesNum;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003707 }
3708}
3709
3710bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003711 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3712 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003713 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3714 if (PerDevice == OffloadEntriesTargetRegion.end())
3715 return false;
3716 auto PerFile = PerDevice->second.find(FileID);
3717 if (PerFile == PerDevice->second.end())
3718 return false;
3719 auto PerParentName = PerFile->second.find(ParentName);
3720 if (PerParentName == PerFile->second.end())
3721 return false;
3722 auto PerLine = PerParentName->second.find(LineNum);
3723 if (PerLine == PerParentName->second.end())
3724 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003725 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003726 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003727 return false;
3728 return true;
3729}
3730
3731void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3732 const OffloadTargetRegionEntryInfoActTy &Action) {
3733 // Scan all target region entries and perform the provided action.
Alexey Bataev03f270c2018-03-30 18:31:07 +00003734 for (const auto &D : OffloadEntriesTargetRegion)
3735 for (const auto &F : D.second)
3736 for (const auto &P : F.second)
3737 for (const auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003738 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003739}
3740
Alexey Bataev03f270c2018-03-30 18:31:07 +00003741void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3742 initializeDeviceGlobalVarEntryInfo(StringRef Name,
3743 OMPTargetGlobalVarEntryKind Flags,
3744 unsigned Order) {
3745 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3746 "only required for the device "
3747 "code generation.");
3748 OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags);
3749 ++OffloadingEntriesNum;
3750}
Samuel Antaoee8fb302016-01-06 13:42:12 +00003751
Alexey Bataev03f270c2018-03-30 18:31:07 +00003752void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3753 registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr,
3754 CharUnits VarSize,
3755 OMPTargetGlobalVarEntryKind Flags,
3756 llvm::GlobalValue::LinkageTypes Linkage) {
3757 if (CGM.getLangOpts().OpenMPIsDevice) {
3758 auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
3759 assert(Entry.isValid() && Entry.getFlags() == Flags &&
3760 "Entry not initialized!");
3761 assert((!Entry.getAddress() || Entry.getAddress() == Addr) &&
3762 "Resetting with the new address.");
3763 if (Entry.getAddress() && hasDeviceGlobalVarEntryInfo(VarName))
3764 return;
3765 Entry.setAddress(Addr);
3766 Entry.setVarSize(VarSize);
3767 Entry.setLinkage(Linkage);
3768 } else {
3769 if (hasDeviceGlobalVarEntryInfo(VarName))
3770 return;
3771 OffloadEntriesDeviceGlobalVar.try_emplace(
3772 VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage);
3773 ++OffloadingEntriesNum;
3774 }
3775}
3776
3777void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3778 actOnDeviceGlobalVarEntriesInfo(
3779 const OffloadDeviceGlobalVarEntryInfoActTy &Action) {
3780 // Scan all target region entries and perform the provided action.
3781 for (const auto &E : OffloadEntriesDeviceGlobalVar)
3782 Action(E.getKey(), E.getValue());
Samuel Antaoee8fb302016-01-06 13:42:12 +00003783}
3784
3785llvm::Function *
3786CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003787 // If we don't have entries or if we are emitting code for the device, we
3788 // don't need to do anything.
3789 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3790 return nullptr;
3791
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003792 llvm::Module &M = CGM.getModule();
3793 ASTContext &C = CGM.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003794
3795 // Get list of devices we care about
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003796 const std::vector<llvm::Triple> &Devices = CGM.getLangOpts().OMPTargetTriples;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003797
3798 // We should be creating an offloading descriptor only if there are devices
3799 // specified.
3800 assert(!Devices.empty() && "No OpenMP offloading devices??");
3801
3802 // Create the external variables that will point to the begin and end of the
3803 // host entries section. These will be defined by the linker.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003804 llvm::Type *OffloadEntryTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00003805 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
Alexey Bataev18fa2322018-05-02 14:20:50 +00003806 std::string EntriesBeginName = getName({"omp_offloading", "entries_begin"});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003807 auto *HostEntriesBegin = new llvm::GlobalVariable(
Samuel Antaoee8fb302016-01-06 13:42:12 +00003808 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003809 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003810 EntriesBeginName);
3811 std::string EntriesEndName = getName({"omp_offloading", "entries_end"});
3812 auto *HostEntriesEnd =
3813 new llvm::GlobalVariable(M, OffloadEntryTy, /*isConstant=*/true,
3814 llvm::GlobalValue::ExternalLinkage,
3815 /*Initializer=*/nullptr, EntriesEndName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003816
3817 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003818 auto *DeviceImageTy = cast<llvm::StructType>(
3819 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003820 ConstantInitBuilder DeviceImagesBuilder(CGM);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003821 ConstantArrayBuilder DeviceImagesEntries =
3822 DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003823
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003824 for (const llvm::Triple &Device : Devices) {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003825 StringRef T = Device.getTriple();
Alexey Bataev18fa2322018-05-02 14:20:50 +00003826 std::string BeginName = getName({"omp_offloading", "img_start", ""});
Samuel Antaoee8fb302016-01-06 13:42:12 +00003827 auto *ImgBegin = new llvm::GlobalVariable(
Alexey Bataev62a4cb02018-07-31 18:27:42 +00003828 M, CGM.Int8Ty, /*isConstant=*/true,
3829 llvm::GlobalValue::ExternalWeakLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003830 /*Initializer=*/nullptr, Twine(BeginName).concat(T));
3831 std::string EndName = getName({"omp_offloading", "img_end", ""});
Samuel Antaoee8fb302016-01-06 13:42:12 +00003832 auto *ImgEnd = new llvm::GlobalVariable(
Alexey Bataev62a4cb02018-07-31 18:27:42 +00003833 M, CGM.Int8Ty, /*isConstant=*/true,
3834 llvm::GlobalValue::ExternalWeakLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003835 /*Initializer=*/nullptr, Twine(EndName).concat(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003836
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003837 llvm::Constant *Data[] = {ImgBegin, ImgEnd, HostEntriesBegin,
3838 HostEntriesEnd};
3839 createConstantGlobalStructAndAddToParent(CGM, getTgtDeviceImageQTy(), Data,
3840 DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003841 }
3842
3843 // Create device images global array.
Alexey Bataev18fa2322018-05-02 14:20:50 +00003844 std::string ImagesName = getName({"omp_offloading", "device_images"});
John McCall6c9f1fdb2016-11-19 08:17:24 +00003845 llvm::GlobalVariable *DeviceImages =
Alexey Bataev18fa2322018-05-02 14:20:50 +00003846 DeviceImagesEntries.finishAndCreateGlobal(ImagesName,
3847 CGM.getPointerAlign(),
3848 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003849 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003850
3851 // This is a Zero array to be used in the creation of the constant expressions
3852 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3853 llvm::Constant::getNullValue(CGM.Int32Ty)};
3854
3855 // Create the target region descriptor.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003856 llvm::Constant *Data[] = {
3857 llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
3858 llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3859 DeviceImages, Index),
3860 HostEntriesBegin, HostEntriesEnd};
Alexey Bataev18fa2322018-05-02 14:20:50 +00003861 std::string Descriptor = getName({"omp_offloading", "descriptor"});
Mike Ricee1ca7b62018-08-29 15:45:11 +00003862 llvm::GlobalVariable *Desc = createGlobalStruct(
3863 CGM, getTgtBinaryDescriptorQTy(), /*IsConstant=*/true, Data, Descriptor);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003864
3865 // Emit code to register or unregister the descriptor at execution
3866 // startup or closing, respectively.
3867
Alexey Bataev03f270c2018-03-30 18:31:07 +00003868 llvm::Function *UnRegFn;
3869 {
3870 FunctionArgList Args;
3871 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
3872 Args.push_back(&DummyPtr);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003873
Alexey Bataev03f270c2018-03-30 18:31:07 +00003874 CodeGenFunction CGF(CGM);
3875 // Disable debug info for global (de-)initializer because they are not part
3876 // of some particular construct.
3877 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003878 const auto &FI =
3879 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3880 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003881 std::string UnregName = getName({"omp_offloading", "descriptor_unreg"});
3882 UnRegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, UnregName, FI);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003883 CGF.StartFunction(GlobalDecl(), C.VoidTy, UnRegFn, FI, Args);
3884 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3885 Desc);
3886 CGF.FinishFunction();
3887 }
3888 llvm::Function *RegFn;
3889 {
3890 CodeGenFunction CGF(CGM);
3891 // Disable debug info for global (de-)initializer because they are not part
3892 // of some particular construct.
3893 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003894 const auto &FI = CGM.getTypes().arrangeNullaryFunction();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003895 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Sergey Dmitrievbde9cf92018-08-03 20:19:28 +00003896
3897 // Encode offload target triples into the registration function name. It
3898 // will serve as a comdat key for the registration/unregistration code for
3899 // this particular combination of offloading targets.
3900 SmallVector<StringRef, 4U> RegFnNameParts(Devices.size() + 2U);
3901 RegFnNameParts[0] = "omp_offloading";
3902 RegFnNameParts[1] = "descriptor_reg";
3903 llvm::transform(Devices, std::next(RegFnNameParts.begin(), 2),
3904 [](const llvm::Triple &T) -> const std::string& {
3905 return T.getTriple();
3906 });
3907 llvm::sort(std::next(RegFnNameParts.begin(), 2), RegFnNameParts.end());
3908 std::string Descriptor = getName(RegFnNameParts);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003909 RegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, Descriptor, FI);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003910 CGF.StartFunction(GlobalDecl(), C.VoidTy, RegFn, FI, FunctionArgList());
3911 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib), Desc);
3912 // Create a variable to drive the registration and unregistration of the
3913 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3914 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(),
3915 SourceLocation(), nullptr, C.CharTy,
3916 ImplicitParamDecl::Other);
3917 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3918 CGF.FinishFunction();
3919 }
George Rokos29d0f002017-05-27 03:03:13 +00003920 if (CGM.supportsCOMDAT()) {
3921 // It is sufficient to call registration function only once, so create a
3922 // COMDAT group for registration/unregistration functions and associated
3923 // data. That would reduce startup time and code size. Registration
3924 // function serves as a COMDAT group key.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003925 llvm::Comdat *ComdatKey = M.getOrInsertComdat(RegFn->getName());
George Rokos29d0f002017-05-27 03:03:13 +00003926 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3927 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3928 RegFn->setComdat(ComdatKey);
3929 UnRegFn->setComdat(ComdatKey);
3930 DeviceImages->setComdat(ComdatKey);
3931 Desc->setComdat(ComdatKey);
3932 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003933 return RegFn;
3934}
3935
Alexey Bataev03f270c2018-03-30 18:31:07 +00003936void CGOpenMPRuntime::createOffloadEntry(
3937 llvm::Constant *ID, llvm::Constant *Addr, uint64_t Size, int32_t Flags,
3938 llvm::GlobalValue::LinkageTypes Linkage) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003939 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003940 llvm::Module &M = CGM.getModule();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003941 llvm::LLVMContext &C = M.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003942
3943 // Create constant string with the name.
3944 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3945
Alexey Bataev18fa2322018-05-02 14:20:50 +00003946 std::string StringName = getName({"omp_offloading", "entry_name"});
3947 auto *Str = new llvm::GlobalVariable(
3948 M, StrPtrInit->getType(), /*isConstant=*/true,
3949 llvm::GlobalValue::InternalLinkage, StrPtrInit, StringName);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003950 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003951
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003952 llvm::Constant *Data[] = {llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy),
3953 llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy),
3954 llvm::ConstantInt::get(CGM.SizeTy, Size),
3955 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
3956 llvm::ConstantInt::get(CGM.Int32Ty, 0)};
Alexey Bataev18fa2322018-05-02 14:20:50 +00003957 std::string EntryName = getName({"omp_offloading", "entry", ""});
Mike Ricee1ca7b62018-08-29 15:45:11 +00003958 llvm::GlobalVariable *Entry = createGlobalStruct(
3959 CGM, getTgtOffloadEntryQTy(), /*IsConstant=*/true, Data,
3960 Twine(EntryName).concat(Name), llvm::GlobalValue::WeakAnyLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003961
3962 // The entry has to be created in the section the linker expects it to be.
Alexey Bataev18fa2322018-05-02 14:20:50 +00003963 std::string Section = getName({"omp_offloading", "entries"});
3964 Entry->setSection(Section);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003965}
3966
3967void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3968 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003969 // can easily figure out what to emit. The produced metadata looks like
3970 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003971 //
3972 // !omp_offload.info = !{!1, ...}
3973 //
3974 // Right now we only generate metadata for function that contain target
3975 // regions.
3976
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003977 // If we do not have entries, we don't need to do anything.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003978 if (OffloadEntriesInfoManager.empty())
3979 return;
3980
3981 llvm::Module &M = CGM.getModule();
3982 llvm::LLVMContext &C = M.getContext();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003983 SmallVector<const OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
Samuel Antaoee8fb302016-01-06 13:42:12 +00003984 OrderedEntries(OffloadEntriesInfoManager.size());
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00003985 llvm::SmallVector<StringRef, 16> ParentFunctions(
3986 OffloadEntriesInfoManager.size());
Samuel Antaoee8fb302016-01-06 13:42:12 +00003987
Simon Pilgrim2c518802017-03-30 14:13:19 +00003988 // Auxiliary methods to create metadata values and strings.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003989 auto &&GetMDInt = [this](unsigned V) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003990 return llvm::ConstantAsMetadata::get(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003991 llvm::ConstantInt::get(CGM.Int32Ty, V));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003992 };
3993
Alexey Bataev03f270c2018-03-30 18:31:07 +00003994 auto &&GetMDString = [&C](StringRef V) { return llvm::MDString::get(C, V); };
3995
3996 // Create the offloading info metadata node.
3997 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003998
3999 // Create function that emits metadata for each target region entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00004000 auto &&TargetRegionMetadataEmitter =
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00004001 [&C, MD, &OrderedEntries, &ParentFunctions, &GetMDInt, &GetMDString](
Alexey Bataev03f270c2018-03-30 18:31:07 +00004002 unsigned DeviceID, unsigned FileID, StringRef ParentName,
4003 unsigned Line,
4004 const OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
4005 // Generate metadata for target regions. Each entry of this metadata
4006 // contains:
4007 // - Entry 0 -> Kind of this type of metadata (0).
4008 // - Entry 1 -> Device ID of the file where the entry was identified.
4009 // - Entry 2 -> File ID of the file where the entry was identified.
4010 // - Entry 3 -> Mangled name of the function where the entry was
4011 // identified.
4012 // - Entry 4 -> Line in the file where the entry was identified.
4013 // - Entry 5 -> Order the entry was created.
4014 // The first element of the metadata node is the kind.
4015 llvm::Metadata *Ops[] = {GetMDInt(E.getKind()), GetMDInt(DeviceID),
4016 GetMDInt(FileID), GetMDString(ParentName),
4017 GetMDInt(Line), GetMDInt(E.getOrder())};
Samuel Antaoee8fb302016-01-06 13:42:12 +00004018
Alexey Bataev03f270c2018-03-30 18:31:07 +00004019 // Save this entry in the right position of the ordered entries array.
4020 OrderedEntries[E.getOrder()] = &E;
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00004021 ParentFunctions[E.getOrder()] = ParentName;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004022
Alexey Bataev03f270c2018-03-30 18:31:07 +00004023 // Add metadata to the named metadata node.
4024 MD->addOperand(llvm::MDNode::get(C, Ops));
4025 };
Samuel Antaoee8fb302016-01-06 13:42:12 +00004026
4027 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
4028 TargetRegionMetadataEmitter);
4029
Alexey Bataev03f270c2018-03-30 18:31:07 +00004030 // Create function that emits metadata for each device global variable entry;
4031 auto &&DeviceGlobalVarMetadataEmitter =
4032 [&C, &OrderedEntries, &GetMDInt, &GetMDString,
4033 MD](StringRef MangledName,
4034 const OffloadEntriesInfoManagerTy::OffloadEntryInfoDeviceGlobalVar
4035 &E) {
4036 // Generate metadata for global variables. Each entry of this metadata
4037 // contains:
4038 // - Entry 0 -> Kind of this type of metadata (1).
4039 // - Entry 1 -> Mangled name of the variable.
4040 // - Entry 2 -> Declare target kind.
4041 // - Entry 3 -> Order the entry was created.
4042 // The first element of the metadata node is the kind.
4043 llvm::Metadata *Ops[] = {
4044 GetMDInt(E.getKind()), GetMDString(MangledName),
4045 GetMDInt(E.getFlags()), GetMDInt(E.getOrder())};
4046
4047 // Save this entry in the right position of the ordered entries array.
4048 OrderedEntries[E.getOrder()] = &E;
4049
4050 // Add metadata to the named metadata node.
4051 MD->addOperand(llvm::MDNode::get(C, Ops));
4052 };
4053
4054 OffloadEntriesInfoManager.actOnDeviceGlobalVarEntriesInfo(
4055 DeviceGlobalVarMetadataEmitter);
4056
4057 for (const auto *E : OrderedEntries) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004058 assert(E && "All ordered entries must exist!");
Alexey Bataev03f270c2018-03-30 18:31:07 +00004059 if (const auto *CE =
Samuel Antaoee8fb302016-01-06 13:42:12 +00004060 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
4061 E)) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004062 if (!CE->getID() || !CE->getAddress()) {
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00004063 // Do not blame the entry if the parent funtion is not emitted.
4064 StringRef FnName = ParentFunctions[CE->getOrder()];
4065 if (!CGM.GetGlobalValue(FnName))
4066 continue;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004067 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4068 DiagnosticsEngine::Error,
Alexey Bataev7f01d202018-07-16 18:12:18 +00004069 "Offloading entry for target region is incorrect: either the "
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004070 "address or the ID is invalid.");
4071 CGM.getDiags().Report(DiagID);
4072 continue;
4073 }
Alexey Bataev34f8a702018-03-28 14:28:54 +00004074 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0,
Alexey Bataev03f270c2018-03-30 18:31:07 +00004075 CE->getFlags(), llvm::GlobalValue::WeakAnyLinkage);
4076 } else if (const auto *CE =
4077 dyn_cast<OffloadEntriesInfoManagerTy::
4078 OffloadEntryInfoDeviceGlobalVar>(E)) {
Alexey Bataevc52f01d2018-07-16 20:05:25 +00004079 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags =
4080 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
4081 CE->getFlags());
4082 switch (Flags) {
4083 case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo: {
4084 if (!CE->getAddress()) {
4085 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4086 DiagnosticsEngine::Error,
4087 "Offloading entry for declare target variable is incorrect: the "
4088 "address is invalid.");
4089 CGM.getDiags().Report(DiagID);
4090 continue;
4091 }
Alexey Bataevb4dd6d22018-08-29 20:41:37 +00004092 // The vaiable has no definition - no need to add the entry.
4093 if (CE->getVarSize().isZero())
4094 continue;
Alexey Bataevc52f01d2018-07-16 20:05:25 +00004095 break;
4096 }
4097 case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink:
4098 assert(((CGM.getLangOpts().OpenMPIsDevice && !CE->getAddress()) ||
4099 (!CGM.getLangOpts().OpenMPIsDevice && CE->getAddress())) &&
4100 "Declaret target link address is set.");
4101 if (CGM.getLangOpts().OpenMPIsDevice)
4102 continue;
4103 if (!CE->getAddress()) {
4104 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4105 DiagnosticsEngine::Error,
4106 "Offloading entry for declare target variable is incorrect: the "
4107 "address is invalid.");
4108 CGM.getDiags().Report(DiagID);
4109 continue;
4110 }
4111 break;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004112 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00004113 createOffloadEntry(CE->getAddress(), CE->getAddress(),
Alexey Bataevc52f01d2018-07-16 20:05:25 +00004114 CE->getVarSize().getQuantity(), Flags,
Alexey Bataev03f270c2018-03-30 18:31:07 +00004115 CE->getLinkage());
4116 } else {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004117 llvm_unreachable("Unsupported entry kind.");
Alexey Bataev03f270c2018-03-30 18:31:07 +00004118 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004119 }
4120}
4121
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004122/// Loads all the offload entries information from the host IR
Samuel Antaoee8fb302016-01-06 13:42:12 +00004123/// metadata.
4124void CGOpenMPRuntime::loadOffloadInfoMetadata() {
4125 // If we are in target mode, load the metadata from the host IR. This code has
4126 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
4127
4128 if (!CGM.getLangOpts().OpenMPIsDevice)
4129 return;
4130
4131 if (CGM.getLangOpts().OMPHostIRFile.empty())
4132 return;
4133
4134 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004135 if (auto EC = Buf.getError()) {
4136 CGM.getDiags().Report(diag::err_cannot_open_file)
4137 << CGM.getLangOpts().OMPHostIRFile << EC.message();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004138 return;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004139 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004140
4141 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00004142 auto ME = expectedToErrorOrAndEmitErrors(
4143 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004144
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004145 if (auto EC = ME.getError()) {
4146 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4147 DiagnosticsEngine::Error, "Unable to parse host IR file '%0':'%1'");
4148 CGM.getDiags().Report(DiagID)
4149 << CGM.getLangOpts().OMPHostIRFile << EC.message();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004150 return;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004151 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004152
4153 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
4154 if (!MD)
4155 return;
4156
George Burgess IV00f70bd2018-03-01 05:43:23 +00004157 for (llvm::MDNode *MN : MD->operands()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004158 auto &&GetMDInt = [MN](unsigned Idx) {
4159 auto *V = cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004160 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
4161 };
4162
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004163 auto &&GetMDString = [MN](unsigned Idx) {
4164 auto *V = cast<llvm::MDString>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004165 return V->getString();
4166 };
4167
Alexey Bataev03f270c2018-03-30 18:31:07 +00004168 switch (GetMDInt(0)) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004169 default:
4170 llvm_unreachable("Unexpected metadata!");
4171 break;
4172 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
Alexey Bataev34f8a702018-03-28 14:28:54 +00004173 OffloadingEntryInfoTargetRegion:
Samuel Antaoee8fb302016-01-06 13:42:12 +00004174 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
Alexey Bataev03f270c2018-03-30 18:31:07 +00004175 /*DeviceID=*/GetMDInt(1), /*FileID=*/GetMDInt(2),
4176 /*ParentName=*/GetMDString(3), /*Line=*/GetMDInt(4),
4177 /*Order=*/GetMDInt(5));
4178 break;
4179 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
4180 OffloadingEntryInfoDeviceGlobalVar:
4181 OffloadEntriesInfoManager.initializeDeviceGlobalVarEntryInfo(
4182 /*MangledName=*/GetMDString(1),
4183 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
4184 /*Flags=*/GetMDInt(2)),
4185 /*Order=*/GetMDInt(3));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004186 break;
4187 }
4188 }
4189}
4190
Alexey Bataev62b63b12015-03-10 07:28:44 +00004191void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
4192 if (!KmpRoutineEntryPtrTy) {
4193 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004194 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004195 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
4196 FunctionProtoType::ExtProtoInfo EPI;
4197 KmpRoutineEntryPtrQTy = C.getPointerType(
4198 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
4199 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
4200 }
4201}
4202
Samuel Antaoee8fb302016-01-06 13:42:12 +00004203QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004204 // Make sure the type of the entry is already created. This is the type we
4205 // have to create:
4206 // struct __tgt_offload_entry{
4207 // void *addr; // Pointer to the offload entry info.
4208 // // (function or global)
4209 // char *name; // Name of the function or global.
4210 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00004211 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
4212 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004213 // };
4214 if (TgtOffloadEntryQTy.isNull()) {
4215 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004216 RecordDecl *RD = C.buildImplicitRecord("__tgt_offload_entry");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004217 RD->startDefinition();
4218 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4219 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
4220 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00004221 addFieldToRecordDecl(
4222 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4223 addFieldToRecordDecl(
4224 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004225 RD->completeDefinition();
Jonas Hahnfeld5e4df282018-01-18 15:38:03 +00004226 RD->addAttr(PackedAttr::CreateImplicit(C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004227 TgtOffloadEntryQTy = C.getRecordType(RD);
4228 }
4229 return TgtOffloadEntryQTy;
4230}
4231
4232QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
4233 // These are the types we need to build:
4234 // struct __tgt_device_image{
4235 // void *ImageStart; // Pointer to the target code start.
4236 // void *ImageEnd; // Pointer to the target code end.
4237 // // We also add the host entries to the device image, as it may be useful
4238 // // for the target runtime to have access to that information.
4239 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
4240 // // the entries.
4241 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4242 // // entries (non inclusive).
4243 // };
4244 if (TgtDeviceImageQTy.isNull()) {
4245 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004246 RecordDecl *RD = C.buildImplicitRecord("__tgt_device_image");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004247 RD->startDefinition();
4248 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4249 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4250 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4251 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4252 RD->completeDefinition();
4253 TgtDeviceImageQTy = C.getRecordType(RD);
4254 }
4255 return TgtDeviceImageQTy;
4256}
4257
4258QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
4259 // struct __tgt_bin_desc{
4260 // int32_t NumDevices; // Number of devices supported.
4261 // __tgt_device_image *DeviceImages; // Arrays of device images
4262 // // (one per device).
4263 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
4264 // // entries.
4265 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4266 // // entries (non inclusive).
4267 // };
4268 if (TgtBinaryDescriptorQTy.isNull()) {
4269 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004270 RecordDecl *RD = C.buildImplicitRecord("__tgt_bin_desc");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004271 RD->startDefinition();
4272 addFieldToRecordDecl(
4273 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4274 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
4275 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4276 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4277 RD->completeDefinition();
4278 TgtBinaryDescriptorQTy = C.getRecordType(RD);
4279 }
4280 return TgtBinaryDescriptorQTy;
4281}
4282
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004283namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00004284struct PrivateHelpersTy {
4285 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
4286 const VarDecl *PrivateElemInit)
4287 : Original(Original), PrivateCopy(PrivateCopy),
4288 PrivateElemInit(PrivateElemInit) {}
4289 const VarDecl *Original;
4290 const VarDecl *PrivateCopy;
4291 const VarDecl *PrivateElemInit;
4292};
4293typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00004294} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004295
Alexey Bataev9e034042015-05-05 04:05:12 +00004296static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00004297createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004298 if (!Privates.empty()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004299 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004300 // Build struct .kmp_privates_t. {
4301 // /* private vars */
4302 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004303 RecordDecl *RD = C.buildImplicitRecord(".kmp_privates.t");
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004304 RD->startDefinition();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004305 for (const auto &Pair : Privates) {
4306 const VarDecl *VD = Pair.second.Original;
4307 QualType Type = VD->getType().getNonReferenceType();
4308 FieldDecl *FD = addFieldToRecordDecl(C, RD, Type);
Alexey Bataevc71a4092015-09-11 10:29:41 +00004309 if (VD->hasAttrs()) {
4310 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
4311 E(VD->getAttrs().end());
4312 I != E; ++I)
4313 FD->addAttr(*I);
4314 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004315 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004316 RD->completeDefinition();
4317 return RD;
4318 }
4319 return nullptr;
4320}
4321
Alexey Bataev9e034042015-05-05 04:05:12 +00004322static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00004323createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
4324 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004325 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004326 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004327 // Build struct kmp_task_t {
4328 // void * shareds;
4329 // kmp_routine_entry_t routine;
4330 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00004331 // kmp_cmplrdata_t data1;
4332 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00004333 // For taskloops additional fields:
4334 // kmp_uint64 lb;
4335 // kmp_uint64 ub;
4336 // kmp_int64 st;
4337 // kmp_int32 liter;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004338 // void * reductions;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004339 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004340 RecordDecl *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004341 UD->startDefinition();
4342 addFieldToRecordDecl(C, UD, KmpInt32Ty);
4343 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
4344 UD->completeDefinition();
4345 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004346 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t");
Alexey Bataev62b63b12015-03-10 07:28:44 +00004347 RD->startDefinition();
4348 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4349 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
4350 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004351 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
4352 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004353 if (isOpenMPTaskLoopDirective(Kind)) {
4354 QualType KmpUInt64Ty =
4355 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4356 QualType KmpInt64Ty =
4357 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4358 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4359 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4360 addFieldToRecordDecl(C, RD, KmpInt64Ty);
4361 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004362 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004363 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004364 RD->completeDefinition();
4365 return RD;
4366}
4367
4368static RecordDecl *
4369createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004370 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004371 ASTContext &C = CGM.getContext();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004372 // Build struct kmp_task_t_with_privates {
4373 // kmp_task_t task_data;
4374 // .kmp_privates_t. privates;
4375 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004376 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004377 RD->startDefinition();
4378 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004379 if (const RecordDecl *PrivateRD = createPrivatesRecordDecl(CGM, Privates))
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004380 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004381 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004382 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004383}
4384
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004385/// Emit a proxy function which accepts kmp_task_t as the second
Alexey Bataev62b63b12015-03-10 07:28:44 +00004386/// argument.
4387/// \code
4388/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004389/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00004390/// For taskloops:
4391/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004392/// tt->reductions, tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004393/// return 0;
4394/// }
4395/// \endcode
James Y Knight9871db02019-02-05 16:42:33 +00004396static llvm::Function *
Alexey Bataev62b63b12015-03-10 07:28:44 +00004397emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00004398 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
4399 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004400 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
James Y Knight9871db02019-02-05 16:42:33 +00004401 QualType SharedsPtrTy, llvm::Function *TaskFunction,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004402 llvm::Value *TaskPrivatesMap) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004403 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004404 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004405 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4406 ImplicitParamDecl::Other);
4407 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4408 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4409 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004410 Args.push_back(&GtidArg);
4411 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004412 const auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004413 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004414 llvm::FunctionType *TaskEntryTy =
4415 CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004416 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_entry", ""});
4417 auto *TaskEntry = llvm::Function::Create(
4418 TaskEntryTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004419 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskEntry, TaskEntryFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004420 TaskEntry->setDoesNotRecurse();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004421 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004422 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args,
4423 Loc, Loc);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004424
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004425 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00004426 // tt,
4427 // For taskloops:
4428 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
4429 // tt->task_data.shareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004430 llvm::Value *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00004431 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00004432 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4433 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4434 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004435 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004436 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004437 LValue Base =
4438 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004439 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004440 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004441 LValue PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
4442 llvm::Value *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004443
4444 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004445 LValue SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
4446 llvm::Value *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev1e491372018-01-23 18:44:14 +00004447 CGF.EmitLoadOfScalar(SharedsLVal, Loc),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004448 CGF.ConvertTypeForMem(SharedsPtrTy));
4449
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004450 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4451 llvm::Value *PrivatesParam;
4452 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004453 LValue PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004454 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004455 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004456 } else {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004457 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004458 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004459
Alexey Bataev7292c292016-04-25 12:22:29 +00004460 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
4461 TaskPrivatesMap,
4462 CGF.Builder
4463 .CreatePointerBitCastOrAddrSpaceCast(
4464 TDBase.getAddress(), CGF.VoidPtrTy)
4465 .getPointer()};
4466 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
4467 std::end(CommonArgs));
4468 if (isOpenMPTaskLoopDirective(Kind)) {
4469 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004470 LValue LBLVal = CGF.EmitLValueForField(Base, *LBFI);
4471 llvm::Value *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004472 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004473 LValue UBLVal = CGF.EmitLValueForField(Base, *UBFI);
4474 llvm::Value *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004475 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004476 LValue StLVal = CGF.EmitLValueForField(Base, *StFI);
4477 llvm::Value *StParam = CGF.EmitLoadOfScalar(StLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004478 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004479 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4480 llvm::Value *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004481 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004482 LValue RLVal = CGF.EmitLValueForField(Base, *RFI);
4483 llvm::Value *RParam = CGF.EmitLoadOfScalar(RLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004484 CallArgs.push_back(LBParam);
4485 CallArgs.push_back(UBParam);
4486 CallArgs.push_back(StParam);
4487 CallArgs.push_back(LIParam);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004488 CallArgs.push_back(RParam);
Alexey Bataev7292c292016-04-25 12:22:29 +00004489 }
4490 CallArgs.push_back(SharedsParam);
4491
Alexey Bataev3c595a62017-08-14 15:01:03 +00004492 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
4493 CallArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004494 CGF.EmitStoreThroughLValue(RValue::get(CGF.Builder.getInt32(/*C=*/0)),
4495 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004496 CGF.FinishFunction();
4497 return TaskEntry;
4498}
4499
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004500static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
4501 SourceLocation Loc,
4502 QualType KmpInt32Ty,
4503 QualType KmpTaskTWithPrivatesPtrQTy,
4504 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004505 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004506 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004507 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4508 ImplicitParamDecl::Other);
4509 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4510 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4511 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004512 Args.push_back(&GtidArg);
4513 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004514 const auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004515 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004516 llvm::FunctionType *DestructorFnTy =
4517 CGM.getTypes().GetFunctionType(DestructorFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004518 std::string Name =
4519 CGM.getOpenMPRuntime().getName({"omp_task_destructor", ""});
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004520 auto *DestructorFn =
4521 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00004522 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004523 CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004524 DestructorFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004525 DestructorFn->setDoesNotRecurse();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004526 CodeGenFunction CGF(CGM);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004527 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004528 Args, Loc, Loc);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004529
Alexey Bataev31300ed2016-02-04 11:27:03 +00004530 LValue Base = CGF.EmitLoadOfPointerLValue(
4531 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4532 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004533 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004534 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
4535 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004536 Base = CGF.EmitLValueForField(Base, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004537 for (const auto *Field :
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004538 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004539 if (QualType::DestructionKind DtorKind =
4540 Field->getType().isDestructedType()) {
4541 LValue FieldLValue = CGF.EmitLValueForField(Base, Field);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004542 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
4543 }
4544 }
4545 CGF.FinishFunction();
4546 return DestructorFn;
4547}
4548
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004549/// Emit a privates mapping function for correct handling of private and
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004550/// firstprivate variables.
4551/// \code
4552/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
4553/// **noalias priv1,..., <tyn> **noalias privn) {
4554/// *priv1 = &.privates.priv1;
4555/// ...;
4556/// *privn = &.privates.privn;
4557/// }
4558/// \endcode
4559static llvm::Value *
4560emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00004561 ArrayRef<const Expr *> PrivateVars,
4562 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004563 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004564 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004565 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004566 ASTContext &C = CGM.getContext();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004567 FunctionArgList Args;
4568 ImplicitParamDecl TaskPrivatesArg(
4569 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00004570 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
4571 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004572 Args.push_back(&TaskPrivatesArg);
4573 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
4574 unsigned Counter = 1;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004575 for (const Expr *E : PrivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004576 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004577 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4578 C.getPointerType(C.getPointerType(E->getType()))
4579 .withConst()
4580 .withRestrict(),
4581 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004582 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004583 PrivateVarsPos[VD] = Counter;
4584 ++Counter;
4585 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004586 for (const Expr *E : FirstprivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004587 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004588 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4589 C.getPointerType(C.getPointerType(E->getType()))
4590 .withConst()
4591 .withRestrict(),
4592 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004593 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004594 PrivateVarsPos[VD] = Counter;
4595 ++Counter;
4596 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004597 for (const Expr *E : LastprivateVars) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004598 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004599 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4600 C.getPointerType(C.getPointerType(E->getType()))
4601 .withConst()
4602 .withRestrict(),
4603 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004604 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004605 PrivateVarsPos[VD] = Counter;
4606 ++Counter;
4607 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004608 const auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004609 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004610 llvm::FunctionType *TaskPrivatesMapTy =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004611 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004612 std::string Name =
4613 CGM.getOpenMPRuntime().getName({"omp_task_privates_map", ""});
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004614 auto *TaskPrivatesMap = llvm::Function::Create(
Alexey Bataev18fa2322018-05-02 14:20:50 +00004615 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage, Name,
4616 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004617 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004618 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00004619 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00004620 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00004621 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004622 CodeGenFunction CGF(CGM);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004623 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004624 TaskPrivatesMapFnInfo, Args, Loc, Loc);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004625
4626 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00004627 LValue Base = CGF.EmitLoadOfPointerLValue(
4628 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4629 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004630 const auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004631 Counter = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004632 for (const FieldDecl *Field : PrivatesQTyRD->fields()) {
4633 LValue FieldLVal = CGF.EmitLValueForField(Base, Field);
4634 const VarDecl *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
4635 LValue RefLVal =
4636 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
4637 LValue RefLoadLVal = CGF.EmitLoadOfPointerLValue(
Alexey Bataev31300ed2016-02-04 11:27:03 +00004638 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00004639 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004640 ++Counter;
4641 }
4642 CGF.FinishFunction();
4643 return TaskPrivatesMap;
4644}
4645
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004646static bool stable_sort_comparator(const PrivateDataTy P1,
4647 const PrivateDataTy P2) {
4648 return P1.first > P2.first;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004649}
4650
Alexey Bataevf93095a2016-05-05 08:46:22 +00004651/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00004652static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004653 const OMPExecutableDirective &D,
4654 Address KmpTaskSharedsPtr, LValue TDBase,
4655 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4656 QualType SharedsTy, QualType SharedsPtrTy,
4657 const OMPTaskDataTy &Data,
4658 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004659 ASTContext &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004660 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4661 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004662 OpenMPDirectiveKind Kind = isOpenMPTaskLoopDirective(D.getDirectiveKind())
4663 ? OMPD_taskloop
4664 : OMPD_task;
4665 const CapturedStmt &CS = *D.getCapturedStmt(Kind);
4666 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004667 LValue SrcBase;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004668 bool IsTargetTask =
4669 isOpenMPTargetDataManagementDirective(D.getDirectiveKind()) ||
4670 isOpenMPTargetExecutionDirective(D.getDirectiveKind());
4671 // For target-based directives skip 3 firstprivate arrays BasePointersArray,
4672 // PointersArray and SizesArray. The original variables for these arrays are
4673 // not captured and we get their addresses explicitly.
4674 if ((!IsTargetTask && !Data.FirstprivateVars.empty()) ||
Alexey Bataev8451efa2018-01-15 19:06:12 +00004675 (IsTargetTask && KmpTaskSharedsPtr.isValid())) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004676 SrcBase = CGF.MakeAddrLValue(
4677 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4678 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4679 SharedsTy);
4680 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004681 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004682 for (const PrivateDataTy &Pair : Privates) {
4683 const VarDecl *VD = Pair.second.PrivateCopy;
4684 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004685 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4686 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004687 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004688 if (const VarDecl *Elem = Pair.second.PrivateElemInit) {
4689 const VarDecl *OriginalVD = Pair.second.Original;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004690 // Check if the variable is the target-based BasePointersArray,
4691 // PointersArray or SizesArray.
4692 LValue SharedRefLValue;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004693 QualType Type = OriginalVD->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004694 const FieldDecl *SharedField = CapturesInfo.lookup(OriginalVD);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004695 if (IsTargetTask && !SharedField) {
4696 assert(isa<ImplicitParamDecl>(OriginalVD) &&
4697 isa<CapturedDecl>(OriginalVD->getDeclContext()) &&
4698 cast<CapturedDecl>(OriginalVD->getDeclContext())
4699 ->getNumParams() == 0 &&
4700 isa<TranslationUnitDecl>(
4701 cast<CapturedDecl>(OriginalVD->getDeclContext())
4702 ->getDeclContext()) &&
4703 "Expected artificial target data variable.");
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004704 SharedRefLValue =
4705 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type);
4706 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004707 SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4708 SharedRefLValue = CGF.MakeAddrLValue(
4709 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
4710 SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl),
4711 SharedRefLValue.getTBAAInfo());
4712 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004713 if (Type->isArrayType()) {
4714 // Initialize firstprivate array.
4715 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4716 // Perform simple memcpy.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004717 CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004718 } else {
4719 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00004720 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00004721 CGF.EmitOMPAggregateAssign(
4722 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4723 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4724 Address SrcElement) {
4725 // Clean up any temporaries needed by the initialization.
4726 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4727 InitScope.addPrivate(
4728 Elem, [SrcElement]() -> Address { return SrcElement; });
4729 (void)InitScope.Privatize();
4730 // Emit initialization for single element.
4731 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4732 CGF, &CapturesInfo);
4733 CGF.EmitAnyExprToMem(Init, DestElement,
4734 Init->getType().getQualifiers(),
4735 /*IsInitializer=*/false);
4736 });
4737 }
4738 } else {
4739 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4740 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4741 return SharedRefLValue.getAddress();
4742 });
4743 (void)InitScope.Privatize();
4744 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4745 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4746 /*capturedByInit=*/false);
4747 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004748 } else {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004749 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004750 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004751 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004752 ++FI;
4753 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004754}
4755
4756/// Check if duplication function is required for taskloops.
4757static bool checkInitIsRequired(CodeGenFunction &CGF,
4758 ArrayRef<PrivateDataTy> Privates) {
4759 bool InitRequired = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004760 for (const PrivateDataTy &Pair : Privates) {
4761 const VarDecl *VD = Pair.second.PrivateCopy;
4762 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004763 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4764 !CGF.isTrivialInitializer(Init));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004765 if (InitRequired)
4766 break;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004767 }
4768 return InitRequired;
4769}
4770
4771
4772/// Emit task_dup function (for initialization of
4773/// private/firstprivate/lastprivate vars and last_iter flag)
4774/// \code
4775/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4776/// lastpriv) {
4777/// // setup lastprivate flag
4778/// task_dst->last = lastpriv;
4779/// // could be constructor calls here...
4780/// }
4781/// \endcode
4782static llvm::Value *
4783emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4784 const OMPExecutableDirective &D,
4785 QualType KmpTaskTWithPrivatesPtrQTy,
4786 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4787 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4788 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4789 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004790 ASTContext &C = CGM.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004791 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004792 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4793 KmpTaskTWithPrivatesPtrQTy,
4794 ImplicitParamDecl::Other);
4795 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4796 KmpTaskTWithPrivatesPtrQTy,
4797 ImplicitParamDecl::Other);
4798 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4799 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004800 Args.push_back(&DstArg);
4801 Args.push_back(&SrcArg);
4802 Args.push_back(&LastprivArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004803 const auto &TaskDupFnInfo =
Alexey Bataevf93095a2016-05-05 08:46:22 +00004804 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004805 llvm::FunctionType *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004806 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_dup", ""});
4807 auto *TaskDup = llvm::Function::Create(
4808 TaskDupTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004809 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskDup, TaskDupFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004810 TaskDup->setDoesNotRecurse();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004811 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004812 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args, Loc,
4813 Loc);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004814
4815 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4816 CGF.GetAddrOfLocalVar(&DstArg),
4817 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4818 // task_dst->liter = lastpriv;
4819 if (WithLastIter) {
4820 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4821 LValue Base = CGF.EmitLValueForField(
4822 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4823 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4824 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4825 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4826 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4827 }
4828
4829 // Emit initial values for private copies (if any).
4830 assert(!Privates.empty());
4831 Address KmpTaskSharedsPtr = Address::invalid();
4832 if (!Data.FirstprivateVars.empty()) {
4833 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4834 CGF.GetAddrOfLocalVar(&SrcArg),
4835 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4836 LValue Base = CGF.EmitLValueForField(
4837 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4838 KmpTaskSharedsPtr = Address(
4839 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4840 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4841 KmpTaskTShareds)),
4842 Loc),
4843 CGF.getNaturalTypeAlignment(SharedsTy));
4844 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004845 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4846 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004847 CGF.FinishFunction();
4848 return TaskDup;
4849}
4850
Alexey Bataev8a831592016-05-10 10:36:51 +00004851/// Checks if destructor function is required to be generated.
4852/// \return true if cleanups are required, false otherwise.
4853static bool
4854checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4855 bool NeedsCleanup = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004856 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4857 const auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4858 for (const FieldDecl *FD : PrivateRD->fields()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004859 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4860 if (NeedsCleanup)
4861 break;
4862 }
4863 return NeedsCleanup;
4864}
4865
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004866CGOpenMPRuntime::TaskResultTy
4867CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4868 const OMPExecutableDirective &D,
James Y Knight9871db02019-02-05 16:42:33 +00004869 llvm::Function *TaskFunction, QualType SharedsTy,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004870 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004871 ASTContext &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004872 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004873 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004874 auto I = Data.PrivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004875 for (const Expr *E : Data.PrivateVars) {
4876 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004877 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004878 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004879 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004880 /*PrivateElemInit=*/nullptr));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004881 ++I;
4882 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004883 I = Data.FirstprivateCopies.begin();
4884 auto IElemInitRef = Data.FirstprivateInits.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004885 for (const Expr *E : Data.FirstprivateVars) {
4886 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004887 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004888 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004889 PrivateHelpersTy(
4890 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004891 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl())));
Richard Trieucc3949d2016-02-18 22:34:54 +00004892 ++I;
4893 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004894 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004895 I = Data.LastprivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004896 for (const Expr *E : Data.LastprivateVars) {
4897 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004898 Privates.emplace_back(
Alexey Bataevf93095a2016-05-05 08:46:22 +00004899 C.getDeclAlign(VD),
4900 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004901 /*PrivateElemInit=*/nullptr));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004902 ++I;
4903 }
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004904 std::stable_sort(Privates.begin(), Privates.end(), stable_sort_comparator);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004905 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004906 // Build type kmp_routine_entry_t (if not built yet).
4907 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004908 // Build type kmp_task_t (if not built yet).
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004909 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
4910 if (SavedKmpTaskloopTQTy.isNull()) {
4911 SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4912 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4913 }
4914 KmpTaskTQTy = SavedKmpTaskloopTQTy;
Alexey Bataev3a03a7f2017-10-11 15:56:38 +00004915 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004916 assert((D.getDirectiveKind() == OMPD_task ||
4917 isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||
4918 isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) &&
4919 "Expected taskloop, task or target directive");
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004920 if (SavedKmpTaskTQTy.isNull()) {
4921 SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4922 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4923 }
4924 KmpTaskTQTy = SavedKmpTaskTQTy;
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004925 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004926 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004927 // Build particular struct kmp_task_t for the given task.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004928 const RecordDecl *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004929 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004930 QualType KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004931 QualType KmpTaskTWithPrivatesPtrQTy =
4932 C.getPointerType(KmpTaskTWithPrivatesQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004933 llvm::Type *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4934 llvm::Type *KmpTaskTWithPrivatesPtrTy =
4935 KmpTaskTWithPrivatesTy->getPointerTo();
4936 llvm::Value *KmpTaskTWithPrivatesTySize =
4937 CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004938 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4939
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004940 // Emit initial values for private copies (if any).
4941 llvm::Value *TaskPrivatesMap = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004942 llvm::Type *TaskPrivatesMapTy =
James Y Knight9871db02019-02-05 16:42:33 +00004943 std::next(TaskFunction->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004944 if (!Privates.empty()) {
4945 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004946 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4947 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4948 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004949 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4950 TaskPrivatesMap, TaskPrivatesMapTy);
4951 } else {
4952 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4953 cast<llvm::PointerType>(TaskPrivatesMapTy));
4954 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004955 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4956 // kmp_task_t *tt);
James Y Knight9871db02019-02-05 16:42:33 +00004957 llvm::Function *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004958 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4959 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4960 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004961
4962 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4963 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4964 // kmp_routine_entry_t *task_entry);
4965 // Task flags. Format is taken from
James Y Knight5d71fc52019-01-29 16:37:27 +00004966 // https://github.com/llvm/llvm-project/blob/master/openmp/runtime/src/kmp.h,
Alexey Bataev62b63b12015-03-10 07:28:44 +00004967 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004968 enum {
4969 TiedFlag = 0x1,
4970 FinalFlag = 0x2,
4971 DestructorsFlag = 0x8,
4972 PriorityFlag = 0x20
4973 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004974 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004975 bool NeedsCleanup = false;
4976 if (!Privates.empty()) {
4977 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4978 if (NeedsCleanup)
4979 Flags = Flags | DestructorsFlag;
4980 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004981 if (Data.Priority.getInt())
4982 Flags = Flags | PriorityFlag;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004983 llvm::Value *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004984 Data.Final.getPointer()
4985 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00004986 CGF.Builder.getInt32(FinalFlag),
4987 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004988 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004989 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004990 llvm::Value *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004991 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4992 getThreadID(CGF, Loc), TaskFlags,
4993 KmpTaskTWithPrivatesTySize, SharedsSize,
4994 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4995 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004996 llvm::Value *NewTask = CGF.EmitRuntimeCall(
Alexey Bataev62b63b12015-03-10 07:28:44 +00004997 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004998 llvm::Value *NewTaskNewTaskTTy =
4999 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5000 NewTask, KmpTaskTWithPrivatesPtrTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00005001 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
5002 KmpTaskTWithPrivatesQTy);
5003 LValue TDBase =
5004 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00005005 // Fill the data in the resulting kmp_task_t record.
5006 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00005007 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00005008 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00005009 KmpTaskSharedsPtr =
5010 Address(CGF.EmitLoadOfScalar(
5011 CGF.EmitLValueForField(
5012 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
5013 KmpTaskTShareds)),
5014 Loc),
5015 CGF.getNaturalTypeAlignment(SharedsTy));
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00005016 LValue Dest = CGF.MakeAddrLValue(KmpTaskSharedsPtr, SharedsTy);
5017 LValue Src = CGF.MakeAddrLValue(Shareds, SharedsTy);
Richard Smithe78fac52018-04-05 20:52:58 +00005018 CGF.EmitAggregateCopy(Dest, Src, SharedsTy, AggValueSlot::DoesNotOverlap);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00005019 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00005020 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00005021 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00005022 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00005023 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
5024 SharedsTy, SharedsPtrTy, Data, Privates,
5025 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00005026 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
5027 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
5028 Result.TaskDupFn = emitTaskDupFunction(
5029 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
5030 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
5031 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00005032 }
5033 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00005034 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
5035 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00005036 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00005037 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005038 const RecordDecl *KmpCmplrdataUD =
5039 (*FI)->getType()->getAsUnionType()->getDecl();
Alexey Bataevad537bb2016-05-30 09:06:50 +00005040 if (NeedsCleanup) {
5041 llvm::Value *DestructorFn = emitDestructorsFunction(
5042 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
5043 KmpTaskTWithPrivatesQTy);
5044 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
5045 LValue DestructorsLV = CGF.EmitLValueForField(
5046 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
5047 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5048 DestructorFn, KmpRoutineEntryPtrTy),
5049 DestructorsLV);
5050 }
5051 // Set priority.
5052 if (Data.Priority.getInt()) {
5053 LValue Data2LV = CGF.EmitLValueForField(
5054 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
5055 LValue PriorityLV = CGF.EmitLValueForField(
5056 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
5057 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
5058 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005059 Result.NewTask = NewTask;
5060 Result.TaskEntry = TaskEntry;
5061 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
5062 Result.TDBase = TDBase;
5063 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
5064 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00005065}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005066
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005067void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
5068 const OMPExecutableDirective &D,
James Y Knight9871db02019-02-05 16:42:33 +00005069 llvm::Function *TaskFunction,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005070 QualType SharedsTy, Address Shareds,
5071 const Expr *IfCond,
5072 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005073 if (!CGF.HaveInsertPoint())
5074 return;
5075
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005076 TaskResultTy Result =
5077 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
5078 llvm::Value *NewTask = Result.NewTask;
James Y Knight9871db02019-02-05 16:42:33 +00005079 llvm::Function *TaskEntry = Result.TaskEntry;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005080 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
5081 LValue TDBase = Result.TDBase;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005082 const RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
5083 ASTContext &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005084 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00005085 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005086 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00005087 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005088 // Dependence kind for RTL.
Sergi Mateo Bellido31df1ad2019-02-04 07:33:19 +00005089 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3, DepMutexInOutSet = 0x4 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005090 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
5091 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005092 QualType FlagsTy =
5093 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005094 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
5095 if (KmpDependInfoTy.isNull()) {
5096 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
5097 KmpDependInfoRD->startDefinition();
5098 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
5099 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
5100 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
5101 KmpDependInfoRD->completeDefinition();
5102 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005103 } else {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005104 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005105 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005106 // Define type kmp_depend_info[<Dependences.size()>];
5107 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00005108 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005109 ArrayType::Normal, /*IndexTypeQuals=*/0);
5110 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00005111 DependenciesArray =
5112 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005113 for (unsigned I = 0; I < NumDependencies; ++I) {
5114 const Expr *E = Data.Dependences[I].second;
5115 LValue Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005116 llvm::Value *Size;
5117 QualType Ty = E->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005118 if (const auto *ASE =
5119 dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005120 LValue UpAddrLVal =
5121 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
5122 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00005123 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005124 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00005125 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005126 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
5127 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005128 } else {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005129 Size = CGF.getTypeSize(Ty);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005130 }
5131 LValue Base = CGF.MakeAddrLValue(
James Y Knight751fe282019-02-09 22:22:28 +00005132 CGF.Builder.CreateConstArrayGEP(DependenciesArray, I),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005133 KmpDependInfoTy);
5134 // deps[i].base_addr = &<Dependences[i].second>;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005135 LValue BaseAddrLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005136 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00005137 CGF.EmitStoreOfScalar(
5138 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
5139 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005140 // deps[i].len = sizeof(<Dependences[i].second>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005141 LValue LenLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005142 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
5143 CGF.EmitStoreOfScalar(Size, LenLVal);
5144 // deps[i].flags = <Dependences[i].first>;
5145 RTLDependenceKindTy DepKind;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005146 switch (Data.Dependences[I].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005147 case OMPC_DEPEND_in:
5148 DepKind = DepIn;
5149 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00005150 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005151 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005152 case OMPC_DEPEND_inout:
5153 DepKind = DepInOut;
5154 break;
Sergi Mateo Bellido31df1ad2019-02-04 07:33:19 +00005155 case OMPC_DEPEND_mutexinoutset:
5156 DepKind = DepMutexInOutSet;
5157 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00005158 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005159 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005160 case OMPC_DEPEND_unknown:
5161 llvm_unreachable("Unknown task dependence type");
5162 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005163 LValue FlagsLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005164 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
5165 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
5166 FlagsLVal);
5167 }
John McCall7f416cc2015-09-08 08:05:57 +00005168 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
James Y Knightf5f1b0e2019-02-08 15:34:12 +00005169 CGF.Builder.CreateConstArrayGEP(DependenciesArray, 0), CGF.VoidPtrTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005170 }
5171
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005172 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev62b63b12015-03-10 07:28:44 +00005173 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005174 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
5175 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
5176 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
5177 // list is not empty
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005178 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5179 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00005180 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
5181 llvm::Value *DepTaskArgs[7];
5182 if (NumDependencies) {
5183 DepTaskArgs[0] = UpLoc;
5184 DepTaskArgs[1] = ThreadID;
5185 DepTaskArgs[2] = NewTask;
5186 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
5187 DepTaskArgs[4] = DependenciesArray.getPointer();
5188 DepTaskArgs[5] = CGF.Builder.getInt32(0);
5189 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5190 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005191 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
5192 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005193 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005194 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005195 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005196 LValue PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005197 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
5198 }
John McCall7f416cc2015-09-08 08:05:57 +00005199 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005200 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00005201 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00005202 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005203 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00005204 TaskArgs);
5205 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00005206 // Check if parent region is untied and build return for untied task;
5207 if (auto *Region =
5208 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5209 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00005210 };
John McCall7f416cc2015-09-08 08:05:57 +00005211
5212 llvm::Value *DepWaitTaskArgs[6];
5213 if (NumDependencies) {
5214 DepWaitTaskArgs[0] = UpLoc;
5215 DepWaitTaskArgs[1] = ThreadID;
5216 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
5217 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
5218 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
5219 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5220 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005221 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00005222 NumDependencies, &DepWaitTaskArgs,
5223 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005224 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005225 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
5226 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
5227 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
5228 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
5229 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00005230 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005231 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005232 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005233 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00005234 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
5235 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005236 Action.Enter(CGF);
5237 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00005238 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00005239 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005240 };
5241
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005242 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
5243 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005244 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
5245 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005246 RegionCodeGenTy RCG(CodeGen);
5247 CommonActionTy Action(
5248 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
5249 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
5250 RCG.setAction(Action);
5251 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005252 };
John McCall7f416cc2015-09-08 08:05:57 +00005253
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005254 if (IfCond) {
Alexey Bataev1d677132015-04-22 13:57:31 +00005255 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005256 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005257 RegionCodeGenTy ThenRCG(ThenCodeGen);
5258 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00005259 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00005260}
5261
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005262void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
5263 const OMPLoopDirective &D,
James Y Knight9871db02019-02-05 16:42:33 +00005264 llvm::Function *TaskFunction,
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005265 QualType SharedsTy, Address Shareds,
5266 const Expr *IfCond,
5267 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005268 if (!CGF.HaveInsertPoint())
5269 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005270 TaskResultTy Result =
5271 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005272 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev7292c292016-04-25 12:22:29 +00005273 // libcall.
5274 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
5275 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
5276 // sched, kmp_uint64 grainsize, void *task_dup);
5277 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5278 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
5279 llvm::Value *IfVal;
5280 if (IfCond) {
5281 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
5282 /*isSigned=*/true);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005283 } else {
Alexey Bataev7292c292016-04-25 12:22:29 +00005284 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005285 }
Alexey Bataev7292c292016-04-25 12:22:29 +00005286
5287 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005288 Result.TDBase,
5289 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005290 const auto *LBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005291 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
5292 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
5293 /*IsInitializer=*/true);
5294 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005295 Result.TDBase,
5296 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005297 const auto *UBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005298 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
5299 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
5300 /*IsInitializer=*/true);
5301 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005302 Result.TDBase,
5303 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005304 const auto *StVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005305 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
5306 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
5307 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005308 // Store reductions address.
5309 LValue RedLVal = CGF.EmitLValueForField(
5310 Result.TDBase,
5311 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005312 if (Data.Reductions) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005313 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005314 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005315 CGF.EmitNullInitialization(RedLVal.getAddress(),
5316 CGF.getContext().VoidPtrTy);
5317 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005318 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00005319 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00005320 UpLoc,
5321 ThreadID,
5322 Result.NewTask,
5323 IfVal,
5324 LBLVal.getPointer(),
5325 UBLVal.getPointer(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005326 CGF.EmitLoadOfScalar(StLVal, Loc),
Alexey Bataevac6e4de2018-10-24 19:06:37 +00005327 llvm::ConstantInt::getSigned(
5328 CGF.IntTy, 1), // Always 1 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005329 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005330 CGF.IntTy, Data.Schedule.getPointer()
5331 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005332 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005333 Data.Schedule.getPointer()
5334 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005335 /*isSigned=*/false)
5336 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00005337 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5338 Result.TaskDupFn, CGF.VoidPtrTy)
5339 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00005340 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
5341}
5342
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005343/// Emit reduction operation for each element of array (required for
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005344/// array sections) LHS op = RHS.
5345/// \param Type Type of array.
5346/// \param LHSVar Variable on the left side of the reduction operation
5347/// (references element of array in original variable).
5348/// \param RHSVar Variable on the right side of the reduction operation
5349/// (references element of array in original variable).
5350/// \param RedOpGen Generator of reduction operation with use of LHSVar and
5351/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00005352static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005353 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
5354 const VarDecl *RHSVar,
5355 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
5356 const Expr *, const Expr *)> &RedOpGen,
5357 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
5358 const Expr *UpExpr = nullptr) {
5359 // Perform element-by-element initialization.
5360 QualType ElementTy;
5361 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
5362 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
5363
5364 // Drill down to the base element type on both arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005365 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
5366 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005367
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005368 llvm::Value *RHSBegin = RHSAddr.getPointer();
5369 llvm::Value *LHSBegin = LHSAddr.getPointer();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005370 // Cast from pointer to array type to pointer to single element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005371 llvm::Value *LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005372 // The basic structure here is a while-do loop.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005373 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
5374 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
5375 llvm::Value *IsEmpty =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005376 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
5377 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
5378
5379 // Enter the loop body, making that address the current address.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005380 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005381 CGF.EmitBlock(BodyBB);
5382
5383 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
5384
5385 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
5386 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
5387 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
5388 Address RHSElementCurrent =
5389 Address(RHSElementPHI,
5390 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5391
5392 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
5393 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
5394 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
5395 Address LHSElementCurrent =
5396 Address(LHSElementPHI,
5397 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5398
5399 // Emit copy.
5400 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005401 Scope.addPrivate(LHSVar, [=]() { return LHSElementCurrent; });
5402 Scope.addPrivate(RHSVar, [=]() { return RHSElementCurrent; });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005403 Scope.Privatize();
5404 RedOpGen(CGF, XExpr, EExpr, UpExpr);
5405 Scope.ForceCleanup();
5406
5407 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005408 llvm::Value *LHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005409 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005410 llvm::Value *RHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005411 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
5412 // Check whether we've reached the end.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005413 llvm::Value *Done =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005414 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
5415 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
5416 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
5417 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
5418
5419 // Done.
5420 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
5421}
5422
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005423/// Emit reduction combiner. If the combiner is a simple expression emit it as
5424/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
5425/// UDR combiner function.
5426static void emitReductionCombiner(CodeGenFunction &CGF,
5427 const Expr *ReductionOp) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005428 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
5429 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
5430 if (const auto *DRE =
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005431 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005432 if (const auto *DRD =
5433 dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005434 std::pair<llvm::Function *, llvm::Function *> Reduction =
5435 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
5436 RValue Func = RValue::get(Reduction.first);
5437 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
5438 CGF.EmitIgnoredExpr(ReductionOp);
5439 return;
5440 }
5441 CGF.EmitIgnoredExpr(ReductionOp);
5442}
5443
James Y Knight9871db02019-02-05 16:42:33 +00005444llvm::Function *CGOpenMPRuntime::emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005445 CodeGenModule &CGM, SourceLocation Loc, llvm::Type *ArgsType,
5446 ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs,
5447 ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005448 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005449
5450 // void reduction_func(void *LHSArg, void *RHSArg);
5451 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005452 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5453 ImplicitParamDecl::Other);
5454 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5455 ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005456 Args.push_back(&LHSArg);
5457 Args.push_back(&RHSArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005458 const auto &CGFI =
5459 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005460 std::string Name = getName({"omp", "reduction", "reduction_func"});
5461 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
5462 llvm::GlobalValue::InternalLinkage, Name,
5463 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005464 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005465 Fn->setDoesNotRecurse();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005466 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005467 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005468
5469 // Dst = (void*[n])(LHSArg);
5470 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00005471 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5472 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
5473 ArgsType), CGF.getPointerAlign());
5474 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5475 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
5476 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005477
5478 // ...
5479 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
5480 // ...
5481 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005482 auto IPriv = Privates.begin();
5483 unsigned Idx = 0;
5484 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005485 const auto *RHSVar =
5486 cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
5487 Scope.addPrivate(RHSVar, [&CGF, RHS, Idx, RHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005488 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005489 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005490 const auto *LHSVar =
5491 cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
5492 Scope.addPrivate(LHSVar, [&CGF, LHS, Idx, LHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005493 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005494 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005495 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00005496 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005497 // Get array size and emit VLA type.
5498 ++Idx;
James Y Knight751fe282019-02-09 22:22:28 +00005499 Address Elem = CGF.Builder.CreateConstArrayGEP(LHS, Idx);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005500 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005501 const VariableArrayType *VLA =
5502 CGF.getContext().getAsVariableArrayType(PrivTy);
5503 const auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005504 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00005505 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005506 CGF.EmitVariablyModifiedType(PrivTy);
5507 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005508 }
5509 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005510 IPriv = Privates.begin();
5511 auto ILHS = LHSExprs.begin();
5512 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005513 for (const Expr *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005514 if ((*IPriv)->getType()->isArrayType()) {
5515 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005516 const auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5517 const auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005518 EmitOMPAggregateReduction(
5519 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5520 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5521 emitReductionCombiner(CGF, E);
5522 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005523 } else {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005524 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005525 emitReductionCombiner(CGF, E);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005526 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005527 ++IPriv;
5528 ++ILHS;
5529 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005530 }
5531 Scope.ForceCleanup();
5532 CGF.FinishFunction();
5533 return Fn;
5534}
5535
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005536void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
5537 const Expr *ReductionOp,
5538 const Expr *PrivateRef,
5539 const DeclRefExpr *LHS,
5540 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005541 if (PrivateRef->getType()->isArrayType()) {
5542 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005543 const auto *LHSVar = cast<VarDecl>(LHS->getDecl());
5544 const auto *RHSVar = cast<VarDecl>(RHS->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005545 EmitOMPAggregateReduction(
5546 CGF, PrivateRef->getType(), LHSVar, RHSVar,
5547 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5548 emitReductionCombiner(CGF, ReductionOp);
5549 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005550 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005551 // Emit reduction for array subscript or single variable.
5552 emitReductionCombiner(CGF, ReductionOp);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005553 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005554}
5555
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005556void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005557 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005558 ArrayRef<const Expr *> LHSExprs,
5559 ArrayRef<const Expr *> RHSExprs,
5560 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005561 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005562 if (!CGF.HaveInsertPoint())
5563 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005564
5565 bool WithNowait = Options.WithNowait;
5566 bool SimpleReduction = Options.SimpleReduction;
5567
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005568 // Next code should be emitted for reduction:
5569 //
5570 // static kmp_critical_name lock = { 0 };
5571 //
5572 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
5573 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
5574 // ...
5575 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
5576 // *(Type<n>-1*)rhs[<n>-1]);
5577 // }
5578 //
5579 // ...
5580 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
5581 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5582 // RedList, reduce_func, &<lock>)) {
5583 // case 1:
5584 // ...
5585 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5586 // ...
5587 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5588 // break;
5589 // case 2:
5590 // ...
5591 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5592 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00005593 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005594 // break;
5595 // default:;
5596 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005597 //
5598 // if SimpleReduction is true, only the next code is generated:
5599 // ...
5600 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5601 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005602
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005603 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005604
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005605 if (SimpleReduction) {
5606 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005607 auto IPriv = Privates.begin();
5608 auto ILHS = LHSExprs.begin();
5609 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005610 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005611 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5612 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005613 ++IPriv;
5614 ++ILHS;
5615 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005616 }
5617 return;
5618 }
5619
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005620 // 1. Build a list of reduction variables.
5621 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005622 auto Size = RHSExprs.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005623 for (const Expr *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005624 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005625 // Reserve place for array size.
5626 ++Size;
5627 }
5628 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005629 QualType ReductionArrayTy =
5630 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
5631 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00005632 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005633 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005634 auto IPriv = Privates.begin();
5635 unsigned Idx = 0;
5636 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
James Y Knight751fe282019-02-09 22:22:28 +00005637 Address Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
John McCall7f416cc2015-09-08 08:05:57 +00005638 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005639 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00005640 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
5641 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005642 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005643 // Store array size.
5644 ++Idx;
James Y Knight751fe282019-02-09 22:22:28 +00005645 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005646 llvm::Value *Size = CGF.Builder.CreateIntCast(
5647 CGF.getVLASize(
5648 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
Sander de Smalen891af03a2018-02-03 13:55:59 +00005649 .NumElts,
Alexey Bataev1189bd02016-01-26 12:20:39 +00005650 CGF.SizeTy, /*isSigned=*/false);
5651 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
5652 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005653 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005654 }
5655
5656 // 2. Emit reduce_func().
James Y Knight9871db02019-02-05 16:42:33 +00005657 llvm::Function *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005658 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
5659 Privates, LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005660
5661 // 3. Create static kmp_critical_name lock = { 0 };
Alexey Bataev18fa2322018-05-02 14:20:50 +00005662 std::string Name = getName({"reduction"});
5663 llvm::Value *Lock = getCriticalRegionLock(Name);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005664
5665 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5666 // RedList, reduce_func, &<lock>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005667 llvm::Value *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
5668 llvm::Value *ThreadId = getThreadID(CGF, Loc);
5669 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
5670 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Samuel Antao4c8035b2016-12-12 18:00:20 +00005671 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005672 llvm::Value *Args[] = {
5673 IdentTLoc, // ident_t *<loc>
5674 ThreadId, // i32 <gtid>
5675 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5676 ReductionArrayTySize, // size_type sizeof(RedList)
5677 RL, // void *RedList
5678 ReductionFn, // void (*) (void *, void *) <reduce_func>
5679 Lock // kmp_critical_name *&<lock>
5680 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005681 llvm::Value *Res = CGF.EmitRuntimeCall(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005682 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5683 : OMPRTL__kmpc_reduce),
5684 Args);
5685
5686 // 5. Build switch(res)
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005687 llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5688 llvm::SwitchInst *SwInst =
5689 CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005690
5691 // 6. Build case 1:
5692 // ...
5693 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5694 // ...
5695 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5696 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005697 llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005698 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5699 CGF.EmitBlock(Case1BB);
5700
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005701 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5702 llvm::Value *EndArgs[] = {
5703 IdentTLoc, // ident_t *<loc>
5704 ThreadId, // i32 <gtid>
5705 Lock // kmp_critical_name *&<lock>
5706 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005707 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps](
5708 CodeGenFunction &CGF, PrePostActionTy &Action) {
5709 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005710 auto IPriv = Privates.begin();
5711 auto ILHS = LHSExprs.begin();
5712 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005713 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005714 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5715 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005716 ++IPriv;
5717 ++ILHS;
5718 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005719 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005720 };
5721 RegionCodeGenTy RCG(CodeGen);
5722 CommonActionTy Action(
5723 nullptr, llvm::None,
5724 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5725 : OMPRTL__kmpc_end_reduce),
5726 EndArgs);
5727 RCG.setAction(Action);
5728 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005729
5730 CGF.EmitBranch(DefaultBB);
5731
5732 // 7. Build case 2:
5733 // ...
5734 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5735 // ...
5736 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005737 llvm::BasicBlock *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005738 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5739 CGF.EmitBlock(Case2BB);
5740
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005741 auto &&AtomicCodeGen = [Loc, Privates, LHSExprs, RHSExprs, ReductionOps](
5742 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005743 auto ILHS = LHSExprs.begin();
5744 auto IRHS = RHSExprs.begin();
5745 auto IPriv = Privates.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005746 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005747 const Expr *XExpr = nullptr;
5748 const Expr *EExpr = nullptr;
5749 const Expr *UpExpr = nullptr;
5750 BinaryOperatorKind BO = BO_Comma;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005751 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005752 if (BO->getOpcode() == BO_Assign) {
5753 XExpr = BO->getLHS();
5754 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005755 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005756 }
5757 // Try to emit update expression as a simple atomic.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005758 const Expr *RHSExpr = UpExpr;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005759 if (RHSExpr) {
5760 // Analyze RHS part of the whole expression.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005761 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005762 RHSExpr->IgnoreParenImpCasts())) {
5763 // If this is a conditional operator, analyze its condition for
5764 // min/max reduction operator.
5765 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005766 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005767 if (const auto *BORHS =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005768 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5769 EExpr = BORHS->getRHS();
5770 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005771 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005772 }
5773 if (XExpr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005774 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005775 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005776 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5777 const Expr *EExpr, const Expr *UpExpr) {
5778 LValue X = CGF.EmitLValue(XExpr);
5779 RValue E;
5780 if (EExpr)
5781 E = CGF.EmitAnyExpr(EExpr);
5782 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005783 X, E, BO, /*IsXLHSInRHSPart=*/true,
5784 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005785 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005786 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5787 PrivateScope.addPrivate(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005788 VD, [&CGF, VD, XRValue, Loc]() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005789 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5790 CGF.emitOMPSimpleStore(
5791 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5792 VD->getType().getNonReferenceType(), Loc);
5793 return LHSTemp;
5794 });
5795 (void)PrivateScope.Privatize();
5796 return CGF.EmitAnyExpr(UpExpr);
5797 });
5798 };
5799 if ((*IPriv)->getType()->isArrayType()) {
5800 // Emit atomic reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005801 const auto *RHSVar =
5802 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005803 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5804 AtomicRedGen, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005805 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005806 // Emit atomic reduction for array subscript or single variable.
5807 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005808 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005809 } else {
5810 // Emit as a critical region.
5811 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005812 const Expr *, const Expr *) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005813 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005814 std::string Name = RT.getName({"atomic_reduction"});
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005815 RT.emitCriticalRegion(
Alexey Bataev18fa2322018-05-02 14:20:50 +00005816 CGF, Name,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005817 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5818 Action.Enter(CGF);
5819 emitReductionCombiner(CGF, E);
5820 },
5821 Loc);
5822 };
5823 if ((*IPriv)->getType()->isArrayType()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005824 const auto *LHSVar =
5825 cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5826 const auto *RHSVar =
5827 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005828 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5829 CritRedGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005830 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005831 CritRedGen(CGF, nullptr, nullptr, nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005832 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005833 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005834 ++ILHS;
5835 ++IRHS;
5836 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005837 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005838 };
5839 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5840 if (!WithNowait) {
5841 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5842 llvm::Value *EndArgs[] = {
5843 IdentTLoc, // ident_t *<loc>
5844 ThreadId, // i32 <gtid>
5845 Lock // kmp_critical_name *&<lock>
5846 };
5847 CommonActionTy Action(nullptr, llvm::None,
5848 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5849 EndArgs);
5850 AtomicRCG.setAction(Action);
5851 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005852 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005853 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005854 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005855
5856 CGF.EmitBranch(DefaultBB);
5857 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5858}
5859
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005860/// Generates unique name for artificial threadprivate variables.
Alexey Bataev1c44e152018-03-06 18:59:43 +00005861/// Format is: <Prefix> "." <Decl_mangled_name> "_" "<Decl_start_loc_raw_enc>"
5862static std::string generateUniqueName(CodeGenModule &CGM, StringRef Prefix,
5863 const Expr *Ref) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005864 SmallString<256> Buffer;
5865 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev1c44e152018-03-06 18:59:43 +00005866 const clang::DeclRefExpr *DE;
5867 const VarDecl *D = ::getBaseDecl(Ref, DE);
5868 if (!D)
5869 D = cast<VarDecl>(cast<DeclRefExpr>(Ref)->getDecl());
5870 D = D->getCanonicalDecl();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005871 std::string Name = CGM.getOpenMPRuntime().getName(
5872 {D->isLocalVarDeclOrParm() ? D->getName() : CGM.getMangledName(D)});
5873 Out << Prefix << Name << "_"
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005874 << D->getCanonicalDecl()->getBeginLoc().getRawEncoding();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005875 return Out.str();
5876}
5877
5878/// Emits reduction initializer function:
5879/// \code
5880/// void @.red_init(void* %arg) {
5881/// %0 = bitcast void* %arg to <type>*
5882/// store <type> <init>, <type>* %0
5883/// ret void
5884/// }
5885/// \endcode
5886static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5887 SourceLocation Loc,
5888 ReductionCodeGen &RCG, unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005889 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005890 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005891 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5892 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005893 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005894 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005895 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005896 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005897 std::string Name = CGM.getOpenMPRuntime().getName({"red_init", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005898 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005899 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005900 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005901 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005902 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005903 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005904 Address PrivateAddr = CGF.EmitLoadOfPointer(
5905 CGF.GetAddrOfLocalVar(&Param),
5906 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5907 llvm::Value *Size = nullptr;
5908 // If the size of the reduction item is non-constant, load it from global
5909 // threadprivate variable.
5910 if (RCG.getSizes(N).second) {
5911 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5912 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005913 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005914 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5915 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005916 }
5917 RCG.emitAggregateType(CGF, N, Size);
5918 LValue SharedLVal;
5919 // If initializer uses initializer from declare reduction construct, emit a
5920 // pointer to the address of the original reduction item (reuired by reduction
5921 // initializer)
5922 if (RCG.usesReductionInitializer(N)) {
5923 Address SharedAddr =
5924 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5925 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00005926 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataev21dab122018-03-09 15:20:30 +00005927 SharedAddr = CGF.EmitLoadOfPointer(
5928 SharedAddr,
5929 CGM.getContext().VoidPtrTy.castAs<PointerType>()->getTypePtr());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005930 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5931 } else {
5932 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5933 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5934 CGM.getContext().VoidPtrTy);
5935 }
5936 // Emit the initializer:
5937 // %0 = bitcast void* %arg to <type>*
5938 // store <type> <init>, <type>* %0
5939 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5940 [](CodeGenFunction &) { return false; });
5941 CGF.FinishFunction();
5942 return Fn;
5943}
5944
5945/// Emits reduction combiner function:
5946/// \code
5947/// void @.red_comb(void* %arg0, void* %arg1) {
5948/// %lhs = bitcast void* %arg0 to <type>*
5949/// %rhs = bitcast void* %arg1 to <type>*
5950/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5951/// store <type> %2, <type>* %lhs
5952/// ret void
5953/// }
5954/// \endcode
5955static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5956 SourceLocation Loc,
5957 ReductionCodeGen &RCG, unsigned N,
5958 const Expr *ReductionOp,
5959 const Expr *LHS, const Expr *RHS,
5960 const Expr *PrivateRef) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005961 ASTContext &C = CGM.getContext();
5962 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5963 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005964 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005965 ImplicitParamDecl ParamInOut(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
5966 C.VoidPtrTy, ImplicitParamDecl::Other);
5967 ImplicitParamDecl ParamIn(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5968 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005969 Args.emplace_back(&ParamInOut);
5970 Args.emplace_back(&ParamIn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005971 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005972 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005973 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005974 std::string Name = CGM.getOpenMPRuntime().getName({"red_comb", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005975 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005976 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005977 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005978 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005979 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005980 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005981 llvm::Value *Size = nullptr;
5982 // If the size of the reduction item is non-constant, load it from global
5983 // threadprivate variable.
5984 if (RCG.getSizes(N).second) {
5985 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5986 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005987 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005988 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5989 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005990 }
5991 RCG.emitAggregateType(CGF, N, Size);
5992 // Remap lhs and rhs variables to the addresses of the function arguments.
5993 // %lhs = bitcast void* %arg0 to <type>*
5994 // %rhs = bitcast void* %arg1 to <type>*
5995 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005996 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005997 // Pull out the pointer to the variable.
5998 Address PtrAddr = CGF.EmitLoadOfPointer(
5999 CGF.GetAddrOfLocalVar(&ParamInOut),
6000 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
6001 return CGF.Builder.CreateElementBitCast(
6002 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
6003 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006004 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006005 // Pull out the pointer to the variable.
6006 Address PtrAddr = CGF.EmitLoadOfPointer(
6007 CGF.GetAddrOfLocalVar(&ParamIn),
6008 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
6009 return CGF.Builder.CreateElementBitCast(
6010 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
6011 });
6012 PrivateScope.Privatize();
6013 // Emit the combiner body:
6014 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
6015 // store <type> %2, <type>* %lhs
6016 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
6017 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
6018 cast<DeclRefExpr>(RHS));
6019 CGF.FinishFunction();
6020 return Fn;
6021}
6022
6023/// Emits reduction finalizer function:
6024/// \code
6025/// void @.red_fini(void* %arg) {
6026/// %0 = bitcast void* %arg to <type>*
6027/// <destroy>(<type>* %0)
6028/// ret void
6029/// }
6030/// \endcode
6031static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
6032 SourceLocation Loc,
6033 ReductionCodeGen &RCG, unsigned N) {
6034 if (!RCG.needCleanups(N))
6035 return nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006036 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006037 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00006038 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
6039 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006040 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006041 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006042 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006043 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00006044 std::string Name = CGM.getOpenMPRuntime().getName({"red_fini", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006045 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00006046 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00006047 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00006048 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006049 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00006050 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006051 Address PrivateAddr = CGF.EmitLoadOfPointer(
6052 CGF.GetAddrOfLocalVar(&Param),
6053 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
6054 llvm::Value *Size = nullptr;
6055 // If the size of the reduction item is non-constant, load it from global
6056 // threadprivate variable.
6057 if (RCG.getSizes(N).second) {
6058 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
6059 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00006060 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00006061 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
6062 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006063 }
6064 RCG.emitAggregateType(CGF, N, Size);
6065 // Emit the finalizer body:
6066 // <destroy>(<type>* %0)
6067 RCG.emitCleanups(CGF, N, PrivateAddr);
6068 CGF.FinishFunction();
6069 return Fn;
6070}
6071
6072llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
6073 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
6074 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
6075 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
6076 return nullptr;
6077
6078 // Build typedef struct:
6079 // kmp_task_red_input {
6080 // void *reduce_shar; // shared reduction item
6081 // size_t reduce_size; // size of data item
6082 // void *reduce_init; // data initialization routine
6083 // void *reduce_fini; // data finalization routine
6084 // void *reduce_comb; // data combiner routine
6085 // kmp_task_red_flags_t flags; // flags for additional info from compiler
6086 // } kmp_task_red_input_t;
6087 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006088 RecordDecl *RD = C.buildImplicitRecord("kmp_task_red_input_t");
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006089 RD->startDefinition();
6090 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6091 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
6092 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6093 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6094 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6095 const FieldDecl *FlagsFD = addFieldToRecordDecl(
6096 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
6097 RD->completeDefinition();
6098 QualType RDType = C.getRecordType(RD);
6099 unsigned Size = Data.ReductionVars.size();
6100 llvm::APInt ArraySize(/*numBits=*/64, Size);
6101 QualType ArrayRDType = C.getConstantArrayType(
6102 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
6103 // kmp_task_red_input_t .rd_input.[Size];
6104 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
6105 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
6106 Data.ReductionOps);
6107 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
6108 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
6109 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
6110 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
6111 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
6112 TaskRedInput.getPointer(), Idxs,
6113 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
6114 ".rd_input.gep.");
6115 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
6116 // ElemLVal.reduce_shar = &Shareds[Cnt];
6117 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
6118 RCG.emitSharedLValue(CGF, Cnt);
6119 llvm::Value *CastedShared =
6120 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
6121 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
6122 RCG.emitAggregateType(CGF, Cnt);
6123 llvm::Value *SizeValInChars;
6124 llvm::Value *SizeVal;
6125 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
6126 // We use delayed creation/initialization for VLAs, array sections and
6127 // custom reduction initializations. It is required because runtime does not
6128 // provide the way to pass the sizes of VLAs/array sections to
6129 // initializer/combiner/finalizer functions and does not pass the pointer to
6130 // original reduction item to the initializer. Instead threadprivate global
6131 // variables are used to store these values and use them in the functions.
6132 bool DelayedCreation = !!SizeVal;
6133 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
6134 /*isSigned=*/false);
6135 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
6136 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
6137 // ElemLVal.reduce_init = init;
6138 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
6139 llvm::Value *InitAddr =
6140 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
6141 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
6142 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
6143 // ElemLVal.reduce_fini = fini;
6144 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
6145 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
6146 llvm::Value *FiniAddr = Fini
6147 ? CGF.EmitCastToVoidPtr(Fini)
6148 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
6149 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
6150 // ElemLVal.reduce_comb = comb;
6151 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
6152 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
6153 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
6154 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
6155 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
6156 // ElemLVal.flags = 0;
6157 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
6158 if (DelayedCreation) {
6159 CGF.EmitStoreOfScalar(
6160 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
6161 FlagsLVal);
6162 } else
6163 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
6164 }
6165 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
6166 // *data);
6167 llvm::Value *Args[] = {
6168 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6169 /*isSigned=*/true),
6170 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
6171 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
6172 CGM.VoidPtrTy)};
6173 return CGF.EmitRuntimeCall(
6174 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
6175}
6176
6177void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
6178 SourceLocation Loc,
6179 ReductionCodeGen &RCG,
6180 unsigned N) {
6181 auto Sizes = RCG.getSizes(N);
6182 // Emit threadprivate global variable if the type is non-constant
6183 // (Sizes.second = nullptr).
6184 if (Sizes.second) {
6185 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
6186 /*isSigned=*/false);
6187 Address SizeAddr = getAddrOfArtificialThreadPrivate(
6188 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00006189 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006190 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
6191 }
6192 // Store address of the original reduction item if custom initializer is used.
6193 if (RCG.usesReductionInitializer(N)) {
6194 Address SharedAddr = getAddrOfArtificialThreadPrivate(
6195 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00006196 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006197 CGF.Builder.CreateStore(
6198 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6199 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
6200 SharedAddr, /*IsVolatile=*/false);
6201 }
6202}
6203
6204Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
6205 SourceLocation Loc,
6206 llvm::Value *ReductionsPtr,
6207 LValue SharedLVal) {
6208 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
6209 // *d);
6210 llvm::Value *Args[] = {
6211 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6212 /*isSigned=*/true),
6213 ReductionsPtr,
6214 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
6215 CGM.VoidPtrTy)};
6216 return Address(
6217 CGF.EmitRuntimeCall(
6218 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
6219 SharedLVal.getAlignment());
6220}
6221
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006222void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
6223 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006224 if (!CGF.HaveInsertPoint())
6225 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006226 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
6227 // global_tid);
6228 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
6229 // Ignore return result until untied tasks are supported.
6230 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00006231 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
6232 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006233}
6234
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006235void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006236 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006237 const RegionCodeGenTy &CodeGen,
6238 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006239 if (!CGF.HaveInsertPoint())
6240 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00006241 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006242 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00006243}
6244
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006245namespace {
6246enum RTCancelKind {
6247 CancelNoreq = 0,
6248 CancelParallel = 1,
6249 CancelLoop = 2,
6250 CancelSections = 3,
6251 CancelTaskgroup = 4
6252};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00006253} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006254
6255static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
6256 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00006257 if (CancelRegion == OMPD_parallel)
6258 CancelKind = CancelParallel;
6259 else if (CancelRegion == OMPD_for)
6260 CancelKind = CancelLoop;
6261 else if (CancelRegion == OMPD_sections)
6262 CancelKind = CancelSections;
6263 else {
6264 assert(CancelRegion == OMPD_taskgroup);
6265 CancelKind = CancelTaskgroup;
6266 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006267 return CancelKind;
6268}
6269
6270void CGOpenMPRuntime::emitCancellationPointCall(
6271 CodeGenFunction &CGF, SourceLocation Loc,
6272 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006273 if (!CGF.HaveInsertPoint())
6274 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006275 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
6276 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006277 if (auto *OMPRegionInfo =
6278 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00006279 // For 'cancellation point taskgroup', the task region info may not have a
6280 // cancel. This may instead happen in another adjacent task.
6281 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006282 llvm::Value *Args[] = {
6283 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
6284 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006285 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006286 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006287 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
6288 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006289 // exit from construct;
6290 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006291 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6292 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6293 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006294 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6295 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006296 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006297 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev25e5b442015-09-15 12:52:43 +00006298 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006299 CGF.EmitBranchThroughCleanup(CancelDest);
6300 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6301 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006302 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006303}
6304
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006305void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00006306 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006307 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006308 if (!CGF.HaveInsertPoint())
6309 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006310 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
6311 // kmp_int32 cncl_kind);
6312 if (auto *OMPRegionInfo =
6313 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006314 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
6315 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006316 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00006317 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006318 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00006319 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
6320 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006321 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006322 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00006323 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00006324 // exit from construct;
6325 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006326 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6327 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6328 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev87933c72015-09-18 08:07:34 +00006329 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6330 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00006331 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006332 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev87933c72015-09-18 08:07:34 +00006333 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
6334 CGF.EmitBranchThroughCleanup(CancelDest);
6335 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6336 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006337 if (IfCond) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006338 emitOMPIfClause(CGF, IfCond, ThenGen,
6339 [](CodeGenFunction &, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006340 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006341 RegionCodeGenTy ThenRCG(ThenGen);
6342 ThenRCG(CGF);
6343 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006344 }
6345}
Samuel Antaobed3c462015-10-02 16:14:20 +00006346
Samuel Antaoee8fb302016-01-06 13:42:12 +00006347void CGOpenMPRuntime::emitTargetOutlinedFunction(
6348 const OMPExecutableDirective &D, StringRef ParentName,
6349 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006350 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00006351 assert(!ParentName.empty() && "Invalid target region parent name!");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006352 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
6353 IsOffloadEntry, CodeGen);
6354}
6355
6356void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
6357 const OMPExecutableDirective &D, StringRef ParentName,
6358 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
6359 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00006360 // Create a unique name for the entry function using the source location
6361 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00006362 //
Samuel Antao2de62b02016-02-13 23:35:10 +00006363 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00006364 //
6365 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00006366 // mangled name of the function that encloses the target region and BB is the
6367 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00006368
6369 unsigned DeviceID;
6370 unsigned FileID;
6371 unsigned Line;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006372 getTargetEntryUniqueInfo(CGM.getContext(), D.getBeginLoc(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00006373 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006374 SmallString<64> EntryFnName;
6375 {
6376 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00006377 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
6378 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00006379 }
6380
Alexey Bataev475a7442018-01-12 19:39:11 +00006381 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006382
Samuel Antaobed3c462015-10-02 16:14:20 +00006383 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006384 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00006385 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006386
Samuel Antao6d004262016-06-16 18:39:34 +00006387 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006388
6389 // If this target outline function is not an offload entry, we don't need to
6390 // register it.
6391 if (!IsOffloadEntry)
6392 return;
6393
6394 // The target region ID is used by the runtime library to identify the current
6395 // target region, so it only has to be unique and not necessarily point to
6396 // anything. It could be the pointer to the outlined function that implements
6397 // the target region, but we aren't using that so that the compiler doesn't
6398 // need to keep that, and could therefore inline the host function if proven
6399 // worthwhile during optimization. In the other hand, if emitting code for the
6400 // device, the ID has to be the function address so that it can retrieved from
6401 // the offloading entry and launched by the runtime library. We also mark the
6402 // outlined function to have external linkage in case we are emitting code for
6403 // the device, because these functions will be entry points to the device.
6404
6405 if (CGM.getLangOpts().OpenMPIsDevice) {
6406 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
Alexey Bataev9a700172018-05-08 14:16:57 +00006407 OutlinedFn->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Rafael Espindolacbca4872018-01-11 22:15:12 +00006408 OutlinedFn->setDSOLocal(false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006409 } else {
Alexey Bataevc15ea702018-05-09 18:02:37 +00006410 std::string Name = getName({EntryFnName, "region_id"});
Samuel Antaoee8fb302016-01-06 13:42:12 +00006411 OutlinedFnID = new llvm::GlobalVariable(
6412 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
Alexey Bataev9a700172018-05-08 14:16:57 +00006413 llvm::GlobalValue::WeakAnyLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00006414 llvm::Constant::getNullValue(CGM.Int8Ty), Name);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006415 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00006416
6417 // Register the information for the entry associated with this target region.
6418 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00006419 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
Alexey Bataev03f270c2018-03-30 18:31:07 +00006420 OffloadEntriesInfoManagerTy::OMPTargetRegionEntryTargetRegion);
Samuel Antaobed3c462015-10-02 16:14:20 +00006421}
6422
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006423/// discard all CompoundStmts intervening between two constructs
6424static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006425 while (const auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006426 Body = CS->body_front();
6427
6428 return Body;
6429}
6430
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006431/// Emit the number of teams for a target directive. Inspect the num_teams
6432/// clause associated with a teams construct combined or closely nested
6433/// with the target directive.
6434///
6435/// Emit a team of size one for directives such as 'target parallel' that
6436/// have no associated teams construct.
6437///
6438/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006439static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006440emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6441 CodeGenFunction &CGF,
6442 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006443 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6444 "teams directive expected to be "
6445 "emitted only for the host!");
6446
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006447 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006448
6449 // If the target directive is combined with a teams directive:
6450 // Return the value in the num_teams clause, if any.
6451 // Otherwise, return 0 to denote the runtime default.
6452 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
6453 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
6454 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006455 llvm::Value *NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
6456 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006457 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6458 /*IsSigned=*/true);
6459 }
6460
6461 // The default value is 0.
6462 return Bld.getInt32(0);
6463 }
6464
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006465 // If the target directive is combined with a parallel directive but not a
6466 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006467 if (isOpenMPParallelDirective(D.getDirectiveKind()))
6468 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006469
6470 // If the current target region has a teams region enclosed, we need to get
6471 // the number of teams to pass to the runtime function call. This is done
6472 // by generating the expression in a inlined region. This is required because
6473 // the expression is captured in the enclosing target environment when the
6474 // teams directive is not combined with target.
6475
Alexey Bataev475a7442018-01-12 19:39:11 +00006476 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006477
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006478 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006479 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006480 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006481 if (const auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006482 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6483 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6484 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
6485 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6486 /*IsSigned=*/true);
6487 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006488
Alexey Bataev50a1c782017-12-01 21:31:08 +00006489 // If we have an enclosed teams directive but no num_teams clause we use
6490 // the default value 0.
6491 return Bld.getInt32(0);
6492 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006493 }
6494
6495 // No teams associated with the directive.
6496 return nullptr;
6497}
6498
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006499/// Emit the number of threads for a target directive. Inspect the
6500/// thread_limit clause associated with a teams construct combined or closely
6501/// nested with the target directive.
6502///
6503/// Emit the num_threads clause for directives such as 'target parallel' that
6504/// have no associated teams construct.
6505///
6506/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006507static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006508emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6509 CodeGenFunction &CGF,
6510 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006511 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6512 "teams directive expected to be "
6513 "emitted only for the host!");
6514
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006515 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006516
6517 //
6518 // If the target directive is combined with a teams directive:
6519 // Return the value in the thread_limit clause, if any.
6520 //
6521 // If the target directive is combined with a parallel directive:
6522 // Return the value in the num_threads clause, if any.
6523 //
6524 // If both clauses are set, select the minimum of the two.
6525 //
6526 // If neither teams or parallel combined directives set the number of threads
6527 // in a team, return 0 to denote the runtime default.
6528 //
6529 // If this is not a teams directive return nullptr.
6530
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006531 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
6532 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006533 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
6534 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006535 llvm::Value *ThreadLimitVal = nullptr;
6536
6537 if (const auto *ThreadLimitClause =
6538 D.getSingleClause<OMPThreadLimitClause>()) {
6539 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006540 llvm::Value *ThreadLimit =
6541 CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
6542 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006543 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6544 /*IsSigned=*/true);
6545 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006546
6547 if (const auto *NumThreadsClause =
6548 D.getSingleClause<OMPNumThreadsClause>()) {
6549 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
6550 llvm::Value *NumThreads =
6551 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
6552 /*IgnoreResultAssign*/ true);
6553 NumThreadsVal =
6554 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
6555 }
6556
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006557 // Select the lesser of thread_limit and num_threads.
6558 if (NumThreadsVal)
6559 ThreadLimitVal = ThreadLimitVal
6560 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
6561 ThreadLimitVal),
6562 NumThreadsVal, ThreadLimitVal)
6563 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00006564
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006565 // Set default value passed to the runtime if either teams or a target
6566 // parallel type directive is found but no clause is specified.
6567 if (!ThreadLimitVal)
6568 ThreadLimitVal = DefaultThreadLimitVal;
6569
6570 return ThreadLimitVal;
6571 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00006572
Samuel Antaob68e2db2016-03-03 16:20:23 +00006573 // If the current target region has a teams region enclosed, we need to get
6574 // the thread limit to pass to the runtime function call. This is done
6575 // by generating the expression in a inlined region. This is required because
6576 // the expression is captured in the enclosing target environment when the
6577 // teams directive is not combined with target.
6578
Alexey Bataev475a7442018-01-12 19:39:11 +00006579 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006580
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006581 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006582 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006583 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006584 if (const auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006585 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6586 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6587 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
6588 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6589 /*IsSigned=*/true);
6590 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006591
Alexey Bataev50a1c782017-12-01 21:31:08 +00006592 // If we have an enclosed teams directive but no thread_limit clause we
6593 // use the default value 0.
6594 return CGF.Builder.getInt32(0);
6595 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006596 }
6597
6598 // No teams associated with the directive.
6599 return nullptr;
6600}
6601
Samuel Antao86ace552016-04-27 22:40:57 +00006602namespace {
Alexey Bataevb3638132018-07-19 16:34:13 +00006603LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
6604
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006605// Utility to handle information from clauses associated with a given
Samuel Antao86ace552016-04-27 22:40:57 +00006606// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
6607// It provides a convenient interface to obtain the information and generate
6608// code for that information.
6609class MappableExprsHandler {
6610public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006611 /// Values for bit flags used to specify the mapping type for
Samuel Antao86ace552016-04-27 22:40:57 +00006612 /// offloading.
Alexey Bataevb3638132018-07-19 16:34:13 +00006613 enum OpenMPOffloadMappingFlags : uint64_t {
6614 /// No flags
6615 OMP_MAP_NONE = 0x0,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006616 /// Allocate memory on the device and move data from host to device.
Samuel Antao86ace552016-04-27 22:40:57 +00006617 OMP_MAP_TO = 0x01,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006618 /// Allocate memory on the device and move data from device to host.
Samuel Antao86ace552016-04-27 22:40:57 +00006619 OMP_MAP_FROM = 0x02,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006620 /// Always perform the requested mapping action on the element, even
Samuel Antao86ace552016-04-27 22:40:57 +00006621 /// if it was already mapped before.
6622 OMP_MAP_ALWAYS = 0x04,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006623 /// Delete the element from the device environment, ignoring the
Samuel Antao86ace552016-04-27 22:40:57 +00006624 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00006625 OMP_MAP_DELETE = 0x08,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006626 /// The element being mapped is a pointer-pointee pair; both the
George Rokos065755d2017-11-07 18:27:04 +00006627 /// pointer and the pointee should be mapped.
6628 OMP_MAP_PTR_AND_OBJ = 0x10,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006629 /// This flags signals that the base address of an entry should be
George Rokos065755d2017-11-07 18:27:04 +00006630 /// passed to the target kernel as an argument.
6631 OMP_MAP_TARGET_PARAM = 0x20,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006632 /// Signal that the runtime library has to return the device pointer
George Rokos065755d2017-11-07 18:27:04 +00006633 /// in the current position for the data being mapped. Used when we have the
6634 /// use_device_ptr clause.
6635 OMP_MAP_RETURN_PARAM = 0x40,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006636 /// This flag signals that the reference being passed is a pointer to
Samuel Antaod486f842016-05-26 16:53:38 +00006637 /// private data.
George Rokos065755d2017-11-07 18:27:04 +00006638 OMP_MAP_PRIVATE = 0x80,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006639 /// Pass the element to the device by value.
George Rokos065755d2017-11-07 18:27:04 +00006640 OMP_MAP_LITERAL = 0x100,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006641 /// Implicit map
6642 OMP_MAP_IMPLICIT = 0x200,
Alexey Bataevb3638132018-07-19 16:34:13 +00006643 /// The 16 MSBs of the flags indicate whether the entry is member of some
6644 /// struct/class.
6645 OMP_MAP_MEMBER_OF = 0xffff000000000000,
6646 LLVM_MARK_AS_BITMASK_ENUM(/* LargestFlag = */ OMP_MAP_MEMBER_OF),
Samuel Antao86ace552016-04-27 22:40:57 +00006647 };
6648
Samuel Antaocc10b852016-07-28 14:23:26 +00006649 /// Class that associates information with a base pointer to be passed to the
6650 /// runtime library.
6651 class BasePointerInfo {
6652 /// The base pointer.
6653 llvm::Value *Ptr = nullptr;
6654 /// The base declaration that refers to this device pointer, or null if
6655 /// there is none.
6656 const ValueDecl *DevPtrDecl = nullptr;
6657
6658 public:
6659 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
6660 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
6661 llvm::Value *operator*() const { return Ptr; }
6662 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
6663 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
6664 };
6665
Alexey Bataevb3638132018-07-19 16:34:13 +00006666 using MapBaseValuesArrayTy = SmallVector<BasePointerInfo, 4>;
6667 using MapValuesArrayTy = SmallVector<llvm::Value *, 4>;
6668 using MapFlagsArrayTy = SmallVector<OpenMPOffloadMappingFlags, 4>;
6669
6670 /// Map between a struct and the its lowest & highest elements which have been
6671 /// mapped.
6672 /// [ValueDecl *] --> {LE(FieldIndex, Pointer),
6673 /// HE(FieldIndex, Pointer)}
6674 struct StructRangeInfoTy {
6675 std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> LowestElem = {
6676 0, Address::invalid()};
6677 std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> HighestElem = {
6678 0, Address::invalid()};
6679 Address Base = Address::invalid();
6680 };
Samuel Antao86ace552016-04-27 22:40:57 +00006681
6682private:
Alexey Bataevb3638132018-07-19 16:34:13 +00006683 /// Kind that defines how a device pointer has to be returned.
6684 struct MapInfo {
6685 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
6686 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
Kelvin Lief579432018-12-18 22:18:41 +00006687 ArrayRef<OpenMPMapModifierKind> MapModifiers;
Alexey Bataevb3638132018-07-19 16:34:13 +00006688 bool ReturnDevicePointer = false;
6689 bool IsImplicit = false;
6690
6691 MapInfo() = default;
6692 MapInfo(
6693 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Kelvin Lief579432018-12-18 22:18:41 +00006694 OpenMPMapClauseKind MapType,
6695 ArrayRef<OpenMPMapModifierKind> MapModifiers,
Alexey Bataevb3638132018-07-19 16:34:13 +00006696 bool ReturnDevicePointer, bool IsImplicit)
Kelvin Lief579432018-12-18 22:18:41 +00006697 : Components(Components), MapType(MapType), MapModifiers(MapModifiers),
Alexey Bataevb3638132018-07-19 16:34:13 +00006698 ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
6699 };
6700
6701 /// If use_device_ptr is used on a pointer which is a struct member and there
6702 /// is no map information about it, then emission of that entry is deferred
6703 /// until the whole struct has been processed.
6704 struct DeferredDevicePtrEntryTy {
6705 const Expr *IE = nullptr;
6706 const ValueDecl *VD = nullptr;
6707
6708 DeferredDevicePtrEntryTy(const Expr *IE, const ValueDecl *VD)
6709 : IE(IE), VD(VD) {}
6710 };
6711
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006712 /// Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00006713 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00006714
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006715 /// Function the directive is being generated for.
Samuel Antao86ace552016-04-27 22:40:57 +00006716 CodeGenFunction &CGF;
6717
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006718 /// Set of all first private variables in the current directive.
Samuel Antaod486f842016-05-26 16:53:38 +00006719 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
6720
Samuel Antao6890b092016-07-28 14:25:09 +00006721 /// Map between device pointer declarations and their expression components.
6722 /// The key value for declarations in 'this' is null.
6723 llvm::DenseMap<
6724 const ValueDecl *,
6725 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6726 DevPointersMap;
6727
Samuel Antao86ace552016-04-27 22:40:57 +00006728 llvm::Value *getExprTypeSize(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006729 QualType ExprTy = E->getType().getCanonicalType();
Samuel Antao86ace552016-04-27 22:40:57 +00006730
6731 // Reference types are ignored for mapping purposes.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006732 if (const auto *RefTy = ExprTy->getAs<ReferenceType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006733 ExprTy = RefTy->getPointeeType().getCanonicalType();
6734
6735 // Given that an array section is considered a built-in type, we need to
6736 // do the calculation based on the length of the section instead of relying
6737 // on CGF.getTypeSize(E->getType()).
6738 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6739 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6740 OAE->getBase()->IgnoreParenImpCasts())
6741 .getCanonicalType();
6742
6743 // If there is no length associated with the expression, that means we
6744 // are using the whole length of the base.
6745 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6746 return CGF.getTypeSize(BaseTy);
6747
6748 llvm::Value *ElemSize;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006749 if (const auto *PTy = BaseTy->getAs<PointerType>()) {
Samuel Antao86ace552016-04-27 22:40:57 +00006750 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006751 } else {
6752 const auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
Samuel Antao86ace552016-04-27 22:40:57 +00006753 assert(ATy && "Expecting array type if not a pointer type.");
6754 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6755 }
6756
6757 // If we don't have a length at this point, that is because we have an
6758 // array section with a single element.
6759 if (!OAE->getLength())
6760 return ElemSize;
6761
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006762 llvm::Value *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
Samuel Antao86ace552016-04-27 22:40:57 +00006763 LengthVal =
6764 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6765 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6766 }
6767 return CGF.getTypeSize(ExprTy);
6768 }
6769
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006770 /// Return the corresponding bits for a given map clause modifier. Add
Samuel Antao86ace552016-04-27 22:40:57 +00006771 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006772 /// map as the first one of a series of maps that relate to the same map
6773 /// expression.
Kelvin Lief579432018-12-18 22:18:41 +00006774 OpenMPOffloadMappingFlags getMapTypeBits(
6775 OpenMPMapClauseKind MapType, ArrayRef<OpenMPMapModifierKind> MapModifiers,
6776 bool IsImplicit, bool AddPtrFlag, bool AddIsTargetParamFlag) const {
Alexey Bataevb3638132018-07-19 16:34:13 +00006777 OpenMPOffloadMappingFlags Bits =
6778 IsImplicit ? OMP_MAP_IMPLICIT : OMP_MAP_NONE;
Samuel Antao86ace552016-04-27 22:40:57 +00006779 switch (MapType) {
6780 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006781 case OMPC_MAP_release:
6782 // alloc and release is the default behavior in the runtime library, i.e.
6783 // if we don't pass any bits alloc/release that is what the runtime is
6784 // going to do. Therefore, we don't need to signal anything for these two
6785 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006786 break;
6787 case OMPC_MAP_to:
Alexey Bataevb3638132018-07-19 16:34:13 +00006788 Bits |= OMP_MAP_TO;
Samuel Antao86ace552016-04-27 22:40:57 +00006789 break;
6790 case OMPC_MAP_from:
Alexey Bataevb3638132018-07-19 16:34:13 +00006791 Bits |= OMP_MAP_FROM;
Samuel Antao86ace552016-04-27 22:40:57 +00006792 break;
6793 case OMPC_MAP_tofrom:
Alexey Bataevb3638132018-07-19 16:34:13 +00006794 Bits |= OMP_MAP_TO | OMP_MAP_FROM;
Samuel Antao86ace552016-04-27 22:40:57 +00006795 break;
6796 case OMPC_MAP_delete:
Alexey Bataevb3638132018-07-19 16:34:13 +00006797 Bits |= OMP_MAP_DELETE;
Samuel Antao86ace552016-04-27 22:40:57 +00006798 break;
Alexey Bataevb3638132018-07-19 16:34:13 +00006799 case OMPC_MAP_unknown:
Samuel Antao86ace552016-04-27 22:40:57 +00006800 llvm_unreachable("Unexpected map type!");
Samuel Antao86ace552016-04-27 22:40:57 +00006801 }
6802 if (AddPtrFlag)
George Rokos065755d2017-11-07 18:27:04 +00006803 Bits |= OMP_MAP_PTR_AND_OBJ;
6804 if (AddIsTargetParamFlag)
6805 Bits |= OMP_MAP_TARGET_PARAM;
Kelvin Lief579432018-12-18 22:18:41 +00006806 if (llvm::find(MapModifiers, OMPC_MAP_MODIFIER_always)
6807 != MapModifiers.end())
Samuel Antao86ace552016-04-27 22:40:57 +00006808 Bits |= OMP_MAP_ALWAYS;
6809 return Bits;
6810 }
6811
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006812 /// Return true if the provided expression is a final array section. A
Samuel Antao86ace552016-04-27 22:40:57 +00006813 /// final array section, is one whose length can't be proved to be one.
6814 bool isFinalArraySectionExpression(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006815 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antao86ace552016-04-27 22:40:57 +00006816
6817 // It is not an array section and therefore not a unity-size one.
6818 if (!OASE)
6819 return false;
6820
6821 // An array section with no colon always refer to a single element.
6822 if (OASE->getColonLoc().isInvalid())
6823 return false;
6824
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006825 const Expr *Length = OASE->getLength();
Samuel Antao86ace552016-04-27 22:40:57 +00006826
6827 // If we don't have a length we have to check if the array has size 1
6828 // for this dimension. Also, we should always expect a length if the
6829 // base type is pointer.
6830 if (!Length) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006831 QualType BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6832 OASE->getBase()->IgnoreParenImpCasts())
6833 .getCanonicalType();
6834 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antao86ace552016-04-27 22:40:57 +00006835 return ATy->getSize().getSExtValue() != 1;
6836 // If we don't have a constant dimension length, we have to consider
6837 // the current section as having any size, so it is not necessarily
6838 // unitary. If it happen to be unity size, that's user fault.
6839 return true;
6840 }
6841
6842 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +00006843 Expr::EvalResult Result;
6844 if (!Length->EvaluateAsInt(Result, CGF.getContext()))
Samuel Antao86ace552016-04-27 22:40:57 +00006845 return true; // Can have more that size 1.
6846
Fangrui Song407659a2018-11-30 23:41:18 +00006847 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antao86ace552016-04-27 22:40:57 +00006848 return ConstLength.getSExtValue() != 1;
6849 }
6850
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006851 /// Generate the base pointers, section pointers, sizes and map type
Samuel Antao86ace552016-04-27 22:40:57 +00006852 /// bits for the provided map type, map modifier, and expression components.
6853 /// \a IsFirstComponent should be set to true if the provided set of
6854 /// components is the first associated with a capture.
6855 void generateInfoForComponentList(
Kelvin Lief579432018-12-18 22:18:41 +00006856 OpenMPMapClauseKind MapType,
6857 ArrayRef<OpenMPMapModifierKind> MapModifiers,
Samuel Antao86ace552016-04-27 22:40:57 +00006858 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006859 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006860 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
Alexey Bataevb3638132018-07-19 16:34:13 +00006861 StructRangeInfoTy &PartialStruct, bool IsFirstComponentList,
Alexey Bataeve82445f2018-09-20 13:54:02 +00006862 bool IsImplicit,
6863 ArrayRef<OMPClauseMappableExprCommon::MappableExprComponentListRef>
6864 OverlappedElements = llvm::None) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006865 // The following summarizes what has to be generated for each map and the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006866 // types below. The generated information is expressed in this order:
Samuel Antao86ace552016-04-27 22:40:57 +00006867 // base pointer, section pointer, size, flags
6868 // (to add to the ones that come from the map type and modifier).
6869 //
6870 // double d;
6871 // int i[100];
6872 // float *p;
6873 //
6874 // struct S1 {
6875 // int i;
6876 // float f[50];
6877 // }
6878 // struct S2 {
6879 // int i;
6880 // float f[50];
6881 // S1 s;
6882 // double *p;
6883 // struct S2 *ps;
6884 // }
6885 // S2 s;
6886 // S2 *ps;
6887 //
6888 // map(d)
Alexey Bataevb3638132018-07-19 16:34:13 +00006889 // &d, &d, sizeof(double), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006890 //
6891 // map(i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006892 // &i, &i, 100*sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006893 //
6894 // map(i[1:23])
Alexey Bataevb3638132018-07-19 16:34:13 +00006895 // &i(=&i[0]), &i[1], 23*sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006896 //
6897 // map(p)
Alexey Bataevb3638132018-07-19 16:34:13 +00006898 // &p, &p, sizeof(float*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006899 //
6900 // map(p[1:24])
Alexey Bataevb3638132018-07-19 16:34:13 +00006901 // p, &p[1], 24*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006902 //
6903 // map(s)
Alexey Bataevb3638132018-07-19 16:34:13 +00006904 // &s, &s, sizeof(S2), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006905 //
6906 // map(s.i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006907 // &s, &(s.i), sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006908 //
6909 // map(s.s.f)
Alexey Bataevb3638132018-07-19 16:34:13 +00006910 // &s, &(s.s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006911 //
6912 // map(s.p)
Alexey Bataevb3638132018-07-19 16:34:13 +00006913 // &s, &(s.p), sizeof(double*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006914 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006915 // map(to: s.p[:22])
6916 // &s, &(s.p), sizeof(double*), TARGET_PARAM (*)
6917 // &s, &(s.p), sizeof(double*), MEMBER_OF(1) (**)
6918 // &(s.p), &(s.p[0]), 22*sizeof(double),
6919 // MEMBER_OF(1) | PTR_AND_OBJ | TO (***)
6920 // (*) alloc space for struct members, only this is a target parameter
6921 // (**) map the pointer (nothing to be mapped in this example) (the compiler
6922 // optimizes this entry out, same in the examples below)
6923 // (***) map the pointee (map: to)
Samuel Antao86ace552016-04-27 22:40:57 +00006924 //
6925 // map(s.ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006926 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006927 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006928 // map(from: s.ps->s.i)
6929 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6930 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6931 // &(s.ps), &(s.ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006932 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006933 // map(to: s.ps->ps)
6934 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6935 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6936 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006937 //
6938 // map(s.ps->ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006939 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6940 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6941 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6942 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006943 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006944 // map(to: s.ps->ps->s.f[:22])
6945 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6946 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6947 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6948 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006949 //
6950 // map(ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006951 // &ps, &ps, sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006952 //
6953 // map(ps->i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006954 // ps, &(ps->i), sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006955 //
6956 // map(ps->s.f)
Alexey Bataevb3638132018-07-19 16:34:13 +00006957 // ps, &(ps->s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006958 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006959 // map(from: ps->p)
6960 // ps, &(ps->p), sizeof(double*), TARGET_PARAM | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006961 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006962 // map(to: ps->p[:22])
6963 // ps, &(ps->p), sizeof(double*), TARGET_PARAM
6964 // ps, &(ps->p), sizeof(double*), MEMBER_OF(1)
6965 // &(ps->p), &(ps->p[0]), 22*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006966 //
6967 // map(ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006968 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006969 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006970 // map(from: ps->ps->s.i)
6971 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6972 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6973 // &(ps->ps), &(ps->ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006974 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006975 // map(from: ps->ps->ps)
6976 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6977 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6978 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006979 //
6980 // map(ps->ps->ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006981 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6982 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6983 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6984 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006985 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006986 // map(to: ps->ps->ps->s.f[:22])
6987 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6988 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6989 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6990 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO
6991 //
6992 // map(to: s.f[:22]) map(from: s.p[:33])
6993 // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1) +
6994 // sizeof(double*) (**), TARGET_PARAM
6995 // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | TO
6996 // &s, &(s.p), sizeof(double*), MEMBER_OF(1)
6997 // &(s.p), &(s.p[0]), 33*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | FROM
6998 // (*) allocate contiguous space needed to fit all mapped members even if
6999 // we allocate space for members not mapped (in this example,
7000 // s.f[22..49] and s.s are not mapped, yet we must allocate space for
7001 // them as well because they fall between &s.f[0] and &s.p)
7002 //
7003 // map(from: s.f[:22]) map(to: ps->p[:33])
7004 // &s, &(s.f[0]), 22*sizeof(float), TARGET_PARAM | FROM
7005 // ps, &(ps->p), sizeof(S2*), TARGET_PARAM
7006 // ps, &(ps->p), sizeof(double*), MEMBER_OF(2) (*)
7007 // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(2) | PTR_AND_OBJ | TO
7008 // (*) the struct this entry pertains to is the 2nd element in the list of
7009 // arguments, hence MEMBER_OF(2)
7010 //
7011 // map(from: s.f[:22], s.s) map(to: ps->p[:33])
7012 // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1), TARGET_PARAM
7013 // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | FROM
7014 // &s, &(s.s), sizeof(struct S1), MEMBER_OF(1) | FROM
7015 // ps, &(ps->p), sizeof(S2*), TARGET_PARAM
7016 // ps, &(ps->p), sizeof(double*), MEMBER_OF(4) (*)
7017 // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(4) | PTR_AND_OBJ | TO
7018 // (*) the struct this entry pertains to is the 4th element in the list
7019 // of arguments, hence MEMBER_OF(4)
Samuel Antao86ace552016-04-27 22:40:57 +00007020
7021 // Track if the map information being generated is the first for a capture.
7022 bool IsCaptureFirstInfo = IsFirstComponentList;
Alexey Bataev92327c52018-03-26 16:40:55 +00007023 bool IsLink = false; // Is this variable a "declare target link"?
Samuel Antao86ace552016-04-27 22:40:57 +00007024
7025 // Scan the components from the base to the complete expression.
7026 auto CI = Components.rbegin();
7027 auto CE = Components.rend();
7028 auto I = CI;
7029
7030 // Track if the map information being generated is the first for a list of
7031 // components.
7032 bool IsExpressionFirstInfo = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00007033 Address BP = Address::invalid();
Patrick Lystere13b1e32019-01-02 19:28:48 +00007034 const Expr *AssocExpr = I->getAssociatedExpression();
7035 const auto *AE = dyn_cast<ArraySubscriptExpr>(AssocExpr);
7036 const auto *OASE = dyn_cast<OMPArraySectionExpr>(AssocExpr);
Samuel Antao86ace552016-04-27 22:40:57 +00007037
Patrick Lystere13b1e32019-01-02 19:28:48 +00007038 if (isa<MemberExpr>(AssocExpr)) {
Samuel Antao86ace552016-04-27 22:40:57 +00007039 // The base is the 'this' pointer. The content of the pointer is going
7040 // to be the base of the field being mapped.
Alexey Bataevb3638132018-07-19 16:34:13 +00007041 BP = CGF.LoadCXXThisAddress();
Patrick Lystere13b1e32019-01-02 19:28:48 +00007042 } else if ((AE && isa<CXXThisExpr>(AE->getBase()->IgnoreParenImpCasts())) ||
7043 (OASE &&
7044 isa<CXXThisExpr>(OASE->getBase()->IgnoreParenImpCasts()))) {
7045 BP = CGF.EmitOMPSharedLValue(AssocExpr).getAddress();
Samuel Antao86ace552016-04-27 22:40:57 +00007046 } else {
7047 // The base is the reference to the variable.
7048 // BP = &Var.
Patrick Lystere13b1e32019-01-02 19:28:48 +00007049 BP = CGF.EmitOMPSharedLValue(AssocExpr).getAddress();
Alexey Bataev92327c52018-03-26 16:40:55 +00007050 if (const auto *VD =
7051 dyn_cast_or_null<VarDecl>(I->getAssociatedDeclaration())) {
7052 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00007053 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataev2c1dffe2018-04-16 20:34:41 +00007054 if (*Res == OMPDeclareTargetDeclAttr::MT_Link) {
7055 IsLink = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00007056 BP = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
Alexey Bataev2c1dffe2018-04-16 20:34:41 +00007057 }
Alexey Bataev92327c52018-03-26 16:40:55 +00007058 }
Samuel Antao86ace552016-04-27 22:40:57 +00007059
7060 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00007061 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00007062 // reference. References are ignored for mapping purposes.
7063 QualType Ty =
7064 I->getAssociatedDeclaration()->getType().getNonReferenceType();
7065 if (Ty->isAnyPointerType() && std::next(I) != CE) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007066 BP = CGF.EmitLoadOfPointer(BP, Ty->castAs<PointerType>());
Samuel Antao86ace552016-04-27 22:40:57 +00007067
7068 // We do not need to generate individual map information for the
7069 // pointer, it can be associated with the combined storage.
7070 ++I;
7071 }
7072 }
7073
Alexey Bataevb3638132018-07-19 16:34:13 +00007074 // Track whether a component of the list should be marked as MEMBER_OF some
7075 // combined entry (for partial structs). Only the first PTR_AND_OBJ entry
7076 // in a component list should be marked as MEMBER_OF, all subsequent entries
7077 // do not belong to the base struct. E.g.
7078 // struct S2 s;
7079 // s.ps->ps->ps->f[:]
7080 // (1) (2) (3) (4)
7081 // ps(1) is a member pointer, ps(2) is a pointee of ps(1), so it is a
7082 // PTR_AND_OBJ entry; the PTR is ps(1), so MEMBER_OF the base struct. ps(3)
7083 // is the pointee of ps(2) which is not member of struct s, so it should not
7084 // be marked as such (it is still PTR_AND_OBJ).
7085 // The variable is initialized to false so that PTR_AND_OBJ entries which
7086 // are not struct members are not considered (e.g. array of pointers to
7087 // data).
7088 bool ShouldBeMemberOf = false;
7089
7090 // Variable keeping track of whether or not we have encountered a component
7091 // in the component list which is a member expression. Useful when we have a
7092 // pointer or a final array section, in which case it is the previous
7093 // component in the list which tells us whether we have a member expression.
7094 // E.g. X.f[:]
7095 // While processing the final array section "[:]" it is "f" which tells us
7096 // whether we are dealing with a member of a declared struct.
7097 const MemberExpr *EncounteredME = nullptr;
7098
Samuel Antao86ace552016-04-27 22:40:57 +00007099 for (; I != CE; ++I) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007100 // If the current component is member of a struct (parent struct) mark it.
7101 if (!EncounteredME) {
7102 EncounteredME = dyn_cast<MemberExpr>(I->getAssociatedExpression());
7103 // If we encounter a PTR_AND_OBJ entry from now on it should be marked
7104 // as MEMBER_OF the parent struct.
7105 if (EncounteredME)
7106 ShouldBeMemberOf = true;
7107 }
7108
Samuel Antao86ace552016-04-27 22:40:57 +00007109 auto Next = std::next(I);
7110
7111 // We need to generate the addresses and sizes if this is the last
7112 // component, if the component is a pointer or if it is an array section
7113 // whose length can't be proved to be one. If this is a pointer, it
7114 // becomes the base address for the following components.
7115
7116 // A final array section, is one whose length can't be proved to be one.
7117 bool IsFinalArraySection =
7118 isFinalArraySectionExpression(I->getAssociatedExpression());
7119
7120 // Get information on whether the element is a pointer. Have to do a
7121 // special treatment for array sections given that they are built-in
7122 // types.
7123 const auto *OASE =
7124 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
7125 bool IsPointer =
Alexey Bataevb3638132018-07-19 16:34:13 +00007126 (OASE && OMPArraySectionExpr::getBaseOriginalType(OASE)
7127 .getCanonicalType()
7128 ->isAnyPointerType()) ||
Samuel Antao86ace552016-04-27 22:40:57 +00007129 I->getAssociatedExpression()->getType()->isAnyPointerType();
7130
7131 if (Next == CE || IsPointer || IsFinalArraySection) {
Samuel Antao86ace552016-04-27 22:40:57 +00007132 // If this is not the last component, we expect the pointer to be
7133 // associated with an array expression or member expression.
7134 assert((Next == CE ||
7135 isa<MemberExpr>(Next->getAssociatedExpression()) ||
7136 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
7137 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
7138 "Unexpected expression");
7139
Alexey Bataevb3638132018-07-19 16:34:13 +00007140 Address LB =
7141 CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getAddress();
Samuel Antao86ace552016-04-27 22:40:57 +00007142
Alexey Bataevb3638132018-07-19 16:34:13 +00007143 // If this component is a pointer inside the base struct then we don't
7144 // need to create any entry for it - it will be combined with the object
7145 // it is pointing to into a single PTR_AND_OBJ entry.
7146 bool IsMemberPointer =
7147 IsPointer && EncounteredME &&
7148 (dyn_cast<MemberExpr>(I->getAssociatedExpression()) ==
7149 EncounteredME);
Alexey Bataeve82445f2018-09-20 13:54:02 +00007150 if (!OverlappedElements.empty()) {
7151 // Handle base element with the info for overlapped elements.
7152 assert(!PartialStruct.Base.isValid() && "The base element is set.");
7153 assert(Next == CE &&
7154 "Expected last element for the overlapped elements.");
7155 assert(!IsPointer &&
7156 "Unexpected base element with the pointer type.");
7157 // Mark the whole struct as the struct that requires allocation on the
7158 // device.
7159 PartialStruct.LowestElem = {0, LB};
7160 CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(
7161 I->getAssociatedExpression()->getType());
7162 Address HB = CGF.Builder.CreateConstGEP(
7163 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(LB,
7164 CGF.VoidPtrTy),
James Y Knight751fe282019-02-09 22:22:28 +00007165 TypeSize.getQuantity() - 1);
Alexey Bataeve82445f2018-09-20 13:54:02 +00007166 PartialStruct.HighestElem = {
7167 std::numeric_limits<decltype(
7168 PartialStruct.HighestElem.first)>::max(),
7169 HB};
7170 PartialStruct.Base = BP;
7171 // Emit data for non-overlapped data.
7172 OpenMPOffloadMappingFlags Flags =
7173 OMP_MAP_MEMBER_OF |
Kelvin Lief579432018-12-18 22:18:41 +00007174 getMapTypeBits(MapType, MapModifiers, IsImplicit,
Alexey Bataeve82445f2018-09-20 13:54:02 +00007175 /*AddPtrFlag=*/false,
7176 /*AddIsTargetParamFlag=*/false);
7177 LB = BP;
7178 llvm::Value *Size = nullptr;
7179 // Do bitcopy of all non-overlapped structure elements.
7180 for (OMPClauseMappableExprCommon::MappableExprComponentListRef
7181 Component : OverlappedElements) {
7182 Address ComponentLB = Address::invalid();
7183 for (const OMPClauseMappableExprCommon::MappableComponent &MC :
7184 Component) {
7185 if (MC.getAssociatedDeclaration()) {
7186 ComponentLB =
7187 CGF.EmitOMPSharedLValue(MC.getAssociatedExpression())
7188 .getAddress();
7189 Size = CGF.Builder.CreatePtrDiff(
7190 CGF.EmitCastToVoidPtr(ComponentLB.getPointer()),
7191 CGF.EmitCastToVoidPtr(LB.getPointer()));
7192 break;
7193 }
7194 }
7195 BasePointers.push_back(BP.getPointer());
7196 Pointers.push_back(LB.getPointer());
7197 Sizes.push_back(Size);
7198 Types.push_back(Flags);
James Y Knight751fe282019-02-09 22:22:28 +00007199 LB = CGF.Builder.CreateConstGEP(ComponentLB, 1);
Alexey Bataeve82445f2018-09-20 13:54:02 +00007200 }
7201 BasePointers.push_back(BP.getPointer());
7202 Pointers.push_back(LB.getPointer());
7203 Size = CGF.Builder.CreatePtrDiff(
7204 CGF.EmitCastToVoidPtr(
James Y Knight751fe282019-02-09 22:22:28 +00007205 CGF.Builder.CreateConstGEP(HB, 1).getPointer()),
Alexey Bataeve82445f2018-09-20 13:54:02 +00007206 CGF.EmitCastToVoidPtr(LB.getPointer()));
7207 Sizes.push_back(Size);
7208 Types.push_back(Flags);
7209 break;
7210 }
7211 llvm::Value *Size = getExprTypeSize(I->getAssociatedExpression());
Alexey Bataevb3638132018-07-19 16:34:13 +00007212 if (!IsMemberPointer) {
7213 BasePointers.push_back(BP.getPointer());
7214 Pointers.push_back(LB.getPointer());
7215 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00007216
Alexey Bataevb3638132018-07-19 16:34:13 +00007217 // We need to add a pointer flag for each map that comes from the
7218 // same expression except for the first one. We also need to signal
7219 // this map is the first one that relates with the current capture
7220 // (there is a set of entries for each capture).
7221 OpenMPOffloadMappingFlags Flags = getMapTypeBits(
Kelvin Lief579432018-12-18 22:18:41 +00007222 MapType, MapModifiers, IsImplicit,
Alexey Bataevb3638132018-07-19 16:34:13 +00007223 !IsExpressionFirstInfo || IsLink, IsCaptureFirstInfo && !IsLink);
7224
7225 if (!IsExpressionFirstInfo) {
7226 // If we have a PTR_AND_OBJ pair where the OBJ is a pointer as well,
7227 // then we reset the TO/FROM/ALWAYS/DELETE flags.
7228 if (IsPointer)
7229 Flags &= ~(OMP_MAP_TO | OMP_MAP_FROM | OMP_MAP_ALWAYS |
7230 OMP_MAP_DELETE);
7231
7232 if (ShouldBeMemberOf) {
7233 // Set placeholder value MEMBER_OF=FFFF to indicate that the flag
7234 // should be later updated with the correct value of MEMBER_OF.
7235 Flags |= OMP_MAP_MEMBER_OF;
7236 // From now on, all subsequent PTR_AND_OBJ entries should not be
7237 // marked as MEMBER_OF.
7238 ShouldBeMemberOf = false;
7239 }
7240 }
7241
7242 Types.push_back(Flags);
Samuel Antao03a3cec2016-07-27 22:52:16 +00007243 }
7244
Alexey Bataevb3638132018-07-19 16:34:13 +00007245 // If we have encountered a member expression so far, keep track of the
7246 // mapped member. If the parent is "*this", then the value declaration
7247 // is nullptr.
7248 if (EncounteredME) {
7249 const auto *FD = dyn_cast<FieldDecl>(EncounteredME->getMemberDecl());
7250 unsigned FieldIndex = FD->getFieldIndex();
Samuel Antao03a3cec2016-07-27 22:52:16 +00007251
Alexey Bataevb3638132018-07-19 16:34:13 +00007252 // Update info about the lowest and highest elements for this struct
7253 if (!PartialStruct.Base.isValid()) {
7254 PartialStruct.LowestElem = {FieldIndex, LB};
7255 PartialStruct.HighestElem = {FieldIndex, LB};
7256 PartialStruct.Base = BP;
7257 } else if (FieldIndex < PartialStruct.LowestElem.first) {
7258 PartialStruct.LowestElem = {FieldIndex, LB};
7259 } else if (FieldIndex > PartialStruct.HighestElem.first) {
7260 PartialStruct.HighestElem = {FieldIndex, LB};
7261 }
7262 }
Samuel Antao86ace552016-04-27 22:40:57 +00007263
7264 // If we have a final array section, we are done with this expression.
7265 if (IsFinalArraySection)
7266 break;
7267
7268 // The pointer becomes the base for the next element.
7269 if (Next != CE)
7270 BP = LB;
7271
7272 IsExpressionFirstInfo = false;
7273 IsCaptureFirstInfo = false;
Samuel Antao86ace552016-04-27 22:40:57 +00007274 }
7275 }
7276 }
7277
Alexey Bataevb3638132018-07-19 16:34:13 +00007278 /// Return the adjusted map modifiers if the declaration a capture refers to
7279 /// appears in a first-private clause. This is expected to be used only with
7280 /// directives that start with 'target'.
7281 MappableExprsHandler::OpenMPOffloadMappingFlags
7282 getMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap) const {
7283 assert(Cap.capturesVariable() && "Expected capture by reference only!");
7284
7285 // A first private variable captured by reference will use only the
7286 // 'private ptr' and 'map to' flag. Return the right flags if the captured
7287 // declaration is known as first-private in this handler.
Alexey Bataev1af5bd52019-03-05 17:47:18 +00007288 if (FirstPrivateDecls.count(Cap.getCapturedVar())) {
7289 if (Cap.getCapturedVar()->getType().isConstant(CGF.getContext()) &&
7290 Cap.getCaptureKind() == CapturedStmt::VCK_ByRef)
7291 return MappableExprsHandler::OMP_MAP_ALWAYS |
7292 MappableExprsHandler::OMP_MAP_TO;
Alexey Bataevb3638132018-07-19 16:34:13 +00007293 return MappableExprsHandler::OMP_MAP_PRIVATE |
7294 MappableExprsHandler::OMP_MAP_TO;
Alexey Bataev1af5bd52019-03-05 17:47:18 +00007295 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007296 return MappableExprsHandler::OMP_MAP_TO |
7297 MappableExprsHandler::OMP_MAP_FROM;
7298 }
7299
7300 static OpenMPOffloadMappingFlags getMemberOfFlag(unsigned Position) {
7301 // Member of is given by the 16 MSB of the flag, so rotate by 48 bits.
7302 return static_cast<OpenMPOffloadMappingFlags>(((uint64_t)Position + 1)
7303 << 48);
7304 }
7305
7306 static void setCorrectMemberOfFlag(OpenMPOffloadMappingFlags &Flags,
7307 OpenMPOffloadMappingFlags MemberOfFlag) {
7308 // If the entry is PTR_AND_OBJ but has not been marked with the special
7309 // placeholder value 0xFFFF in the MEMBER_OF field, then it should not be
7310 // marked as MEMBER_OF.
7311 if ((Flags & OMP_MAP_PTR_AND_OBJ) &&
7312 ((Flags & OMP_MAP_MEMBER_OF) != OMP_MAP_MEMBER_OF))
7313 return;
7314
7315 // Reset the placeholder value to prepare the flag for the assignment of the
7316 // proper MEMBER_OF value.
7317 Flags &= ~OMP_MAP_MEMBER_OF;
7318 Flags |= MemberOfFlag;
7319 }
7320
Alexey Bataeve82445f2018-09-20 13:54:02 +00007321 void getPlainLayout(const CXXRecordDecl *RD,
7322 llvm::SmallVectorImpl<const FieldDecl *> &Layout,
7323 bool AsBase) const {
7324 const CGRecordLayout &RL = CGF.getTypes().getCGRecordLayout(RD);
7325
7326 llvm::StructType *St =
7327 AsBase ? RL.getBaseSubobjectLLVMType() : RL.getLLVMType();
7328
7329 unsigned NumElements = St->getNumElements();
7330 llvm::SmallVector<
7331 llvm::PointerUnion<const CXXRecordDecl *, const FieldDecl *>, 4>
7332 RecordLayout(NumElements);
7333
7334 // Fill bases.
7335 for (const auto &I : RD->bases()) {
7336 if (I.isVirtual())
7337 continue;
7338 const auto *Base = I.getType()->getAsCXXRecordDecl();
7339 // Ignore empty bases.
7340 if (Base->isEmpty() || CGF.getContext()
7341 .getASTRecordLayout(Base)
7342 .getNonVirtualSize()
7343 .isZero())
7344 continue;
7345
7346 unsigned FieldIndex = RL.getNonVirtualBaseLLVMFieldNo(Base);
7347 RecordLayout[FieldIndex] = Base;
7348 }
7349 // Fill in virtual bases.
7350 for (const auto &I : RD->vbases()) {
7351 const auto *Base = I.getType()->getAsCXXRecordDecl();
7352 // Ignore empty bases.
7353 if (Base->isEmpty())
7354 continue;
7355 unsigned FieldIndex = RL.getVirtualBaseIndex(Base);
7356 if (RecordLayout[FieldIndex])
7357 continue;
7358 RecordLayout[FieldIndex] = Base;
7359 }
7360 // Fill in all the fields.
7361 assert(!RD->isUnion() && "Unexpected union.");
7362 for (const auto *Field : RD->fields()) {
7363 // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
7364 // will fill in later.)
7365 if (!Field->isBitField()) {
7366 unsigned FieldIndex = RL.getLLVMFieldNo(Field);
7367 RecordLayout[FieldIndex] = Field;
7368 }
7369 }
7370 for (const llvm::PointerUnion<const CXXRecordDecl *, const FieldDecl *>
7371 &Data : RecordLayout) {
7372 if (Data.isNull())
7373 continue;
7374 if (const auto *Base = Data.dyn_cast<const CXXRecordDecl *>())
7375 getPlainLayout(Base, Layout, /*AsBase=*/true);
7376 else
7377 Layout.push_back(Data.get<const FieldDecl *>());
7378 }
7379 }
7380
Alexey Bataevb3638132018-07-19 16:34:13 +00007381public:
7382 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
7383 : CurDir(Dir), CGF(CGF) {
7384 // Extract firstprivate clause information.
7385 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
7386 for (const auto *D : C->varlists())
7387 FirstPrivateDecls.insert(
7388 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
7389 // Extract device pointer clause information.
7390 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
7391 for (auto L : C->component_lists())
7392 DevPointersMap[L.first].push_back(L.second);
7393 }
7394
7395 /// Generate code for the combined entry if we have a partially mapped struct
7396 /// and take care of the mapping flags of the arguments corresponding to
7397 /// individual struct members.
7398 void emitCombinedEntry(MapBaseValuesArrayTy &BasePointers,
7399 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7400 MapFlagsArrayTy &Types, MapFlagsArrayTy &CurTypes,
7401 const StructRangeInfoTy &PartialStruct) const {
7402 // Base is the base of the struct
7403 BasePointers.push_back(PartialStruct.Base.getPointer());
7404 // Pointer is the address of the lowest element
7405 llvm::Value *LB = PartialStruct.LowestElem.second.getPointer();
7406 Pointers.push_back(LB);
7407 // Size is (addr of {highest+1} element) - (addr of lowest element)
7408 llvm::Value *HB = PartialStruct.HighestElem.second.getPointer();
7409 llvm::Value *HAddr = CGF.Builder.CreateConstGEP1_32(HB, /*Idx0=*/1);
7410 llvm::Value *CLAddr = CGF.Builder.CreatePointerCast(LB, CGF.VoidPtrTy);
7411 llvm::Value *CHAddr = CGF.Builder.CreatePointerCast(HAddr, CGF.VoidPtrTy);
7412 llvm::Value *Diff = CGF.Builder.CreatePtrDiff(CHAddr, CLAddr);
7413 llvm::Value *Size = CGF.Builder.CreateIntCast(Diff, CGF.SizeTy,
7414 /*isSinged=*/false);
7415 Sizes.push_back(Size);
7416 // Map type is always TARGET_PARAM
7417 Types.push_back(OMP_MAP_TARGET_PARAM);
7418 // Remove TARGET_PARAM flag from the first element
7419 (*CurTypes.begin()) &= ~OMP_MAP_TARGET_PARAM;
7420
7421 // All other current entries will be MEMBER_OF the combined entry
7422 // (except for PTR_AND_OBJ entries which do not have a placeholder value
7423 // 0xFFFF in the MEMBER_OF field).
7424 OpenMPOffloadMappingFlags MemberOfFlag =
7425 getMemberOfFlag(BasePointers.size() - 1);
7426 for (auto &M : CurTypes)
7427 setCorrectMemberOfFlag(M, MemberOfFlag);
7428 }
7429
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007430 /// Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00007431 /// types for the extracted mappable expressions. Also, for each item that
7432 /// relates with a device pointer, a pair of the relevant declaration and
7433 /// index where it occurs is appended to the device pointers info array.
7434 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007435 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7436 MapFlagsArrayTy &Types) const {
Samuel Antao86ace552016-04-27 22:40:57 +00007437 // We have to process the component lists that relate with the same
7438 // declaration in a single chunk so that we can generate the map flags
7439 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00007440 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00007441
7442 // Helper function to fill the information map for the different supported
7443 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00007444 auto &&InfoGen = [&Info](
7445 const ValueDecl *D,
7446 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
Kelvin Lief579432018-12-18 22:18:41 +00007447 OpenMPMapClauseKind MapType,
7448 ArrayRef<OpenMPMapModifierKind> MapModifiers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007449 bool ReturnDevicePointer, bool IsImplicit) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007450 const ValueDecl *VD =
7451 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Kelvin Lief579432018-12-18 22:18:41 +00007452 Info[VD].emplace_back(L, MapType, MapModifiers, ReturnDevicePointer,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007453 IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007454 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00007455
Paul Robinson78fb1322016-08-01 22:12:46 +00007456 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007457 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
7458 for (const auto &L : C->component_lists()) {
Kelvin Lief579432018-12-18 22:18:41 +00007459 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifiers(),
Alexey Bataevb3638132018-07-19 16:34:13 +00007460 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007461 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007462 for (const auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
7463 for (const auto &L : C->component_lists()) {
Kelvin Lief579432018-12-18 22:18:41 +00007464 InfoGen(L.first, L.second, OMPC_MAP_to, llvm::None,
Alexey Bataevb3638132018-07-19 16:34:13 +00007465 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007466 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007467 for (const auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
7468 for (const auto &L : C->component_lists()) {
Kelvin Lief579432018-12-18 22:18:41 +00007469 InfoGen(L.first, L.second, OMPC_MAP_from, llvm::None,
Alexey Bataevb3638132018-07-19 16:34:13 +00007470 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007471 }
Samuel Antao86ace552016-04-27 22:40:57 +00007472
Samuel Antaocc10b852016-07-28 14:23:26 +00007473 // Look at the use_device_ptr clause information and mark the existing map
7474 // entries as such. If there is no map information for an entry in the
7475 // use_device_ptr list, we create one with map type 'alloc' and zero size
Alexey Bataevb3638132018-07-19 16:34:13 +00007476 // section. It is the user fault if that was not mapped before. If there is
7477 // no map information and the pointer is a struct member, then we defer the
7478 // emission of that entry until the whole struct has been processed.
7479 llvm::MapVector<const ValueDecl *, SmallVector<DeferredDevicePtrEntryTy, 4>>
7480 DeferredInfo;
7481
Paul Robinson78fb1322016-08-01 22:12:46 +00007482 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataevb3638132018-07-19 16:34:13 +00007483 for (const auto *C :
7484 this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007485 for (const auto &L : C->component_lists()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007486 assert(!L.second.empty() && "Not expecting empty list of components!");
7487 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
7488 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007489 const Expr *IE = L.second.back().getAssociatedExpression();
Samuel Antaocc10b852016-07-28 14:23:26 +00007490 // If the first component is a member expression, we have to look into
7491 // 'this', which maps to null in the map of map information. Otherwise
7492 // look directly for the information.
7493 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
7494
7495 // We potentially have map information for this declaration already.
7496 // Look for the first set of components that refer to it.
7497 if (It != Info.end()) {
7498 auto CI = std::find_if(
7499 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
7500 return MI.Components.back().getAssociatedDeclaration() == VD;
7501 });
7502 // If we found a map entry, signal that the pointer has to be returned
7503 // and move on to the next declaration.
7504 if (CI != It->second.end()) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007505 CI->ReturnDevicePointer = true;
Samuel Antaocc10b852016-07-28 14:23:26 +00007506 continue;
7507 }
7508 }
7509
7510 // We didn't find any match in our map information - generate a zero
Alexey Bataevb3638132018-07-19 16:34:13 +00007511 // size array section - if the pointer is a struct member we defer this
7512 // action until the whole struct has been processed.
Paul Robinson78fb1322016-08-01 22:12:46 +00007513 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Alexey Bataevb3638132018-07-19 16:34:13 +00007514 if (isa<MemberExpr>(IE)) {
7515 // Insert the pointer into Info to be processed by
7516 // generateInfoForComponentList. Because it is a member pointer
7517 // without a pointee, no entry will be generated for it, therefore
7518 // we need to generate one after the whole struct has been processed.
7519 // Nonetheless, generateInfoForComponentList must be called to take
7520 // the pointer into account for the calculation of the range of the
7521 // partial struct.
Kelvin Lief579432018-12-18 22:18:41 +00007522 InfoGen(nullptr, L.second, OMPC_MAP_unknown, llvm::None,
Alexey Bataevb3638132018-07-19 16:34:13 +00007523 /*ReturnDevicePointer=*/false, C->isImplicit());
7524 DeferredInfo[nullptr].emplace_back(IE, VD);
7525 } else {
7526 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(
7527 this->CGF.EmitLValue(IE), IE->getExprLoc());
7528 BasePointers.emplace_back(Ptr, VD);
7529 Pointers.push_back(Ptr);
7530 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
7531 Types.push_back(OMP_MAP_RETURN_PARAM | OMP_MAP_TARGET_PARAM);
7532 }
Samuel Antaocc10b852016-07-28 14:23:26 +00007533 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007534 }
Samuel Antaocc10b852016-07-28 14:23:26 +00007535
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007536 for (const auto &M : Info) {
Samuel Antao86ace552016-04-27 22:40:57 +00007537 // We need to know when we generate information for the first component
7538 // associated with a capture, because the mapping flags depend on it.
7539 bool IsFirstComponentList = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00007540
7541 // Temporary versions of arrays
7542 MapBaseValuesArrayTy CurBasePointers;
7543 MapValuesArrayTy CurPointers;
7544 MapValuesArrayTy CurSizes;
7545 MapFlagsArrayTy CurTypes;
7546 StructRangeInfoTy PartialStruct;
7547
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007548 for (const MapInfo &L : M.second) {
Samuel Antao86ace552016-04-27 22:40:57 +00007549 assert(!L.Components.empty() &&
7550 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00007551
7552 // Remember the current base pointer index.
Alexey Bataevb3638132018-07-19 16:34:13 +00007553 unsigned CurrentBasePointersIdx = CurBasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00007554 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007555 this->generateInfoForComponentList(
Kelvin Lief579432018-12-18 22:18:41 +00007556 L.MapType, L.MapModifiers, L.Components, CurBasePointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007557 CurPointers, CurSizes, CurTypes, PartialStruct,
7558 IsFirstComponentList, L.IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007559
7560 // If this entry relates with a device pointer, set the relevant
7561 // declaration and add the 'return pointer' flag.
Alexey Bataevb3638132018-07-19 16:34:13 +00007562 if (L.ReturnDevicePointer) {
7563 assert(CurBasePointers.size() > CurrentBasePointersIdx &&
Samuel Antaocc10b852016-07-28 14:23:26 +00007564 "Unexpected number of mapped base pointers.");
7565
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007566 const ValueDecl *RelevantVD =
7567 L.Components.back().getAssociatedDeclaration();
Samuel Antaocc10b852016-07-28 14:23:26 +00007568 assert(RelevantVD &&
7569 "No relevant declaration related with device pointer??");
7570
Alexey Bataevb3638132018-07-19 16:34:13 +00007571 CurBasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
7572 CurTypes[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PARAM;
Samuel Antaocc10b852016-07-28 14:23:26 +00007573 }
Samuel Antao86ace552016-04-27 22:40:57 +00007574 IsFirstComponentList = false;
7575 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007576
7577 // Append any pending zero-length pointers which are struct members and
7578 // used with use_device_ptr.
7579 auto CI = DeferredInfo.find(M.first);
7580 if (CI != DeferredInfo.end()) {
7581 for (const DeferredDevicePtrEntryTy &L : CI->second) {
7582 llvm::Value *BasePtr = this->CGF.EmitLValue(L.IE).getPointer();
7583 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(
7584 this->CGF.EmitLValue(L.IE), L.IE->getExprLoc());
7585 CurBasePointers.emplace_back(BasePtr, L.VD);
7586 CurPointers.push_back(Ptr);
7587 CurSizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
7588 // Entry is PTR_AND_OBJ and RETURN_PARAM. Also, set the placeholder
7589 // value MEMBER_OF=FFFF so that the entry is later updated with the
7590 // correct value of MEMBER_OF.
7591 CurTypes.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_RETURN_PARAM |
7592 OMP_MAP_MEMBER_OF);
7593 }
7594 }
7595
7596 // If there is an entry in PartialStruct it means we have a struct with
7597 // individual members mapped. Emit an extra combined entry.
7598 if (PartialStruct.Base.isValid())
7599 emitCombinedEntry(BasePointers, Pointers, Sizes, Types, CurTypes,
7600 PartialStruct);
7601
7602 // We need to append the results of this capture to what we already have.
7603 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
7604 Pointers.append(CurPointers.begin(), CurPointers.end());
7605 Sizes.append(CurSizes.begin(), CurSizes.end());
7606 Types.append(CurTypes.begin(), CurTypes.end());
Samuel Antao86ace552016-04-27 22:40:57 +00007607 }
7608 }
7609
Alexey Bataev60705422018-10-30 15:50:12 +00007610 /// Emit capture info for lambdas for variables captured by reference.
Alexey Bataev969dbc02018-11-08 15:47:39 +00007611 void generateInfoForLambdaCaptures(
7612 const ValueDecl *VD, llvm::Value *Arg, MapBaseValuesArrayTy &BasePointers,
7613 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7614 MapFlagsArrayTy &Types,
7615 llvm::DenseMap<llvm::Value *, llvm::Value *> &LambdaPointers) const {
Alexey Bataev60705422018-10-30 15:50:12 +00007616 const auto *RD = VD->getType()
7617 .getCanonicalType()
7618 .getNonReferenceType()
7619 ->getAsCXXRecordDecl();
7620 if (!RD || !RD->isLambda())
7621 return;
7622 Address VDAddr = Address(Arg, CGF.getContext().getDeclAlign(VD));
7623 LValue VDLVal = CGF.MakeAddrLValue(
7624 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
7625 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
7626 FieldDecl *ThisCapture = nullptr;
7627 RD->getCaptureFields(Captures, ThisCapture);
7628 if (ThisCapture) {
7629 LValue ThisLVal =
7630 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
Alexey Bataev969dbc02018-11-08 15:47:39 +00007631 LValue ThisLValVal = CGF.EmitLValueForField(VDLVal, ThisCapture);
7632 LambdaPointers.try_emplace(ThisLVal.getPointer(), VDLVal.getPointer());
7633 BasePointers.push_back(ThisLVal.getPointer());
7634 Pointers.push_back(ThisLValVal.getPointer());
Alexey Bataev60705422018-10-30 15:50:12 +00007635 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
Alexey Bataev2dc07d02018-11-02 15:25:06 +00007636 Types.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
Alexey Bataev60705422018-10-30 15:50:12 +00007637 OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT);
7638 }
7639 for (const LambdaCapture &LC : RD->captures()) {
7640 if (LC.getCaptureKind() != LCK_ByRef)
7641 continue;
7642 const VarDecl *VD = LC.getCapturedVar();
7643 auto It = Captures.find(VD);
7644 assert(It != Captures.end() && "Found lambda capture without field.");
7645 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
Alexey Bataev969dbc02018-11-08 15:47:39 +00007646 LValue VarLValVal = CGF.EmitLValueForField(VDLVal, It->second);
7647 LambdaPointers.try_emplace(VarLVal.getPointer(), VDLVal.getPointer());
7648 BasePointers.push_back(VarLVal.getPointer());
7649 Pointers.push_back(VarLValVal.getPointer());
Alexey Bataev60705422018-10-30 15:50:12 +00007650 Sizes.push_back(CGF.getTypeSize(
7651 VD->getType().getCanonicalType().getNonReferenceType()));
Alexey Bataev2dc07d02018-11-02 15:25:06 +00007652 Types.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
Alexey Bataev60705422018-10-30 15:50:12 +00007653 OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT);
7654 }
7655 }
7656
7657 /// Set correct indices for lambdas captures.
Alexey Bataev969dbc02018-11-08 15:47:39 +00007658 void adjustMemberOfForLambdaCaptures(
7659 const llvm::DenseMap<llvm::Value *, llvm::Value *> &LambdaPointers,
7660 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
7661 MapFlagsArrayTy &Types) const {
Alexey Bataev60705422018-10-30 15:50:12 +00007662 for (unsigned I = 0, E = Types.size(); I < E; ++I) {
7663 // Set correct member_of idx for all implicit lambda captures.
Alexey Bataev2dc07d02018-11-02 15:25:06 +00007664 if (Types[I] != (OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
Alexey Bataev60705422018-10-30 15:50:12 +00007665 OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT))
7666 continue;
Alexey Bataev969dbc02018-11-08 15:47:39 +00007667 llvm::Value *BasePtr = LambdaPointers.lookup(*BasePointers[I]);
7668 assert(BasePtr && "Unable to find base lambda address.");
Alexey Bataev60705422018-10-30 15:50:12 +00007669 int TgtIdx = -1;
7670 for (unsigned J = I; J > 0; --J) {
7671 unsigned Idx = J - 1;
7672 if (Pointers[Idx] != BasePtr)
7673 continue;
7674 TgtIdx = Idx;
7675 break;
7676 }
7677 assert(TgtIdx != -1 && "Unable to find parent lambda.");
7678 // All other current entries will be MEMBER_OF the combined entry
7679 // (except for PTR_AND_OBJ entries which do not have a placeholder value
7680 // 0xFFFF in the MEMBER_OF field).
7681 OpenMPOffloadMappingFlags MemberOfFlag = getMemberOfFlag(TgtIdx);
7682 setCorrectMemberOfFlag(Types[I], MemberOfFlag);
7683 }
7684 }
7685
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007686 /// Generate the base pointers, section pointers, sizes and map types
Samuel Antao86ace552016-04-27 22:40:57 +00007687 /// associated to a given capture.
7688 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00007689 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007690 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007691 MapValuesArrayTy &Pointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007692 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
7693 StructRangeInfoTy &PartialStruct) const {
Samuel Antao86ace552016-04-27 22:40:57 +00007694 assert(!Cap->capturesVariableArrayType() &&
7695 "Not expecting to generate map info for a variable array type!");
7696
Samuel Antao6890b092016-07-28 14:25:09 +00007697 // We need to know when we generating information for the first component
Alexey Bataevb3638132018-07-19 16:34:13 +00007698 const ValueDecl *VD = Cap->capturesThis()
7699 ? nullptr
7700 : Cap->getCapturedVar()->getCanonicalDecl();
Samuel Antao86ace552016-04-27 22:40:57 +00007701
Samuel Antao6890b092016-07-28 14:25:09 +00007702 // If this declaration appears in a is_device_ptr clause we just have to
7703 // pass the pointer by value. If it is a reference to a declaration, we just
Alexey Bataevb3638132018-07-19 16:34:13 +00007704 // pass its value.
7705 if (DevPointersMap.count(VD)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007706 BasePointers.emplace_back(Arg, VD);
Samuel Antao6890b092016-07-28 14:25:09 +00007707 Pointers.push_back(Arg);
7708 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
George Rokos065755d2017-11-07 18:27:04 +00007709 Types.push_back(OMP_MAP_LITERAL | OMP_MAP_TARGET_PARAM);
Samuel Antao6890b092016-07-28 14:25:09 +00007710 return;
7711 }
7712
Alexey Bataeve82445f2018-09-20 13:54:02 +00007713 using MapData =
7714 std::tuple<OMPClauseMappableExprCommon::MappableExprComponentListRef,
Kelvin Lief579432018-12-18 22:18:41 +00007715 OpenMPMapClauseKind, ArrayRef<OpenMPMapModifierKind>, bool>;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007716 SmallVector<MapData, 4> DeclComponentLists;
Paul Robinson78fb1322016-08-01 22:12:46 +00007717 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeve82445f2018-09-20 13:54:02 +00007718 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007719 for (const auto &L : C->decl_component_lists(VD)) {
Samuel Antao86ace552016-04-27 22:40:57 +00007720 assert(L.first == VD &&
7721 "We got information for the wrong declaration??");
7722 assert(!L.second.empty() &&
7723 "Not expecting declaration with no component lists.");
Alexey Bataeve82445f2018-09-20 13:54:02 +00007724 DeclComponentLists.emplace_back(L.second, C->getMapType(),
Kelvin Lief579432018-12-18 22:18:41 +00007725 C->getMapTypeModifiers(),
Alexey Bataeve82445f2018-09-20 13:54:02 +00007726 C->isImplicit());
Samuel Antao86ace552016-04-27 22:40:57 +00007727 }
Alexey Bataeve82445f2018-09-20 13:54:02 +00007728 }
7729
7730 // Find overlapping elements (including the offset from the base element).
7731 llvm::SmallDenseMap<
7732 const MapData *,
7733 llvm::SmallVector<
7734 OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>,
7735 4>
7736 OverlappedData;
7737 size_t Count = 0;
7738 for (const MapData &L : DeclComponentLists) {
7739 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7740 OpenMPMapClauseKind MapType;
Kelvin Lief579432018-12-18 22:18:41 +00007741 ArrayRef<OpenMPMapModifierKind> MapModifiers;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007742 bool IsImplicit;
Kelvin Lief579432018-12-18 22:18:41 +00007743 std::tie(Components, MapType, MapModifiers, IsImplicit) = L;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007744 ++Count;
7745 for (const MapData &L1 : makeArrayRef(DeclComponentLists).slice(Count)) {
7746 OMPClauseMappableExprCommon::MappableExprComponentListRef Components1;
Kelvin Lief579432018-12-18 22:18:41 +00007747 std::tie(Components1, MapType, MapModifiers, IsImplicit) = L1;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007748 auto CI = Components.rbegin();
7749 auto CE = Components.rend();
7750 auto SI = Components1.rbegin();
7751 auto SE = Components1.rend();
7752 for (; CI != CE && SI != SE; ++CI, ++SI) {
7753 if (CI->getAssociatedExpression()->getStmtClass() !=
7754 SI->getAssociatedExpression()->getStmtClass())
7755 break;
7756 // Are we dealing with different variables/fields?
7757 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
7758 break;
7759 }
7760 // Found overlapping if, at least for one component, reached the head of
7761 // the components list.
7762 if (CI == CE || SI == SE) {
7763 assert((CI != CE || SI != SE) &&
7764 "Unexpected full match of the mapping components.");
7765 const MapData &BaseData = CI == CE ? L : L1;
7766 OMPClauseMappableExprCommon::MappableExprComponentListRef SubData =
7767 SI == SE ? Components : Components1;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007768 auto &OverlappedElements = OverlappedData.FindAndConstruct(&BaseData);
7769 OverlappedElements.getSecond().push_back(SubData);
7770 }
7771 }
7772 }
7773 // Sort the overlapped elements for each item.
7774 llvm::SmallVector<const FieldDecl *, 4> Layout;
7775 if (!OverlappedData.empty()) {
7776 if (const auto *CRD =
7777 VD->getType().getCanonicalType()->getAsCXXRecordDecl())
7778 getPlainLayout(CRD, Layout, /*AsBase=*/false);
7779 else {
7780 const auto *RD = VD->getType().getCanonicalType()->getAsRecordDecl();
7781 Layout.append(RD->field_begin(), RD->field_end());
7782 }
7783 }
7784 for (auto &Pair : OverlappedData) {
7785 llvm::sort(
7786 Pair.getSecond(),
7787 [&Layout](
7788 OMPClauseMappableExprCommon::MappableExprComponentListRef First,
7789 OMPClauseMappableExprCommon::MappableExprComponentListRef
7790 Second) {
7791 auto CI = First.rbegin();
7792 auto CE = First.rend();
7793 auto SI = Second.rbegin();
7794 auto SE = Second.rend();
7795 for (; CI != CE && SI != SE; ++CI, ++SI) {
7796 if (CI->getAssociatedExpression()->getStmtClass() !=
7797 SI->getAssociatedExpression()->getStmtClass())
7798 break;
7799 // Are we dealing with different variables/fields?
7800 if (CI->getAssociatedDeclaration() !=
7801 SI->getAssociatedDeclaration())
7802 break;
7803 }
Richard Trieu5061e832018-09-21 21:20:33 +00007804
7805 // Lists contain the same elements.
7806 if (CI == CE && SI == SE)
7807 return false;
7808
7809 // List with less elements is less than list with more elements.
7810 if (CI == CE || SI == SE)
7811 return CI == CE;
7812
Alexey Bataeve82445f2018-09-20 13:54:02 +00007813 const auto *FD1 = cast<FieldDecl>(CI->getAssociatedDeclaration());
7814 const auto *FD2 = cast<FieldDecl>(SI->getAssociatedDeclaration());
7815 if (FD1->getParent() == FD2->getParent())
7816 return FD1->getFieldIndex() < FD2->getFieldIndex();
7817 const auto It =
7818 llvm::find_if(Layout, [FD1, FD2](const FieldDecl *FD) {
7819 return FD == FD1 || FD == FD2;
7820 });
7821 return *It == FD1;
7822 });
7823 }
7824
7825 // Associated with a capture, because the mapping flags depend on it.
7826 // Go through all of the elements with the overlapped elements.
7827 for (const auto &Pair : OverlappedData) {
7828 const MapData &L = *Pair.getFirst();
7829 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7830 OpenMPMapClauseKind MapType;
Kelvin Lief579432018-12-18 22:18:41 +00007831 ArrayRef<OpenMPMapModifierKind> MapModifiers;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007832 bool IsImplicit;
Kelvin Lief579432018-12-18 22:18:41 +00007833 std::tie(Components, MapType, MapModifiers, IsImplicit) = L;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007834 ArrayRef<OMPClauseMappableExprCommon::MappableExprComponentListRef>
7835 OverlappedComponents = Pair.getSecond();
7836 bool IsFirstComponentList = true;
Kelvin Lief579432018-12-18 22:18:41 +00007837 generateInfoForComponentList(MapType, MapModifiers, Components,
Alexey Bataeve82445f2018-09-20 13:54:02 +00007838 BasePointers, Pointers, Sizes, Types,
7839 PartialStruct, IsFirstComponentList,
7840 IsImplicit, OverlappedComponents);
7841 }
7842 // Go through other elements without overlapped elements.
7843 bool IsFirstComponentList = OverlappedData.empty();
7844 for (const MapData &L : DeclComponentLists) {
7845 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7846 OpenMPMapClauseKind MapType;
Kelvin Lief579432018-12-18 22:18:41 +00007847 ArrayRef<OpenMPMapModifierKind> MapModifiers;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007848 bool IsImplicit;
Kelvin Lief579432018-12-18 22:18:41 +00007849 std::tie(Components, MapType, MapModifiers, IsImplicit) = L;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007850 auto It = OverlappedData.find(&L);
7851 if (It == OverlappedData.end())
Kelvin Lief579432018-12-18 22:18:41 +00007852 generateInfoForComponentList(MapType, MapModifiers, Components,
Alexey Bataeve82445f2018-09-20 13:54:02 +00007853 BasePointers, Pointers, Sizes, Types,
7854 PartialStruct, IsFirstComponentList,
7855 IsImplicit);
7856 IsFirstComponentList = false;
7857 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007858 }
Samuel Antao86ace552016-04-27 22:40:57 +00007859
Alexey Bataevb3638132018-07-19 16:34:13 +00007860 /// Generate the base pointers, section pointers, sizes and map types
7861 /// associated with the declare target link variables.
7862 void generateInfoForDeclareTargetLink(MapBaseValuesArrayTy &BasePointers,
7863 MapValuesArrayTy &Pointers,
7864 MapValuesArrayTy &Sizes,
7865 MapFlagsArrayTy &Types) const {
7866 // Map other list items in the map clause which are not captured variables
7867 // but "declare target link" global variables.,
7868 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) {
7869 for (const auto &L : C->component_lists()) {
7870 if (!L.first)
7871 continue;
7872 const auto *VD = dyn_cast<VarDecl>(L.first);
7873 if (!VD)
7874 continue;
7875 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00007876 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataevb3638132018-07-19 16:34:13 +00007877 if (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link)
7878 continue;
7879 StructRangeInfoTy PartialStruct;
7880 generateInfoForComponentList(
Kelvin Lief579432018-12-18 22:18:41 +00007881 C->getMapType(), C->getMapTypeModifiers(), L.second, BasePointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007882 Pointers, Sizes, Types, PartialStruct,
7883 /*IsFirstComponentList=*/true, C->isImplicit());
7884 assert(!PartialStruct.Base.isValid() &&
7885 "No partial structs for declare target link expected.");
7886 }
7887 }
Samuel Antao86ace552016-04-27 22:40:57 +00007888 }
Samuel Antaod486f842016-05-26 16:53:38 +00007889
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007890 /// Generate the default map information for a given capture \a CI,
Samuel Antaod486f842016-05-26 16:53:38 +00007891 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00007892 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
7893 const FieldDecl &RI, llvm::Value *CV,
7894 MapBaseValuesArrayTy &CurBasePointers,
7895 MapValuesArrayTy &CurPointers,
7896 MapValuesArrayTy &CurSizes,
Alexey Bataevb3638132018-07-19 16:34:13 +00007897 MapFlagsArrayTy &CurMapTypes) const {
Samuel Antaod486f842016-05-26 16:53:38 +00007898 // Do the default mapping.
7899 if (CI.capturesThis()) {
7900 CurBasePointers.push_back(CV);
7901 CurPointers.push_back(CV);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007902 const auto *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007903 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
7904 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00007905 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00007906 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007907 CurBasePointers.push_back(CV);
7908 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00007909 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007910 // We have to signal to the runtime captures passed by value that are
7911 // not pointers.
George Rokos065755d2017-11-07 18:27:04 +00007912 CurMapTypes.push_back(OMP_MAP_LITERAL);
Samuel Antaod486f842016-05-26 16:53:38 +00007913 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
7914 } else {
7915 // Pointers are implicitly mapped with a zero size and no flags
7916 // (other than first map that is added for all implicit maps).
Alexey Bataevb3638132018-07-19 16:34:13 +00007917 CurMapTypes.push_back(OMP_MAP_NONE);
Samuel Antaod486f842016-05-26 16:53:38 +00007918 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
7919 }
7920 } else {
7921 assert(CI.capturesVariable() && "Expected captured reference.");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007922 const auto *PtrTy = cast<ReferenceType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007923 QualType ElementType = PtrTy->getPointeeType();
7924 CurSizes.push_back(CGF.getTypeSize(ElementType));
7925 // The default map type for a scalar/complex type is 'to' because by
7926 // default the value doesn't have to be retrieved. For an aggregate
7927 // type, the default is 'tofrom'.
Alexey Bataevb3638132018-07-19 16:34:13 +00007928 CurMapTypes.push_back(getMapModifiersForPrivateClauses(CI));
Alexey Bataev1af5bd52019-03-05 17:47:18 +00007929 const VarDecl *VD = CI.getCapturedVar();
7930 if (FirstPrivateDecls.count(VD) &&
7931 VD->getType().isConstant(CGF.getContext())) {
7932 llvm::Constant *Addr =
7933 CGF.CGM.getOpenMPRuntime().registerTargetFirstprivateCopy(CGF, VD);
7934 // Copy the value of the original variable to the new global copy.
7935 CGF.Builder.CreateMemCpy(
7936 CGF.MakeNaturalAlignAddrLValue(Addr, ElementType).getAddress(),
7937 Address(CV, CGF.getContext().getTypeAlignInChars(ElementType)),
7938 CurSizes.back(),
7939 /*isVolatile=*/false);
7940 // Use new global variable as the base pointers.
7941 CurBasePointers.push_back(Addr);
7942 CurPointers.push_back(Addr);
7943 } else {
7944 CurBasePointers.push_back(CV);
7945 CurPointers.push_back(CV);
7946 }
Samuel Antaod486f842016-05-26 16:53:38 +00007947 }
George Rokos065755d2017-11-07 18:27:04 +00007948 // Every default map produces a single argument which is a target parameter.
7949 CurMapTypes.back() |= OMP_MAP_TARGET_PARAM;
Alexey Bataevb3638132018-07-19 16:34:13 +00007950
7951 // Add flag stating this is an implicit map.
7952 CurMapTypes.back() |= OMP_MAP_IMPLICIT;
Samuel Antaod486f842016-05-26 16:53:38 +00007953 }
Samuel Antao86ace552016-04-27 22:40:57 +00007954};
Samuel Antaodf158d52016-04-27 22:58:19 +00007955
7956enum OpenMPOffloadingReservedDeviceIDs {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007957 /// Device ID if the device was not defined, runtime should get it
Samuel Antaodf158d52016-04-27 22:58:19 +00007958 /// from environment variables in the spec.
7959 OMP_DEVICEID_UNDEF = -1,
7960};
7961} // anonymous namespace
7962
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007963/// Emit the arrays used to pass the captures and map information to the
Samuel Antaodf158d52016-04-27 22:58:19 +00007964/// offloading runtime library. If there is no map or capture information,
7965/// return nullptr by reference.
7966static void
Samuel Antaocc10b852016-07-28 14:23:26 +00007967emitOffloadingArrays(CodeGenFunction &CGF,
7968 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00007969 MappableExprsHandler::MapValuesArrayTy &Pointers,
7970 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00007971 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
7972 CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007973 CodeGenModule &CGM = CGF.CGM;
7974 ASTContext &Ctx = CGF.getContext();
Samuel Antaodf158d52016-04-27 22:58:19 +00007975
Samuel Antaocc10b852016-07-28 14:23:26 +00007976 // Reset the array information.
7977 Info.clearArrayInfo();
7978 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00007979
Samuel Antaocc10b852016-07-28 14:23:26 +00007980 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007981 // Detect if we have any capture size requiring runtime evaluation of the
7982 // size so that a constant array could be eventually used.
7983 bool hasRuntimeEvaluationCaptureSize = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007984 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00007985 if (!isa<llvm::Constant>(S)) {
7986 hasRuntimeEvaluationCaptureSize = true;
7987 break;
7988 }
7989
Samuel Antaocc10b852016-07-28 14:23:26 +00007990 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00007991 QualType PointerArrayType =
7992 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
7993 /*IndexTypeQuals=*/0);
7994
Samuel Antaocc10b852016-07-28 14:23:26 +00007995 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007996 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00007997 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007998 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
7999
8000 // If we don't have any VLA types or other types that require runtime
8001 // evaluation, we can use a constant array for the map sizes, otherwise we
8002 // need to fill up the arrays as we do for the pointers.
8003 if (hasRuntimeEvaluationCaptureSize) {
8004 QualType SizeArrayType = Ctx.getConstantArrayType(
8005 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
8006 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00008007 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00008008 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
8009 } else {
8010 // We expect all the sizes to be constant, so we collect them to create
8011 // a constant array.
8012 SmallVector<llvm::Constant *, 16> ConstSizes;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008013 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00008014 ConstSizes.push_back(cast<llvm::Constant>(S));
8015
8016 auto *SizesArrayInit = llvm::ConstantArray::get(
8017 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
Alexey Bataev18fa2322018-05-02 14:20:50 +00008018 std::string Name = CGM.getOpenMPRuntime().getName({"offload_sizes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00008019 auto *SizesArrayGbl = new llvm::GlobalVariable(
8020 CGM.getModule(), SizesArrayInit->getType(),
8021 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00008022 SizesArrayInit, Name);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00008023 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00008024 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00008025 }
8026
8027 // The map types are always constant so we don't need to generate code to
8028 // fill arrays. Instead, we create an array constant.
Alexey Bataevb3638132018-07-19 16:34:13 +00008029 SmallVector<uint64_t, 4> Mapping(MapTypes.size(), 0);
8030 llvm::copy(MapTypes, Mapping.begin());
Samuel Antaodf158d52016-04-27 22:58:19 +00008031 llvm::Constant *MapTypesArrayInit =
Alexey Bataevb3638132018-07-19 16:34:13 +00008032 llvm::ConstantDataArray::get(CGF.Builder.getContext(), Mapping);
Alexey Bataev18fa2322018-05-02 14:20:50 +00008033 std::string MaptypesName =
8034 CGM.getOpenMPRuntime().getName({"offload_maptypes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00008035 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
8036 CGM.getModule(), MapTypesArrayInit->getType(),
8037 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00008038 MapTypesArrayInit, MaptypesName);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00008039 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00008040 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00008041
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008042 for (unsigned I = 0; I < Info.NumberOfPtrs; ++I) {
8043 llvm::Value *BPVal = *BasePointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00008044 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008045 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008046 Info.BasePointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00008047 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
8048 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00008049 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
8050 CGF.Builder.CreateStore(BPVal, BPAddr);
8051
Samuel Antaocc10b852016-07-28 14:23:26 +00008052 if (Info.requiresDevicePointerInfo())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008053 if (const ValueDecl *DevVD = BasePointers[I].getDevicePtrDecl())
Alexey Bataev43a919f2018-04-13 17:48:43 +00008054 Info.CaptureDeviceAddrMap.try_emplace(DevVD, BPAddr);
Samuel Antaocc10b852016-07-28 14:23:26 +00008055
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008056 llvm::Value *PVal = Pointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00008057 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008058 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008059 Info.PointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00008060 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
8061 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00008062 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
8063 CGF.Builder.CreateStore(PVal, PAddr);
8064
8065 if (hasRuntimeEvaluationCaptureSize) {
8066 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008067 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
8068 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008069 /*Idx0=*/0,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008070 /*Idx1=*/I);
Samuel Antaodf158d52016-04-27 22:58:19 +00008071 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
8072 CGF.Builder.CreateStore(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008073 CGF.Builder.CreateIntCast(Sizes[I], CGM.SizeTy, /*isSigned=*/true),
Samuel Antaodf158d52016-04-27 22:58:19 +00008074 SAddr);
8075 }
8076 }
8077 }
8078}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008079/// Emit the arguments to be passed to the runtime library based on the
Samuel Antaodf158d52016-04-27 22:58:19 +00008080/// arrays of pointers, sizes and map types.
8081static void emitOffloadingArraysArgument(
8082 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
8083 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008084 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008085 CodeGenModule &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00008086 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008087 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008088 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
8089 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008090 /*Idx0=*/0, /*Idx1=*/0);
8091 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008092 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
8093 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008094 /*Idx0=*/0,
8095 /*Idx1=*/0);
8096 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008097 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008098 /*Idx0=*/0, /*Idx1=*/0);
8099 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
George Rokos63bc9d62017-11-21 18:25:12 +00008100 llvm::ArrayType::get(CGM.Int64Ty, Info.NumberOfPtrs),
Samuel Antaocc10b852016-07-28 14:23:26 +00008101 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008102 /*Idx0=*/0,
8103 /*Idx1=*/0);
8104 } else {
8105 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
8106 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
8107 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
8108 MapTypesArrayArg =
George Rokos63bc9d62017-11-21 18:25:12 +00008109 llvm::ConstantPointerNull::get(CGM.Int64Ty->getPointerTo());
Samuel Antaodf158d52016-04-27 22:58:19 +00008110 }
Samuel Antao86ace552016-04-27 22:40:57 +00008111}
8112
Alexey Bataev7bb33532019-01-07 21:30:43 +00008113/// Checks if the expression is constant or does not have non-trivial function
8114/// calls.
8115static bool isTrivial(ASTContext &Ctx, const Expr * E) {
8116 // We can skip constant expressions.
8117 // We can skip expressions with trivial calls or simple expressions.
8118 return (E->isEvaluatable(Ctx, Expr::SE_AllowUndefinedBehavior) ||
8119 !E->hasNonTrivialCall(Ctx)) &&
8120 !E->HasSideEffects(Ctx, /*IncludePossibleEffects=*/true);
8121}
8122
8123/// Checks if the \p Body is the \a CompoundStmt and returns its child statement
8124/// iff there is only one that is not evaluatable at the compile time.
8125static const Stmt *getSingleCompoundChild(ASTContext &Ctx, const Stmt *Body) {
8126 if (const auto *C = dyn_cast<CompoundStmt>(Body)) {
8127 const Stmt *Child = nullptr;
8128 for (const Stmt *S : C->body()) {
8129 if (const auto *E = dyn_cast<Expr>(S)) {
8130 if (isTrivial(Ctx, E))
8131 continue;
8132 }
8133 // Some of the statements can be ignored.
8134 if (isa<AsmStmt>(S) || isa<NullStmt>(S) || isa<OMPFlushDirective>(S) ||
8135 isa<OMPBarrierDirective>(S) || isa<OMPTaskyieldDirective>(S))
8136 continue;
8137 // Analyze declarations.
8138 if (const auto *DS = dyn_cast<DeclStmt>(S)) {
8139 if (llvm::all_of(DS->decls(), [&Ctx](const Decl *D) {
8140 if (isa<EmptyDecl>(D) || isa<DeclContext>(D) ||
8141 isa<TypeDecl>(D) || isa<PragmaCommentDecl>(D) ||
8142 isa<PragmaDetectMismatchDecl>(D) || isa<UsingDecl>(D) ||
8143 isa<UsingDirectiveDecl>(D) ||
8144 isa<OMPDeclareReductionDecl>(D) ||
8145 isa<OMPThreadPrivateDecl>(D))
8146 return true;
8147 const auto *VD = dyn_cast<VarDecl>(D);
8148 if (!VD)
8149 return false;
8150 return VD->isConstexpr() ||
8151 ((VD->getType().isTrivialType(Ctx) ||
8152 VD->getType()->isReferenceType()) &&
8153 (!VD->hasInit() || isTrivial(Ctx, VD->getInit())));
8154 }))
8155 continue;
8156 }
8157 // Found multiple children - cannot get the one child only.
8158 if (Child)
8159 return Body;
8160 Child = S;
8161 }
8162 if (Child)
8163 return Child;
8164 }
8165 return Body;
8166}
8167
8168/// Check for inner distribute directive.
8169static const OMPExecutableDirective *
8170getNestedDistributeDirective(ASTContext &Ctx, const OMPExecutableDirective &D) {
8171 const auto *CS = D.getInnermostCapturedStmt();
8172 const auto *Body =
8173 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
8174 const Stmt *ChildStmt = getSingleCompoundChild(Ctx, Body);
8175
8176 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
8177 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
8178 switch (D.getDirectiveKind()) {
8179 case OMPD_target:
8180 if (isOpenMPDistributeDirective(DKind))
8181 return NestedDir;
8182 if (DKind == OMPD_teams) {
8183 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
8184 /*IgnoreCaptured=*/true);
8185 if (!Body)
8186 return nullptr;
8187 ChildStmt = getSingleCompoundChild(Ctx, Body);
8188 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
8189 DKind = NND->getDirectiveKind();
8190 if (isOpenMPDistributeDirective(DKind))
8191 return NND;
8192 }
8193 }
8194 return nullptr;
8195 case OMPD_target_teams:
8196 if (isOpenMPDistributeDirective(DKind))
8197 return NestedDir;
8198 return nullptr;
8199 case OMPD_target_parallel:
8200 case OMPD_target_simd:
8201 case OMPD_target_parallel_for:
8202 case OMPD_target_parallel_for_simd:
8203 return nullptr;
8204 case OMPD_target_teams_distribute:
8205 case OMPD_target_teams_distribute_simd:
8206 case OMPD_target_teams_distribute_parallel_for:
8207 case OMPD_target_teams_distribute_parallel_for_simd:
8208 case OMPD_parallel:
8209 case OMPD_for:
8210 case OMPD_parallel_for:
8211 case OMPD_parallel_sections:
8212 case OMPD_for_simd:
8213 case OMPD_parallel_for_simd:
8214 case OMPD_cancel:
8215 case OMPD_cancellation_point:
8216 case OMPD_ordered:
8217 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008218 case OMPD_allocate:
Alexey Bataev7bb33532019-01-07 21:30:43 +00008219 case OMPD_task:
8220 case OMPD_simd:
8221 case OMPD_sections:
8222 case OMPD_section:
8223 case OMPD_single:
8224 case OMPD_master:
8225 case OMPD_critical:
8226 case OMPD_taskyield:
8227 case OMPD_barrier:
8228 case OMPD_taskwait:
8229 case OMPD_taskgroup:
8230 case OMPD_atomic:
8231 case OMPD_flush:
8232 case OMPD_teams:
8233 case OMPD_target_data:
8234 case OMPD_target_exit_data:
8235 case OMPD_target_enter_data:
8236 case OMPD_distribute:
8237 case OMPD_distribute_simd:
8238 case OMPD_distribute_parallel_for:
8239 case OMPD_distribute_parallel_for_simd:
8240 case OMPD_teams_distribute:
8241 case OMPD_teams_distribute_simd:
8242 case OMPD_teams_distribute_parallel_for:
8243 case OMPD_teams_distribute_parallel_for_simd:
8244 case OMPD_target_update:
8245 case OMPD_declare_simd:
8246 case OMPD_declare_target:
8247 case OMPD_end_declare_target:
8248 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008249 case OMPD_declare_mapper:
Alexey Bataev7bb33532019-01-07 21:30:43 +00008250 case OMPD_taskloop:
8251 case OMPD_taskloop_simd:
8252 case OMPD_requires:
8253 case OMPD_unknown:
8254 llvm_unreachable("Unexpected directive.");
8255 }
8256 }
8257
8258 return nullptr;
8259}
8260
8261void CGOpenMPRuntime::emitTargetNumIterationsCall(
8262 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *Device,
8263 const llvm::function_ref<llvm::Value *(
8264 CodeGenFunction &CGF, const OMPLoopDirective &D)> &SizeEmitter) {
8265 OpenMPDirectiveKind Kind = D.getDirectiveKind();
8266 const OMPExecutableDirective *TD = &D;
8267 // Get nested teams distribute kind directive, if any.
8268 if (!isOpenMPDistributeDirective(Kind) || !isOpenMPTeamsDirective(Kind))
8269 TD = getNestedDistributeDirective(CGM.getContext(), D);
8270 if (!TD)
8271 return;
8272 const auto *LD = cast<OMPLoopDirective>(TD);
8273 auto &&CodeGen = [LD, &Device, &SizeEmitter, this](CodeGenFunction &CGF,
8274 PrePostActionTy &) {
8275 llvm::Value *NumIterations = SizeEmitter(CGF, *LD);
8276
8277 // Emit device ID if any.
8278 llvm::Value *DeviceID;
8279 if (Device)
8280 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
8281 CGF.Int64Ty, /*isSigned=*/true);
8282 else
8283 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8284
8285 llvm::Value *Args[] = {DeviceID, NumIterations};
8286 CGF.EmitRuntimeCall(
8287 createRuntimeFunction(OMPRTL__kmpc_push_target_tripcount), Args);
8288 };
8289 emitInlinedDirective(CGF, OMPD_unknown, CodeGen);
8290}
8291
Samuel Antaobed3c462015-10-02 16:14:20 +00008292void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
8293 const OMPExecutableDirective &D,
James Y Knight9871db02019-02-05 16:42:33 +00008294 llvm::Function *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00008295 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00008296 const Expr *IfCond, const Expr *Device) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00008297 if (!CGF.HaveInsertPoint())
8298 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00008299
Samuel Antaoee8fb302016-01-06 13:42:12 +00008300 assert(OutlinedFn && "Invalid outlined function!");
8301
Alexey Bataev8451efa2018-01-15 19:06:12 +00008302 const bool RequiresOuterTask = D.hasClausesOfKind<OMPDependClause>();
8303 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Alexey Bataev475a7442018-01-12 19:39:11 +00008304 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008305 auto &&ArgsCodegen = [&CS, &CapturedVars](CodeGenFunction &CGF,
8306 PrePostActionTy &) {
8307 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
8308 };
8309 emitInlinedDirective(CGF, OMPD_unknown, ArgsCodegen);
Samuel Antao86ace552016-04-27 22:40:57 +00008310
Alexey Bataev8451efa2018-01-15 19:06:12 +00008311 CodeGenFunction::OMPTargetDataInfo InputInfo;
8312 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00008313 // Fill up the pointer arrays and transfer execution to the device.
Alexey Bataev8451efa2018-01-15 19:06:12 +00008314 auto &&ThenGen = [this, Device, OutlinedFn, OutlinedFnID, &D, &InputInfo,
8315 &MapTypesArray, &CS, RequiresOuterTask,
8316 &CapturedVars](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobed3c462015-10-02 16:14:20 +00008317 // On top of the arrays that were filled up, the target offloading call
8318 // takes as arguments the device id as well as the host pointer. The host
8319 // pointer is used by the runtime library to identify the current target
8320 // region, so it only has to be unique and not necessarily point to
8321 // anything. It could be the pointer to the outlined function that
8322 // implements the target region, but we aren't using that so that the
8323 // compiler doesn't need to keep that, and could therefore inline the host
8324 // function if proven worthwhile during optimization.
8325
Samuel Antaoee8fb302016-01-06 13:42:12 +00008326 // From this point on, we need to have an ID of the target region defined.
8327 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00008328
8329 // Emit device ID if any.
8330 llvm::Value *DeviceID;
George Rokos63bc9d62017-11-21 18:25:12 +00008331 if (Device) {
Samuel Antaobed3c462015-10-02 16:14:20 +00008332 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008333 CGF.Int64Ty, /*isSigned=*/true);
8334 } else {
8335 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8336 }
Samuel Antaobed3c462015-10-02 16:14:20 +00008337
Samuel Antaodf158d52016-04-27 22:58:19 +00008338 // Emit the number of elements in the offloading arrays.
Alexey Bataev8451efa2018-01-15 19:06:12 +00008339 llvm::Value *PointerNum =
8340 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaodf158d52016-04-27 22:58:19 +00008341
Samuel Antaob68e2db2016-03-03 16:20:23 +00008342 // Return value of the runtime offloading call.
8343 llvm::Value *Return;
8344
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008345 llvm::Value *NumTeams = emitNumTeamsForTargetDirective(*this, CGF, D);
8346 llvm::Value *NumThreads = emitNumThreadsForTargetDirective(*this, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00008347
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008348 bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008349 // The target region is an outlined function launched by the runtime
8350 // via calls __tgt_target() or __tgt_target_teams().
8351 //
8352 // __tgt_target() launches a target region with one team and one thread,
8353 // executing a serial region. This master thread may in turn launch
8354 // more threads within its team upon encountering a parallel region,
8355 // however, no additional teams can be launched on the device.
8356 //
8357 // __tgt_target_teams() launches a target region with one or more teams,
8358 // each with one or more threads. This call is required for target
8359 // constructs such as:
8360 // 'target teams'
8361 // 'target' / 'teams'
8362 // 'target teams distribute parallel for'
8363 // 'target parallel'
8364 // and so on.
8365 //
8366 // Note that on the host and CPU targets, the runtime implementation of
8367 // these calls simply call the outlined function without forking threads.
8368 // The outlined functions themselves have runtime calls to
8369 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
8370 // the compiler in emitTeamsCall() and emitParallelCall().
8371 //
8372 // In contrast, on the NVPTX target, the implementation of
8373 // __tgt_target_teams() launches a GPU kernel with the requested number
8374 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00008375 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008376 // If we have NumTeams defined this means that we have an enclosed teams
8377 // region. Therefore we also expect to have NumThreads defined. These two
8378 // values should be defined in the presence of a teams directive,
8379 // regardless of having any clauses associated. If the user is using teams
8380 // but no clauses, these two values will be the default that should be
8381 // passed to the runtime library - a 32-bit integer with the value zero.
8382 assert(NumThreads && "Thread limit expression should be available along "
8383 "with number of teams.");
Alexey Bataev8451efa2018-01-15 19:06:12 +00008384 llvm::Value *OffloadingArgs[] = {DeviceID,
8385 OutlinedFnID,
8386 PointerNum,
8387 InputInfo.BasePointersArray.getPointer(),
8388 InputInfo.PointersArray.getPointer(),
8389 InputInfo.SizesArray.getPointer(),
8390 MapTypesArray,
8391 NumTeams,
8392 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00008393 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00008394 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_teams_nowait
8395 : OMPRTL__tgt_target_teams),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008396 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00008397 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00008398 llvm::Value *OffloadingArgs[] = {DeviceID,
8399 OutlinedFnID,
8400 PointerNum,
8401 InputInfo.BasePointersArray.getPointer(),
8402 InputInfo.PointersArray.getPointer(),
8403 InputInfo.SizesArray.getPointer(),
8404 MapTypesArray};
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008405 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00008406 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_nowait
8407 : OMPRTL__tgt_target),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008408 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00008409 }
Samuel Antaobed3c462015-10-02 16:14:20 +00008410
Alexey Bataev2a007e02017-10-02 14:20:58 +00008411 // Check the error code and execute the host version if required.
8412 llvm::BasicBlock *OffloadFailedBlock =
8413 CGF.createBasicBlock("omp_offload.failed");
8414 llvm::BasicBlock *OffloadContBlock =
8415 CGF.createBasicBlock("omp_offload.cont");
8416 llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
8417 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
8418
8419 CGF.EmitBlock(OffloadFailedBlock);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008420 if (RequiresOuterTask) {
8421 CapturedVars.clear();
8422 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
8423 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008424 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars);
Alexey Bataev2a007e02017-10-02 14:20:58 +00008425 CGF.EmitBranch(OffloadContBlock);
8426
8427 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00008428 };
8429
Samuel Antaoee8fb302016-01-06 13:42:12 +00008430 // Notify that the host version must be executed.
Alexey Bataev8451efa2018-01-15 19:06:12 +00008431 auto &&ElseGen = [this, &D, OutlinedFn, &CS, &CapturedVars,
8432 RequiresOuterTask](CodeGenFunction &CGF,
8433 PrePostActionTy &) {
8434 if (RequiresOuterTask) {
8435 CapturedVars.clear();
8436 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
8437 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008438 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008439 };
8440
8441 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray,
8442 &CapturedVars, RequiresOuterTask,
8443 &CS](CodeGenFunction &CGF, PrePostActionTy &) {
8444 // Fill up the arrays with all the captured variables.
8445 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
8446 MappableExprsHandler::MapValuesArrayTy Pointers;
8447 MappableExprsHandler::MapValuesArrayTy Sizes;
8448 MappableExprsHandler::MapFlagsArrayTy MapTypes;
8449
Alexey Bataev8451efa2018-01-15 19:06:12 +00008450 // Get mappable expression information.
8451 MappableExprsHandler MEHandler(D, CGF);
Alexey Bataev969dbc02018-11-08 15:47:39 +00008452 llvm::DenseMap<llvm::Value *, llvm::Value *> LambdaPointers;
Alexey Bataev8451efa2018-01-15 19:06:12 +00008453
8454 auto RI = CS.getCapturedRecordDecl()->field_begin();
8455 auto CV = CapturedVars.begin();
8456 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
8457 CE = CS.capture_end();
8458 CI != CE; ++CI, ++RI, ++CV) {
Alexey Bataevb3638132018-07-19 16:34:13 +00008459 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
8460 MappableExprsHandler::MapValuesArrayTy CurPointers;
8461 MappableExprsHandler::MapValuesArrayTy CurSizes;
8462 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
8463 MappableExprsHandler::StructRangeInfoTy PartialStruct;
Alexey Bataev8451efa2018-01-15 19:06:12 +00008464
8465 // VLA sizes are passed to the outlined region by copy and do not have map
8466 // information associated.
8467 if (CI->capturesVariableArrayType()) {
8468 CurBasePointers.push_back(*CV);
8469 CurPointers.push_back(*CV);
8470 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
8471 // Copy to the device as an argument. No need to retrieve it.
8472 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_LITERAL |
8473 MappableExprsHandler::OMP_MAP_TARGET_PARAM);
8474 } else {
8475 // If we have any information in the map clause, we use it, otherwise we
8476 // just do a default mapping.
8477 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00008478 CurSizes, CurMapTypes, PartialStruct);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008479 if (CurBasePointers.empty())
8480 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
8481 CurPointers, CurSizes, CurMapTypes);
Alexey Bataev60705422018-10-30 15:50:12 +00008482 // Generate correct mapping for variables captured by reference in
8483 // lambdas.
8484 if (CI->capturesVariable())
Alexey Bataev969dbc02018-11-08 15:47:39 +00008485 MEHandler.generateInfoForLambdaCaptures(
8486 CI->getCapturedVar(), *CV, CurBasePointers, CurPointers, CurSizes,
8487 CurMapTypes, LambdaPointers);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008488 }
8489 // We expect to have at least an element of information for this capture.
8490 assert(!CurBasePointers.empty() &&
8491 "Non-existing map pointer for capture!");
8492 assert(CurBasePointers.size() == CurPointers.size() &&
8493 CurBasePointers.size() == CurSizes.size() &&
8494 CurBasePointers.size() == CurMapTypes.size() &&
8495 "Inconsistent map information sizes!");
8496
Alexey Bataevb3638132018-07-19 16:34:13 +00008497 // If there is an entry in PartialStruct it means we have a struct with
8498 // individual members mapped. Emit an extra combined entry.
8499 if (PartialStruct.Base.isValid())
8500 MEHandler.emitCombinedEntry(BasePointers, Pointers, Sizes, MapTypes,
8501 CurMapTypes, PartialStruct);
8502
Alexey Bataev8451efa2018-01-15 19:06:12 +00008503 // We need to append the results of this capture to what we already have.
8504 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
8505 Pointers.append(CurPointers.begin(), CurPointers.end());
8506 Sizes.append(CurSizes.begin(), CurSizes.end());
8507 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
8508 }
Alexey Bataev60705422018-10-30 15:50:12 +00008509 // Adjust MEMBER_OF flags for the lambdas captures.
Alexey Bataev969dbc02018-11-08 15:47:39 +00008510 MEHandler.adjustMemberOfForLambdaCaptures(LambdaPointers, BasePointers,
8511 Pointers, MapTypes);
Alexey Bataev92327c52018-03-26 16:40:55 +00008512 // Map other list items in the map clause which are not captured variables
8513 // but "declare target link" global variables.
Alexey Bataevb3638132018-07-19 16:34:13 +00008514 MEHandler.generateInfoForDeclareTargetLink(BasePointers, Pointers, Sizes,
8515 MapTypes);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008516
8517 TargetDataInfo Info;
8518 // Fill up the arrays and create the arguments.
8519 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
8520 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
8521 Info.PointersArray, Info.SizesArray,
8522 Info.MapTypesArray, Info);
8523 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
8524 InputInfo.BasePointersArray =
8525 Address(Info.BasePointersArray, CGM.getPointerAlign());
8526 InputInfo.PointersArray =
8527 Address(Info.PointersArray, CGM.getPointerAlign());
8528 InputInfo.SizesArray = Address(Info.SizesArray, CGM.getPointerAlign());
8529 MapTypesArray = Info.MapTypesArray;
8530 if (RequiresOuterTask)
8531 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
8532 else
8533 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
8534 };
8535
8536 auto &&TargetElseGen = [this, &ElseGen, &D, RequiresOuterTask](
8537 CodeGenFunction &CGF, PrePostActionTy &) {
8538 if (RequiresOuterTask) {
8539 CodeGenFunction::OMPTargetDataInfo InputInfo;
8540 CGF.EmitOMPTargetTaskBasedDirective(D, ElseGen, InputInfo);
8541 } else {
8542 emitInlinedDirective(CGF, D.getDirectiveKind(), ElseGen);
8543 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00008544 };
8545
8546 // If we have a target function ID it means that we need to support
8547 // offloading, otherwise, just execute on the host. We need to execute on host
8548 // regardless of the conditional in the if clause if, e.g., the user do not
8549 // specify target triples.
8550 if (OutlinedFnID) {
Alexey Bataev8451efa2018-01-15 19:06:12 +00008551 if (IfCond) {
8552 emitOMPIfClause(CGF, IfCond, TargetThenGen, TargetElseGen);
8553 } else {
8554 RegionCodeGenTy ThenRCG(TargetThenGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00008555 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00008556 }
8557 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00008558 RegionCodeGenTy ElseRCG(TargetElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00008559 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00008560 }
Samuel Antaobed3c462015-10-02 16:14:20 +00008561}
Samuel Antaoee8fb302016-01-06 13:42:12 +00008562
8563void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
8564 StringRef ParentName) {
8565 if (!S)
8566 return;
8567
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008568 // Codegen OMP target directives that offload compute to the device.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008569 bool RequiresDeviceCodegen =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008570 isa<OMPExecutableDirective>(S) &&
8571 isOpenMPTargetExecutionDirective(
8572 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00008573
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008574 if (RequiresDeviceCodegen) {
8575 const auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008576 unsigned DeviceID;
8577 unsigned FileID;
8578 unsigned Line;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008579 getTargetEntryUniqueInfo(CGM.getContext(), E.getBeginLoc(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00008580 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008581
8582 // Is this a target region that should not be emitted as an entry point? If
8583 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00008584 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
8585 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008586 return;
8587
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008588 switch (E.getDirectiveKind()) {
8589 case OMPD_target:
8590 CodeGenFunction::EmitOMPTargetDeviceFunction(CGM, ParentName,
8591 cast<OMPTargetDirective>(E));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008592 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008593 case OMPD_target_parallel:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00008594 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008595 CGM, ParentName, cast<OMPTargetParallelDirective>(E));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00008596 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008597 case OMPD_target_teams:
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00008598 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008599 CGM, ParentName, cast<OMPTargetTeamsDirective>(E));
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00008600 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008601 case OMPD_target_teams_distribute:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008602 CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008603 CGM, ParentName, cast<OMPTargetTeamsDistributeDirective>(E));
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008604 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008605 case OMPD_target_teams_distribute_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008606 CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008607 CGM, ParentName, cast<OMPTargetTeamsDistributeSimdDirective>(E));
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008608 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008609 case OMPD_target_parallel_for:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008610 CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008611 CGM, ParentName, cast<OMPTargetParallelForDirective>(E));
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008612 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008613 case OMPD_target_parallel_for_simd:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008614 CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008615 CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(E));
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008616 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008617 case OMPD_target_simd:
Alexey Bataevf8365372017-11-17 17:57:25 +00008618 CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008619 CGM, ParentName, cast<OMPTargetSimdDirective>(E));
Alexey Bataevf8365372017-11-17 17:57:25 +00008620 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008621 case OMPD_target_teams_distribute_parallel_for:
Carlo Bertolli52978c32018-01-03 21:12:44 +00008622 CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
8623 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008624 cast<OMPTargetTeamsDistributeParallelForDirective>(E));
Carlo Bertolli52978c32018-01-03 21:12:44 +00008625 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008626 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00008627 CodeGenFunction::
8628 EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
8629 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008630 cast<OMPTargetTeamsDistributeParallelForSimdDirective>(E));
Alexey Bataev647dd842018-01-15 20:59:40 +00008631 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008632 case OMPD_parallel:
8633 case OMPD_for:
8634 case OMPD_parallel_for:
8635 case OMPD_parallel_sections:
8636 case OMPD_for_simd:
8637 case OMPD_parallel_for_simd:
8638 case OMPD_cancel:
8639 case OMPD_cancellation_point:
8640 case OMPD_ordered:
8641 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008642 case OMPD_allocate:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008643 case OMPD_task:
8644 case OMPD_simd:
8645 case OMPD_sections:
8646 case OMPD_section:
8647 case OMPD_single:
8648 case OMPD_master:
8649 case OMPD_critical:
8650 case OMPD_taskyield:
8651 case OMPD_barrier:
8652 case OMPD_taskwait:
8653 case OMPD_taskgroup:
8654 case OMPD_atomic:
8655 case OMPD_flush:
8656 case OMPD_teams:
8657 case OMPD_target_data:
8658 case OMPD_target_exit_data:
8659 case OMPD_target_enter_data:
8660 case OMPD_distribute:
8661 case OMPD_distribute_simd:
8662 case OMPD_distribute_parallel_for:
8663 case OMPD_distribute_parallel_for_simd:
8664 case OMPD_teams_distribute:
8665 case OMPD_teams_distribute_simd:
8666 case OMPD_teams_distribute_parallel_for:
8667 case OMPD_teams_distribute_parallel_for_simd:
8668 case OMPD_target_update:
8669 case OMPD_declare_simd:
8670 case OMPD_declare_target:
8671 case OMPD_end_declare_target:
8672 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008673 case OMPD_declare_mapper:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008674 case OMPD_taskloop:
8675 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008676 case OMPD_requires:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008677 case OMPD_unknown:
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008678 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
8679 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00008680 return;
8681 }
8682
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008683 if (const auto *E = dyn_cast<OMPExecutableDirective>(S)) {
Alexey Bataev475a7442018-01-12 19:39:11 +00008684 if (!E->hasAssociatedStmt() || !E->getAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00008685 return;
8686
8687 scanForTargetRegionsFunctions(
Alexey Bataev475a7442018-01-12 19:39:11 +00008688 E->getInnermostCapturedStmt()->getCapturedStmt(), ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008689 return;
8690 }
8691
8692 // If this is a lambda function, look into its body.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008693 if (const auto *L = dyn_cast<LambdaExpr>(S))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008694 S = L->getBody();
8695
8696 // Keep looking for target regions recursively.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008697 for (const Stmt *II : S->children())
Samuel Antaoee8fb302016-01-06 13:42:12 +00008698 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008699}
8700
8701bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008702 // If emitting code for the host, we do not process FD here. Instead we do
8703 // the normal code generation.
8704 if (!CGM.getLangOpts().OpenMPIsDevice)
8705 return false;
8706
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008707 const ValueDecl *VD = cast<ValueDecl>(GD.getDecl());
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008708 StringRef Name = CGM.getMangledName(GD);
8709 // Try to detect target regions in the function.
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008710 if (const auto *FD = dyn_cast<FunctionDecl>(VD))
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008711 scanForTargetRegionsFunctions(FD->getBody(), Name);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008712
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008713 // Do not to emit function if it is not marked as declare target.
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008714 return !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008715 AlreadyEmittedTargetFunctions.count(Name) == 0;
Samuel Antaoee8fb302016-01-06 13:42:12 +00008716}
8717
8718bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
8719 if (!CGM.getLangOpts().OpenMPIsDevice)
8720 return false;
8721
8722 // Check if there are Ctors/Dtors in this declaration and look for target
8723 // regions in it. We use the complete variant to produce the kernel name
8724 // mangling.
8725 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008726 if (const auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
8727 for (const CXXConstructorDecl *Ctor : RD->ctors()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008728 StringRef ParentName =
8729 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
8730 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
8731 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008732 if (const CXXDestructorDecl *Dtor = RD->getDestructor()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008733 StringRef ParentName =
8734 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
8735 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
8736 }
8737 }
8738
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008739 // Do not to emit variable if it is not marked as declare target.
Alexey Bataev92327c52018-03-26 16:40:55 +00008740 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00008741 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
8742 cast<VarDecl>(GD.getDecl()));
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008743 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Alexey Bataevd01b7492018-08-15 19:45:12 +00008744 DeferredGlobalVariables.insert(cast<VarDecl>(GD.getDecl()));
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008745 return true;
8746 }
8747 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00008748}
8749
Alexey Bataev1af5bd52019-03-05 17:47:18 +00008750llvm::Constant *
8751CGOpenMPRuntime::registerTargetFirstprivateCopy(CodeGenFunction &CGF,
8752 const VarDecl *VD) {
8753 assert(VD->getType().isConstant(CGM.getContext()) &&
8754 "Expected constant variable.");
8755 StringRef VarName;
8756 llvm::Constant *Addr;
8757 llvm::GlobalValue::LinkageTypes Linkage;
8758 QualType Ty = VD->getType();
8759 SmallString<128> Buffer;
8760 {
8761 unsigned DeviceID;
8762 unsigned FileID;
8763 unsigned Line;
8764 getTargetEntryUniqueInfo(CGM.getContext(), VD->getLocation(), DeviceID,
8765 FileID, Line);
8766 llvm::raw_svector_ostream OS(Buffer);
8767 OS << "__omp_offloading_firstprivate_" << llvm::format("_%x", DeviceID)
8768 << llvm::format("_%x_", FileID) << VD->getName() << "_l" << Line;
8769 VarName = OS.str();
8770 }
8771 Linkage = llvm::GlobalValue::InternalLinkage;
8772 Addr =
8773 getOrCreateInternalVariable(CGM.getTypes().ConvertTypeForMem(Ty), VarName,
8774 getDefaultFirstprivateAddressSpace());
8775 cast<llvm::GlobalValue>(Addr)->setLinkage(Linkage);
8776 CharUnits VarSize = CGM.getContext().getTypeSizeInChars(Ty);
8777 CGM.addCompilerUsedGlobal(cast<llvm::GlobalValue>(Addr));
8778 OffloadEntriesInfoManager.registerDeviceGlobalVarEntryInfo(
8779 VarName, Addr, VarSize,
8780 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo, Linkage);
8781 return Addr;
8782}
8783
Alexey Bataev03f270c2018-03-30 18:31:07 +00008784void CGOpenMPRuntime::registerTargetGlobalVariable(const VarDecl *VD,
8785 llvm::Constant *Addr) {
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008786 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
8787 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
8788 if (!Res) {
8789 if (CGM.getLangOpts().OpenMPIsDevice) {
8790 // Register non-target variables being emitted in device code (debug info
8791 // may cause this).
8792 StringRef VarName = CGM.getMangledName(VD);
8793 EmittedNonTargetVariables.try_emplace(VarName, Addr);
Alexey Bataev03f270c2018-03-30 18:31:07 +00008794 }
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008795 return;
Alexey Bataev03f270c2018-03-30 18:31:07 +00008796 }
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008797 // Register declare target variables.
8798 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags;
8799 StringRef VarName;
8800 CharUnits VarSize;
8801 llvm::GlobalValue::LinkageTypes Linkage;
8802 switch (*Res) {
8803 case OMPDeclareTargetDeclAttr::MT_To:
8804 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo;
8805 VarName = CGM.getMangledName(VD);
8806 if (VD->hasDefinition(CGM.getContext()) != VarDecl::DeclarationOnly) {
8807 VarSize = CGM.getContext().getTypeSizeInChars(VD->getType());
8808 assert(!VarSize.isZero() && "Expected non-zero size of the variable");
8809 } else {
8810 VarSize = CharUnits::Zero();
8811 }
8812 Linkage = CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false);
8813 // Temp solution to prevent optimizations of the internal variables.
8814 if (CGM.getLangOpts().OpenMPIsDevice && !VD->isExternallyVisible()) {
8815 std::string RefName = getName({VarName, "ref"});
8816 if (!CGM.GetGlobalValue(RefName)) {
8817 llvm::Constant *AddrRef =
8818 getOrCreateInternalVariable(Addr->getType(), RefName);
8819 auto *GVAddrRef = cast<llvm::GlobalVariable>(AddrRef);
8820 GVAddrRef->setConstant(/*Val=*/true);
8821 GVAddrRef->setLinkage(llvm::GlobalValue::InternalLinkage);
8822 GVAddrRef->setInitializer(Addr);
8823 CGM.addCompilerUsedGlobal(GVAddrRef);
8824 }
8825 }
8826 break;
8827 case OMPDeclareTargetDeclAttr::MT_Link:
8828 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink;
8829 if (CGM.getLangOpts().OpenMPIsDevice) {
8830 VarName = Addr->getName();
8831 Addr = nullptr;
8832 } else {
8833 VarName = getAddrOfDeclareTargetLink(VD).getName();
8834 Addr = cast<llvm::Constant>(getAddrOfDeclareTargetLink(VD).getPointer());
8835 }
8836 VarSize = CGM.getPointerSize();
8837 Linkage = llvm::GlobalValue::WeakAnyLinkage;
8838 break;
8839 }
8840 OffloadEntriesInfoManager.registerDeviceGlobalVarEntryInfo(
8841 VarName, Addr, VarSize, Flags, Linkage);
Alexey Bataev03f270c2018-03-30 18:31:07 +00008842}
8843
Samuel Antaoee8fb302016-01-06 13:42:12 +00008844bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008845 if (isa<FunctionDecl>(GD.getDecl()) ||
8846 isa<OMPDeclareReductionDecl>(GD.getDecl()))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008847 return emitTargetFunctions(GD);
8848
8849 return emitTargetGlobalVariable(GD);
8850}
8851
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008852void CGOpenMPRuntime::emitDeferredTargetDecls() const {
8853 for (const VarDecl *VD : DeferredGlobalVariables) {
8854 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00008855 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataevd01b7492018-08-15 19:45:12 +00008856 if (!Res)
8857 continue;
8858 if (*Res == OMPDeclareTargetDeclAttr::MT_To) {
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008859 CGM.EmitGlobal(VD);
Alexey Bataevd01b7492018-08-15 19:45:12 +00008860 } else {
8861 assert(*Res == OMPDeclareTargetDeclAttr::MT_Link &&
8862 "Expected to or link clauses.");
8863 (void)CGM.getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008864 }
8865 }
8866}
8867
Alexey Bataev60705422018-10-30 15:50:12 +00008868void CGOpenMPRuntime::adjustTargetSpecificDataForLambdas(
8869 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
8870 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
8871 " Expected target-based directive.");
8872}
8873
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008874CGOpenMPRuntime::DisableAutoDeclareTargetRAII::DisableAutoDeclareTargetRAII(
8875 CodeGenModule &CGM)
8876 : CGM(CGM) {
8877 if (CGM.getLangOpts().OpenMPIsDevice) {
8878 SavedShouldMarkAsGlobal = CGM.getOpenMPRuntime().ShouldMarkAsGlobal;
8879 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = false;
8880 }
8881}
8882
8883CGOpenMPRuntime::DisableAutoDeclareTargetRAII::~DisableAutoDeclareTargetRAII() {
8884 if (CGM.getLangOpts().OpenMPIsDevice)
8885 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = SavedShouldMarkAsGlobal;
8886}
8887
Alexey Bataev6d944102018-05-02 15:45:28 +00008888bool CGOpenMPRuntime::markAsGlobalTarget(GlobalDecl GD) {
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008889 if (!CGM.getLangOpts().OpenMPIsDevice || !ShouldMarkAsGlobal)
8890 return true;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008891
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008892 StringRef Name = CGM.getMangledName(GD);
Alexey Bataev6d944102018-05-02 15:45:28 +00008893 const auto *D = cast<FunctionDecl>(GD.getDecl());
Alexey Bataev34f8a702018-03-28 14:28:54 +00008894 // Do not to emit function if it is marked as declare target as it was already
8895 // emitted.
Alexey Bataev97b72212018-08-14 18:31:20 +00008896 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(D)) {
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008897 if (D->hasBody() && AlreadyEmittedTargetFunctions.count(Name) == 0) {
8898 if (auto *F = dyn_cast_or_null<llvm::Function>(CGM.GetGlobalValue(Name)))
Alexey Bataev34f8a702018-03-28 14:28:54 +00008899 return !F->isDeclaration();
8900 return false;
8901 }
8902 return true;
8903 }
8904
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008905 return !AlreadyEmittedTargetFunctions.insert(Name).second;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008906}
8907
Samuel Antaoee8fb302016-01-06 13:42:12 +00008908llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
8909 // If we have offloading in the current module, we need to emit the entries
8910 // now and register the offloading descriptor.
8911 createOffloadEntriesAndInfoMetadata();
8912
8913 // Create and register the offloading binary descriptors. This is the main
8914 // entity that captures all the information about offloading in the current
8915 // compilation unit.
8916 return createOffloadingBinaryDescriptorRegistration();
8917}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008918
8919void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
8920 const OMPExecutableDirective &D,
8921 SourceLocation Loc,
James Y Knight9871db02019-02-05 16:42:33 +00008922 llvm::Function *OutlinedFn,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008923 ArrayRef<llvm::Value *> CapturedVars) {
8924 if (!CGF.HaveInsertPoint())
8925 return;
8926
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008927 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008928 CodeGenFunction::RunCleanupsScope Scope(CGF);
8929
8930 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
8931 llvm::Value *Args[] = {
8932 RTLoc,
8933 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
8934 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
8935 llvm::SmallVector<llvm::Value *, 16> RealArgs;
8936 RealArgs.append(std::begin(Args), std::end(Args));
8937 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
8938
James Y Knight9871db02019-02-05 16:42:33 +00008939 llvm::FunctionCallee RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008940 CGF.EmitRuntimeCall(RTLFn, RealArgs);
8941}
8942
8943void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00008944 const Expr *NumTeams,
8945 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008946 SourceLocation Loc) {
8947 if (!CGF.HaveInsertPoint())
8948 return;
8949
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008950 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008951
Carlo Bertollic6872252016-04-04 15:55:02 +00008952 llvm::Value *NumTeamsVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008953 NumTeams
Carlo Bertollic6872252016-04-04 15:55:02 +00008954 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
8955 CGF.CGM.Int32Ty, /* isSigned = */ true)
8956 : CGF.Builder.getInt32(0);
8957
8958 llvm::Value *ThreadLimitVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008959 ThreadLimit
Carlo Bertollic6872252016-04-04 15:55:02 +00008960 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
8961 CGF.CGM.Int32Ty, /* isSigned = */ true)
8962 : CGF.Builder.getInt32(0);
8963
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008964 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00008965 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
8966 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008967 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
8968 PushNumTeamsArgs);
8969}
Samuel Antaodf158d52016-04-27 22:58:19 +00008970
Samuel Antaocc10b852016-07-28 14:23:26 +00008971void CGOpenMPRuntime::emitTargetDataCalls(
8972 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8973 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008974 if (!CGF.HaveInsertPoint())
8975 return;
8976
Samuel Antaocc10b852016-07-28 14:23:26 +00008977 // Action used to replace the default codegen action and turn privatization
8978 // off.
8979 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00008980
8981 // Generate the code for the opening of the data environment. Capture all the
8982 // arguments of the runtime call by reference because they are used in the
8983 // closing of the region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008984 auto &&BeginThenGen = [this, &D, Device, &Info,
8985 &CodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008986 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00008987 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00008988 MappableExprsHandler::MapValuesArrayTy Pointers;
8989 MappableExprsHandler::MapValuesArrayTy Sizes;
8990 MappableExprsHandler::MapFlagsArrayTy MapTypes;
8991
8992 // Get map clause information.
8993 MappableExprsHandler MCHandler(D, CGF);
8994 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00008995
8996 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00008997 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008998
8999 llvm::Value *BasePointersArrayArg = nullptr;
9000 llvm::Value *PointersArrayArg = nullptr;
9001 llvm::Value *SizesArrayArg = nullptr;
9002 llvm::Value *MapTypesArrayArg = nullptr;
9003 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00009004 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00009005
9006 // Emit device ID if any.
9007 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00009008 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00009009 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00009010 CGF.Int64Ty, /*isSigned=*/true);
9011 } else {
9012 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
9013 }
Samuel Antaodf158d52016-04-27 22:58:19 +00009014
9015 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009016 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00009017
9018 llvm::Value *OffloadingArgs[] = {
9019 DeviceID, PointerNum, BasePointersArrayArg,
9020 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009021 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_begin),
Samuel Antaodf158d52016-04-27 22:58:19 +00009022 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00009023
9024 // If device pointer privatization is required, emit the body of the region
9025 // here. It will have to be duplicated: with and without privatization.
9026 if (!Info.CaptureDeviceAddrMap.empty())
9027 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00009028 };
9029
9030 // Generate code for the closing of the data region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009031 auto &&EndThenGen = [this, Device, &Info](CodeGenFunction &CGF,
9032 PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00009033 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00009034
9035 llvm::Value *BasePointersArrayArg = nullptr;
9036 llvm::Value *PointersArrayArg = nullptr;
9037 llvm::Value *SizesArrayArg = nullptr;
9038 llvm::Value *MapTypesArrayArg = nullptr;
9039 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00009040 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00009041
9042 // Emit device ID if any.
9043 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00009044 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00009045 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00009046 CGF.Int64Ty, /*isSigned=*/true);
9047 } else {
9048 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
9049 }
Samuel Antaodf158d52016-04-27 22:58:19 +00009050
9051 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009052 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00009053
9054 llvm::Value *OffloadingArgs[] = {
9055 DeviceID, PointerNum, BasePointersArrayArg,
9056 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009057 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_end),
Samuel Antaodf158d52016-04-27 22:58:19 +00009058 OffloadingArgs);
9059 };
9060
Samuel Antaocc10b852016-07-28 14:23:26 +00009061 // If we need device pointer privatization, we need to emit the body of the
9062 // region with no privatization in the 'else' branch of the conditional.
9063 // Otherwise, we don't have to do anything.
9064 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
9065 PrePostActionTy &) {
9066 if (!Info.CaptureDeviceAddrMap.empty()) {
9067 CodeGen.setAction(NoPrivAction);
9068 CodeGen(CGF);
9069 }
9070 };
9071
9072 // We don't have to do anything to close the region if the if clause evaluates
9073 // to false.
9074 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00009075
9076 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00009077 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00009078 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00009079 RegionCodeGenTy RCG(BeginThenGen);
9080 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00009081 }
9082
Samuel Antaocc10b852016-07-28 14:23:26 +00009083 // If we don't require privatization of device pointers, we emit the body in
9084 // between the runtime calls. This avoids duplicating the body code.
9085 if (Info.CaptureDeviceAddrMap.empty()) {
9086 CodeGen.setAction(NoPrivAction);
9087 CodeGen(CGF);
9088 }
Samuel Antaodf158d52016-04-27 22:58:19 +00009089
9090 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00009091 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00009092 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00009093 RegionCodeGenTy RCG(EndThenGen);
9094 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00009095 }
9096}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009097
Samuel Antao8d2d7302016-05-26 18:30:22 +00009098void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00009099 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
9100 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009101 if (!CGF.HaveInsertPoint())
9102 return;
9103
Samuel Antao8dd66282016-04-27 23:14:30 +00009104 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00009105 isa<OMPTargetExitDataDirective>(D) ||
9106 isa<OMPTargetUpdateDirective>(D)) &&
9107 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00009108
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009109 CodeGenFunction::OMPTargetDataInfo InputInfo;
9110 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009111 // Generate the code for the opening of the data environment.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009112 auto &&ThenGen = [this, &D, Device, &InputInfo,
9113 &MapTypesArray](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009114 // Emit device ID if any.
9115 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00009116 if (Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009117 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00009118 CGF.Int64Ty, /*isSigned=*/true);
9119 } else {
9120 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
9121 }
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009122
9123 // Emit the number of elements in the offloading arrays.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009124 llvm::Constant *PointerNum =
9125 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009126
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009127 llvm::Value *OffloadingArgs[] = {DeviceID,
9128 PointerNum,
9129 InputInfo.BasePointersArray.getPointer(),
9130 InputInfo.PointersArray.getPointer(),
9131 InputInfo.SizesArray.getPointer(),
9132 MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00009133
Samuel Antao8d2d7302016-05-26 18:30:22 +00009134 // Select the right runtime function call for each expected standalone
9135 // directive.
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00009136 const bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Samuel Antao8d2d7302016-05-26 18:30:22 +00009137 OpenMPRTLFunction RTLFn;
9138 switch (D.getDirectiveKind()) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00009139 case OMPD_target_enter_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00009140 RTLFn = HasNowait ? OMPRTL__tgt_target_data_begin_nowait
9141 : OMPRTL__tgt_target_data_begin;
Samuel Antao8d2d7302016-05-26 18:30:22 +00009142 break;
9143 case OMPD_target_exit_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00009144 RTLFn = HasNowait ? OMPRTL__tgt_target_data_end_nowait
9145 : OMPRTL__tgt_target_data_end;
Samuel Antao8d2d7302016-05-26 18:30:22 +00009146 break;
9147 case OMPD_target_update:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00009148 RTLFn = HasNowait ? OMPRTL__tgt_target_data_update_nowait
9149 : OMPRTL__tgt_target_data_update;
Samuel Antao8d2d7302016-05-26 18:30:22 +00009150 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009151 case OMPD_parallel:
9152 case OMPD_for:
9153 case OMPD_parallel_for:
9154 case OMPD_parallel_sections:
9155 case OMPD_for_simd:
9156 case OMPD_parallel_for_simd:
9157 case OMPD_cancel:
9158 case OMPD_cancellation_point:
9159 case OMPD_ordered:
9160 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009161 case OMPD_allocate:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009162 case OMPD_task:
9163 case OMPD_simd:
9164 case OMPD_sections:
9165 case OMPD_section:
9166 case OMPD_single:
9167 case OMPD_master:
9168 case OMPD_critical:
9169 case OMPD_taskyield:
9170 case OMPD_barrier:
9171 case OMPD_taskwait:
9172 case OMPD_taskgroup:
9173 case OMPD_atomic:
9174 case OMPD_flush:
9175 case OMPD_teams:
9176 case OMPD_target_data:
9177 case OMPD_distribute:
9178 case OMPD_distribute_simd:
9179 case OMPD_distribute_parallel_for:
9180 case OMPD_distribute_parallel_for_simd:
9181 case OMPD_teams_distribute:
9182 case OMPD_teams_distribute_simd:
9183 case OMPD_teams_distribute_parallel_for:
9184 case OMPD_teams_distribute_parallel_for_simd:
9185 case OMPD_declare_simd:
9186 case OMPD_declare_target:
9187 case OMPD_end_declare_target:
9188 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009189 case OMPD_declare_mapper:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009190 case OMPD_taskloop:
9191 case OMPD_taskloop_simd:
9192 case OMPD_target:
9193 case OMPD_target_simd:
9194 case OMPD_target_teams_distribute:
9195 case OMPD_target_teams_distribute_simd:
9196 case OMPD_target_teams_distribute_parallel_for:
9197 case OMPD_target_teams_distribute_parallel_for_simd:
9198 case OMPD_target_teams:
9199 case OMPD_target_parallel:
9200 case OMPD_target_parallel_for:
9201 case OMPD_target_parallel_for_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00009202 case OMPD_requires:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009203 case OMPD_unknown:
9204 llvm_unreachable("Unexpected standalone target data directive.");
9205 break;
Samuel Antao8d2d7302016-05-26 18:30:22 +00009206 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009207 CGF.EmitRuntimeCall(createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009208 };
9209
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009210 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray](
9211 CodeGenFunction &CGF, PrePostActionTy &) {
9212 // Fill up the arrays with all the mapped variables.
9213 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
9214 MappableExprsHandler::MapValuesArrayTy Pointers;
9215 MappableExprsHandler::MapValuesArrayTy Sizes;
9216 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009217
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009218 // Get map clause information.
9219 MappableExprsHandler MEHandler(D, CGF);
9220 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
9221
9222 TargetDataInfo Info;
9223 // Fill up the arrays and create the arguments.
9224 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
9225 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
9226 Info.PointersArray, Info.SizesArray,
9227 Info.MapTypesArray, Info);
9228 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
9229 InputInfo.BasePointersArray =
9230 Address(Info.BasePointersArray, CGM.getPointerAlign());
9231 InputInfo.PointersArray =
9232 Address(Info.PointersArray, CGM.getPointerAlign());
9233 InputInfo.SizesArray =
9234 Address(Info.SizesArray, CGM.getPointerAlign());
9235 MapTypesArray = Info.MapTypesArray;
9236 if (D.hasClausesOfKind<OMPDependClause>())
9237 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
9238 else
Alexey Bataev768f1f22018-01-09 19:59:25 +00009239 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009240 };
9241
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009242 if (IfCond) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009243 emitOMPIfClause(CGF, IfCond, TargetThenGen,
9244 [](CodeGenFunction &CGF, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009245 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009246 RegionCodeGenTy ThenRCG(TargetThenGen);
9247 ThenRCG(CGF);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009248 }
9249}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009250
9251namespace {
9252 /// Kind of parameter in a function with 'declare simd' directive.
9253 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
9254 /// Attribute set of the parameter.
9255 struct ParamAttrTy {
9256 ParamKindTy Kind = Vector;
9257 llvm::APSInt StrideOrArg;
9258 llvm::APSInt Alignment;
9259 };
9260} // namespace
9261
9262static unsigned evaluateCDTSize(const FunctionDecl *FD,
9263 ArrayRef<ParamAttrTy> ParamAttrs) {
9264 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
9265 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
9266 // of that clause. The VLEN value must be power of 2.
9267 // In other case the notion of the function`s "characteristic data type" (CDT)
9268 // is used to compute the vector length.
9269 // CDT is defined in the following order:
9270 // a) For non-void function, the CDT is the return type.
9271 // b) If the function has any non-uniform, non-linear parameters, then the
9272 // CDT is the type of the first such parameter.
9273 // c) If the CDT determined by a) or b) above is struct, union, or class
9274 // type which is pass-by-value (except for the type that maps to the
9275 // built-in complex data type), the characteristic data type is int.
9276 // d) If none of the above three cases is applicable, the CDT is int.
9277 // The VLEN is then determined based on the CDT and the size of vector
9278 // register of that ISA for which current vector version is generated. The
9279 // VLEN is computed using the formula below:
9280 // VLEN = sizeof(vector_register) / sizeof(CDT),
9281 // where vector register size specified in section 3.2.1 Registers and the
9282 // Stack Frame of original AMD64 ABI document.
9283 QualType RetType = FD->getReturnType();
9284 if (RetType.isNull())
9285 return 0;
9286 ASTContext &C = FD->getASTContext();
9287 QualType CDT;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009288 if (!RetType.isNull() && !RetType->isVoidType()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009289 CDT = RetType;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009290 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009291 unsigned Offset = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009292 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009293 if (ParamAttrs[Offset].Kind == Vector)
9294 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
9295 ++Offset;
9296 }
9297 if (CDT.isNull()) {
9298 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
9299 if (ParamAttrs[I + Offset].Kind == Vector) {
9300 CDT = FD->getParamDecl(I)->getType();
9301 break;
9302 }
9303 }
9304 }
9305 }
9306 if (CDT.isNull())
9307 CDT = C.IntTy;
9308 CDT = CDT->getCanonicalTypeUnqualified();
9309 if (CDT->isRecordType() || CDT->isUnionType())
9310 CDT = C.IntTy;
9311 return C.getTypeSize(CDT);
9312}
9313
9314static void
9315emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00009316 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009317 ArrayRef<ParamAttrTy> ParamAttrs,
9318 OMPDeclareSimdDeclAttr::BranchStateTy State) {
9319 struct ISADataTy {
9320 char ISA;
9321 unsigned VecRegSize;
9322 };
9323 ISADataTy ISAData[] = {
9324 {
9325 'b', 128
9326 }, // SSE
9327 {
9328 'c', 256
9329 }, // AVX
9330 {
9331 'd', 256
9332 }, // AVX2
9333 {
9334 'e', 512
9335 }, // AVX512
9336 };
9337 llvm::SmallVector<char, 2> Masked;
9338 switch (State) {
9339 case OMPDeclareSimdDeclAttr::BS_Undefined:
9340 Masked.push_back('N');
9341 Masked.push_back('M');
9342 break;
9343 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
9344 Masked.push_back('N');
9345 break;
9346 case OMPDeclareSimdDeclAttr::BS_Inbranch:
9347 Masked.push_back('M');
9348 break;
9349 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009350 for (char Mask : Masked) {
9351 for (const ISADataTy &Data : ISAData) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009352 SmallString<256> Buffer;
9353 llvm::raw_svector_ostream Out(Buffer);
9354 Out << "_ZGV" << Data.ISA << Mask;
9355 if (!VLENVal) {
9356 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
9357 evaluateCDTSize(FD, ParamAttrs));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009358 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009359 Out << VLENVal;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009360 }
9361 for (const ParamAttrTy &ParamAttr : ParamAttrs) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009362 switch (ParamAttr.Kind){
9363 case LinearWithVarStride:
9364 Out << 's' << ParamAttr.StrideOrArg;
9365 break;
9366 case Linear:
9367 Out << 'l';
9368 if (!!ParamAttr.StrideOrArg)
9369 Out << ParamAttr.StrideOrArg;
9370 break;
9371 case Uniform:
9372 Out << 'u';
9373 break;
9374 case Vector:
9375 Out << 'v';
9376 break;
9377 }
9378 if (!!ParamAttr.Alignment)
9379 Out << 'a' << ParamAttr.Alignment;
9380 }
9381 Out << '_' << Fn->getName();
9382 Fn->addFnAttr(Out.str());
9383 }
9384 }
9385}
9386
9387void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
9388 llvm::Function *Fn) {
9389 ASTContext &C = CGM.getContext();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009390 FD = FD->getMostRecentDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009391 // Map params to their positions in function decl.
9392 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
9393 if (isa<CXXMethodDecl>(FD))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009394 ParamPositions.try_emplace(FD, 0);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009395 unsigned ParamPos = ParamPositions.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009396 for (const ParmVarDecl *P : FD->parameters()) {
9397 ParamPositions.try_emplace(P->getCanonicalDecl(), ParamPos);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009398 ++ParamPos;
9399 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009400 while (FD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009401 for (const auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009402 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
9403 // Mark uniform parameters.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009404 for (const Expr *E : Attr->uniforms()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009405 E = E->IgnoreParenImpCasts();
9406 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009407 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009408 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009409 } else {
9410 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
9411 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009412 Pos = ParamPositions[PVD];
9413 }
9414 ParamAttrs[Pos].Kind = Uniform;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009415 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009416 // Get alignment info.
9417 auto NI = Attr->alignments_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009418 for (const Expr *E : Attr->aligneds()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009419 E = E->IgnoreParenImpCasts();
9420 unsigned Pos;
9421 QualType ParmTy;
9422 if (isa<CXXThisExpr>(E)) {
9423 Pos = ParamPositions[FD];
9424 ParmTy = E->getType();
9425 } else {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009426 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
9427 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009428 Pos = ParamPositions[PVD];
9429 ParmTy = PVD->getType();
9430 }
9431 ParamAttrs[Pos].Alignment =
9432 (*NI)
9433 ? (*NI)->EvaluateKnownConstInt(C)
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009434 : llvm::APSInt::getUnsigned(
9435 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
9436 .getQuantity());
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009437 ++NI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009438 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009439 // Mark linear parameters.
9440 auto SI = Attr->steps_begin();
9441 auto MI = Attr->modifiers_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009442 for (const Expr *E : Attr->linears()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009443 E = E->IgnoreParenImpCasts();
9444 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009445 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009446 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009447 } else {
9448 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
9449 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009450 Pos = ParamPositions[PVD];
9451 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009452 ParamAttrTy &ParamAttr = ParamAttrs[Pos];
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009453 ParamAttr.Kind = Linear;
9454 if (*SI) {
Fangrui Song407659a2018-11-30 23:41:18 +00009455 Expr::EvalResult Result;
9456 if (!(*SI)->EvaluateAsInt(Result, C, Expr::SE_AllowSideEffects)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009457 if (const auto *DRE =
9458 cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
9459 if (const auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009460 ParamAttr.Kind = LinearWithVarStride;
9461 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
9462 ParamPositions[StridePVD->getCanonicalDecl()]);
9463 }
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009464 }
Fangrui Song407659a2018-11-30 23:41:18 +00009465 } else {
9466 ParamAttr.StrideOrArg = Result.Val.getInt();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009467 }
9468 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009469 ++SI;
9470 ++MI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009471 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009472 llvm::APSInt VLENVal;
9473 if (const Expr *VLEN = Attr->getSimdlen())
9474 VLENVal = VLEN->EvaluateKnownConstInt(C);
9475 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
9476 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
9477 CGM.getTriple().getArch() == llvm::Triple::x86_64)
9478 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009479 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009480 FD = FD->getPreviousDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009481 }
9482}
Alexey Bataev8b427062016-05-25 12:36:08 +00009483
9484namespace {
9485/// Cleanup action for doacross support.
9486class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
9487public:
9488 static const int DoacrossFinArgs = 2;
9489
9490private:
James Y Knight9871db02019-02-05 16:42:33 +00009491 llvm::FunctionCallee RTLFn;
Alexey Bataev8b427062016-05-25 12:36:08 +00009492 llvm::Value *Args[DoacrossFinArgs];
9493
9494public:
James Y Knight9871db02019-02-05 16:42:33 +00009495 DoacrossCleanupTy(llvm::FunctionCallee RTLFn,
9496 ArrayRef<llvm::Value *> CallArgs)
Alexey Bataev8b427062016-05-25 12:36:08 +00009497 : RTLFn(RTLFn) {
9498 assert(CallArgs.size() == DoacrossFinArgs);
9499 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
9500 }
9501 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
9502 if (!CGF.HaveInsertPoint())
9503 return;
9504 CGF.EmitRuntimeCall(RTLFn, Args);
9505 }
9506};
9507} // namespace
9508
9509void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
Alexey Bataevf138fda2018-08-13 19:04:24 +00009510 const OMPLoopDirective &D,
9511 ArrayRef<Expr *> NumIterations) {
Alexey Bataev8b427062016-05-25 12:36:08 +00009512 if (!CGF.HaveInsertPoint())
9513 return;
9514
9515 ASTContext &C = CGM.getContext();
9516 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
9517 RecordDecl *RD;
9518 if (KmpDimTy.isNull()) {
9519 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
9520 // kmp_int64 lo; // lower
9521 // kmp_int64 up; // upper
9522 // kmp_int64 st; // stride
9523 // };
9524 RD = C.buildImplicitRecord("kmp_dim");
9525 RD->startDefinition();
9526 addFieldToRecordDecl(C, RD, Int64Ty);
9527 addFieldToRecordDecl(C, RD, Int64Ty);
9528 addFieldToRecordDecl(C, RD, Int64Ty);
9529 RD->completeDefinition();
9530 KmpDimTy = C.getRecordType(RD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009531 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00009532 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009533 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00009534 llvm::APInt Size(/*numBits=*/32, NumIterations.size());
9535 QualType ArrayTy =
9536 C.getConstantArrayType(KmpDimTy, Size, ArrayType::Normal, 0);
Alexey Bataev8b427062016-05-25 12:36:08 +00009537
Alexey Bataevf138fda2018-08-13 19:04:24 +00009538 Address DimsAddr = CGF.CreateMemTemp(ArrayTy, "dims");
9539 CGF.EmitNullInitialization(DimsAddr, ArrayTy);
Alexey Bataev8b427062016-05-25 12:36:08 +00009540 enum { LowerFD = 0, UpperFD, StrideFD };
9541 // Fill dims with data.
Alexey Bataevf138fda2018-08-13 19:04:24 +00009542 for (unsigned I = 0, E = NumIterations.size(); I < E; ++I) {
James Y Knight751fe282019-02-09 22:22:28 +00009543 LValue DimsLVal = CGF.MakeAddrLValue(
9544 CGF.Builder.CreateConstArrayGEP(DimsAddr, I), KmpDimTy);
Alexey Bataevf138fda2018-08-13 19:04:24 +00009545 // dims.upper = num_iterations;
9546 LValue UpperLVal = CGF.EmitLValueForField(
9547 DimsLVal, *std::next(RD->field_begin(), UpperFD));
9548 llvm::Value *NumIterVal =
9549 CGF.EmitScalarConversion(CGF.EmitScalarExpr(NumIterations[I]),
9550 D.getNumIterations()->getType(), Int64Ty,
9551 D.getNumIterations()->getExprLoc());
9552 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
9553 // dims.stride = 1;
9554 LValue StrideLVal = CGF.EmitLValueForField(
9555 DimsLVal, *std::next(RD->field_begin(), StrideFD));
9556 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
9557 StrideLVal);
9558 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009559
9560 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
9561 // kmp_int32 num_dims, struct kmp_dim * dims);
Alexey Bataevf138fda2018-08-13 19:04:24 +00009562 llvm::Value *Args[] = {
9563 emitUpdateLocation(CGF, D.getBeginLoc()),
9564 getThreadID(CGF, D.getBeginLoc()),
9565 llvm::ConstantInt::getSigned(CGM.Int32Ty, NumIterations.size()),
9566 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
James Y Knight751fe282019-02-09 22:22:28 +00009567 CGF.Builder.CreateConstArrayGEP(DimsAddr, 0).getPointer(),
Alexey Bataevf138fda2018-08-13 19:04:24 +00009568 CGM.VoidPtrTy)};
Alexey Bataev8b427062016-05-25 12:36:08 +00009569
James Y Knight9871db02019-02-05 16:42:33 +00009570 llvm::FunctionCallee RTLFn =
9571 createRuntimeFunction(OMPRTL__kmpc_doacross_init);
Alexey Bataev8b427062016-05-25 12:36:08 +00009572 CGF.EmitRuntimeCall(RTLFn, Args);
9573 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009574 emitUpdateLocation(CGF, D.getEndLoc()), getThreadID(CGF, D.getEndLoc())};
James Y Knight9871db02019-02-05 16:42:33 +00009575 llvm::FunctionCallee FiniRTLFn =
9576 createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
Alexey Bataev8b427062016-05-25 12:36:08 +00009577 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
9578 llvm::makeArrayRef(FiniArgs));
9579}
9580
9581void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
9582 const OMPDependClause *C) {
9583 QualType Int64Ty =
9584 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
Alexey Bataevf138fda2018-08-13 19:04:24 +00009585 llvm::APInt Size(/*numBits=*/32, C->getNumLoops());
9586 QualType ArrayTy = CGM.getContext().getConstantArrayType(
9587 Int64Ty, Size, ArrayType::Normal, 0);
9588 Address CntAddr = CGF.CreateMemTemp(ArrayTy, ".cnt.addr");
9589 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I) {
9590 const Expr *CounterVal = C->getLoopData(I);
9591 assert(CounterVal);
9592 llvm::Value *CntVal = CGF.EmitScalarConversion(
9593 CGF.EmitScalarExpr(CounterVal), CounterVal->getType(), Int64Ty,
9594 CounterVal->getExprLoc());
James Y Knight751fe282019-02-09 22:22:28 +00009595 CGF.EmitStoreOfScalar(CntVal, CGF.Builder.CreateConstArrayGEP(CntAddr, I),
9596 /*Volatile=*/false, Int64Ty);
Alexey Bataevf138fda2018-08-13 19:04:24 +00009597 }
9598 llvm::Value *Args[] = {
9599 emitUpdateLocation(CGF, C->getBeginLoc()),
9600 getThreadID(CGF, C->getBeginLoc()),
James Y Knight751fe282019-02-09 22:22:28 +00009601 CGF.Builder.CreateConstArrayGEP(CntAddr, 0).getPointer()};
James Y Knight9871db02019-02-05 16:42:33 +00009602 llvm::FunctionCallee RTLFn;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009603 if (C->getDependencyKind() == OMPC_DEPEND_source) {
Alexey Bataev8b427062016-05-25 12:36:08 +00009604 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009605 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00009606 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
9607 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
9608 }
9609 CGF.EmitRuntimeCall(RTLFn, Args);
9610}
9611
Alexey Bataev7ef47a62018-02-22 18:33:31 +00009612void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, SourceLocation Loc,
James Y Knight9871db02019-02-05 16:42:33 +00009613 llvm::FunctionCallee Callee,
Alexey Bataev7ef47a62018-02-22 18:33:31 +00009614 ArrayRef<llvm::Value *> Args) const {
9615 assert(Loc.isValid() && "Outlined function call location must be valid.");
Alexey Bataev3c595a62017-08-14 15:01:03 +00009616 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
9617
James Y Knight9871db02019-02-05 16:42:33 +00009618 if (auto *Fn = dyn_cast<llvm::Function>(Callee.getCallee())) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00009619 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00009620 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00009621 return;
9622 }
9623 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00009624 CGF.EmitRuntimeCall(Callee, Args);
9625}
9626
9627void CGOpenMPRuntime::emitOutlinedFunctionCall(
James Y Knight9871db02019-02-05 16:42:33 +00009628 CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn,
Alexey Bataev3c595a62017-08-14 15:01:03 +00009629 ArrayRef<llvm::Value *> Args) const {
Alexey Bataev7ef47a62018-02-22 18:33:31 +00009630 emitCall(CGF, Loc, OutlinedFn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00009631}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00009632
9633Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
9634 const VarDecl *NativeParam,
9635 const VarDecl *TargetParam) const {
9636 return CGF.GetAddrOfLocalVar(NativeParam);
9637}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009638
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00009639Address CGOpenMPRuntime::getAddressOfLocalVariable(CodeGenFunction &CGF,
9640 const VarDecl *VD) {
9641 return Address::invalid();
9642}
9643
James Y Knight9871db02019-02-05 16:42:33 +00009644llvm::Function *CGOpenMPSIMDRuntime::emitParallelOutlinedFunction(
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009645 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
9646 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
9647 llvm_unreachable("Not supported in SIMD-only mode");
9648}
9649
James Y Knight9871db02019-02-05 16:42:33 +00009650llvm::Function *CGOpenMPSIMDRuntime::emitTeamsOutlinedFunction(
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009651 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
9652 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
9653 llvm_unreachable("Not supported in SIMD-only mode");
9654}
9655
James Y Knight9871db02019-02-05 16:42:33 +00009656llvm::Function *CGOpenMPSIMDRuntime::emitTaskOutlinedFunction(
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009657 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
9658 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
9659 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
9660 bool Tied, unsigned &NumberOfParts) {
9661 llvm_unreachable("Not supported in SIMD-only mode");
9662}
9663
9664void CGOpenMPSIMDRuntime::emitParallelCall(CodeGenFunction &CGF,
9665 SourceLocation Loc,
James Y Knight9871db02019-02-05 16:42:33 +00009666 llvm::Function *OutlinedFn,
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009667 ArrayRef<llvm::Value *> CapturedVars,
9668 const Expr *IfCond) {
9669 llvm_unreachable("Not supported in SIMD-only mode");
9670}
9671
9672void CGOpenMPSIMDRuntime::emitCriticalRegion(
9673 CodeGenFunction &CGF, StringRef CriticalName,
9674 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
9675 const Expr *Hint) {
9676 llvm_unreachable("Not supported in SIMD-only mode");
9677}
9678
9679void CGOpenMPSIMDRuntime::emitMasterRegion(CodeGenFunction &CGF,
9680 const RegionCodeGenTy &MasterOpGen,
9681 SourceLocation Loc) {
9682 llvm_unreachable("Not supported in SIMD-only mode");
9683}
9684
9685void CGOpenMPSIMDRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
9686 SourceLocation Loc) {
9687 llvm_unreachable("Not supported in SIMD-only mode");
9688}
9689
9690void CGOpenMPSIMDRuntime::emitTaskgroupRegion(
9691 CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen,
9692 SourceLocation Loc) {
9693 llvm_unreachable("Not supported in SIMD-only mode");
9694}
9695
9696void CGOpenMPSIMDRuntime::emitSingleRegion(
9697 CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen,
9698 SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars,
9699 ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs,
9700 ArrayRef<const Expr *> AssignmentOps) {
9701 llvm_unreachable("Not supported in SIMD-only mode");
9702}
9703
9704void CGOpenMPSIMDRuntime::emitOrderedRegion(CodeGenFunction &CGF,
9705 const RegionCodeGenTy &OrderedOpGen,
9706 SourceLocation Loc,
9707 bool IsThreads) {
9708 llvm_unreachable("Not supported in SIMD-only mode");
9709}
9710
9711void CGOpenMPSIMDRuntime::emitBarrierCall(CodeGenFunction &CGF,
9712 SourceLocation Loc,
9713 OpenMPDirectiveKind Kind,
9714 bool EmitChecks,
9715 bool ForceSimpleCall) {
9716 llvm_unreachable("Not supported in SIMD-only mode");
9717}
9718
9719void CGOpenMPSIMDRuntime::emitForDispatchInit(
9720 CodeGenFunction &CGF, SourceLocation Loc,
9721 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
9722 bool Ordered, const DispatchRTInput &DispatchValues) {
9723 llvm_unreachable("Not supported in SIMD-only mode");
9724}
9725
9726void CGOpenMPSIMDRuntime::emitForStaticInit(
9727 CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind,
9728 const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values) {
9729 llvm_unreachable("Not supported in SIMD-only mode");
9730}
9731
9732void CGOpenMPSIMDRuntime::emitDistributeStaticInit(
9733 CodeGenFunction &CGF, SourceLocation Loc,
9734 OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values) {
9735 llvm_unreachable("Not supported in SIMD-only mode");
9736}
9737
9738void CGOpenMPSIMDRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
9739 SourceLocation Loc,
9740 unsigned IVSize,
9741 bool IVSigned) {
9742 llvm_unreachable("Not supported in SIMD-only mode");
9743}
9744
9745void CGOpenMPSIMDRuntime::emitForStaticFinish(CodeGenFunction &CGF,
9746 SourceLocation Loc,
9747 OpenMPDirectiveKind DKind) {
9748 llvm_unreachable("Not supported in SIMD-only mode");
9749}
9750
9751llvm::Value *CGOpenMPSIMDRuntime::emitForNext(CodeGenFunction &CGF,
9752 SourceLocation Loc,
9753 unsigned IVSize, bool IVSigned,
9754 Address IL, Address LB,
9755 Address UB, Address ST) {
9756 llvm_unreachable("Not supported in SIMD-only mode");
9757}
9758
9759void CGOpenMPSIMDRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
9760 llvm::Value *NumThreads,
9761 SourceLocation Loc) {
9762 llvm_unreachable("Not supported in SIMD-only mode");
9763}
9764
9765void CGOpenMPSIMDRuntime::emitProcBindClause(CodeGenFunction &CGF,
9766 OpenMPProcBindClauseKind ProcBind,
9767 SourceLocation Loc) {
9768 llvm_unreachable("Not supported in SIMD-only mode");
9769}
9770
9771Address CGOpenMPSIMDRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
9772 const VarDecl *VD,
9773 Address VDAddr,
9774 SourceLocation Loc) {
9775 llvm_unreachable("Not supported in SIMD-only mode");
9776}
9777
9778llvm::Function *CGOpenMPSIMDRuntime::emitThreadPrivateVarDefinition(
9779 const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit,
9780 CodeGenFunction *CGF) {
9781 llvm_unreachable("Not supported in SIMD-only mode");
9782}
9783
9784Address CGOpenMPSIMDRuntime::getAddrOfArtificialThreadPrivate(
9785 CodeGenFunction &CGF, QualType VarType, StringRef Name) {
9786 llvm_unreachable("Not supported in SIMD-only mode");
9787}
9788
9789void CGOpenMPSIMDRuntime::emitFlush(CodeGenFunction &CGF,
9790 ArrayRef<const Expr *> Vars,
9791 SourceLocation Loc) {
9792 llvm_unreachable("Not supported in SIMD-only mode");
9793}
9794
9795void CGOpenMPSIMDRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
9796 const OMPExecutableDirective &D,
James Y Knight9871db02019-02-05 16:42:33 +00009797 llvm::Function *TaskFunction,
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009798 QualType SharedsTy, Address Shareds,
9799 const Expr *IfCond,
9800 const OMPTaskDataTy &Data) {
9801 llvm_unreachable("Not supported in SIMD-only mode");
9802}
9803
9804void CGOpenMPSIMDRuntime::emitTaskLoopCall(
9805 CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D,
James Y Knight9871db02019-02-05 16:42:33 +00009806 llvm::Function *TaskFunction, QualType SharedsTy, Address Shareds,
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009807 const Expr *IfCond, const OMPTaskDataTy &Data) {
9808 llvm_unreachable("Not supported in SIMD-only mode");
9809}
9810
9811void CGOpenMPSIMDRuntime::emitReduction(
9812 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
9813 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
9814 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
9815 assert(Options.SimpleReduction && "Only simple reduction is expected.");
9816 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
9817 ReductionOps, Options);
9818}
9819
9820llvm::Value *CGOpenMPSIMDRuntime::emitTaskReductionInit(
9821 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
9822 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
9823 llvm_unreachable("Not supported in SIMD-only mode");
9824}
9825
9826void CGOpenMPSIMDRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
9827 SourceLocation Loc,
9828 ReductionCodeGen &RCG,
9829 unsigned N) {
9830 llvm_unreachable("Not supported in SIMD-only mode");
9831}
9832
9833Address CGOpenMPSIMDRuntime::getTaskReductionItem(CodeGenFunction &CGF,
9834 SourceLocation Loc,
9835 llvm::Value *ReductionsPtr,
9836 LValue SharedLVal) {
9837 llvm_unreachable("Not supported in SIMD-only mode");
9838}
9839
9840void CGOpenMPSIMDRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
9841 SourceLocation Loc) {
9842 llvm_unreachable("Not supported in SIMD-only mode");
9843}
9844
9845void CGOpenMPSIMDRuntime::emitCancellationPointCall(
9846 CodeGenFunction &CGF, SourceLocation Loc,
9847 OpenMPDirectiveKind CancelRegion) {
9848 llvm_unreachable("Not supported in SIMD-only mode");
9849}
9850
9851void CGOpenMPSIMDRuntime::emitCancelCall(CodeGenFunction &CGF,
9852 SourceLocation Loc, const Expr *IfCond,
9853 OpenMPDirectiveKind CancelRegion) {
9854 llvm_unreachable("Not supported in SIMD-only mode");
9855}
9856
9857void CGOpenMPSIMDRuntime::emitTargetOutlinedFunction(
9858 const OMPExecutableDirective &D, StringRef ParentName,
9859 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
9860 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
9861 llvm_unreachable("Not supported in SIMD-only mode");
9862}
9863
9864void CGOpenMPSIMDRuntime::emitTargetCall(CodeGenFunction &CGF,
9865 const OMPExecutableDirective &D,
James Y Knight9871db02019-02-05 16:42:33 +00009866 llvm::Function *OutlinedFn,
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009867 llvm::Value *OutlinedFnID,
James Y Knight9871db02019-02-05 16:42:33 +00009868 const Expr *IfCond,
9869 const Expr *Device) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009870 llvm_unreachable("Not supported in SIMD-only mode");
9871}
9872
9873bool CGOpenMPSIMDRuntime::emitTargetFunctions(GlobalDecl GD) {
9874 llvm_unreachable("Not supported in SIMD-only mode");
9875}
9876
9877bool CGOpenMPSIMDRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
9878 llvm_unreachable("Not supported in SIMD-only mode");
9879}
9880
9881bool CGOpenMPSIMDRuntime::emitTargetGlobal(GlobalDecl GD) {
9882 return false;
9883}
9884
9885llvm::Function *CGOpenMPSIMDRuntime::emitRegistrationFunction() {
9886 return nullptr;
9887}
9888
9889void CGOpenMPSIMDRuntime::emitTeamsCall(CodeGenFunction &CGF,
9890 const OMPExecutableDirective &D,
9891 SourceLocation Loc,
James Y Knight9871db02019-02-05 16:42:33 +00009892 llvm::Function *OutlinedFn,
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009893 ArrayRef<llvm::Value *> CapturedVars) {
9894 llvm_unreachable("Not supported in SIMD-only mode");
9895}
9896
9897void CGOpenMPSIMDRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
9898 const Expr *NumTeams,
9899 const Expr *ThreadLimit,
9900 SourceLocation Loc) {
9901 llvm_unreachable("Not supported in SIMD-only mode");
9902}
9903
9904void CGOpenMPSIMDRuntime::emitTargetDataCalls(
9905 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
9906 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
9907 llvm_unreachable("Not supported in SIMD-only mode");
9908}
9909
9910void CGOpenMPSIMDRuntime::emitTargetDataStandAloneCall(
9911 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
9912 const Expr *Device) {
9913 llvm_unreachable("Not supported in SIMD-only mode");
9914}
9915
9916void CGOpenMPSIMDRuntime::emitDoacrossInit(CodeGenFunction &CGF,
Alexey Bataevf138fda2018-08-13 19:04:24 +00009917 const OMPLoopDirective &D,
9918 ArrayRef<Expr *> NumIterations) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009919 llvm_unreachable("Not supported in SIMD-only mode");
9920}
9921
9922void CGOpenMPSIMDRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
9923 const OMPDependClause *C) {
9924 llvm_unreachable("Not supported in SIMD-only mode");
9925}
9926
9927const VarDecl *
9928CGOpenMPSIMDRuntime::translateParameter(const FieldDecl *FD,
9929 const VarDecl *NativeParam) const {
9930 llvm_unreachable("Not supported in SIMD-only mode");
9931}
9932
9933Address
9934CGOpenMPSIMDRuntime::getParameterAddress(CodeGenFunction &CGF,
9935 const VarDecl *NativeParam,
9936 const VarDecl *TargetParam) const {
9937 llvm_unreachable("Not supported in SIMD-only mode");
9938}