blob: 9058c42a4d130a4035ac22ab563907a44f558d52 [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
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001341static llvm::Value *emitParallelOrTeamsOutlinedFunction(
1342 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
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001371llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
1372 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
1379llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1380 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
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001387llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
1388 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);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001418 llvm::Value *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
1666llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001667CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001668 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001669 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001670 case OMPRTL__kmpc_fork_call: {
1671 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1672 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001673 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1674 getKmpc_MicroPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001675 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001676 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001677 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
Johannes Doerfertac991bb2019-01-19 05:36:54 +00001678 if (auto *F = dyn_cast<llvm::Function>(RTLFn)) {
1679 if (!F->hasMetadata(llvm::LLVMContext::MD_callback)) {
1680 llvm::LLVMContext &Ctx = F->getContext();
1681 llvm::MDBuilder MDB(Ctx);
1682 // Annotate the callback behavior of the __kmpc_fork_call:
1683 // - The callback callee is argument number 2 (microtask).
1684 // - The first two arguments of the callback callee are unknown (-1).
1685 // - All variadic arguments to the __kmpc_fork_call are passed to the
1686 // callback callee.
1687 F->addMetadata(
1688 llvm::LLVMContext::MD_callback,
1689 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
1690 2, {-1, -1},
1691 /* VarArgsArePassed */ true)}));
1692 }
1693 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001694 break;
1695 }
1696 case OMPRTL__kmpc_global_thread_num: {
1697 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001698 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001699 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001700 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001701 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1702 break;
1703 }
Alexey Bataev97720002014-11-11 04:05:39 +00001704 case OMPRTL__kmpc_threadprivate_cached: {
1705 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1706 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1707 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1708 CGM.VoidPtrTy, CGM.SizeTy,
1709 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001710 auto *FnTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001711 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1712 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1713 break;
1714 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001715 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001716 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1717 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001718 llvm::Type *TypeParams[] = {
1719 getIdentTyPointerTy(), CGM.Int32Ty,
1720 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001721 auto *FnTy =
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001722 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1723 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1724 break;
1725 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001726 case OMPRTL__kmpc_critical_with_hint: {
1727 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1728 // kmp_critical_name *crit, uintptr_t hint);
1729 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1730 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1731 CGM.IntPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001732 auto *FnTy =
Alexey Bataevfc57d162015-12-15 10:55:09 +00001733 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1734 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1735 break;
1736 }
Alexey Bataev97720002014-11-11 04:05:39 +00001737 case OMPRTL__kmpc_threadprivate_register: {
1738 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1739 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1740 // typedef void *(*kmpc_ctor)(void *);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001741 auto *KmpcCtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001742 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1743 /*isVarArg*/ false)->getPointerTo();
1744 // typedef void *(*kmpc_cctor)(void *, void *);
1745 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001746 auto *KmpcCopyCtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001747 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001748 /*isVarArg*/ false)
1749 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00001750 // typedef void (*kmpc_dtor)(void *);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001751 auto *KmpcDtorTy =
Alexey Bataev97720002014-11-11 04:05:39 +00001752 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1753 ->getPointerTo();
1754 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1755 KmpcCopyCtorTy, KmpcDtorTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001756 auto *FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
Alexey Bataev97720002014-11-11 04:05:39 +00001757 /*isVarArg*/ false);
1758 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1759 break;
1760 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001761 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001762 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1763 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001764 llvm::Type *TypeParams[] = {
1765 getIdentTyPointerTy(), CGM.Int32Ty,
1766 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001767 auto *FnTy =
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001768 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1769 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1770 break;
1771 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001772 case OMPRTL__kmpc_cancel_barrier: {
1773 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1774 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001775 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001776 auto *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001777 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1778 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001779 break;
1780 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001781 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001782 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001783 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001784 auto *FnTy =
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001785 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1786 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1787 break;
1788 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001789 case OMPRTL__kmpc_for_static_fini: {
1790 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1791 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001792 auto *FnTy =
Alexander Musmanc6388682014-12-15 07:07:06 +00001793 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1794 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1795 break;
1796 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001797 case OMPRTL__kmpc_push_num_threads: {
1798 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1799 // kmp_int32 num_threads)
1800 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1801 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001802 auto *FnTy =
Alexey Bataevb2059782014-10-13 08:23:51 +00001803 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1804 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1805 break;
1806 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001807 case OMPRTL__kmpc_serialized_parallel: {
1808 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1809 // global_tid);
1810 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001811 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001812 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1813 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1814 break;
1815 }
1816 case OMPRTL__kmpc_end_serialized_parallel: {
1817 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1818 // global_tid);
1819 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001820 auto *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001821 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1822 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1823 break;
1824 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001825 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001826 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001827 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001828 auto *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001829 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001830 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1831 break;
1832 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001833 case OMPRTL__kmpc_master: {
1834 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1835 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001836 auto *FnTy =
Alexey Bataev8d690652014-12-04 07:23:53 +00001837 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1838 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1839 break;
1840 }
1841 case OMPRTL__kmpc_end_master: {
1842 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1843 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001844 auto *FnTy =
Alexey Bataev8d690652014-12-04 07:23:53 +00001845 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1846 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1847 break;
1848 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001849 case OMPRTL__kmpc_omp_taskyield: {
1850 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1851 // int end_part);
1852 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001853 auto *FnTy =
Alexey Bataev9f797f32015-02-05 05:57:51 +00001854 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1855 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1856 break;
1857 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001858 case OMPRTL__kmpc_single: {
1859 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1860 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001861 auto *FnTy =
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001862 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1863 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1864 break;
1865 }
1866 case OMPRTL__kmpc_end_single: {
1867 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1868 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001869 auto *FnTy =
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001870 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1871 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1872 break;
1873 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001874 case OMPRTL__kmpc_omp_task_alloc: {
1875 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1876 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1877 // kmp_routine_entry_t *task_entry);
1878 assert(KmpRoutineEntryPtrTy != nullptr &&
1879 "Type kmp_routine_entry_t must be created.");
1880 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1881 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1882 // Return void * and then cast to particular kmp_task_t type.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001883 auto *FnTy =
Alexey Bataev62b63b12015-03-10 07:28:44 +00001884 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1885 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1886 break;
1887 }
1888 case OMPRTL__kmpc_omp_task: {
1889 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1890 // *new_task);
1891 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1892 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001893 auto *FnTy =
Alexey Bataev62b63b12015-03-10 07:28:44 +00001894 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1895 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1896 break;
1897 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001898 case OMPRTL__kmpc_copyprivate: {
1899 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001900 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001901 // kmp_int32 didit);
1902 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1903 auto *CpyFnTy =
1904 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001905 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001906 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1907 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001908 auto *FnTy =
Alexey Bataeva63048e2015-03-23 06:18:07 +00001909 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1910 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1911 break;
1912 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001913 case OMPRTL__kmpc_reduce: {
1914 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1915 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1916 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1917 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1918 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1919 /*isVarArg=*/false);
1920 llvm::Type *TypeParams[] = {
1921 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1922 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1923 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001924 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001925 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1926 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1927 break;
1928 }
1929 case OMPRTL__kmpc_reduce_nowait: {
1930 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1931 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1932 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1933 // *lck);
1934 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1935 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1936 /*isVarArg=*/false);
1937 llvm::Type *TypeParams[] = {
1938 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1939 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1940 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001941 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001942 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1943 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1944 break;
1945 }
1946 case OMPRTL__kmpc_end_reduce: {
1947 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1948 // kmp_critical_name *lck);
1949 llvm::Type *TypeParams[] = {
1950 getIdentTyPointerTy(), CGM.Int32Ty,
1951 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001952 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001953 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1954 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1955 break;
1956 }
1957 case OMPRTL__kmpc_end_reduce_nowait: {
1958 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1959 // kmp_critical_name *lck);
1960 llvm::Type *TypeParams[] = {
1961 getIdentTyPointerTy(), CGM.Int32Ty,
1962 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001963 auto *FnTy =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001964 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1965 RTLFn =
1966 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1967 break;
1968 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001969 case OMPRTL__kmpc_omp_task_begin_if0: {
1970 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1971 // *new_task);
1972 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1973 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001974 auto *FnTy =
Alexey Bataev1d677132015-04-22 13:57:31 +00001975 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1976 RTLFn =
1977 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1978 break;
1979 }
1980 case OMPRTL__kmpc_omp_task_complete_if0: {
1981 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1982 // *new_task);
1983 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1984 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001985 auto *FnTy =
Alexey Bataev1d677132015-04-22 13:57:31 +00001986 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1987 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1988 /*Name=*/"__kmpc_omp_task_complete_if0");
1989 break;
1990 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001991 case OMPRTL__kmpc_ordered: {
1992 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1993 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00001994 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001995 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1996 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1997 break;
1998 }
1999 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002000 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002001 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002002 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002003 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2004 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
2005 break;
2006 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002007 case OMPRTL__kmpc_omp_taskwait: {
2008 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
2009 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002010 auto *FnTy =
Alexey Bataev8b8e2022015-04-27 05:22:09 +00002011 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
2012 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
2013 break;
2014 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002015 case OMPRTL__kmpc_taskgroup: {
2016 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
2017 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002018 auto *FnTy =
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002019 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2020 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
2021 break;
2022 }
2023 case OMPRTL__kmpc_end_taskgroup: {
2024 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
2025 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002026 auto *FnTy =
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002027 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2028 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
2029 break;
2030 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00002031 case OMPRTL__kmpc_push_proc_bind: {
2032 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
2033 // int proc_bind)
2034 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002035 auto *FnTy =
Alexey Bataev7f210c62015-06-18 13:40:03 +00002036 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2037 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
2038 break;
2039 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002040 case OMPRTL__kmpc_omp_task_with_deps: {
2041 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
2042 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
2043 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
2044 llvm::Type *TypeParams[] = {
2045 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
2046 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002047 auto *FnTy =
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002048 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
2049 RTLFn =
2050 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
2051 break;
2052 }
2053 case OMPRTL__kmpc_omp_wait_deps: {
2054 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
2055 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
2056 // kmp_depend_info_t *noalias_dep_list);
2057 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2058 CGM.Int32Ty, CGM.VoidPtrTy,
2059 CGM.Int32Ty, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002060 auto *FnTy =
Alexey Bataev1d2353d2015-06-24 11:01:36 +00002061 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2062 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
2063 break;
2064 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00002065 case OMPRTL__kmpc_cancellationpoint: {
2066 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
2067 // global_tid, kmp_int32 cncl_kind)
2068 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002069 auto *FnTy =
Alexey Bataev0f34da12015-07-02 04:17:07 +00002070 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2071 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
2072 break;
2073 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002074 case OMPRTL__kmpc_cancel: {
2075 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
2076 // kmp_int32 cncl_kind)
2077 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002078 auto *FnTy =
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00002079 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2080 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
2081 break;
2082 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002083 case OMPRTL__kmpc_push_num_teams: {
2084 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
2085 // kmp_int32 num_teams, kmp_int32 num_threads)
2086 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
2087 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002088 auto *FnTy =
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002089 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2090 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
2091 break;
2092 }
2093 case OMPRTL__kmpc_fork_teams: {
2094 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
2095 // microtask, ...);
2096 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2097 getKmpc_MicroPointerTy()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002098 auto *FnTy =
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002099 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
2100 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
Johannes Doerfertac991bb2019-01-19 05:36:54 +00002101 if (auto *F = dyn_cast<llvm::Function>(RTLFn)) {
2102 if (!F->hasMetadata(llvm::LLVMContext::MD_callback)) {
2103 llvm::LLVMContext &Ctx = F->getContext();
2104 llvm::MDBuilder MDB(Ctx);
2105 // Annotate the callback behavior of the __kmpc_fork_teams:
2106 // - The callback callee is argument number 2 (microtask).
2107 // - The first two arguments of the callback callee are unknown (-1).
2108 // - All variadic arguments to the __kmpc_fork_teams are passed to the
2109 // callback callee.
2110 F->addMetadata(
2111 llvm::LLVMContext::MD_callback,
2112 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
2113 2, {-1, -1},
2114 /* VarArgsArePassed */ true)}));
2115 }
2116 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00002117 break;
2118 }
Alexey Bataev7292c292016-04-25 12:22:29 +00002119 case OMPRTL__kmpc_taskloop: {
2120 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
2121 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
2122 // sched, kmp_uint64 grainsize, void *task_dup);
2123 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2124 CGM.IntTy,
2125 CGM.VoidPtrTy,
2126 CGM.IntTy,
2127 CGM.Int64Ty->getPointerTo(),
2128 CGM.Int64Ty->getPointerTo(),
2129 CGM.Int64Ty,
2130 CGM.IntTy,
2131 CGM.IntTy,
2132 CGM.Int64Ty,
2133 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002134 auto *FnTy =
Alexey Bataev7292c292016-04-25 12:22:29 +00002135 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2136 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
2137 break;
2138 }
Alexey Bataev8b427062016-05-25 12:36:08 +00002139 case OMPRTL__kmpc_doacross_init: {
2140 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
2141 // num_dims, struct kmp_dim *dims);
2142 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
2143 CGM.Int32Ty,
2144 CGM.Int32Ty,
2145 CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002146 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002147 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2148 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
2149 break;
2150 }
2151 case OMPRTL__kmpc_doacross_fini: {
2152 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
2153 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002154 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002155 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2156 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
2157 break;
2158 }
2159 case OMPRTL__kmpc_doacross_post: {
2160 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
2161 // *vec);
2162 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2163 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002164 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002165 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2166 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
2167 break;
2168 }
2169 case OMPRTL__kmpc_doacross_wait: {
2170 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
2171 // *vec);
2172 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
2173 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002174 auto *FnTy =
Alexey Bataev8b427062016-05-25 12:36:08 +00002175 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2176 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
2177 break;
2178 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002179 case OMPRTL__kmpc_task_reduction_init: {
2180 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
2181 // *data);
2182 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002183 auto *FnTy =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002184 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2185 RTLFn =
2186 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
2187 break;
2188 }
2189 case OMPRTL__kmpc_task_reduction_get_th_data: {
2190 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
2191 // *d);
2192 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002193 auto *FnTy =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002194 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
2195 RTLFn = CGM.CreateRuntimeFunction(
2196 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
2197 break;
2198 }
Alexey Bataev7bb33532019-01-07 21:30:43 +00002199 case OMPRTL__kmpc_push_target_tripcount: {
2200 // Build void __kmpc_push_target_tripcount(int64_t device_id, kmp_uint64
2201 // size);
2202 llvm::Type *TypeParams[] = {CGM.Int64Ty, CGM.Int64Ty};
2203 llvm::FunctionType *FnTy =
2204 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2205 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_target_tripcount");
2206 break;
2207 }
Samuel Antaobed3c462015-10-02 16:14:20 +00002208 case OMPRTL__tgt_target: {
George Rokos63bc9d62017-11-21 18:25:12 +00002209 // Build int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t
2210 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
Samuel Antaobed3c462015-10-02 16:14:20 +00002211 // *arg_types);
George Rokos63bc9d62017-11-21 18:25:12 +00002212 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaobed3c462015-10-02 16:14:20 +00002213 CGM.VoidPtrTy,
2214 CGM.Int32Ty,
2215 CGM.VoidPtrPtrTy,
2216 CGM.VoidPtrPtrTy,
2217 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002218 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002219 auto *FnTy =
Samuel Antaobed3c462015-10-02 16:14:20 +00002220 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2221 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2222 break;
2223 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002224 case OMPRTL__tgt_target_nowait: {
2225 // Build int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr,
2226 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2227 // int64_t *arg_types);
2228 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2229 CGM.VoidPtrTy,
2230 CGM.Int32Ty,
2231 CGM.VoidPtrPtrTy,
2232 CGM.VoidPtrPtrTy,
2233 CGM.SizeTy->getPointerTo(),
2234 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002235 auto *FnTy =
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002236 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2237 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_nowait");
2238 break;
2239 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00002240 case OMPRTL__tgt_target_teams: {
George Rokos63bc9d62017-11-21 18:25:12 +00002241 // Build int32_t __tgt_target_teams(int64_t device_id, void *host_ptr,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002242 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
George Rokos63bc9d62017-11-21 18:25:12 +00002243 // int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2244 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaob68e2db2016-03-03 16:20:23 +00002245 CGM.VoidPtrTy,
2246 CGM.Int32Ty,
2247 CGM.VoidPtrPtrTy,
2248 CGM.VoidPtrPtrTy,
2249 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002250 CGM.Int64Ty->getPointerTo(),
Samuel Antaob68e2db2016-03-03 16:20:23 +00002251 CGM.Int32Ty,
2252 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002253 auto *FnTy =
Samuel Antaob68e2db2016-03-03 16:20:23 +00002254 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2255 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2256 break;
2257 }
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002258 case OMPRTL__tgt_target_teams_nowait: {
2259 // Build int32_t __tgt_target_teams_nowait(int64_t device_id, void
2260 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t
2261 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit);
2262 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2263 CGM.VoidPtrTy,
2264 CGM.Int32Ty,
2265 CGM.VoidPtrPtrTy,
2266 CGM.VoidPtrPtrTy,
2267 CGM.SizeTy->getPointerTo(),
2268 CGM.Int64Ty->getPointerTo(),
2269 CGM.Int32Ty,
2270 CGM.Int32Ty};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002271 auto *FnTy =
Alexey Bataeva9f77c62017-12-13 21:04:20 +00002272 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2273 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams_nowait");
2274 break;
2275 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002276 case OMPRTL__tgt_register_lib: {
2277 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2278 QualType ParamTy =
2279 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2280 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002281 auto *FnTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002282 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2283 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2284 break;
2285 }
2286 case OMPRTL__tgt_unregister_lib: {
2287 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2288 QualType ParamTy =
2289 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2290 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002291 auto *FnTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002292 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2293 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2294 break;
2295 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002296 case OMPRTL__tgt_target_data_begin: {
George Rokos63bc9d62017-11-21 18:25:12 +00002297 // Build void __tgt_target_data_begin(int64_t device_id, int32_t arg_num,
2298 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2299 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002300 CGM.Int32Ty,
2301 CGM.VoidPtrPtrTy,
2302 CGM.VoidPtrPtrTy,
2303 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002304 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002305 auto *FnTy =
Samuel Antaodf158d52016-04-27 22:58:19 +00002306 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2307 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2308 break;
2309 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002310 case OMPRTL__tgt_target_data_begin_nowait: {
2311 // Build void __tgt_target_data_begin_nowait(int64_t device_id, int32_t
2312 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2313 // *arg_types);
2314 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2315 CGM.Int32Ty,
2316 CGM.VoidPtrPtrTy,
2317 CGM.VoidPtrPtrTy,
2318 CGM.SizeTy->getPointerTo(),
2319 CGM.Int64Ty->getPointerTo()};
2320 auto *FnTy =
2321 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2322 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin_nowait");
2323 break;
2324 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002325 case OMPRTL__tgt_target_data_end: {
George Rokos63bc9d62017-11-21 18:25:12 +00002326 // Build void __tgt_target_data_end(int64_t device_id, int32_t arg_num,
2327 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2328 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antaodf158d52016-04-27 22:58:19 +00002329 CGM.Int32Ty,
2330 CGM.VoidPtrPtrTy,
2331 CGM.VoidPtrPtrTy,
2332 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002333 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002334 auto *FnTy =
Samuel Antaodf158d52016-04-27 22:58:19 +00002335 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2336 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2337 break;
2338 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002339 case OMPRTL__tgt_target_data_end_nowait: {
2340 // Build void __tgt_target_data_end_nowait(int64_t device_id, int32_t
2341 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2342 // *arg_types);
2343 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2344 CGM.Int32Ty,
2345 CGM.VoidPtrPtrTy,
2346 CGM.VoidPtrPtrTy,
2347 CGM.SizeTy->getPointerTo(),
2348 CGM.Int64Ty->getPointerTo()};
2349 auto *FnTy =
2350 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2351 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end_nowait");
2352 break;
2353 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002354 case OMPRTL__tgt_target_data_update: {
George Rokos63bc9d62017-11-21 18:25:12 +00002355 // Build void __tgt_target_data_update(int64_t device_id, int32_t arg_num,
2356 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types);
2357 llvm::Type *TypeParams[] = {CGM.Int64Ty,
Samuel Antao8d2d7302016-05-26 18:30:22 +00002358 CGM.Int32Ty,
2359 CGM.VoidPtrPtrTy,
2360 CGM.VoidPtrPtrTy,
2361 CGM.SizeTy->getPointerTo(),
George Rokos63bc9d62017-11-21 18:25:12 +00002362 CGM.Int64Ty->getPointerTo()};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002363 auto *FnTy =
Samuel Antao8d2d7302016-05-26 18:30:22 +00002364 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2365 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2366 break;
2367 }
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00002368 case OMPRTL__tgt_target_data_update_nowait: {
2369 // Build void __tgt_target_data_update_nowait(int64_t device_id, int32_t
2370 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t
2371 // *arg_types);
2372 llvm::Type *TypeParams[] = {CGM.Int64Ty,
2373 CGM.Int32Ty,
2374 CGM.VoidPtrPtrTy,
2375 CGM.VoidPtrPtrTy,
2376 CGM.SizeTy->getPointerTo(),
2377 CGM.Int64Ty->getPointerTo()};
2378 auto *FnTy =
2379 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2380 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update_nowait");
2381 break;
2382 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002383 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002384 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002385 return RTLFn;
2386}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002387
Alexander Musman21212e42015-03-13 10:38:23 +00002388llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2389 bool IVSigned) {
2390 assert((IVSize == 32 || IVSize == 64) &&
2391 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002392 StringRef Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2393 : "__kmpc_for_static_init_4u")
2394 : (IVSigned ? "__kmpc_for_static_init_8"
2395 : "__kmpc_for_static_init_8u");
2396 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2397 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
Alexander Musman21212e42015-03-13 10:38:23 +00002398 llvm::Type *TypeParams[] = {
2399 getIdentTyPointerTy(), // loc
2400 CGM.Int32Ty, // tid
2401 CGM.Int32Ty, // schedtype
2402 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2403 PtrTy, // p_lower
2404 PtrTy, // p_upper
2405 PtrTy, // p_stride
2406 ITy, // incr
2407 ITy // chunk
2408 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002409 auto *FnTy =
Alexander Musman21212e42015-03-13 10:38:23 +00002410 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2411 return CGM.CreateRuntimeFunction(FnTy, Name);
2412}
2413
Alexander Musman92bdaab2015-03-12 13:37:50 +00002414llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2415 bool IVSigned) {
2416 assert((IVSize == 32 || IVSize == 64) &&
2417 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002418 StringRef Name =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002419 IVSize == 32
2420 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2421 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002422 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
Alexander Musman92bdaab2015-03-12 13:37:50 +00002423 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2424 CGM.Int32Ty, // tid
2425 CGM.Int32Ty, // schedtype
2426 ITy, // lower
2427 ITy, // upper
2428 ITy, // stride
2429 ITy // chunk
2430 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002431 auto *FnTy =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002432 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2433 return CGM.CreateRuntimeFunction(FnTy, Name);
2434}
2435
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002436llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2437 bool IVSigned) {
2438 assert((IVSize == 32 || IVSize == 64) &&
2439 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002440 StringRef Name =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002441 IVSize == 32
2442 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2443 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2444 llvm::Type *TypeParams[] = {
2445 getIdentTyPointerTy(), // loc
2446 CGM.Int32Ty, // tid
2447 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002448 auto *FnTy =
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002449 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2450 return CGM.CreateRuntimeFunction(FnTy, Name);
2451}
2452
Alexander Musman92bdaab2015-03-12 13:37:50 +00002453llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2454 bool IVSigned) {
2455 assert((IVSize == 32 || IVSize == 64) &&
2456 "IV size is not compatible with the omp runtime");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002457 StringRef Name =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002458 IVSize == 32
2459 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2460 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002461 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2462 auto *PtrTy = llvm::PointerType::getUnqual(ITy);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002463 llvm::Type *TypeParams[] = {
2464 getIdentTyPointerTy(), // loc
2465 CGM.Int32Ty, // tid
2466 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2467 PtrTy, // p_lower
2468 PtrTy, // p_upper
2469 PtrTy // p_stride
2470 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002471 auto *FnTy =
Alexander Musman92bdaab2015-03-12 13:37:50 +00002472 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2473 return CGM.CreateRuntimeFunction(FnTy, Name);
2474}
2475
Alexey Bataev03f270c2018-03-30 18:31:07 +00002476Address CGOpenMPRuntime::getAddrOfDeclareTargetLink(const VarDecl *VD) {
2477 if (CGM.getLangOpts().OpenMPSimd)
2478 return Address::invalid();
Alexey Bataev92327c52018-03-26 16:40:55 +00002479 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002480 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00002481 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2482 SmallString<64> PtrName;
2483 {
2484 llvm::raw_svector_ostream OS(PtrName);
2485 OS << CGM.getMangledName(GlobalDecl(VD)) << "_decl_tgt_link_ptr";
2486 }
2487 llvm::Value *Ptr = CGM.getModule().getNamedValue(PtrName);
2488 if (!Ptr) {
2489 QualType PtrTy = CGM.getContext().getPointerType(VD->getType());
2490 Ptr = getOrCreateInternalVariable(CGM.getTypes().ConvertTypeForMem(PtrTy),
2491 PtrName);
Alexey Bataev03f270c2018-03-30 18:31:07 +00002492 if (!CGM.getLangOpts().OpenMPIsDevice) {
2493 auto *GV = cast<llvm::GlobalVariable>(Ptr);
2494 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
2495 GV->setInitializer(CGM.GetAddrOfGlobal(VD));
2496 }
2497 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ptr));
2498 registerTargetGlobalVariable(VD, cast<llvm::Constant>(Ptr));
Alexey Bataev92327c52018-03-26 16:40:55 +00002499 }
2500 return Address(Ptr, CGM.getContext().getDeclAlign(VD));
2501 }
2502 return Address::invalid();
2503}
2504
Alexey Bataev97720002014-11-11 04:05:39 +00002505llvm::Constant *
2506CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002507 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2508 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002509 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev18fa2322018-05-02 14:20:50 +00002510 std::string Suffix = getName({"cache", ""});
2511 return getOrCreateInternalVariable(
2512 CGM.Int8PtrPtrTy, Twine(CGM.getMangledName(VD)).concat(Suffix));
Alexey Bataev97720002014-11-11 04:05:39 +00002513}
2514
John McCall7f416cc2015-09-08 08:05:57 +00002515Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2516 const VarDecl *VD,
2517 Address VDAddr,
2518 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002519 if (CGM.getLangOpts().OpenMPUseTLS &&
2520 CGM.getContext().getTargetInfo().isTLSSupported())
2521 return VDAddr;
2522
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002523 llvm::Type *VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002524 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002525 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2526 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002527 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2528 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002529 return Address(CGF.EmitRuntimeCall(
2530 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2531 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002532}
2533
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002534void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002535 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002536 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2537 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2538 // library.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002539 llvm::Value *OMPLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002540 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002541 OMPLoc);
2542 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2543 // to register constructor/destructor for variable.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002544 llvm::Value *Args[] = {
2545 OMPLoc, CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.VoidPtrTy),
2546 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002547 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002548 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002549}
2550
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002551llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002552 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002553 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002554 if (CGM.getLangOpts().OpenMPUseTLS &&
2555 CGM.getContext().getTargetInfo().isTLSSupported())
2556 return nullptr;
2557
Alexey Bataev97720002014-11-11 04:05:39 +00002558 VD = VD->getDefinition(CGM.getContext());
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00002559 if (VD && ThreadPrivateWithDefinition.insert(CGM.getMangledName(VD)).second) {
Alexey Bataev97720002014-11-11 04:05:39 +00002560 QualType ASTTy = VD->getType();
2561
2562 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002563 const Expr *Init = VD->getAnyInitializer();
Alexey Bataev97720002014-11-11 04:05:39 +00002564 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2565 // Generate function that re-emits the declaration's initializer into the
2566 // threadprivate copy of the variable VD
2567 CodeGenFunction CtorCGF(CGM);
2568 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002569 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2570 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002571 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002572 Args.push_back(&Dst);
2573
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002574 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
John McCallc56a8b32016-03-11 04:30:31 +00002575 CGM.getContext().VoidPtrTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002576 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002577 std::string Name = getName({"__kmpc_global_ctor_", ""});
2578 llvm::Function *Fn =
2579 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002580 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002581 Args, Loc, Loc);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002582 llvm::Value *ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002583 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002584 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002585 Address Arg = Address(ArgVal, VDAddr.getAlignment());
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002586 Arg = CtorCGF.Builder.CreateElementBitCast(
2587 Arg, CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002588 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2589 /*IsInitializer=*/true);
2590 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002591 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002592 CGM.getContext().VoidPtrTy, Dst.getLocation());
2593 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2594 CtorCGF.FinishFunction();
2595 Ctor = Fn;
2596 }
2597 if (VD->getType().isDestructedType() != QualType::DK_none) {
2598 // Generate function that emits destructor call for the threadprivate copy
2599 // of the variable VD
2600 CodeGenFunction DtorCGF(CGM);
2601 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002602 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
2603 /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
Alexey Bataev56223232017-06-09 13:40:18 +00002604 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002605 Args.push_back(&Dst);
2606
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002607 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
John McCallc56a8b32016-03-11 04:30:31 +00002608 CGM.getContext().VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002609 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002610 std::string Name = getName({"__kmpc_global_dtor_", ""});
2611 llvm::Function *Fn =
2612 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002613 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002614 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002615 Loc, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002616 // Create a scope with an artificial location for the body of this function.
2617 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002618 llvm::Value *ArgVal = DtorCGF.EmitLoadOfScalar(
Alexey Bataev97720002014-11-11 04:05:39 +00002619 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002620 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2621 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002622 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2623 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2624 DtorCGF.FinishFunction();
2625 Dtor = Fn;
2626 }
2627 // Do not emit init function if it is not required.
2628 if (!Ctor && !Dtor)
2629 return nullptr;
2630
2631 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002632 auto *CopyCtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2633 /*isVarArg=*/false)
2634 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002635 // Copying constructor for the threadprivate variable.
2636 // Must be NULL - reserved by runtime, but currently it requires that this
2637 // parameter is always NULL. Otherwise it fires assertion.
2638 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2639 if (Ctor == nullptr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002640 auto *CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2641 /*isVarArg=*/false)
2642 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002643 Ctor = llvm::Constant::getNullValue(CtorTy);
2644 }
2645 if (Dtor == nullptr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002646 auto *DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2647 /*isVarArg=*/false)
2648 ->getPointerTo();
Alexey Bataev97720002014-11-11 04:05:39 +00002649 Dtor = llvm::Constant::getNullValue(DtorTy);
2650 }
2651 if (!CGF) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002652 auto *InitFunctionTy =
Alexey Bataev97720002014-11-11 04:05:39 +00002653 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002654 std::string Name = getName({"__omp_threadprivate_init_", ""});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002655 llvm::Function *InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Alexey Bataev18fa2322018-05-02 14:20:50 +00002656 InitFunctionTy, Name, CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002657 CodeGenFunction InitCGF(CGM);
2658 FunctionArgList ArgList;
2659 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2660 CGM.getTypes().arrangeNullaryFunction(), ArgList,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00002661 Loc, Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002662 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002663 InitCGF.FinishFunction();
2664 return InitFunction;
2665 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002666 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002667 }
2668 return nullptr;
2669}
2670
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002671/// Obtain information that uniquely identifies a target entry. This
Alexey Bataev34f8a702018-03-28 14:28:54 +00002672/// consists of the file and device IDs as well as line number associated with
2673/// the relevant entry source location.
2674static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
2675 unsigned &DeviceID, unsigned &FileID,
2676 unsigned &LineNum) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002677 SourceManager &SM = C.getSourceManager();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002678
2679 // The loc should be always valid and have a file ID (the user cannot use
2680 // #pragma directives in macros)
2681
2682 assert(Loc.isValid() && "Source location is expected to be always valid.");
Alexey Bataev34f8a702018-03-28 14:28:54 +00002683
2684 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
2685 assert(PLoc.isValid() && "Source location is expected to be always valid.");
2686
2687 llvm::sys::fs::UniqueID ID;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00002688 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
2689 SM.getDiagnostics().Report(diag::err_cannot_open_file)
2690 << PLoc.getFilename() << EC.message();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002691
2692 DeviceID = ID.getDevice();
2693 FileID = ID.getFile();
2694 LineNum = PLoc.getLine();
2695}
2696
2697bool CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD,
2698 llvm::GlobalVariable *Addr,
2699 bool PerformInit) {
2700 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002701 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002702 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link)
Alexey Bataevd01b7492018-08-15 19:45:12 +00002703 return CGM.getLangOpts().OpenMPIsDevice;
Alexey Bataev34f8a702018-03-28 14:28:54 +00002704 VD = VD->getDefinition(CGM.getContext());
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00002705 if (VD && !DeclareTargetWithDefinition.insert(CGM.getMangledName(VD)).second)
Alexey Bataev34f8a702018-03-28 14:28:54 +00002706 return CGM.getLangOpts().OpenMPIsDevice;
2707
2708 QualType ASTTy = VD->getType();
2709
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002710 SourceLocation Loc = VD->getCanonicalDecl()->getBeginLoc();
Alexey Bataev34f8a702018-03-28 14:28:54 +00002711 // Produce the unique prefix to identify the new target regions. We use
2712 // the source location of the variable declaration which we know to not
2713 // conflict with any target region.
2714 unsigned DeviceID;
2715 unsigned FileID;
2716 unsigned Line;
2717 getTargetEntryUniqueInfo(CGM.getContext(), Loc, DeviceID, FileID, Line);
2718 SmallString<128> Buffer, Out;
2719 {
2720 llvm::raw_svector_ostream OS(Buffer);
2721 OS << "__omp_offloading_" << llvm::format("_%x", DeviceID)
2722 << llvm::format("_%x_", FileID) << VD->getName() << "_l" << Line;
2723 }
2724
2725 const Expr *Init = VD->getAnyInitializer();
2726 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2727 llvm::Constant *Ctor;
2728 llvm::Constant *ID;
2729 if (CGM.getLangOpts().OpenMPIsDevice) {
2730 // Generate function that re-emits the declaration's initializer into
2731 // the threadprivate copy of the variable VD
2732 CodeGenFunction CtorCGF(CGM);
2733
2734 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2735 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2736 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2737 FTy, Twine(Buffer, "_ctor"), FI, Loc);
2738 auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF);
2739 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2740 FunctionArgList(), Loc, Loc);
2741 auto AL = ApplyDebugLocation::CreateArtificial(CtorCGF);
2742 CtorCGF.EmitAnyExprToMem(Init,
2743 Address(Addr, CGM.getContext().getDeclAlign(VD)),
2744 Init->getType().getQualifiers(),
2745 /*IsInitializer=*/true);
2746 CtorCGF.FinishFunction();
2747 Ctor = Fn;
2748 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
Alexey Bataeve253f2f2018-05-09 14:15:18 +00002749 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ctor));
Alexey Bataev34f8a702018-03-28 14:28:54 +00002750 } else {
2751 Ctor = new llvm::GlobalVariable(
2752 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2753 llvm::GlobalValue::PrivateLinkage,
2754 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_ctor"));
2755 ID = Ctor;
2756 }
2757
2758 // Register the information for the entry associated with the constructor.
2759 Out.clear();
2760 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2761 DeviceID, FileID, Twine(Buffer, "_ctor").toStringRef(Out), Line, Ctor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002762 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryCtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002763 }
2764 if (VD->getType().isDestructedType() != QualType::DK_none) {
2765 llvm::Constant *Dtor;
2766 llvm::Constant *ID;
2767 if (CGM.getLangOpts().OpenMPIsDevice) {
2768 // Generate function that emits destructor call for the threadprivate
2769 // copy of the variable VD
2770 CodeGenFunction DtorCGF(CGM);
2771
2772 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
2773 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
2774 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction(
2775 FTy, Twine(Buffer, "_dtor"), FI, Loc);
2776 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
2777 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
2778 FunctionArgList(), Loc, Loc);
2779 // Create a scope with an artificial location for the body of this
2780 // function.
2781 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
2782 DtorCGF.emitDestroy(Address(Addr, CGM.getContext().getDeclAlign(VD)),
2783 ASTTy, DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2784 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2785 DtorCGF.FinishFunction();
2786 Dtor = Fn;
2787 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
Alexey Bataeve253f2f2018-05-09 14:15:18 +00002788 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Dtor));
Alexey Bataev34f8a702018-03-28 14:28:54 +00002789 } else {
2790 Dtor = new llvm::GlobalVariable(
2791 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
2792 llvm::GlobalValue::PrivateLinkage,
2793 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_dtor"));
2794 ID = Dtor;
2795 }
2796 // Register the information for the entry associated with the destructor.
2797 Out.clear();
2798 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
2799 DeviceID, FileID, Twine(Buffer, "_dtor").toStringRef(Out), Line, Dtor,
Alexey Bataev03f270c2018-03-30 18:31:07 +00002800 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryDtor);
Alexey Bataev34f8a702018-03-28 14:28:54 +00002801 }
2802 return CGM.getLangOpts().OpenMPIsDevice;
2803}
2804
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002805Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2806 QualType VarType,
2807 StringRef Name) {
Alexey Bataev18fa2322018-05-02 14:20:50 +00002808 std::string Suffix = getName({"artificial", ""});
2809 std::string CacheSuffix = getName({"cache", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002810 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
Alexey Bataev18fa2322018-05-02 14:20:50 +00002811 llvm::Value *GAddr =
2812 getOrCreateInternalVariable(VarLVType, Twine(Name).concat(Suffix));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002813 llvm::Value *Args[] = {
2814 emitUpdateLocation(CGF, SourceLocation()),
2815 getThreadID(CGF, SourceLocation()),
2816 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2817 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2818 /*IsSigned=*/false),
Alexey Bataev18fa2322018-05-02 14:20:50 +00002819 getOrCreateInternalVariable(
2820 CGM.VoidPtrPtrTy, Twine(Name).concat(Suffix).concat(CacheSuffix))};
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002821 return Address(
2822 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2823 CGF.EmitRuntimeCall(
2824 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2825 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2826 CGM.getPointerAlign());
2827}
2828
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002829void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2830 const RegionCodeGenTy &ThenGen,
2831 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002832 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2833
2834 // If the condition constant folds and can be elided, try to avoid emitting
2835 // the condition and the dead arm of the if/else.
2836 bool CondConstant;
2837 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002838 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002839 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002840 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002841 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002842 return;
2843 }
2844
2845 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2846 // emit the conditional branch.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002847 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("omp_if.then");
2848 llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else");
2849 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("omp_if.end");
Alexey Bataev1d677132015-04-22 13:57:31 +00002850 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2851
2852 // Emit the 'then' code.
2853 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002854 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002855 CGF.EmitBranch(ContBlock);
2856 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002857 // There is no need to emit line number for unconditional branch.
2858 (void)ApplyDebugLocation::CreateEmpty(CGF);
2859 CGF.EmitBlock(ElseBlock);
2860 ElseGen(CGF);
2861 // There is no need to emit line number for unconditional branch.
2862 (void)ApplyDebugLocation::CreateEmpty(CGF);
2863 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002864 // Emit the continuation block for code after the if.
2865 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002866}
2867
Alexey Bataev1d677132015-04-22 13:57:31 +00002868void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2869 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002870 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002871 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002872 if (!CGF.HaveInsertPoint())
2873 return;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002874 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002875 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2876 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002877 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002878 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002879 llvm::Value *Args[] = {
2880 RTLoc,
2881 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002882 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002883 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2884 RealArgs.append(std::begin(Args), std::end(Args));
2885 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2886
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002887 llvm::Value *RTLFn = 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 Bataev97720002014-11-11 04:05:39 +00002948llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002949CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002950 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002951 SmallString<256> Buffer;
2952 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002953 Out << Name;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00002954 StringRef RuntimeName = Out.str();
Alexey Bataev43a919f2018-04-13 17:48:43 +00002955 auto &Elem = *InternalVars.try_emplace(RuntimeName, nullptr).first;
David Blaikie13156b62014-11-19 03:06:06 +00002956 if (Elem.second) {
2957 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002958 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002959 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002960 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002961
David Blaikie13156b62014-11-19 03:06:06 +00002962 return Elem.second = new llvm::GlobalVariable(
2963 CGM.getModule(), Ty, /*IsConstant*/ false,
2964 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2965 Elem.first());
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 {
2977 llvm::Value *EnterCallee;
2978 ArrayRef<llvm::Value *> EnterArgs;
2979 llvm::Value *ExitCallee;
2980 ArrayRef<llvm::Value *> ExitArgs;
2981 bool Conditional;
2982 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002983
2984public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002985 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2986 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2987 bool Conditional = false)
2988 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2989 ExitArgs(ExitArgs), Conditional(Conditional) {}
2990 void Enter(CodeGenFunction &CGF) override {
2991 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2992 if (Conditional) {
2993 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2994 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2995 ContBlock = CGF.createBasicBlock("omp_if.end");
2996 // Generate the branch (If-stmt)
2997 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2998 CGF.EmitBlock(ThenBlock);
2999 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00003000 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003001 void Done(CodeGenFunction &CGF) {
3002 // Emit the rest of blocks/branches
3003 CGF.EmitBranch(ContBlock);
3004 CGF.EmitBlock(ContBlock, true);
3005 }
3006 void Exit(CodeGenFunction &CGF) override {
3007 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00003008 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003009};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003010} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003011
3012void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
3013 StringRef CriticalName,
3014 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00003015 SourceLocation Loc, const Expr *Hint) {
3016 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00003017 // CriticalOpGen();
3018 // __kmpc_end_critical(ident_t *, gtid, Lock);
3019 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00003020 if (!CGF.HaveInsertPoint())
3021 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00003022 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3023 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003024 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
3025 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00003026 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003027 EnterArgs.push_back(CGF.Builder.CreateIntCast(
3028 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
3029 }
3030 CommonActionTy Action(
3031 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
3032 : OMPRTL__kmpc_critical),
3033 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
3034 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00003035 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00003036}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00003037
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003038void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00003039 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003040 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003041 if (!CGF.HaveInsertPoint())
3042 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00003043 // if(__kmpc_master(ident_t *, gtid)) {
3044 // MasterOpGen();
3045 // __kmpc_end_master(ident_t *, gtid);
3046 // }
3047 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00003048 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003049 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
3050 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
3051 /*Conditional=*/true);
3052 MasterOpGen.setAction(Action);
3053 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
3054 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00003055}
3056
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003057void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
3058 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003059 if (!CGF.HaveInsertPoint())
3060 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00003061 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
3062 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003063 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00003064 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003065 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003066 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
3067 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00003068}
3069
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003070void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
3071 const RegionCodeGenTy &TaskgroupOpGen,
3072 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003073 if (!CGF.HaveInsertPoint())
3074 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003075 // __kmpc_taskgroup(ident_t *, gtid);
3076 // TaskgroupOpGen();
3077 // __kmpc_end_taskgroup(ident_t *, gtid);
3078 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003079 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
3080 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
3081 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
3082 Args);
3083 TaskgroupOpGen.setAction(Action);
3084 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003085}
3086
John McCall7f416cc2015-09-08 08:05:57 +00003087/// Given an array of pointers to variables, project the address of a
3088/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003089static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
3090 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00003091 // Pull out the pointer to the variable.
3092 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003093 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
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) {
John McCall7f416cc2015-09-08 08:05:57 +00003209 Address Elem = CGF.Builder.CreateConstArrayGEP(
3210 CopyprivateList, I, CGF.getPointerSize());
3211 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00003212 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003213 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
3214 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003215 }
3216 // Build function that copies private values from single region to all other
3217 // threads in the corresponding parallel region.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003218 llvm::Value *CpyFn = emitCopyprivateCopyFunction(
Alexey Bataeva63048e2015-03-23 06:18:07 +00003219 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev7cae94e2018-01-04 19:45:16 +00003220 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps, Loc);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003221 llvm::Value *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00003222 Address CL =
3223 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
3224 CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003225 llvm::Value *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00003226 llvm::Value *Args[] = {
3227 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
3228 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00003229 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00003230 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00003231 CpyFn, // void (*) (void *, void *) <copy_func>
3232 DidItVal // i32 did_it
3233 };
3234 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
3235 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00003236}
3237
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003238void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
3239 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00003240 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003241 if (!CGF.HaveInsertPoint())
3242 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003243 // __kmpc_ordered(ident_t *, gtid);
3244 // OrderedOpGen();
3245 // __kmpc_end_ordered(ident_t *, gtid);
3246 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00003247 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003248 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003249 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
3250 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
3251 Args);
3252 OrderedOpGen.setAction(Action);
3253 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
3254 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003255 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00003256 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003257}
3258
Alexey Bataevc3028ca2018-12-04 15:03:25 +00003259unsigned CGOpenMPRuntime::getDefaultFlagsForBarriers(OpenMPDirectiveKind Kind) {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003260 unsigned Flags;
3261 if (Kind == OMPD_for)
3262 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
3263 else if (Kind == OMPD_sections)
3264 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
3265 else if (Kind == OMPD_single)
3266 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
3267 else if (Kind == OMPD_barrier)
3268 Flags = OMP_IDENT_BARRIER_EXPL;
3269 else
3270 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataevc3028ca2018-12-04 15:03:25 +00003271 return Flags;
3272}
3273
3274void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
3275 OpenMPDirectiveKind Kind, bool EmitChecks,
3276 bool ForceSimpleCall) {
3277 if (!CGF.HaveInsertPoint())
3278 return;
3279 // Build call __kmpc_cancel_barrier(loc, thread_id);
3280 // Build call __kmpc_barrier(loc, thread_id);
3281 unsigned Flags = getDefaultFlagsForBarriers(Kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003282 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
3283 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003284 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
3285 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00003286 if (auto *OMPRegionInfo =
3287 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00003288 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003289 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003290 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00003291 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003292 // if (__kmpc_cancel_barrier()) {
3293 // exit from construct;
3294 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003295 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
3296 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
3297 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003298 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
3299 CGF.EmitBlock(ExitBB);
3300 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003301 CodeGenFunction::JumpDest CancelDestination =
Alexey Bataev25e5b442015-09-15 12:52:43 +00003302 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00003303 CGF.EmitBranchThroughCleanup(CancelDestination);
3304 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
3305 }
3306 return;
3307 }
3308 }
3309 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00003310}
3311
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003312/// Map the OpenMP loop schedule to the runtime enumeration.
Alexander Musmanc6388682014-12-15 07:07:06 +00003313static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003314 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00003315 switch (ScheduleKind) {
3316 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003317 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
3318 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00003319 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003320 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003321 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003322 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00003323 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003324 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
3325 case OMPC_SCHEDULE_auto:
3326 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00003327 case OMPC_SCHEDULE_unknown:
3328 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003329 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00003330 }
3331 llvm_unreachable("Unexpected runtime schedule");
3332}
3333
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003334/// Map the OpenMP distribute schedule to the runtime enumeration.
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003335static OpenMPSchedType
3336getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
3337 // only static is allowed for dist_schedule
3338 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
3339}
3340
Alexander Musmanc6388682014-12-15 07:07:06 +00003341bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
3342 bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003343 OpenMPSchedType Schedule =
3344 getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00003345 return Schedule == OMP_sch_static;
3346}
3347
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003348bool CGOpenMPRuntime::isStaticNonchunked(
3349 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003350 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003351 return Schedule == OMP_dist_sch_static;
3352}
3353
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00003354bool CGOpenMPRuntime::isStaticChunked(OpenMPScheduleClauseKind ScheduleKind,
3355 bool Chunked) const {
3356 OpenMPSchedType Schedule =
3357 getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
3358 return Schedule == OMP_sch_static_chunked;
3359}
3360
3361bool CGOpenMPRuntime::isStaticChunked(
3362 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
3363 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
3364 return Schedule == OMP_dist_sch_static_chunked;
3365}
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003366
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003367bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003368 OpenMPSchedType Schedule =
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003369 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00003370 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
3371 return Schedule != OMP_sch_static;
3372}
3373
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003374static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
3375 OpenMPScheduleClauseModifier M1,
3376 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00003377 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003378 switch (M1) {
3379 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003380 Modifier = OMP_sch_modifier_monotonic;
3381 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003382 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003383 Modifier = OMP_sch_modifier_nonmonotonic;
3384 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003385 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003386 if (Schedule == OMP_sch_static_chunked)
3387 Schedule = OMP_sch_static_balanced_chunked;
3388 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003389 case OMPC_SCHEDULE_MODIFIER_last:
3390 case OMPC_SCHEDULE_MODIFIER_unknown:
3391 break;
3392 }
3393 switch (M2) {
3394 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003395 Modifier = OMP_sch_modifier_monotonic;
3396 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003397 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003398 Modifier = OMP_sch_modifier_nonmonotonic;
3399 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003400 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00003401 if (Schedule == OMP_sch_static_chunked)
3402 Schedule = OMP_sch_static_balanced_chunked;
3403 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003404 case OMPC_SCHEDULE_MODIFIER_last:
3405 case OMPC_SCHEDULE_MODIFIER_unknown:
3406 break;
3407 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00003408 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003409}
3410
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003411void CGOpenMPRuntime::emitForDispatchInit(
3412 CodeGenFunction &CGF, SourceLocation Loc,
3413 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
3414 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003415 if (!CGF.HaveInsertPoint())
3416 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003417 OpenMPSchedType Schedule = getRuntimeSchedule(
3418 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00003419 assert(Ordered ||
3420 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00003421 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
3422 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00003423 // Call __kmpc_dispatch_init(
3424 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
3425 // kmp_int[32|64] lower, kmp_int[32|64] upper,
3426 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00003427
John McCall7f416cc2015-09-08 08:05:57 +00003428 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003429 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
3430 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00003431 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003432 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3433 CGF.Builder.getInt32(addMonoNonMonoModifier(
3434 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00003435 DispatchValues.LB, // Lower
3436 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003437 CGF.Builder.getIntN(IVSize, 1), // Stride
3438 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00003439 };
3440 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
3441}
3442
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003443static void emitForStaticInitCall(
3444 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
3445 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
3446 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003447 const CGOpenMPRuntime::StaticRTInput &Values) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003448 if (!CGF.HaveInsertPoint())
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003449 return;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003450
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003451 assert(!Values.Ordered);
3452 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
3453 Schedule == OMP_sch_static_balanced_chunked ||
3454 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
3455 Schedule == OMP_dist_sch_static ||
3456 Schedule == OMP_dist_sch_static_chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003457
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003458 // Call __kmpc_for_static_init(
3459 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
3460 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
3461 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
3462 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
3463 llvm::Value *Chunk = Values.Chunk;
3464 if (Chunk == nullptr) {
3465 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
3466 Schedule == OMP_dist_sch_static) &&
3467 "expected static non-chunked schedule");
3468 // If the Chunk was not specified in the clause - use default value 1.
3469 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
3470 } else {
3471 assert((Schedule == OMP_sch_static_chunked ||
3472 Schedule == OMP_sch_static_balanced_chunked ||
3473 Schedule == OMP_ord_static_chunked ||
3474 Schedule == OMP_dist_sch_static_chunked) &&
3475 "expected static chunked schedule");
3476 }
3477 llvm::Value *Args[] = {
3478 UpdateLocation,
3479 ThreadId,
3480 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3481 M2)), // Schedule type
3482 Values.IL.getPointer(), // &isLastIter
3483 Values.LB.getPointer(), // &LB
3484 Values.UB.getPointer(), // &UB
3485 Values.ST.getPointer(), // &Stride
3486 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3487 Chunk // Chunk
3488 };
3489 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003490}
3491
John McCall7f416cc2015-09-08 08:05:57 +00003492void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3493 SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003494 OpenMPDirectiveKind DKind,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003495 const OpenMPScheduleTy &ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003496 const StaticRTInput &Values) {
3497 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3498 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3499 assert(isOpenMPWorksharingDirective(DKind) &&
3500 "Expected loop-based or sections-based directive.");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003501 llvm::Value *UpdatedLocation = emitUpdateLocation(CGF, Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003502 isOpenMPLoopDirective(DKind)
3503 ? OMP_IDENT_WORK_LOOP
3504 : OMP_IDENT_WORK_SECTIONS);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003505 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3506 llvm::Constant *StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003507 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003508 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003509 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003510}
John McCall7f416cc2015-09-08 08:05:57 +00003511
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003512void CGOpenMPRuntime::emitDistributeStaticInit(
3513 CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003514 OpenMPDistScheduleClauseKind SchedKind,
3515 const CGOpenMPRuntime::StaticRTInput &Values) {
3516 OpenMPSchedType ScheduleNum =
3517 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003518 llvm::Value *UpdatedLocation =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003519 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003520 llvm::Value *ThreadId = getThreadID(CGF, Loc);
3521 llvm::Constant *StaticInitFunction =
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003522 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003523 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3524 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003525 OMPC_SCHEDULE_MODIFIER_unknown, Values);
Alexander Musmanc6388682014-12-15 07:07:06 +00003526}
3527
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003528void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
Alexey Bataevf43f7142017-09-06 16:17:35 +00003529 SourceLocation Loc,
3530 OpenMPDirectiveKind DKind) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003531 if (!CGF.HaveInsertPoint())
3532 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003533 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataevf43f7142017-09-06 16:17:35 +00003534 llvm::Value *Args[] = {
3535 emitUpdateLocation(CGF, Loc,
3536 isOpenMPDistributeDirective(DKind)
3537 ? OMP_IDENT_WORK_DISTRIBUTE
3538 : isOpenMPLoopDirective(DKind)
3539 ? OMP_IDENT_WORK_LOOP
3540 : OMP_IDENT_WORK_SECTIONS),
3541 getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003542 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3543 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003544}
3545
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003546void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3547 SourceLocation Loc,
3548 unsigned IVSize,
3549 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003550 if (!CGF.HaveInsertPoint())
3551 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003552 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003553 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003554 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3555}
3556
Alexander Musman92bdaab2015-03-12 13:37:50 +00003557llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3558 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003559 bool IVSigned, Address IL,
3560 Address LB, Address UB,
3561 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003562 // Call __kmpc_dispatch_next(
3563 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3564 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3565 // kmp_int[32|64] *p_stride);
3566 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003567 emitUpdateLocation(CGF, Loc),
3568 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003569 IL.getPointer(), // &isLastIter
3570 LB.getPointer(), // &Lower
3571 UB.getPointer(), // &Upper
3572 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003573 };
3574 llvm::Value *Call =
3575 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3576 return CGF.EmitScalarConversion(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003577 Call, CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/1),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003578 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003579}
3580
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003581void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3582 llvm::Value *NumThreads,
3583 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003584 if (!CGF.HaveInsertPoint())
3585 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003586 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3587 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003588 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003589 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003590 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3591 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003592}
3593
Alexey Bataev7f210c62015-06-18 13:40:03 +00003594void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3595 OpenMPProcBindClauseKind ProcBind,
3596 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003597 if (!CGF.HaveInsertPoint())
3598 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003599 // Constants for proc bind value accepted by the runtime.
3600 enum ProcBindTy {
3601 ProcBindFalse = 0,
3602 ProcBindTrue,
3603 ProcBindMaster,
3604 ProcBindClose,
3605 ProcBindSpread,
3606 ProcBindIntel,
3607 ProcBindDefault
3608 } RuntimeProcBind;
3609 switch (ProcBind) {
3610 case OMPC_PROC_BIND_master:
3611 RuntimeProcBind = ProcBindMaster;
3612 break;
3613 case OMPC_PROC_BIND_close:
3614 RuntimeProcBind = ProcBindClose;
3615 break;
3616 case OMPC_PROC_BIND_spread:
3617 RuntimeProcBind = ProcBindSpread;
3618 break;
3619 case OMPC_PROC_BIND_unknown:
3620 llvm_unreachable("Unsupported proc_bind value.");
3621 }
3622 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3623 llvm::Value *Args[] = {
3624 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3625 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3626 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3627}
3628
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003629void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3630 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003631 if (!CGF.HaveInsertPoint())
3632 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003633 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003634 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3635 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003636}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003637
Alexey Bataev62b63b12015-03-10 07:28:44 +00003638namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003639/// Indexes of fields for type kmp_task_t.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003640enum KmpTaskTFields {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003641 /// List of shared variables.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003642 KmpTaskTShareds,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003643 /// Task routine.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003644 KmpTaskTRoutine,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003645 /// Partition id for the untied tasks.
Alexey Bataev62b63b12015-03-10 07:28:44 +00003646 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003647 /// Function with call of destructors for private variables.
3648 Data1,
3649 /// Task priority.
3650 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003651 /// (Taskloops only) Lower bound.
3652 KmpTaskTLowerBound,
3653 /// (Taskloops only) Upper bound.
3654 KmpTaskTUpperBound,
3655 /// (Taskloops only) Stride.
3656 KmpTaskTStride,
3657 /// (Taskloops only) Is last iteration flag.
3658 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003659 /// (Taskloops only) Reduction data.
3660 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003661};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003662} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003663
Samuel Antaoee8fb302016-01-06 13:42:12 +00003664bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003665 return OffloadEntriesTargetRegion.empty() &&
3666 OffloadEntriesDeviceGlobalVar.empty();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003667}
3668
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003669/// Initialize target region entry.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003670void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3671 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3672 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003673 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003674 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3675 "only required for the device "
3676 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003677 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003678 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003679 OMPTargetRegionEntryTargetRegion);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003680 ++OffloadingEntriesNum;
3681}
3682
3683void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3684 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3685 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003686 llvm::Constant *Addr, llvm::Constant *ID,
Alexey Bataev34f8a702018-03-28 14:28:54 +00003687 OMPTargetRegionEntryKind Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003688 // If we are emitting code for a target, the entry is already initialized,
3689 // only has to be registered.
3690 if (CGM.getLangOpts().OpenMPIsDevice) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00003691 if (!hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum)) {
3692 unsigned DiagID = CGM.getDiags().getCustomDiagID(
3693 DiagnosticsEngine::Error,
3694 "Unable to find target region on line '%0' in the device code.");
3695 CGM.getDiags().Report(DiagID) << LineNum;
3696 return;
3697 }
Samuel Antao2de62b02016-02-13 23:35:10 +00003698 auto &Entry =
3699 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003700 assert(Entry.isValid() && "Entry not initialized!");
3701 Entry.setAddress(Addr);
3702 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003703 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003704 } else {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003705 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003706 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00003707 ++OffloadingEntriesNum;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003708 }
3709}
3710
3711bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003712 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3713 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003714 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3715 if (PerDevice == OffloadEntriesTargetRegion.end())
3716 return false;
3717 auto PerFile = PerDevice->second.find(FileID);
3718 if (PerFile == PerDevice->second.end())
3719 return false;
3720 auto PerParentName = PerFile->second.find(ParentName);
3721 if (PerParentName == PerFile->second.end())
3722 return false;
3723 auto PerLine = PerParentName->second.find(LineNum);
3724 if (PerLine == PerParentName->second.end())
3725 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003726 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003727 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003728 return false;
3729 return true;
3730}
3731
3732void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3733 const OffloadTargetRegionEntryInfoActTy &Action) {
3734 // Scan all target region entries and perform the provided action.
Alexey Bataev03f270c2018-03-30 18:31:07 +00003735 for (const auto &D : OffloadEntriesTargetRegion)
3736 for (const auto &F : D.second)
3737 for (const auto &P : F.second)
3738 for (const auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003739 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003740}
3741
Alexey Bataev03f270c2018-03-30 18:31:07 +00003742void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3743 initializeDeviceGlobalVarEntryInfo(StringRef Name,
3744 OMPTargetGlobalVarEntryKind Flags,
3745 unsigned Order) {
3746 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3747 "only required for the device "
3748 "code generation.");
3749 OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags);
3750 ++OffloadingEntriesNum;
3751}
Samuel Antaoee8fb302016-01-06 13:42:12 +00003752
Alexey Bataev03f270c2018-03-30 18:31:07 +00003753void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3754 registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr,
3755 CharUnits VarSize,
3756 OMPTargetGlobalVarEntryKind Flags,
3757 llvm::GlobalValue::LinkageTypes Linkage) {
3758 if (CGM.getLangOpts().OpenMPIsDevice) {
3759 auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
3760 assert(Entry.isValid() && Entry.getFlags() == Flags &&
3761 "Entry not initialized!");
3762 assert((!Entry.getAddress() || Entry.getAddress() == Addr) &&
3763 "Resetting with the new address.");
3764 if (Entry.getAddress() && hasDeviceGlobalVarEntryInfo(VarName))
3765 return;
3766 Entry.setAddress(Addr);
3767 Entry.setVarSize(VarSize);
3768 Entry.setLinkage(Linkage);
3769 } else {
3770 if (hasDeviceGlobalVarEntryInfo(VarName))
3771 return;
3772 OffloadEntriesDeviceGlobalVar.try_emplace(
3773 VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage);
3774 ++OffloadingEntriesNum;
3775 }
3776}
3777
3778void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3779 actOnDeviceGlobalVarEntriesInfo(
3780 const OffloadDeviceGlobalVarEntryInfoActTy &Action) {
3781 // Scan all target region entries and perform the provided action.
3782 for (const auto &E : OffloadEntriesDeviceGlobalVar)
3783 Action(E.getKey(), E.getValue());
Samuel Antaoee8fb302016-01-06 13:42:12 +00003784}
3785
3786llvm::Function *
3787CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003788 // If we don't have entries or if we are emitting code for the device, we
3789 // don't need to do anything.
3790 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3791 return nullptr;
3792
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003793 llvm::Module &M = CGM.getModule();
3794 ASTContext &C = CGM.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003795
3796 // Get list of devices we care about
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003797 const std::vector<llvm::Triple> &Devices = CGM.getLangOpts().OMPTargetTriples;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003798
3799 // We should be creating an offloading descriptor only if there are devices
3800 // specified.
3801 assert(!Devices.empty() && "No OpenMP offloading devices??");
3802
3803 // Create the external variables that will point to the begin and end of the
3804 // host entries section. These will be defined by the linker.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003805 llvm::Type *OffloadEntryTy =
Samuel Antaoee8fb302016-01-06 13:42:12 +00003806 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
Alexey Bataev18fa2322018-05-02 14:20:50 +00003807 std::string EntriesBeginName = getName({"omp_offloading", "entries_begin"});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003808 auto *HostEntriesBegin = new llvm::GlobalVariable(
Samuel Antaoee8fb302016-01-06 13:42:12 +00003809 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003810 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003811 EntriesBeginName);
3812 std::string EntriesEndName = getName({"omp_offloading", "entries_end"});
3813 auto *HostEntriesEnd =
3814 new llvm::GlobalVariable(M, OffloadEntryTy, /*isConstant=*/true,
3815 llvm::GlobalValue::ExternalLinkage,
3816 /*Initializer=*/nullptr, EntriesEndName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003817
3818 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003819 auto *DeviceImageTy = cast<llvm::StructType>(
3820 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003821 ConstantInitBuilder DeviceImagesBuilder(CGM);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003822 ConstantArrayBuilder DeviceImagesEntries =
3823 DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003824
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003825 for (const llvm::Triple &Device : Devices) {
Alexey Bataev03f270c2018-03-30 18:31:07 +00003826 StringRef T = Device.getTriple();
Alexey Bataev18fa2322018-05-02 14:20:50 +00003827 std::string BeginName = getName({"omp_offloading", "img_start", ""});
Samuel Antaoee8fb302016-01-06 13:42:12 +00003828 auto *ImgBegin = new llvm::GlobalVariable(
Alexey Bataev62a4cb02018-07-31 18:27:42 +00003829 M, CGM.Int8Ty, /*isConstant=*/true,
3830 llvm::GlobalValue::ExternalWeakLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003831 /*Initializer=*/nullptr, Twine(BeginName).concat(T));
3832 std::string EndName = getName({"omp_offloading", "img_end", ""});
Samuel Antaoee8fb302016-01-06 13:42:12 +00003833 auto *ImgEnd = new llvm::GlobalVariable(
Alexey Bataev62a4cb02018-07-31 18:27:42 +00003834 M, CGM.Int8Ty, /*isConstant=*/true,
3835 llvm::GlobalValue::ExternalWeakLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00003836 /*Initializer=*/nullptr, Twine(EndName).concat(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003837
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003838 llvm::Constant *Data[] = {ImgBegin, ImgEnd, HostEntriesBegin,
3839 HostEntriesEnd};
3840 createConstantGlobalStructAndAddToParent(CGM, getTgtDeviceImageQTy(), Data,
3841 DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003842 }
3843
3844 // Create device images global array.
Alexey Bataev18fa2322018-05-02 14:20:50 +00003845 std::string ImagesName = getName({"omp_offloading", "device_images"});
John McCall6c9f1fdb2016-11-19 08:17:24 +00003846 llvm::GlobalVariable *DeviceImages =
Alexey Bataev18fa2322018-05-02 14:20:50 +00003847 DeviceImagesEntries.finishAndCreateGlobal(ImagesName,
3848 CGM.getPointerAlign(),
3849 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003850 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003851
3852 // This is a Zero array to be used in the creation of the constant expressions
3853 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3854 llvm::Constant::getNullValue(CGM.Int32Ty)};
3855
3856 // Create the target region descriptor.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003857 llvm::Constant *Data[] = {
3858 llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
3859 llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3860 DeviceImages, Index),
3861 HostEntriesBegin, HostEntriesEnd};
Alexey Bataev18fa2322018-05-02 14:20:50 +00003862 std::string Descriptor = getName({"omp_offloading", "descriptor"});
Mike Ricee1ca7b62018-08-29 15:45:11 +00003863 llvm::GlobalVariable *Desc = createGlobalStruct(
3864 CGM, getTgtBinaryDescriptorQTy(), /*IsConstant=*/true, Data, Descriptor);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003865
3866 // Emit code to register or unregister the descriptor at execution
3867 // startup or closing, respectively.
3868
Alexey Bataev03f270c2018-03-30 18:31:07 +00003869 llvm::Function *UnRegFn;
3870 {
3871 FunctionArgList Args;
3872 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
3873 Args.push_back(&DummyPtr);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003874
Alexey Bataev03f270c2018-03-30 18:31:07 +00003875 CodeGenFunction CGF(CGM);
3876 // Disable debug info for global (de-)initializer because they are not part
3877 // of some particular construct.
3878 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003879 const auto &FI =
3880 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3881 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003882 std::string UnregName = getName({"omp_offloading", "descriptor_unreg"});
3883 UnRegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, UnregName, FI);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003884 CGF.StartFunction(GlobalDecl(), C.VoidTy, UnRegFn, FI, Args);
3885 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3886 Desc);
3887 CGF.FinishFunction();
3888 }
3889 llvm::Function *RegFn;
3890 {
3891 CodeGenFunction CGF(CGM);
3892 // Disable debug info for global (de-)initializer because they are not part
3893 // of some particular construct.
3894 CGF.disableDebugInfo();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003895 const auto &FI = CGM.getTypes().arrangeNullaryFunction();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003896 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Sergey Dmitrievbde9cf92018-08-03 20:19:28 +00003897
3898 // Encode offload target triples into the registration function name. It
3899 // will serve as a comdat key for the registration/unregistration code for
3900 // this particular combination of offloading targets.
3901 SmallVector<StringRef, 4U> RegFnNameParts(Devices.size() + 2U);
3902 RegFnNameParts[0] = "omp_offloading";
3903 RegFnNameParts[1] = "descriptor_reg";
3904 llvm::transform(Devices, std::next(RegFnNameParts.begin(), 2),
3905 [](const llvm::Triple &T) -> const std::string& {
3906 return T.getTriple();
3907 });
3908 llvm::sort(std::next(RegFnNameParts.begin(), 2), RegFnNameParts.end());
3909 std::string Descriptor = getName(RegFnNameParts);
Alexey Bataev18fa2322018-05-02 14:20:50 +00003910 RegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, Descriptor, FI);
Alexey Bataev03f270c2018-03-30 18:31:07 +00003911 CGF.StartFunction(GlobalDecl(), C.VoidTy, RegFn, FI, FunctionArgList());
3912 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib), Desc);
3913 // Create a variable to drive the registration and unregistration of the
3914 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3915 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(),
3916 SourceLocation(), nullptr, C.CharTy,
3917 ImplicitParamDecl::Other);
3918 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3919 CGF.FinishFunction();
3920 }
George Rokos29d0f002017-05-27 03:03:13 +00003921 if (CGM.supportsCOMDAT()) {
3922 // It is sufficient to call registration function only once, so create a
3923 // COMDAT group for registration/unregistration functions and associated
3924 // data. That would reduce startup time and code size. Registration
3925 // function serves as a COMDAT group key.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003926 llvm::Comdat *ComdatKey = M.getOrInsertComdat(RegFn->getName());
George Rokos29d0f002017-05-27 03:03:13 +00003927 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3928 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3929 RegFn->setComdat(ComdatKey);
3930 UnRegFn->setComdat(ComdatKey);
3931 DeviceImages->setComdat(ComdatKey);
3932 Desc->setComdat(ComdatKey);
3933 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003934 return RegFn;
3935}
3936
Alexey Bataev03f270c2018-03-30 18:31:07 +00003937void CGOpenMPRuntime::createOffloadEntry(
3938 llvm::Constant *ID, llvm::Constant *Addr, uint64_t Size, int32_t Flags,
3939 llvm::GlobalValue::LinkageTypes Linkage) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003940 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003941 llvm::Module &M = CGM.getModule();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003942 llvm::LLVMContext &C = M.getContext();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003943
3944 // Create constant string with the name.
3945 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3946
Alexey Bataev18fa2322018-05-02 14:20:50 +00003947 std::string StringName = getName({"omp_offloading", "entry_name"});
3948 auto *Str = new llvm::GlobalVariable(
3949 M, StrPtrInit->getType(), /*isConstant=*/true,
3950 llvm::GlobalValue::InternalLinkage, StrPtrInit, StringName);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003951 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003952
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003953 llvm::Constant *Data[] = {llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy),
3954 llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy),
3955 llvm::ConstantInt::get(CGM.SizeTy, Size),
3956 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
3957 llvm::ConstantInt::get(CGM.Int32Ty, 0)};
Alexey Bataev18fa2322018-05-02 14:20:50 +00003958 std::string EntryName = getName({"omp_offloading", "entry", ""});
Mike Ricee1ca7b62018-08-29 15:45:11 +00003959 llvm::GlobalVariable *Entry = createGlobalStruct(
3960 CGM, getTgtOffloadEntryQTy(), /*IsConstant=*/true, Data,
3961 Twine(EntryName).concat(Name), llvm::GlobalValue::WeakAnyLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003962
3963 // The entry has to be created in the section the linker expects it to be.
Alexey Bataev18fa2322018-05-02 14:20:50 +00003964 std::string Section = getName({"omp_offloading", "entries"});
3965 Entry->setSection(Section);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003966}
3967
3968void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3969 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003970 // can easily figure out what to emit. The produced metadata looks like
3971 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003972 //
3973 // !omp_offload.info = !{!1, ...}
3974 //
3975 // Right now we only generate metadata for function that contain target
3976 // regions.
3977
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003978 // If we do not have entries, we don't need to do anything.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003979 if (OffloadEntriesInfoManager.empty())
3980 return;
3981
3982 llvm::Module &M = CGM.getModule();
3983 llvm::LLVMContext &C = M.getContext();
Alexey Bataev03f270c2018-03-30 18:31:07 +00003984 SmallVector<const OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
Samuel Antaoee8fb302016-01-06 13:42:12 +00003985 OrderedEntries(OffloadEntriesInfoManager.size());
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00003986 llvm::SmallVector<StringRef, 16> ParentFunctions(
3987 OffloadEntriesInfoManager.size());
Samuel Antaoee8fb302016-01-06 13:42:12 +00003988
Simon Pilgrim2c518802017-03-30 14:13:19 +00003989 // Auxiliary methods to create metadata values and strings.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003990 auto &&GetMDInt = [this](unsigned V) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003991 return llvm::ConstantAsMetadata::get(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00003992 llvm::ConstantInt::get(CGM.Int32Ty, V));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003993 };
3994
Alexey Bataev03f270c2018-03-30 18:31:07 +00003995 auto &&GetMDString = [&C](StringRef V) { return llvm::MDString::get(C, V); };
3996
3997 // Create the offloading info metadata node.
3998 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003999
4000 // Create function that emits metadata for each target region entry;
Alexey Bataev03f270c2018-03-30 18:31:07 +00004001 auto &&TargetRegionMetadataEmitter =
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00004002 [&C, MD, &OrderedEntries, &ParentFunctions, &GetMDInt, &GetMDString](
Alexey Bataev03f270c2018-03-30 18:31:07 +00004003 unsigned DeviceID, unsigned FileID, StringRef ParentName,
4004 unsigned Line,
4005 const OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
4006 // Generate metadata for target regions. Each entry of this metadata
4007 // contains:
4008 // - Entry 0 -> Kind of this type of metadata (0).
4009 // - Entry 1 -> Device ID of the file where the entry was identified.
4010 // - Entry 2 -> File ID of the file where the entry was identified.
4011 // - Entry 3 -> Mangled name of the function where the entry was
4012 // identified.
4013 // - Entry 4 -> Line in the file where the entry was identified.
4014 // - Entry 5 -> Order the entry was created.
4015 // The first element of the metadata node is the kind.
4016 llvm::Metadata *Ops[] = {GetMDInt(E.getKind()), GetMDInt(DeviceID),
4017 GetMDInt(FileID), GetMDString(ParentName),
4018 GetMDInt(Line), GetMDInt(E.getOrder())};
Samuel Antaoee8fb302016-01-06 13:42:12 +00004019
Alexey Bataev03f270c2018-03-30 18:31:07 +00004020 // Save this entry in the right position of the ordered entries array.
4021 OrderedEntries[E.getOrder()] = &E;
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00004022 ParentFunctions[E.getOrder()] = ParentName;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004023
Alexey Bataev03f270c2018-03-30 18:31:07 +00004024 // Add metadata to the named metadata node.
4025 MD->addOperand(llvm::MDNode::get(C, Ops));
4026 };
Samuel Antaoee8fb302016-01-06 13:42:12 +00004027
4028 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
4029 TargetRegionMetadataEmitter);
4030
Alexey Bataev03f270c2018-03-30 18:31:07 +00004031 // Create function that emits metadata for each device global variable entry;
4032 auto &&DeviceGlobalVarMetadataEmitter =
4033 [&C, &OrderedEntries, &GetMDInt, &GetMDString,
4034 MD](StringRef MangledName,
4035 const OffloadEntriesInfoManagerTy::OffloadEntryInfoDeviceGlobalVar
4036 &E) {
4037 // Generate metadata for global variables. Each entry of this metadata
4038 // contains:
4039 // - Entry 0 -> Kind of this type of metadata (1).
4040 // - Entry 1 -> Mangled name of the variable.
4041 // - Entry 2 -> Declare target kind.
4042 // - Entry 3 -> Order the entry was created.
4043 // The first element of the metadata node is the kind.
4044 llvm::Metadata *Ops[] = {
4045 GetMDInt(E.getKind()), GetMDString(MangledName),
4046 GetMDInt(E.getFlags()), GetMDInt(E.getOrder())};
4047
4048 // Save this entry in the right position of the ordered entries array.
4049 OrderedEntries[E.getOrder()] = &E;
4050
4051 // Add metadata to the named metadata node.
4052 MD->addOperand(llvm::MDNode::get(C, Ops));
4053 };
4054
4055 OffloadEntriesInfoManager.actOnDeviceGlobalVarEntriesInfo(
4056 DeviceGlobalVarMetadataEmitter);
4057
4058 for (const auto *E : OrderedEntries) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004059 assert(E && "All ordered entries must exist!");
Alexey Bataev03f270c2018-03-30 18:31:07 +00004060 if (const auto *CE =
Samuel Antaoee8fb302016-01-06 13:42:12 +00004061 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
4062 E)) {
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004063 if (!CE->getID() || !CE->getAddress()) {
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00004064 // Do not blame the entry if the parent funtion is not emitted.
4065 StringRef FnName = ParentFunctions[CE->getOrder()];
4066 if (!CGM.GetGlobalValue(FnName))
4067 continue;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004068 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4069 DiagnosticsEngine::Error,
Alexey Bataev7f01d202018-07-16 18:12:18 +00004070 "Offloading entry for target region is incorrect: either the "
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004071 "address or the ID is invalid.");
4072 CGM.getDiags().Report(DiagID);
4073 continue;
4074 }
Alexey Bataev34f8a702018-03-28 14:28:54 +00004075 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0,
Alexey Bataev03f270c2018-03-30 18:31:07 +00004076 CE->getFlags(), llvm::GlobalValue::WeakAnyLinkage);
4077 } else if (const auto *CE =
4078 dyn_cast<OffloadEntriesInfoManagerTy::
4079 OffloadEntryInfoDeviceGlobalVar>(E)) {
Alexey Bataevc52f01d2018-07-16 20:05:25 +00004080 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags =
4081 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
4082 CE->getFlags());
4083 switch (Flags) {
4084 case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo: {
4085 if (!CE->getAddress()) {
4086 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4087 DiagnosticsEngine::Error,
4088 "Offloading entry for declare target variable is incorrect: the "
4089 "address is invalid.");
4090 CGM.getDiags().Report(DiagID);
4091 continue;
4092 }
Alexey Bataevb4dd6d22018-08-29 20:41:37 +00004093 // The vaiable has no definition - no need to add the entry.
4094 if (CE->getVarSize().isZero())
4095 continue;
Alexey Bataevc52f01d2018-07-16 20:05:25 +00004096 break;
4097 }
4098 case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink:
4099 assert(((CGM.getLangOpts().OpenMPIsDevice && !CE->getAddress()) ||
4100 (!CGM.getLangOpts().OpenMPIsDevice && CE->getAddress())) &&
4101 "Declaret target link address is set.");
4102 if (CGM.getLangOpts().OpenMPIsDevice)
4103 continue;
4104 if (!CE->getAddress()) {
4105 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4106 DiagnosticsEngine::Error,
4107 "Offloading entry for declare target variable is incorrect: the "
4108 "address is invalid.");
4109 CGM.getDiags().Report(DiagID);
4110 continue;
4111 }
4112 break;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004113 }
Alexey Bataev03f270c2018-03-30 18:31:07 +00004114 createOffloadEntry(CE->getAddress(), CE->getAddress(),
Alexey Bataevc52f01d2018-07-16 20:05:25 +00004115 CE->getVarSize().getQuantity(), Flags,
Alexey Bataev03f270c2018-03-30 18:31:07 +00004116 CE->getLinkage());
4117 } else {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004118 llvm_unreachable("Unsupported entry kind.");
Alexey Bataev03f270c2018-03-30 18:31:07 +00004119 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004120 }
4121}
4122
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004123/// Loads all the offload entries information from the host IR
Samuel Antaoee8fb302016-01-06 13:42:12 +00004124/// metadata.
4125void CGOpenMPRuntime::loadOffloadInfoMetadata() {
4126 // If we are in target mode, load the metadata from the host IR. This code has
4127 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
4128
4129 if (!CGM.getLangOpts().OpenMPIsDevice)
4130 return;
4131
4132 if (CGM.getLangOpts().OMPHostIRFile.empty())
4133 return;
4134
4135 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004136 if (auto EC = Buf.getError()) {
4137 CGM.getDiags().Report(diag::err_cannot_open_file)
4138 << CGM.getLangOpts().OMPHostIRFile << EC.message();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004139 return;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004140 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004141
4142 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00004143 auto ME = expectedToErrorOrAndEmitErrors(
4144 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004145
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004146 if (auto EC = ME.getError()) {
4147 unsigned DiagID = CGM.getDiags().getCustomDiagID(
4148 DiagnosticsEngine::Error, "Unable to parse host IR file '%0':'%1'");
4149 CGM.getDiags().Report(DiagID)
4150 << CGM.getLangOpts().OMPHostIRFile << EC.message();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004151 return;
Alexey Bataev64e62dc2018-04-30 16:26:57 +00004152 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00004153
4154 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
4155 if (!MD)
4156 return;
4157
George Burgess IV00f70bd2018-03-01 05:43:23 +00004158 for (llvm::MDNode *MN : MD->operands()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004159 auto &&GetMDInt = [MN](unsigned Idx) {
4160 auto *V = cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004161 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
4162 };
4163
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004164 auto &&GetMDString = [MN](unsigned Idx) {
4165 auto *V = cast<llvm::MDString>(MN->getOperand(Idx));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004166 return V->getString();
4167 };
4168
Alexey Bataev03f270c2018-03-30 18:31:07 +00004169 switch (GetMDInt(0)) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004170 default:
4171 llvm_unreachable("Unexpected metadata!");
4172 break;
4173 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
Alexey Bataev34f8a702018-03-28 14:28:54 +00004174 OffloadingEntryInfoTargetRegion:
Samuel Antaoee8fb302016-01-06 13:42:12 +00004175 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
Alexey Bataev03f270c2018-03-30 18:31:07 +00004176 /*DeviceID=*/GetMDInt(1), /*FileID=*/GetMDInt(2),
4177 /*ParentName=*/GetMDString(3), /*Line=*/GetMDInt(4),
4178 /*Order=*/GetMDInt(5));
4179 break;
4180 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
4181 OffloadingEntryInfoDeviceGlobalVar:
4182 OffloadEntriesInfoManager.initializeDeviceGlobalVarEntryInfo(
4183 /*MangledName=*/GetMDString(1),
4184 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
4185 /*Flags=*/GetMDInt(2)),
4186 /*Order=*/GetMDInt(3));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004187 break;
4188 }
4189 }
4190}
4191
Alexey Bataev62b63b12015-03-10 07:28:44 +00004192void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
4193 if (!KmpRoutineEntryPtrTy) {
4194 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004195 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004196 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
4197 FunctionProtoType::ExtProtoInfo EPI;
4198 KmpRoutineEntryPtrQTy = C.getPointerType(
4199 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
4200 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
4201 }
4202}
4203
Samuel Antaoee8fb302016-01-06 13:42:12 +00004204QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004205 // Make sure the type of the entry is already created. This is the type we
4206 // have to create:
4207 // struct __tgt_offload_entry{
4208 // void *addr; // Pointer to the offload entry info.
4209 // // (function or global)
4210 // char *name; // Name of the function or global.
4211 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00004212 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
4213 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004214 // };
4215 if (TgtOffloadEntryQTy.isNull()) {
4216 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004217 RecordDecl *RD = C.buildImplicitRecord("__tgt_offload_entry");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004218 RD->startDefinition();
4219 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4220 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
4221 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00004222 addFieldToRecordDecl(
4223 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4224 addFieldToRecordDecl(
4225 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004226 RD->completeDefinition();
Jonas Hahnfeld5e4df282018-01-18 15:38:03 +00004227 RD->addAttr(PackedAttr::CreateImplicit(C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00004228 TgtOffloadEntryQTy = C.getRecordType(RD);
4229 }
4230 return TgtOffloadEntryQTy;
4231}
4232
4233QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
4234 // These are the types we need to build:
4235 // struct __tgt_device_image{
4236 // void *ImageStart; // Pointer to the target code start.
4237 // void *ImageEnd; // Pointer to the target code end.
4238 // // We also add the host entries to the device image, as it may be useful
4239 // // for the target runtime to have access to that information.
4240 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
4241 // // the entries.
4242 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4243 // // entries (non inclusive).
4244 // };
4245 if (TgtDeviceImageQTy.isNull()) {
4246 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004247 RecordDecl *RD = C.buildImplicitRecord("__tgt_device_image");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004248 RD->startDefinition();
4249 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4250 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4251 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4252 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4253 RD->completeDefinition();
4254 TgtDeviceImageQTy = C.getRecordType(RD);
4255 }
4256 return TgtDeviceImageQTy;
4257}
4258
4259QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
4260 // struct __tgt_bin_desc{
4261 // int32_t NumDevices; // Number of devices supported.
4262 // __tgt_device_image *DeviceImages; // Arrays of device images
4263 // // (one per device).
4264 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
4265 // // entries.
4266 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
4267 // // entries (non inclusive).
4268 // };
4269 if (TgtBinaryDescriptorQTy.isNull()) {
4270 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004271 RecordDecl *RD = C.buildImplicitRecord("__tgt_bin_desc");
Samuel Antaoee8fb302016-01-06 13:42:12 +00004272 RD->startDefinition();
4273 addFieldToRecordDecl(
4274 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
4275 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
4276 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4277 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
4278 RD->completeDefinition();
4279 TgtBinaryDescriptorQTy = C.getRecordType(RD);
4280 }
4281 return TgtBinaryDescriptorQTy;
4282}
4283
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004284namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00004285struct PrivateHelpersTy {
4286 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
4287 const VarDecl *PrivateElemInit)
4288 : Original(Original), PrivateCopy(PrivateCopy),
4289 PrivateElemInit(PrivateElemInit) {}
4290 const VarDecl *Original;
4291 const VarDecl *PrivateCopy;
4292 const VarDecl *PrivateElemInit;
4293};
4294typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00004295} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004296
Alexey Bataev9e034042015-05-05 04:05:12 +00004297static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00004298createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004299 if (!Privates.empty()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004300 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004301 // Build struct .kmp_privates_t. {
4302 // /* private vars */
4303 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004304 RecordDecl *RD = C.buildImplicitRecord(".kmp_privates.t");
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004305 RD->startDefinition();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004306 for (const auto &Pair : Privates) {
4307 const VarDecl *VD = Pair.second.Original;
4308 QualType Type = VD->getType().getNonReferenceType();
4309 FieldDecl *FD = addFieldToRecordDecl(C, RD, Type);
Alexey Bataevc71a4092015-09-11 10:29:41 +00004310 if (VD->hasAttrs()) {
4311 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
4312 E(VD->getAttrs().end());
4313 I != E; ++I)
4314 FD->addAttr(*I);
4315 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004316 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004317 RD->completeDefinition();
4318 return RD;
4319 }
4320 return nullptr;
4321}
4322
Alexey Bataev9e034042015-05-05 04:05:12 +00004323static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00004324createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
4325 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004326 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004327 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004328 // Build struct kmp_task_t {
4329 // void * shareds;
4330 // kmp_routine_entry_t routine;
4331 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00004332 // kmp_cmplrdata_t data1;
4333 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00004334 // For taskloops additional fields:
4335 // kmp_uint64 lb;
4336 // kmp_uint64 ub;
4337 // kmp_int64 st;
4338 // kmp_int32 liter;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004339 // void * reductions;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004340 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004341 RecordDecl *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004342 UD->startDefinition();
4343 addFieldToRecordDecl(C, UD, KmpInt32Ty);
4344 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
4345 UD->completeDefinition();
4346 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004347 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t");
Alexey Bataev62b63b12015-03-10 07:28:44 +00004348 RD->startDefinition();
4349 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
4350 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
4351 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00004352 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
4353 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004354 if (isOpenMPTaskLoopDirective(Kind)) {
4355 QualType KmpUInt64Ty =
4356 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4357 QualType KmpInt64Ty =
4358 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4359 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4360 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
4361 addFieldToRecordDecl(C, RD, KmpInt64Ty);
4362 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004363 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00004364 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004365 RD->completeDefinition();
4366 return RD;
4367}
4368
4369static RecordDecl *
4370createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004371 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004372 ASTContext &C = CGM.getContext();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004373 // Build struct kmp_task_t_with_privates {
4374 // kmp_task_t task_data;
4375 // .kmp_privates_t. privates;
4376 // };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004377 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004378 RD->startDefinition();
4379 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004380 if (const RecordDecl *PrivateRD = createPrivatesRecordDecl(CGM, Privates))
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004381 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004382 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004383 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004384}
4385
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004386/// Emit a proxy function which accepts kmp_task_t as the second
Alexey Bataev62b63b12015-03-10 07:28:44 +00004387/// argument.
4388/// \code
4389/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004390/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00004391/// For taskloops:
4392/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004393/// tt->reductions, tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004394/// return 0;
4395/// }
4396/// \endcode
4397static llvm::Value *
4398emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00004399 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
4400 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004401 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004402 QualType SharedsPtrTy, llvm::Value *TaskFunction,
4403 llvm::Value *TaskPrivatesMap) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004404 ASTContext &C = CGM.getContext();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004405 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004406 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4407 ImplicitParamDecl::Other);
4408 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4409 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4410 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004411 Args.push_back(&GtidArg);
4412 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004413 const auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004414 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004415 llvm::FunctionType *TaskEntryTy =
4416 CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004417 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_entry", ""});
4418 auto *TaskEntry = llvm::Function::Create(
4419 TaskEntryTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004420 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskEntry, TaskEntryFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004421 TaskEntry->setDoesNotRecurse();
Alexey Bataev62b63b12015-03-10 07:28:44 +00004422 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004423 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args,
4424 Loc, Loc);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004425
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004426 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00004427 // tt,
4428 // For taskloops:
4429 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
4430 // tt->task_data.shareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004431 llvm::Value *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00004432 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00004433 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4434 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4435 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004436 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004437 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004438 LValue Base =
4439 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004440 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004441 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004442 LValue PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
4443 llvm::Value *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004444
4445 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004446 LValue SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
4447 llvm::Value *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev1e491372018-01-23 18:44:14 +00004448 CGF.EmitLoadOfScalar(SharedsLVal, Loc),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004449 CGF.ConvertTypeForMem(SharedsPtrTy));
4450
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004451 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4452 llvm::Value *PrivatesParam;
4453 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004454 LValue PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004455 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004456 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004457 } else {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004458 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004459 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004460
Alexey Bataev7292c292016-04-25 12:22:29 +00004461 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
4462 TaskPrivatesMap,
4463 CGF.Builder
4464 .CreatePointerBitCastOrAddrSpaceCast(
4465 TDBase.getAddress(), CGF.VoidPtrTy)
4466 .getPointer()};
4467 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
4468 std::end(CommonArgs));
4469 if (isOpenMPTaskLoopDirective(Kind)) {
4470 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004471 LValue LBLVal = CGF.EmitLValueForField(Base, *LBFI);
4472 llvm::Value *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004473 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004474 LValue UBLVal = CGF.EmitLValueForField(Base, *UBFI);
4475 llvm::Value *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004476 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004477 LValue StLVal = CGF.EmitLValueForField(Base, *StFI);
4478 llvm::Value *StParam = CGF.EmitLoadOfScalar(StLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004479 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004480 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4481 llvm::Value *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004482 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004483 LValue RLVal = CGF.EmitLValueForField(Base, *RFI);
4484 llvm::Value *RParam = CGF.EmitLoadOfScalar(RLVal, Loc);
Alexey Bataev7292c292016-04-25 12:22:29 +00004485 CallArgs.push_back(LBParam);
4486 CallArgs.push_back(UBParam);
4487 CallArgs.push_back(StParam);
4488 CallArgs.push_back(LIParam);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004489 CallArgs.push_back(RParam);
Alexey Bataev7292c292016-04-25 12:22:29 +00004490 }
4491 CallArgs.push_back(SharedsParam);
4492
Alexey Bataev3c595a62017-08-14 15:01:03 +00004493 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
4494 CallArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004495 CGF.EmitStoreThroughLValue(RValue::get(CGF.Builder.getInt32(/*C=*/0)),
4496 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00004497 CGF.FinishFunction();
4498 return TaskEntry;
4499}
4500
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004501static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
4502 SourceLocation Loc,
4503 QualType KmpInt32Ty,
4504 QualType KmpTaskTWithPrivatesPtrQTy,
4505 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004506 ASTContext &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004507 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004508 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
4509 ImplicitParamDecl::Other);
4510 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4511 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
4512 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004513 Args.push_back(&GtidArg);
4514 Args.push_back(&TaskTypeArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004515 const auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004516 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004517 llvm::FunctionType *DestructorFnTy =
4518 CGM.getTypes().GetFunctionType(DestructorFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004519 std::string Name =
4520 CGM.getOpenMPRuntime().getName({"omp_task_destructor", ""});
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004521 auto *DestructorFn =
4522 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00004523 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004524 CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004525 DestructorFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004526 DestructorFn->setDoesNotRecurse();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004527 CodeGenFunction CGF(CGM);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004528 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004529 Args, Loc, Loc);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004530
Alexey Bataev31300ed2016-02-04 11:27:03 +00004531 LValue Base = CGF.EmitLoadOfPointerLValue(
4532 CGF.GetAddrOfLocalVar(&TaskTypeArg),
4533 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004534 const auto *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004535 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
4536 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004537 Base = CGF.EmitLValueForField(Base, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004538 for (const auto *Field :
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004539 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004540 if (QualType::DestructionKind DtorKind =
4541 Field->getType().isDestructedType()) {
4542 LValue FieldLValue = CGF.EmitLValueForField(Base, Field);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004543 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
4544 }
4545 }
4546 CGF.FinishFunction();
4547 return DestructorFn;
4548}
4549
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004550/// Emit a privates mapping function for correct handling of private and
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004551/// firstprivate variables.
4552/// \code
4553/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
4554/// **noalias priv1,..., <tyn> **noalias privn) {
4555/// *priv1 = &.privates.priv1;
4556/// ...;
4557/// *privn = &.privates.privn;
4558/// }
4559/// \endcode
4560static llvm::Value *
4561emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00004562 ArrayRef<const Expr *> PrivateVars,
4563 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004564 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004565 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00004566 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004567 ASTContext &C = CGM.getContext();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004568 FunctionArgList Args;
4569 ImplicitParamDecl TaskPrivatesArg(
4570 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00004571 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
4572 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004573 Args.push_back(&TaskPrivatesArg);
4574 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
4575 unsigned Counter = 1;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004576 for (const Expr *E : PrivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004577 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004578 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4579 C.getPointerType(C.getPointerType(E->getType()))
4580 .withConst()
4581 .withRestrict(),
4582 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004583 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004584 PrivateVarsPos[VD] = Counter;
4585 ++Counter;
4586 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004587 for (const Expr *E : FirstprivateVars) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004588 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004589 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4590 C.getPointerType(C.getPointerType(E->getType()))
4591 .withConst()
4592 .withRestrict(),
4593 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004594 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004595 PrivateVarsPos[VD] = Counter;
4596 ++Counter;
4597 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004598 for (const Expr *E : LastprivateVars) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004599 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00004600 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4601 C.getPointerType(C.getPointerType(E->getType()))
4602 .withConst()
4603 .withRestrict(),
4604 ImplicitParamDecl::Other));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004605 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004606 PrivateVarsPos[VD] = Counter;
4607 ++Counter;
4608 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004609 const auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00004610 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004611 llvm::FunctionType *TaskPrivatesMapTy =
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004612 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004613 std::string Name =
4614 CGM.getOpenMPRuntime().getName({"omp_task_privates_map", ""});
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004615 auto *TaskPrivatesMap = llvm::Function::Create(
Alexey Bataev18fa2322018-05-02 14:20:50 +00004616 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage, Name,
4617 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004618 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap,
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004619 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00004620 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00004621 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00004622 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004623 CodeGenFunction CGF(CGM);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004624 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004625 TaskPrivatesMapFnInfo, Args, Loc, Loc);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004626
4627 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00004628 LValue Base = CGF.EmitLoadOfPointerLValue(
4629 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4630 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004631 const auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004632 Counter = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004633 for (const FieldDecl *Field : PrivatesQTyRD->fields()) {
4634 LValue FieldLVal = CGF.EmitLValueForField(Base, Field);
4635 const VarDecl *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
4636 LValue RefLVal =
4637 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
4638 LValue RefLoadLVal = CGF.EmitLoadOfPointerLValue(
Alexey Bataev31300ed2016-02-04 11:27:03 +00004639 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00004640 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004641 ++Counter;
4642 }
4643 CGF.FinishFunction();
4644 return TaskPrivatesMap;
4645}
4646
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004647static bool stable_sort_comparator(const PrivateDataTy P1,
4648 const PrivateDataTy P2) {
4649 return P1.first > P2.first;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004650}
4651
Alexey Bataevf93095a2016-05-05 08:46:22 +00004652/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00004653static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004654 const OMPExecutableDirective &D,
4655 Address KmpTaskSharedsPtr, LValue TDBase,
4656 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4657 QualType SharedsTy, QualType SharedsPtrTy,
4658 const OMPTaskDataTy &Data,
4659 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004660 ASTContext &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004661 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4662 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004663 OpenMPDirectiveKind Kind = isOpenMPTaskLoopDirective(D.getDirectiveKind())
4664 ? OMPD_taskloop
4665 : OMPD_task;
4666 const CapturedStmt &CS = *D.getCapturedStmt(Kind);
4667 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004668 LValue SrcBase;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004669 bool IsTargetTask =
4670 isOpenMPTargetDataManagementDirective(D.getDirectiveKind()) ||
4671 isOpenMPTargetExecutionDirective(D.getDirectiveKind());
4672 // For target-based directives skip 3 firstprivate arrays BasePointersArray,
4673 // PointersArray and SizesArray. The original variables for these arrays are
4674 // not captured and we get their addresses explicitly.
4675 if ((!IsTargetTask && !Data.FirstprivateVars.empty()) ||
Alexey Bataev8451efa2018-01-15 19:06:12 +00004676 (IsTargetTask && KmpTaskSharedsPtr.isValid())) {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004677 SrcBase = CGF.MakeAddrLValue(
4678 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4679 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4680 SharedsTy);
4681 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004682 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004683 for (const PrivateDataTy &Pair : Privates) {
4684 const VarDecl *VD = Pair.second.PrivateCopy;
4685 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004686 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4687 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004688 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004689 if (const VarDecl *Elem = Pair.second.PrivateElemInit) {
4690 const VarDecl *OriginalVD = Pair.second.Original;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004691 // Check if the variable is the target-based BasePointersArray,
4692 // PointersArray or SizesArray.
4693 LValue SharedRefLValue;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004694 QualType Type = OriginalVD->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004695 const FieldDecl *SharedField = CapturesInfo.lookup(OriginalVD);
Alexey Bataev8451efa2018-01-15 19:06:12 +00004696 if (IsTargetTask && !SharedField) {
4697 assert(isa<ImplicitParamDecl>(OriginalVD) &&
4698 isa<CapturedDecl>(OriginalVD->getDeclContext()) &&
4699 cast<CapturedDecl>(OriginalVD->getDeclContext())
4700 ->getNumParams() == 0 &&
4701 isa<TranslationUnitDecl>(
4702 cast<CapturedDecl>(OriginalVD->getDeclContext())
4703 ->getDeclContext()) &&
4704 "Expected artificial target data variable.");
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004705 SharedRefLValue =
4706 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type);
4707 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004708 SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4709 SharedRefLValue = CGF.MakeAddrLValue(
4710 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
4711 SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl),
4712 SharedRefLValue.getTBAAInfo());
4713 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004714 if (Type->isArrayType()) {
4715 // Initialize firstprivate array.
4716 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4717 // Perform simple memcpy.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00004718 CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004719 } else {
4720 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00004721 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00004722 CGF.EmitOMPAggregateAssign(
4723 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4724 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4725 Address SrcElement) {
4726 // Clean up any temporaries needed by the initialization.
4727 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4728 InitScope.addPrivate(
4729 Elem, [SrcElement]() -> Address { return SrcElement; });
4730 (void)InitScope.Privatize();
4731 // Emit initialization for single element.
4732 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4733 CGF, &CapturesInfo);
4734 CGF.EmitAnyExprToMem(Init, DestElement,
4735 Init->getType().getQualifiers(),
4736 /*IsInitializer=*/false);
4737 });
4738 }
4739 } else {
4740 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4741 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4742 return SharedRefLValue.getAddress();
4743 });
4744 (void)InitScope.Privatize();
4745 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4746 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4747 /*capturedByInit=*/false);
4748 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004749 } else {
Alexey Bataevf93095a2016-05-05 08:46:22 +00004750 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004751 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004752 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004753 ++FI;
4754 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004755}
4756
4757/// Check if duplication function is required for taskloops.
4758static bool checkInitIsRequired(CodeGenFunction &CGF,
4759 ArrayRef<PrivateDataTy> Privates) {
4760 bool InitRequired = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004761 for (const PrivateDataTy &Pair : Privates) {
4762 const VarDecl *VD = Pair.second.PrivateCopy;
4763 const Expr *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004764 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4765 !CGF.isTrivialInitializer(Init));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004766 if (InitRequired)
4767 break;
Alexey Bataevf93095a2016-05-05 08:46:22 +00004768 }
4769 return InitRequired;
4770}
4771
4772
4773/// Emit task_dup function (for initialization of
4774/// private/firstprivate/lastprivate vars and last_iter flag)
4775/// \code
4776/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4777/// lastpriv) {
4778/// // setup lastprivate flag
4779/// task_dst->last = lastpriv;
4780/// // could be constructor calls here...
4781/// }
4782/// \endcode
4783static llvm::Value *
4784emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4785 const OMPExecutableDirective &D,
4786 QualType KmpTaskTWithPrivatesPtrQTy,
4787 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4788 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4789 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4790 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004791 ASTContext &C = CGM.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004792 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004793 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4794 KmpTaskTWithPrivatesPtrQTy,
4795 ImplicitParamDecl::Other);
4796 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4797 KmpTaskTWithPrivatesPtrQTy,
4798 ImplicitParamDecl::Other);
4799 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4800 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004801 Args.push_back(&DstArg);
4802 Args.push_back(&SrcArg);
4803 Args.push_back(&LastprivArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004804 const auto &TaskDupFnInfo =
Alexey Bataevf93095a2016-05-05 08:46:22 +00004805 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004806 llvm::FunctionType *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00004807 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_dup", ""});
4808 auto *TaskDup = llvm::Function::Create(
4809 TaskDupTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00004810 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskDup, TaskDupFnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00004811 TaskDup->setDoesNotRecurse();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004812 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00004813 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args, Loc,
4814 Loc);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004815
4816 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4817 CGF.GetAddrOfLocalVar(&DstArg),
4818 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4819 // task_dst->liter = lastpriv;
4820 if (WithLastIter) {
4821 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4822 LValue Base = CGF.EmitLValueForField(
4823 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4824 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4825 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4826 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4827 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4828 }
4829
4830 // Emit initial values for private copies (if any).
4831 assert(!Privates.empty());
4832 Address KmpTaskSharedsPtr = Address::invalid();
4833 if (!Data.FirstprivateVars.empty()) {
4834 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4835 CGF.GetAddrOfLocalVar(&SrcArg),
4836 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4837 LValue Base = CGF.EmitLValueForField(
4838 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4839 KmpTaskSharedsPtr = Address(
4840 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4841 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4842 KmpTaskTShareds)),
4843 Loc),
4844 CGF.getNaturalTypeAlignment(SharedsTy));
4845 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004846 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4847 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004848 CGF.FinishFunction();
4849 return TaskDup;
4850}
4851
Alexey Bataev8a831592016-05-10 10:36:51 +00004852/// Checks if destructor function is required to be generated.
4853/// \return true if cleanups are required, false otherwise.
4854static bool
4855checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4856 bool NeedsCleanup = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004857 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
4858 const auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4859 for (const FieldDecl *FD : PrivateRD->fields()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004860 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4861 if (NeedsCleanup)
4862 break;
4863 }
4864 return NeedsCleanup;
4865}
4866
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004867CGOpenMPRuntime::TaskResultTy
4868CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4869 const OMPExecutableDirective &D,
4870 llvm::Value *TaskFunction, QualType SharedsTy,
4871 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004872 ASTContext &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004873 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004874 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004875 auto I = Data.PrivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004876 for (const Expr *E : Data.PrivateVars) {
4877 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004878 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004879 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004880 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004881 /*PrivateElemInit=*/nullptr));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004882 ++I;
4883 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004884 I = Data.FirstprivateCopies.begin();
4885 auto IElemInitRef = Data.FirstprivateInits.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004886 for (const Expr *E : Data.FirstprivateVars) {
4887 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004888 Privates.emplace_back(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004889 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004890 PrivateHelpersTy(
4891 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004892 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl())));
Richard Trieucc3949d2016-02-18 22:34:54 +00004893 ++I;
4894 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004895 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004896 I = Data.LastprivateCopies.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004897 for (const Expr *E : Data.LastprivateVars) {
4898 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
Alexey Bataev43a919f2018-04-13 17:48:43 +00004899 Privates.emplace_back(
Alexey Bataevf93095a2016-05-05 08:46:22 +00004900 C.getDeclAlign(VD),
4901 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
Alexey Bataev43a919f2018-04-13 17:48:43 +00004902 /*PrivateElemInit=*/nullptr));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004903 ++I;
4904 }
Mandeep Singh Grangb14fb6a22017-11-28 20:41:13 +00004905 std::stable_sort(Privates.begin(), Privates.end(), stable_sort_comparator);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004906 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004907 // Build type kmp_routine_entry_t (if not built yet).
4908 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004909 // Build type kmp_task_t (if not built yet).
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004910 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
4911 if (SavedKmpTaskloopTQTy.isNull()) {
4912 SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4913 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4914 }
4915 KmpTaskTQTy = SavedKmpTaskloopTQTy;
Alexey Bataev3a03a7f2017-10-11 15:56:38 +00004916 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00004917 assert((D.getDirectiveKind() == OMPD_task ||
4918 isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||
4919 isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) &&
4920 "Expected taskloop, task or target directive");
Alexey Bataeve213f3e2017-10-11 15:29:40 +00004921 if (SavedKmpTaskTQTy.isNull()) {
4922 SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4923 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4924 }
4925 KmpTaskTQTy = SavedKmpTaskTQTy;
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004926 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004927 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004928 // Build particular struct kmp_task_t for the given task.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004929 const RecordDecl *KmpTaskTWithPrivatesQTyRD =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004930 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004931 QualType KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004932 QualType KmpTaskTWithPrivatesPtrQTy =
4933 C.getPointerType(KmpTaskTWithPrivatesQTy);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004934 llvm::Type *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4935 llvm::Type *KmpTaskTWithPrivatesPtrTy =
4936 KmpTaskTWithPrivatesTy->getPointerTo();
4937 llvm::Value *KmpTaskTWithPrivatesTySize =
4938 CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004939 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4940
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004941 // Emit initial values for private copies (if any).
4942 llvm::Value *TaskPrivatesMap = nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004943 llvm::Type *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00004944 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004945 if (!Privates.empty()) {
4946 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004947 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4948 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4949 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004950 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4951 TaskPrivatesMap, TaskPrivatesMapTy);
4952 } else {
4953 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4954 cast<llvm::PointerType>(TaskPrivatesMapTy));
4955 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004956 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4957 // kmp_task_t *tt);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004958 llvm::Value *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004959 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4960 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4961 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004962
4963 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4964 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4965 // kmp_routine_entry_t *task_entry);
4966 // Task flags. Format is taken from
James Y Knight5d71fc52019-01-29 16:37:27 +00004967 // https://github.com/llvm/llvm-project/blob/master/openmp/runtime/src/kmp.h,
Alexey Bataev62b63b12015-03-10 07:28:44 +00004968 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004969 enum {
4970 TiedFlag = 0x1,
4971 FinalFlag = 0x2,
4972 DestructorsFlag = 0x8,
4973 PriorityFlag = 0x20
4974 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004975 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004976 bool NeedsCleanup = false;
4977 if (!Privates.empty()) {
4978 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4979 if (NeedsCleanup)
4980 Flags = Flags | DestructorsFlag;
4981 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004982 if (Data.Priority.getInt())
4983 Flags = Flags | PriorityFlag;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004984 llvm::Value *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004985 Data.Final.getPointer()
4986 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00004987 CGF.Builder.getInt32(FinalFlag),
4988 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004989 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004990 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004991 llvm::Value *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004992 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4993 getThreadID(CGF, Loc), TaskFlags,
4994 KmpTaskTWithPrivatesTySize, SharedsSize,
4995 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4996 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004997 llvm::Value *NewTask = CGF.EmitRuntimeCall(
Alexey Bataev62b63b12015-03-10 07:28:44 +00004998 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00004999 llvm::Value *NewTaskNewTaskTTy =
5000 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5001 NewTask, KmpTaskTWithPrivatesPtrTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00005002 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
5003 KmpTaskTWithPrivatesQTy);
5004 LValue TDBase =
5005 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00005006 // Fill the data in the resulting kmp_task_t record.
5007 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00005008 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00005009 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00005010 KmpTaskSharedsPtr =
5011 Address(CGF.EmitLoadOfScalar(
5012 CGF.EmitLValueForField(
5013 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
5014 KmpTaskTShareds)),
5015 Loc),
5016 CGF.getNaturalTypeAlignment(SharedsTy));
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00005017 LValue Dest = CGF.MakeAddrLValue(KmpTaskSharedsPtr, SharedsTy);
5018 LValue Src = CGF.MakeAddrLValue(Shareds, SharedsTy);
Richard Smithe78fac52018-04-05 20:52:58 +00005019 CGF.EmitAggregateCopy(Dest, Src, SharedsTy, AggValueSlot::DoesNotOverlap);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00005020 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00005021 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00005022 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00005023 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00005024 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
5025 SharedsTy, SharedsPtrTy, Data, Privates,
5026 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00005027 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
5028 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
5029 Result.TaskDupFn = emitTaskDupFunction(
5030 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
5031 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
5032 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00005033 }
5034 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00005035 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
5036 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00005037 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00005038 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005039 const RecordDecl *KmpCmplrdataUD =
5040 (*FI)->getType()->getAsUnionType()->getDecl();
Alexey Bataevad537bb2016-05-30 09:06:50 +00005041 if (NeedsCleanup) {
5042 llvm::Value *DestructorFn = emitDestructorsFunction(
5043 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
5044 KmpTaskTWithPrivatesQTy);
5045 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
5046 LValue DestructorsLV = CGF.EmitLValueForField(
5047 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
5048 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5049 DestructorFn, KmpRoutineEntryPtrTy),
5050 DestructorsLV);
5051 }
5052 // Set priority.
5053 if (Data.Priority.getInt()) {
5054 LValue Data2LV = CGF.EmitLValueForField(
5055 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
5056 LValue PriorityLV = CGF.EmitLValueForField(
5057 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
5058 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
5059 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005060 Result.NewTask = NewTask;
5061 Result.TaskEntry = TaskEntry;
5062 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
5063 Result.TDBase = TDBase;
5064 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
5065 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00005066}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005067
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005068void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
5069 const OMPExecutableDirective &D,
5070 llvm::Value *TaskFunction,
5071 QualType SharedsTy, Address Shareds,
5072 const Expr *IfCond,
5073 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005074 if (!CGF.HaveInsertPoint())
5075 return;
5076
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005077 TaskResultTy Result =
5078 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
5079 llvm::Value *NewTask = Result.NewTask;
5080 llvm::Value *TaskEntry = Result.TaskEntry;
5081 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
5082 LValue TDBase = Result.TDBase;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005083 const RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
5084 ASTContext &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005085 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00005086 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005087 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00005088 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005089 // Dependence kind for RTL.
Sergi Mateo Bellido31df1ad2019-02-04 07:33:19 +00005090 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3, DepMutexInOutSet = 0x4 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005091 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
5092 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005093 QualType FlagsTy =
5094 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005095 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
5096 if (KmpDependInfoTy.isNull()) {
5097 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
5098 KmpDependInfoRD->startDefinition();
5099 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
5100 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
5101 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
5102 KmpDependInfoRD->completeDefinition();
5103 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005104 } else {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005105 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005106 }
John McCall7f416cc2015-09-08 08:05:57 +00005107 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005108 // Define type kmp_depend_info[<Dependences.size()>];
5109 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00005110 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005111 ArrayType::Normal, /*IndexTypeQuals=*/0);
5112 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00005113 DependenciesArray =
5114 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005115 for (unsigned I = 0; I < NumDependencies; ++I) {
5116 const Expr *E = Data.Dependences[I].second;
5117 LValue Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005118 llvm::Value *Size;
5119 QualType Ty = E->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005120 if (const auto *ASE =
5121 dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005122 LValue UpAddrLVal =
5123 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
5124 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00005125 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005126 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00005127 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00005128 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
5129 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005130 } else {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005131 Size = CGF.getTypeSize(Ty);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005132 }
5133 LValue Base = CGF.MakeAddrLValue(
5134 CGF.Builder.CreateConstArrayGEP(DependenciesArray, I, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005135 KmpDependInfoTy);
5136 // deps[i].base_addr = &<Dependences[i].second>;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005137 LValue BaseAddrLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005138 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00005139 CGF.EmitStoreOfScalar(
5140 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
5141 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005142 // deps[i].len = sizeof(<Dependences[i].second>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005143 LValue LenLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005144 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
5145 CGF.EmitStoreOfScalar(Size, LenLVal);
5146 // deps[i].flags = <Dependences[i].first>;
5147 RTLDependenceKindTy DepKind;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005148 switch (Data.Dependences[I].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005149 case OMPC_DEPEND_in:
5150 DepKind = DepIn;
5151 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00005152 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005153 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005154 case OMPC_DEPEND_inout:
5155 DepKind = DepInOut;
5156 break;
Sergi Mateo Bellido31df1ad2019-02-04 07:33:19 +00005157 case OMPC_DEPEND_mutexinoutset:
5158 DepKind = DepMutexInOutSet;
5159 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00005160 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005161 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005162 case OMPC_DEPEND_unknown:
5163 llvm_unreachable("Unknown task dependence type");
5164 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005165 LValue FlagsLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005166 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
5167 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
5168 FlagsLVal);
5169 }
John McCall7f416cc2015-09-08 08:05:57 +00005170 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5171 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005172 CGF.VoidPtrTy);
5173 }
5174
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005175 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev62b63b12015-03-10 07:28:44 +00005176 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005177 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
5178 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
5179 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
5180 // list is not empty
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005181 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5182 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00005183 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
5184 llvm::Value *DepTaskArgs[7];
5185 if (NumDependencies) {
5186 DepTaskArgs[0] = UpLoc;
5187 DepTaskArgs[1] = ThreadID;
5188 DepTaskArgs[2] = NewTask;
5189 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
5190 DepTaskArgs[4] = DependenciesArray.getPointer();
5191 DepTaskArgs[5] = CGF.Builder.getInt32(0);
5192 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5193 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005194 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
5195 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005196 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005197 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005198 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005199 LValue PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005200 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
5201 }
John McCall7f416cc2015-09-08 08:05:57 +00005202 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005203 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00005204 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00005205 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005206 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00005207 TaskArgs);
5208 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00005209 // Check if parent region is untied and build return for untied task;
5210 if (auto *Region =
5211 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5212 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00005213 };
John McCall7f416cc2015-09-08 08:05:57 +00005214
5215 llvm::Value *DepWaitTaskArgs[6];
5216 if (NumDependencies) {
5217 DepWaitTaskArgs[0] = UpLoc;
5218 DepWaitTaskArgs[1] = ThreadID;
5219 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
5220 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
5221 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
5222 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5223 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005224 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00005225 NumDependencies, &DepWaitTaskArgs,
5226 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005227 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005228 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
5229 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
5230 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
5231 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
5232 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00005233 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005234 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005235 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005236 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00005237 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
5238 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005239 Action.Enter(CGF);
5240 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00005241 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00005242 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005243 };
5244
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005245 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
5246 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005247 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
5248 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005249 RegionCodeGenTy RCG(CodeGen);
5250 CommonActionTy Action(
5251 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
5252 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
5253 RCG.setAction(Action);
5254 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005255 };
John McCall7f416cc2015-09-08 08:05:57 +00005256
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005257 if (IfCond) {
Alexey Bataev1d677132015-04-22 13:57:31 +00005258 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005259 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005260 RegionCodeGenTy ThenRCG(ThenCodeGen);
5261 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00005262 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00005263}
5264
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005265void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
5266 const OMPLoopDirective &D,
5267 llvm::Value *TaskFunction,
5268 QualType SharedsTy, Address Shareds,
5269 const Expr *IfCond,
5270 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005271 if (!CGF.HaveInsertPoint())
5272 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005273 TaskResultTy Result =
5274 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005275 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev7292c292016-04-25 12:22:29 +00005276 // libcall.
5277 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
5278 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
5279 // sched, kmp_uint64 grainsize, void *task_dup);
5280 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5281 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
5282 llvm::Value *IfVal;
5283 if (IfCond) {
5284 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
5285 /*isSigned=*/true);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005286 } else {
Alexey Bataev7292c292016-04-25 12:22:29 +00005287 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005288 }
Alexey Bataev7292c292016-04-25 12:22:29 +00005289
5290 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005291 Result.TDBase,
5292 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005293 const auto *LBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005294 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
5295 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
5296 /*IsInitializer=*/true);
5297 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005298 Result.TDBase,
5299 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005300 const auto *UBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005301 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
5302 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
5303 /*IsInitializer=*/true);
5304 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005305 Result.TDBase,
5306 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005307 const auto *StVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005308 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
5309 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
5310 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005311 // Store reductions address.
5312 LValue RedLVal = CGF.EmitLValueForField(
5313 Result.TDBase,
5314 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005315 if (Data.Reductions) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005316 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005317 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005318 CGF.EmitNullInitialization(RedLVal.getAddress(),
5319 CGF.getContext().VoidPtrTy);
5320 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005321 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00005322 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00005323 UpLoc,
5324 ThreadID,
5325 Result.NewTask,
5326 IfVal,
5327 LBLVal.getPointer(),
5328 UBLVal.getPointer(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005329 CGF.EmitLoadOfScalar(StLVal, Loc),
Alexey Bataevac6e4de2018-10-24 19:06:37 +00005330 llvm::ConstantInt::getSigned(
5331 CGF.IntTy, 1), // Always 1 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005332 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005333 CGF.IntTy, Data.Schedule.getPointer()
5334 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005335 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005336 Data.Schedule.getPointer()
5337 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005338 /*isSigned=*/false)
5339 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00005340 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5341 Result.TaskDupFn, CGF.VoidPtrTy)
5342 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00005343 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
5344}
5345
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005346/// Emit reduction operation for each element of array (required for
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005347/// array sections) LHS op = RHS.
5348/// \param Type Type of array.
5349/// \param LHSVar Variable on the left side of the reduction operation
5350/// (references element of array in original variable).
5351/// \param RHSVar Variable on the right side of the reduction operation
5352/// (references element of array in original variable).
5353/// \param RedOpGen Generator of reduction operation with use of LHSVar and
5354/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00005355static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005356 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
5357 const VarDecl *RHSVar,
5358 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
5359 const Expr *, const Expr *)> &RedOpGen,
5360 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
5361 const Expr *UpExpr = nullptr) {
5362 // Perform element-by-element initialization.
5363 QualType ElementTy;
5364 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
5365 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
5366
5367 // Drill down to the base element type on both arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005368 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
5369 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005370
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005371 llvm::Value *RHSBegin = RHSAddr.getPointer();
5372 llvm::Value *LHSBegin = LHSAddr.getPointer();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005373 // Cast from pointer to array type to pointer to single element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005374 llvm::Value *LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005375 // The basic structure here is a while-do loop.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005376 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
5377 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
5378 llvm::Value *IsEmpty =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005379 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
5380 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
5381
5382 // Enter the loop body, making that address the current address.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005383 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005384 CGF.EmitBlock(BodyBB);
5385
5386 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
5387
5388 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
5389 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
5390 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
5391 Address RHSElementCurrent =
5392 Address(RHSElementPHI,
5393 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5394
5395 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
5396 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
5397 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
5398 Address LHSElementCurrent =
5399 Address(LHSElementPHI,
5400 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5401
5402 // Emit copy.
5403 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005404 Scope.addPrivate(LHSVar, [=]() { return LHSElementCurrent; });
5405 Scope.addPrivate(RHSVar, [=]() { return RHSElementCurrent; });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005406 Scope.Privatize();
5407 RedOpGen(CGF, XExpr, EExpr, UpExpr);
5408 Scope.ForceCleanup();
5409
5410 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005411 llvm::Value *LHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005412 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005413 llvm::Value *RHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005414 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
5415 // Check whether we've reached the end.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005416 llvm::Value *Done =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005417 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
5418 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
5419 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
5420 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
5421
5422 // Done.
5423 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
5424}
5425
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005426/// Emit reduction combiner. If the combiner is a simple expression emit it as
5427/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
5428/// UDR combiner function.
5429static void emitReductionCombiner(CodeGenFunction &CGF,
5430 const Expr *ReductionOp) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005431 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
5432 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
5433 if (const auto *DRE =
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005434 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005435 if (const auto *DRD =
5436 dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005437 std::pair<llvm::Function *, llvm::Function *> Reduction =
5438 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
5439 RValue Func = RValue::get(Reduction.first);
5440 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
5441 CGF.EmitIgnoredExpr(ReductionOp);
5442 return;
5443 }
5444 CGF.EmitIgnoredExpr(ReductionOp);
5445}
5446
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005447llvm::Value *CGOpenMPRuntime::emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005448 CodeGenModule &CGM, SourceLocation Loc, llvm::Type *ArgsType,
5449 ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs,
5450 ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005451 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005452
5453 // void reduction_func(void *LHSArg, void *RHSArg);
5454 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005455 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5456 ImplicitParamDecl::Other);
5457 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5458 ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005459 Args.push_back(&LHSArg);
5460 Args.push_back(&RHSArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005461 const auto &CGFI =
5462 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005463 std::string Name = getName({"omp", "reduction", "reduction_func"});
5464 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
5465 llvm::GlobalValue::InternalLinkage, Name,
5466 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005467 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005468 Fn->setDoesNotRecurse();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005469 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005470 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005471
5472 // Dst = (void*[n])(LHSArg);
5473 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00005474 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5475 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
5476 ArgsType), CGF.getPointerAlign());
5477 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5478 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
5479 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005480
5481 // ...
5482 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
5483 // ...
5484 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005485 auto IPriv = Privates.begin();
5486 unsigned Idx = 0;
5487 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005488 const auto *RHSVar =
5489 cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
5490 Scope.addPrivate(RHSVar, [&CGF, RHS, Idx, RHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005491 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005492 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005493 const auto *LHSVar =
5494 cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
5495 Scope.addPrivate(LHSVar, [&CGF, LHS, Idx, LHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005496 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005497 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005498 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00005499 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005500 // Get array size and emit VLA type.
5501 ++Idx;
5502 Address Elem =
5503 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
5504 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005505 const VariableArrayType *VLA =
5506 CGF.getContext().getAsVariableArrayType(PrivTy);
5507 const auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005508 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00005509 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005510 CGF.EmitVariablyModifiedType(PrivTy);
5511 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005512 }
5513 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005514 IPriv = Privates.begin();
5515 auto ILHS = LHSExprs.begin();
5516 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005517 for (const Expr *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005518 if ((*IPriv)->getType()->isArrayType()) {
5519 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005520 const auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5521 const auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005522 EmitOMPAggregateReduction(
5523 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5524 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5525 emitReductionCombiner(CGF, E);
5526 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005527 } else {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005528 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005529 emitReductionCombiner(CGF, E);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005530 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005531 ++IPriv;
5532 ++ILHS;
5533 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005534 }
5535 Scope.ForceCleanup();
5536 CGF.FinishFunction();
5537 return Fn;
5538}
5539
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005540void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
5541 const Expr *ReductionOp,
5542 const Expr *PrivateRef,
5543 const DeclRefExpr *LHS,
5544 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005545 if (PrivateRef->getType()->isArrayType()) {
5546 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005547 const auto *LHSVar = cast<VarDecl>(LHS->getDecl());
5548 const auto *RHSVar = cast<VarDecl>(RHS->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005549 EmitOMPAggregateReduction(
5550 CGF, PrivateRef->getType(), LHSVar, RHSVar,
5551 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5552 emitReductionCombiner(CGF, ReductionOp);
5553 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005554 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005555 // Emit reduction for array subscript or single variable.
5556 emitReductionCombiner(CGF, ReductionOp);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005557 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005558}
5559
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005560void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005561 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005562 ArrayRef<const Expr *> LHSExprs,
5563 ArrayRef<const Expr *> RHSExprs,
5564 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005565 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005566 if (!CGF.HaveInsertPoint())
5567 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005568
5569 bool WithNowait = Options.WithNowait;
5570 bool SimpleReduction = Options.SimpleReduction;
5571
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005572 // Next code should be emitted for reduction:
5573 //
5574 // static kmp_critical_name lock = { 0 };
5575 //
5576 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
5577 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
5578 // ...
5579 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
5580 // *(Type<n>-1*)rhs[<n>-1]);
5581 // }
5582 //
5583 // ...
5584 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
5585 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5586 // RedList, reduce_func, &<lock>)) {
5587 // case 1:
5588 // ...
5589 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5590 // ...
5591 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5592 // break;
5593 // case 2:
5594 // ...
5595 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5596 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00005597 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005598 // break;
5599 // default:;
5600 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005601 //
5602 // if SimpleReduction is true, only the next code is generated:
5603 // ...
5604 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5605 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005606
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005607 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005608
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005609 if (SimpleReduction) {
5610 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005611 auto IPriv = Privates.begin();
5612 auto ILHS = LHSExprs.begin();
5613 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005614 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005615 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5616 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005617 ++IPriv;
5618 ++ILHS;
5619 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005620 }
5621 return;
5622 }
5623
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005624 // 1. Build a list of reduction variables.
5625 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005626 auto Size = RHSExprs.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005627 for (const Expr *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005628 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005629 // Reserve place for array size.
5630 ++Size;
5631 }
5632 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005633 QualType ReductionArrayTy =
5634 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
5635 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00005636 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005637 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005638 auto IPriv = Privates.begin();
5639 unsigned Idx = 0;
5640 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00005641 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005642 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00005643 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005644 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00005645 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
5646 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005647 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005648 // Store array size.
5649 ++Idx;
5650 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
5651 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00005652 llvm::Value *Size = CGF.Builder.CreateIntCast(
5653 CGF.getVLASize(
5654 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
Sander de Smalen891af03a2018-02-03 13:55:59 +00005655 .NumElts,
Alexey Bataev1189bd02016-01-26 12:20:39 +00005656 CGF.SizeTy, /*isSigned=*/false);
5657 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
5658 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005659 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005660 }
5661
5662 // 2. Emit reduce_func().
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005663 llvm::Value *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005664 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
5665 Privates, LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005666
5667 // 3. Create static kmp_critical_name lock = { 0 };
Alexey Bataev18fa2322018-05-02 14:20:50 +00005668 std::string Name = getName({"reduction"});
5669 llvm::Value *Lock = getCriticalRegionLock(Name);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005670
5671 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5672 // RedList, reduce_func, &<lock>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005673 llvm::Value *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
5674 llvm::Value *ThreadId = getThreadID(CGF, Loc);
5675 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
5676 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Samuel Antao4c8035b2016-12-12 18:00:20 +00005677 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005678 llvm::Value *Args[] = {
5679 IdentTLoc, // ident_t *<loc>
5680 ThreadId, // i32 <gtid>
5681 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5682 ReductionArrayTySize, // size_type sizeof(RedList)
5683 RL, // void *RedList
5684 ReductionFn, // void (*) (void *, void *) <reduce_func>
5685 Lock // kmp_critical_name *&<lock>
5686 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005687 llvm::Value *Res = CGF.EmitRuntimeCall(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005688 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5689 : OMPRTL__kmpc_reduce),
5690 Args);
5691
5692 // 5. Build switch(res)
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005693 llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5694 llvm::SwitchInst *SwInst =
5695 CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005696
5697 // 6. Build case 1:
5698 // ...
5699 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5700 // ...
5701 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5702 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005703 llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005704 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5705 CGF.EmitBlock(Case1BB);
5706
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005707 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5708 llvm::Value *EndArgs[] = {
5709 IdentTLoc, // ident_t *<loc>
5710 ThreadId, // i32 <gtid>
5711 Lock // kmp_critical_name *&<lock>
5712 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005713 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps](
5714 CodeGenFunction &CGF, PrePostActionTy &Action) {
5715 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005716 auto IPriv = Privates.begin();
5717 auto ILHS = LHSExprs.begin();
5718 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005719 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005720 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5721 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005722 ++IPriv;
5723 ++ILHS;
5724 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005725 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005726 };
5727 RegionCodeGenTy RCG(CodeGen);
5728 CommonActionTy Action(
5729 nullptr, llvm::None,
5730 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5731 : OMPRTL__kmpc_end_reduce),
5732 EndArgs);
5733 RCG.setAction(Action);
5734 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005735
5736 CGF.EmitBranch(DefaultBB);
5737
5738 // 7. Build case 2:
5739 // ...
5740 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5741 // ...
5742 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005743 llvm::BasicBlock *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005744 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5745 CGF.EmitBlock(Case2BB);
5746
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005747 auto &&AtomicCodeGen = [Loc, Privates, LHSExprs, RHSExprs, ReductionOps](
5748 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005749 auto ILHS = LHSExprs.begin();
5750 auto IRHS = RHSExprs.begin();
5751 auto IPriv = Privates.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005752 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005753 const Expr *XExpr = nullptr;
5754 const Expr *EExpr = nullptr;
5755 const Expr *UpExpr = nullptr;
5756 BinaryOperatorKind BO = BO_Comma;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005757 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005758 if (BO->getOpcode() == BO_Assign) {
5759 XExpr = BO->getLHS();
5760 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005761 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005762 }
5763 // Try to emit update expression as a simple atomic.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005764 const Expr *RHSExpr = UpExpr;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005765 if (RHSExpr) {
5766 // Analyze RHS part of the whole expression.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005767 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005768 RHSExpr->IgnoreParenImpCasts())) {
5769 // If this is a conditional operator, analyze its condition for
5770 // min/max reduction operator.
5771 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005772 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005773 if (const auto *BORHS =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005774 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5775 EExpr = BORHS->getRHS();
5776 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005777 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005778 }
5779 if (XExpr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005780 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005781 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005782 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5783 const Expr *EExpr, const Expr *UpExpr) {
5784 LValue X = CGF.EmitLValue(XExpr);
5785 RValue E;
5786 if (EExpr)
5787 E = CGF.EmitAnyExpr(EExpr);
5788 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005789 X, E, BO, /*IsXLHSInRHSPart=*/true,
5790 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005791 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005792 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5793 PrivateScope.addPrivate(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005794 VD, [&CGF, VD, XRValue, Loc]() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005795 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5796 CGF.emitOMPSimpleStore(
5797 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5798 VD->getType().getNonReferenceType(), Loc);
5799 return LHSTemp;
5800 });
5801 (void)PrivateScope.Privatize();
5802 return CGF.EmitAnyExpr(UpExpr);
5803 });
5804 };
5805 if ((*IPriv)->getType()->isArrayType()) {
5806 // Emit atomic reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005807 const auto *RHSVar =
5808 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005809 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5810 AtomicRedGen, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005811 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005812 // Emit atomic reduction for array subscript or single variable.
5813 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005814 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005815 } else {
5816 // Emit as a critical region.
5817 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005818 const Expr *, const Expr *) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005819 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005820 std::string Name = RT.getName({"atomic_reduction"});
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005821 RT.emitCriticalRegion(
Alexey Bataev18fa2322018-05-02 14:20:50 +00005822 CGF, Name,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005823 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5824 Action.Enter(CGF);
5825 emitReductionCombiner(CGF, E);
5826 },
5827 Loc);
5828 };
5829 if ((*IPriv)->getType()->isArrayType()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005830 const auto *LHSVar =
5831 cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5832 const auto *RHSVar =
5833 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005834 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5835 CritRedGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005836 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005837 CritRedGen(CGF, nullptr, nullptr, nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005838 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005839 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005840 ++ILHS;
5841 ++IRHS;
5842 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005843 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005844 };
5845 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5846 if (!WithNowait) {
5847 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5848 llvm::Value *EndArgs[] = {
5849 IdentTLoc, // ident_t *<loc>
5850 ThreadId, // i32 <gtid>
5851 Lock // kmp_critical_name *&<lock>
5852 };
5853 CommonActionTy Action(nullptr, llvm::None,
5854 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5855 EndArgs);
5856 AtomicRCG.setAction(Action);
5857 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005858 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005859 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005860 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005861
5862 CGF.EmitBranch(DefaultBB);
5863 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5864}
5865
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005866/// Generates unique name for artificial threadprivate variables.
Alexey Bataev1c44e152018-03-06 18:59:43 +00005867/// Format is: <Prefix> "." <Decl_mangled_name> "_" "<Decl_start_loc_raw_enc>"
5868static std::string generateUniqueName(CodeGenModule &CGM, StringRef Prefix,
5869 const Expr *Ref) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005870 SmallString<256> Buffer;
5871 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev1c44e152018-03-06 18:59:43 +00005872 const clang::DeclRefExpr *DE;
5873 const VarDecl *D = ::getBaseDecl(Ref, DE);
5874 if (!D)
5875 D = cast<VarDecl>(cast<DeclRefExpr>(Ref)->getDecl());
5876 D = D->getCanonicalDecl();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005877 std::string Name = CGM.getOpenMPRuntime().getName(
5878 {D->isLocalVarDeclOrParm() ? D->getName() : CGM.getMangledName(D)});
5879 Out << Prefix << Name << "_"
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005880 << D->getCanonicalDecl()->getBeginLoc().getRawEncoding();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005881 return Out.str();
5882}
5883
5884/// Emits reduction initializer function:
5885/// \code
5886/// void @.red_init(void* %arg) {
5887/// %0 = bitcast void* %arg to <type>*
5888/// store <type> <init>, <type>* %0
5889/// ret void
5890/// }
5891/// \endcode
5892static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5893 SourceLocation Loc,
5894 ReductionCodeGen &RCG, unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005895 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005896 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005897 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5898 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005899 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005900 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005901 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005902 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005903 std::string Name = CGM.getOpenMPRuntime().getName({"red_init", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005904 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005905 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005906 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005907 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005908 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005909 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005910 Address PrivateAddr = CGF.EmitLoadOfPointer(
5911 CGF.GetAddrOfLocalVar(&Param),
5912 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5913 llvm::Value *Size = nullptr;
5914 // If the size of the reduction item is non-constant, load it from global
5915 // threadprivate variable.
5916 if (RCG.getSizes(N).second) {
5917 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5918 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005919 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005920 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5921 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005922 }
5923 RCG.emitAggregateType(CGF, N, Size);
5924 LValue SharedLVal;
5925 // If initializer uses initializer from declare reduction construct, emit a
5926 // pointer to the address of the original reduction item (reuired by reduction
5927 // initializer)
5928 if (RCG.usesReductionInitializer(N)) {
5929 Address SharedAddr =
5930 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5931 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00005932 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataev21dab122018-03-09 15:20:30 +00005933 SharedAddr = CGF.EmitLoadOfPointer(
5934 SharedAddr,
5935 CGM.getContext().VoidPtrTy.castAs<PointerType>()->getTypePtr());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005936 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5937 } else {
5938 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5939 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5940 CGM.getContext().VoidPtrTy);
5941 }
5942 // Emit the initializer:
5943 // %0 = bitcast void* %arg to <type>*
5944 // store <type> <init>, <type>* %0
5945 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5946 [](CodeGenFunction &) { return false; });
5947 CGF.FinishFunction();
5948 return Fn;
5949}
5950
5951/// Emits reduction combiner function:
5952/// \code
5953/// void @.red_comb(void* %arg0, void* %arg1) {
5954/// %lhs = bitcast void* %arg0 to <type>*
5955/// %rhs = bitcast void* %arg1 to <type>*
5956/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5957/// store <type> %2, <type>* %lhs
5958/// ret void
5959/// }
5960/// \endcode
5961static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5962 SourceLocation Loc,
5963 ReductionCodeGen &RCG, unsigned N,
5964 const Expr *ReductionOp,
5965 const Expr *LHS, const Expr *RHS,
5966 const Expr *PrivateRef) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005967 ASTContext &C = CGM.getContext();
5968 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5969 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005970 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005971 ImplicitParamDecl ParamInOut(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
5972 C.VoidPtrTy, ImplicitParamDecl::Other);
5973 ImplicitParamDecl ParamIn(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5974 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005975 Args.emplace_back(&ParamInOut);
5976 Args.emplace_back(&ParamIn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005977 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005978 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005979 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005980 std::string Name = CGM.getOpenMPRuntime().getName({"red_comb", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005981 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005982 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005983 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005984 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005985 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005986 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005987 llvm::Value *Size = nullptr;
5988 // If the size of the reduction item is non-constant, load it from global
5989 // threadprivate variable.
5990 if (RCG.getSizes(N).second) {
5991 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5992 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005993 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005994 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5995 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005996 }
5997 RCG.emitAggregateType(CGF, N, Size);
5998 // Remap lhs and rhs variables to the addresses of the function arguments.
5999 // %lhs = bitcast void* %arg0 to <type>*
6000 // %rhs = bitcast void* %arg1 to <type>*
6001 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006002 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006003 // Pull out the pointer to the variable.
6004 Address PtrAddr = CGF.EmitLoadOfPointer(
6005 CGF.GetAddrOfLocalVar(&ParamInOut),
6006 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
6007 return CGF.Builder.CreateElementBitCast(
6008 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
6009 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006010 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006011 // Pull out the pointer to the variable.
6012 Address PtrAddr = CGF.EmitLoadOfPointer(
6013 CGF.GetAddrOfLocalVar(&ParamIn),
6014 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
6015 return CGF.Builder.CreateElementBitCast(
6016 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
6017 });
6018 PrivateScope.Privatize();
6019 // Emit the combiner body:
6020 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
6021 // store <type> %2, <type>* %lhs
6022 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
6023 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
6024 cast<DeclRefExpr>(RHS));
6025 CGF.FinishFunction();
6026 return Fn;
6027}
6028
6029/// Emits reduction finalizer function:
6030/// \code
6031/// void @.red_fini(void* %arg) {
6032/// %0 = bitcast void* %arg to <type>*
6033/// <destroy>(<type>* %0)
6034/// ret void
6035/// }
6036/// \endcode
6037static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
6038 SourceLocation Loc,
6039 ReductionCodeGen &RCG, unsigned N) {
6040 if (!RCG.needCleanups(N))
6041 return nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006042 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006043 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00006044 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
6045 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006046 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006047 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006048 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006049 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00006050 std::string Name = CGM.getOpenMPRuntime().getName({"red_fini", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006051 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00006052 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00006053 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00006054 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006055 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00006056 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006057 Address PrivateAddr = CGF.EmitLoadOfPointer(
6058 CGF.GetAddrOfLocalVar(&Param),
6059 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
6060 llvm::Value *Size = nullptr;
6061 // If the size of the reduction item is non-constant, load it from global
6062 // threadprivate variable.
6063 if (RCG.getSizes(N).second) {
6064 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
6065 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00006066 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00006067 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
6068 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006069 }
6070 RCG.emitAggregateType(CGF, N, Size);
6071 // Emit the finalizer body:
6072 // <destroy>(<type>* %0)
6073 RCG.emitCleanups(CGF, N, PrivateAddr);
6074 CGF.FinishFunction();
6075 return Fn;
6076}
6077
6078llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
6079 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
6080 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
6081 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
6082 return nullptr;
6083
6084 // Build typedef struct:
6085 // kmp_task_red_input {
6086 // void *reduce_shar; // shared reduction item
6087 // size_t reduce_size; // size of data item
6088 // void *reduce_init; // data initialization routine
6089 // void *reduce_fini; // data finalization routine
6090 // void *reduce_comb; // data combiner routine
6091 // kmp_task_red_flags_t flags; // flags for additional info from compiler
6092 // } kmp_task_red_input_t;
6093 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006094 RecordDecl *RD = C.buildImplicitRecord("kmp_task_red_input_t");
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006095 RD->startDefinition();
6096 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6097 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
6098 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6099 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6100 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6101 const FieldDecl *FlagsFD = addFieldToRecordDecl(
6102 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
6103 RD->completeDefinition();
6104 QualType RDType = C.getRecordType(RD);
6105 unsigned Size = Data.ReductionVars.size();
6106 llvm::APInt ArraySize(/*numBits=*/64, Size);
6107 QualType ArrayRDType = C.getConstantArrayType(
6108 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
6109 // kmp_task_red_input_t .rd_input.[Size];
6110 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
6111 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
6112 Data.ReductionOps);
6113 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
6114 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
6115 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
6116 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
6117 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
6118 TaskRedInput.getPointer(), Idxs,
6119 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
6120 ".rd_input.gep.");
6121 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
6122 // ElemLVal.reduce_shar = &Shareds[Cnt];
6123 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
6124 RCG.emitSharedLValue(CGF, Cnt);
6125 llvm::Value *CastedShared =
6126 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
6127 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
6128 RCG.emitAggregateType(CGF, Cnt);
6129 llvm::Value *SizeValInChars;
6130 llvm::Value *SizeVal;
6131 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
6132 // We use delayed creation/initialization for VLAs, array sections and
6133 // custom reduction initializations. It is required because runtime does not
6134 // provide the way to pass the sizes of VLAs/array sections to
6135 // initializer/combiner/finalizer functions and does not pass the pointer to
6136 // original reduction item to the initializer. Instead threadprivate global
6137 // variables are used to store these values and use them in the functions.
6138 bool DelayedCreation = !!SizeVal;
6139 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
6140 /*isSigned=*/false);
6141 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
6142 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
6143 // ElemLVal.reduce_init = init;
6144 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
6145 llvm::Value *InitAddr =
6146 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
6147 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
6148 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
6149 // ElemLVal.reduce_fini = fini;
6150 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
6151 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
6152 llvm::Value *FiniAddr = Fini
6153 ? CGF.EmitCastToVoidPtr(Fini)
6154 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
6155 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
6156 // ElemLVal.reduce_comb = comb;
6157 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
6158 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
6159 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
6160 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
6161 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
6162 // ElemLVal.flags = 0;
6163 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
6164 if (DelayedCreation) {
6165 CGF.EmitStoreOfScalar(
6166 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
6167 FlagsLVal);
6168 } else
6169 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
6170 }
6171 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
6172 // *data);
6173 llvm::Value *Args[] = {
6174 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6175 /*isSigned=*/true),
6176 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
6177 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
6178 CGM.VoidPtrTy)};
6179 return CGF.EmitRuntimeCall(
6180 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
6181}
6182
6183void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
6184 SourceLocation Loc,
6185 ReductionCodeGen &RCG,
6186 unsigned N) {
6187 auto Sizes = RCG.getSizes(N);
6188 // Emit threadprivate global variable if the type is non-constant
6189 // (Sizes.second = nullptr).
6190 if (Sizes.second) {
6191 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
6192 /*isSigned=*/false);
6193 Address SizeAddr = getAddrOfArtificialThreadPrivate(
6194 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00006195 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006196 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
6197 }
6198 // Store address of the original reduction item if custom initializer is used.
6199 if (RCG.usesReductionInitializer(N)) {
6200 Address SharedAddr = getAddrOfArtificialThreadPrivate(
6201 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00006202 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006203 CGF.Builder.CreateStore(
6204 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6205 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
6206 SharedAddr, /*IsVolatile=*/false);
6207 }
6208}
6209
6210Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
6211 SourceLocation Loc,
6212 llvm::Value *ReductionsPtr,
6213 LValue SharedLVal) {
6214 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
6215 // *d);
6216 llvm::Value *Args[] = {
6217 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6218 /*isSigned=*/true),
6219 ReductionsPtr,
6220 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
6221 CGM.VoidPtrTy)};
6222 return Address(
6223 CGF.EmitRuntimeCall(
6224 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
6225 SharedLVal.getAlignment());
6226}
6227
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006228void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
6229 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006230 if (!CGF.HaveInsertPoint())
6231 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006232 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
6233 // global_tid);
6234 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
6235 // Ignore return result until untied tasks are supported.
6236 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00006237 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
6238 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006239}
6240
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006241void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006242 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006243 const RegionCodeGenTy &CodeGen,
6244 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006245 if (!CGF.HaveInsertPoint())
6246 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00006247 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006248 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00006249}
6250
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006251namespace {
6252enum RTCancelKind {
6253 CancelNoreq = 0,
6254 CancelParallel = 1,
6255 CancelLoop = 2,
6256 CancelSections = 3,
6257 CancelTaskgroup = 4
6258};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00006259} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006260
6261static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
6262 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00006263 if (CancelRegion == OMPD_parallel)
6264 CancelKind = CancelParallel;
6265 else if (CancelRegion == OMPD_for)
6266 CancelKind = CancelLoop;
6267 else if (CancelRegion == OMPD_sections)
6268 CancelKind = CancelSections;
6269 else {
6270 assert(CancelRegion == OMPD_taskgroup);
6271 CancelKind = CancelTaskgroup;
6272 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006273 return CancelKind;
6274}
6275
6276void CGOpenMPRuntime::emitCancellationPointCall(
6277 CodeGenFunction &CGF, SourceLocation Loc,
6278 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006279 if (!CGF.HaveInsertPoint())
6280 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006281 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
6282 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006283 if (auto *OMPRegionInfo =
6284 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00006285 // For 'cancellation point taskgroup', the task region info may not have a
6286 // cancel. This may instead happen in another adjacent task.
6287 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006288 llvm::Value *Args[] = {
6289 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
6290 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006291 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006292 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006293 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
6294 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006295 // exit from construct;
6296 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006297 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6298 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6299 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006300 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6301 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006302 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006303 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev25e5b442015-09-15 12:52:43 +00006304 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006305 CGF.EmitBranchThroughCleanup(CancelDest);
6306 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6307 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006308 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006309}
6310
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006311void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00006312 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006313 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006314 if (!CGF.HaveInsertPoint())
6315 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006316 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
6317 // kmp_int32 cncl_kind);
6318 if (auto *OMPRegionInfo =
6319 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006320 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
6321 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006322 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00006323 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006324 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00006325 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
6326 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006327 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006328 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00006329 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00006330 // exit from construct;
6331 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006332 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6333 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6334 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev87933c72015-09-18 08:07:34 +00006335 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6336 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00006337 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006338 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev87933c72015-09-18 08:07:34 +00006339 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
6340 CGF.EmitBranchThroughCleanup(CancelDest);
6341 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6342 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006343 if (IfCond) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006344 emitOMPIfClause(CGF, IfCond, ThenGen,
6345 [](CodeGenFunction &, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006346 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006347 RegionCodeGenTy ThenRCG(ThenGen);
6348 ThenRCG(CGF);
6349 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006350 }
6351}
Samuel Antaobed3c462015-10-02 16:14:20 +00006352
Samuel Antaoee8fb302016-01-06 13:42:12 +00006353void CGOpenMPRuntime::emitTargetOutlinedFunction(
6354 const OMPExecutableDirective &D, StringRef ParentName,
6355 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006356 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00006357 assert(!ParentName.empty() && "Invalid target region parent name!");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006358 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
6359 IsOffloadEntry, CodeGen);
6360}
6361
6362void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
6363 const OMPExecutableDirective &D, StringRef ParentName,
6364 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
6365 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00006366 // Create a unique name for the entry function using the source location
6367 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00006368 //
Samuel Antao2de62b02016-02-13 23:35:10 +00006369 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00006370 //
6371 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00006372 // mangled name of the function that encloses the target region and BB is the
6373 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00006374
6375 unsigned DeviceID;
6376 unsigned FileID;
6377 unsigned Line;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006378 getTargetEntryUniqueInfo(CGM.getContext(), D.getBeginLoc(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00006379 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006380 SmallString<64> EntryFnName;
6381 {
6382 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00006383 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
6384 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00006385 }
6386
Alexey Bataev475a7442018-01-12 19:39:11 +00006387 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006388
Samuel Antaobed3c462015-10-02 16:14:20 +00006389 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006390 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00006391 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006392
Samuel Antao6d004262016-06-16 18:39:34 +00006393 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006394
6395 // If this target outline function is not an offload entry, we don't need to
6396 // register it.
6397 if (!IsOffloadEntry)
6398 return;
6399
6400 // The target region ID is used by the runtime library to identify the current
6401 // target region, so it only has to be unique and not necessarily point to
6402 // anything. It could be the pointer to the outlined function that implements
6403 // the target region, but we aren't using that so that the compiler doesn't
6404 // need to keep that, and could therefore inline the host function if proven
6405 // worthwhile during optimization. In the other hand, if emitting code for the
6406 // device, the ID has to be the function address so that it can retrieved from
6407 // the offloading entry and launched by the runtime library. We also mark the
6408 // outlined function to have external linkage in case we are emitting code for
6409 // the device, because these functions will be entry points to the device.
6410
6411 if (CGM.getLangOpts().OpenMPIsDevice) {
6412 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
Alexey Bataev9a700172018-05-08 14:16:57 +00006413 OutlinedFn->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Rafael Espindolacbca4872018-01-11 22:15:12 +00006414 OutlinedFn->setDSOLocal(false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006415 } else {
Alexey Bataevc15ea702018-05-09 18:02:37 +00006416 std::string Name = getName({EntryFnName, "region_id"});
Samuel Antaoee8fb302016-01-06 13:42:12 +00006417 OutlinedFnID = new llvm::GlobalVariable(
6418 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
Alexey Bataev9a700172018-05-08 14:16:57 +00006419 llvm::GlobalValue::WeakAnyLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00006420 llvm::Constant::getNullValue(CGM.Int8Ty), Name);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006421 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00006422
6423 // Register the information for the entry associated with this target region.
6424 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00006425 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
Alexey Bataev03f270c2018-03-30 18:31:07 +00006426 OffloadEntriesInfoManagerTy::OMPTargetRegionEntryTargetRegion);
Samuel Antaobed3c462015-10-02 16:14:20 +00006427}
6428
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006429/// discard all CompoundStmts intervening between two constructs
6430static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006431 while (const auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006432 Body = CS->body_front();
6433
6434 return Body;
6435}
6436
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006437/// Emit the number of teams for a target directive. Inspect the num_teams
6438/// clause associated with a teams construct combined or closely nested
6439/// with the target directive.
6440///
6441/// Emit a team of size one for directives such as 'target parallel' that
6442/// have no associated teams construct.
6443///
6444/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006445static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006446emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6447 CodeGenFunction &CGF,
6448 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006449 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6450 "teams directive expected to be "
6451 "emitted only for the host!");
6452
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006453 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006454
6455 // If the target directive is combined with a teams directive:
6456 // Return the value in the num_teams clause, if any.
6457 // Otherwise, return 0 to denote the runtime default.
6458 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
6459 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
6460 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006461 llvm::Value *NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
6462 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006463 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6464 /*IsSigned=*/true);
6465 }
6466
6467 // The default value is 0.
6468 return Bld.getInt32(0);
6469 }
6470
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006471 // If the target directive is combined with a parallel directive but not a
6472 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006473 if (isOpenMPParallelDirective(D.getDirectiveKind()))
6474 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006475
6476 // If the current target region has a teams region enclosed, we need to get
6477 // the number of teams to pass to the runtime function call. This is done
6478 // by generating the expression in a inlined region. This is required because
6479 // the expression is captured in the enclosing target environment when the
6480 // teams directive is not combined with target.
6481
Alexey Bataev475a7442018-01-12 19:39:11 +00006482 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006483
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006484 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006485 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006486 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006487 if (const auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006488 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6489 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6490 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
6491 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6492 /*IsSigned=*/true);
6493 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006494
Alexey Bataev50a1c782017-12-01 21:31:08 +00006495 // If we have an enclosed teams directive but no num_teams clause we use
6496 // the default value 0.
6497 return Bld.getInt32(0);
6498 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006499 }
6500
6501 // No teams associated with the directive.
6502 return nullptr;
6503}
6504
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006505/// Emit the number of threads for a target directive. Inspect the
6506/// thread_limit clause associated with a teams construct combined or closely
6507/// nested with the target directive.
6508///
6509/// Emit the num_threads clause for directives such as 'target parallel' that
6510/// have no associated teams construct.
6511///
6512/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006513static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006514emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6515 CodeGenFunction &CGF,
6516 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006517 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6518 "teams directive expected to be "
6519 "emitted only for the host!");
6520
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006521 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006522
6523 //
6524 // If the target directive is combined with a teams directive:
6525 // Return the value in the thread_limit clause, if any.
6526 //
6527 // If the target directive is combined with a parallel directive:
6528 // Return the value in the num_threads clause, if any.
6529 //
6530 // If both clauses are set, select the minimum of the two.
6531 //
6532 // If neither teams or parallel combined directives set the number of threads
6533 // in a team, return 0 to denote the runtime default.
6534 //
6535 // If this is not a teams directive return nullptr.
6536
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006537 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
6538 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006539 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
6540 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006541 llvm::Value *ThreadLimitVal = nullptr;
6542
6543 if (const auto *ThreadLimitClause =
6544 D.getSingleClause<OMPThreadLimitClause>()) {
6545 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006546 llvm::Value *ThreadLimit =
6547 CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
6548 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006549 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6550 /*IsSigned=*/true);
6551 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006552
6553 if (const auto *NumThreadsClause =
6554 D.getSingleClause<OMPNumThreadsClause>()) {
6555 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
6556 llvm::Value *NumThreads =
6557 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
6558 /*IgnoreResultAssign*/ true);
6559 NumThreadsVal =
6560 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
6561 }
6562
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006563 // Select the lesser of thread_limit and num_threads.
6564 if (NumThreadsVal)
6565 ThreadLimitVal = ThreadLimitVal
6566 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
6567 ThreadLimitVal),
6568 NumThreadsVal, ThreadLimitVal)
6569 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00006570
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006571 // Set default value passed to the runtime if either teams or a target
6572 // parallel type directive is found but no clause is specified.
6573 if (!ThreadLimitVal)
6574 ThreadLimitVal = DefaultThreadLimitVal;
6575
6576 return ThreadLimitVal;
6577 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00006578
Samuel Antaob68e2db2016-03-03 16:20:23 +00006579 // If the current target region has a teams region enclosed, we need to get
6580 // the thread limit to pass to the runtime function call. This is done
6581 // by generating the expression in a inlined region. This is required because
6582 // the expression is captured in the enclosing target environment when the
6583 // teams directive is not combined with target.
6584
Alexey Bataev475a7442018-01-12 19:39:11 +00006585 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006586
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006587 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006588 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006589 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006590 if (const auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006591 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6592 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6593 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
6594 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6595 /*IsSigned=*/true);
6596 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006597
Alexey Bataev50a1c782017-12-01 21:31:08 +00006598 // If we have an enclosed teams directive but no thread_limit clause we
6599 // use the default value 0.
6600 return CGF.Builder.getInt32(0);
6601 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006602 }
6603
6604 // No teams associated with the directive.
6605 return nullptr;
6606}
6607
Samuel Antao86ace552016-04-27 22:40:57 +00006608namespace {
Alexey Bataevb3638132018-07-19 16:34:13 +00006609LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
6610
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006611// Utility to handle information from clauses associated with a given
Samuel Antao86ace552016-04-27 22:40:57 +00006612// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
6613// It provides a convenient interface to obtain the information and generate
6614// code for that information.
6615class MappableExprsHandler {
6616public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006617 /// Values for bit flags used to specify the mapping type for
Samuel Antao86ace552016-04-27 22:40:57 +00006618 /// offloading.
Alexey Bataevb3638132018-07-19 16:34:13 +00006619 enum OpenMPOffloadMappingFlags : uint64_t {
6620 /// No flags
6621 OMP_MAP_NONE = 0x0,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006622 /// Allocate memory on the device and move data from host to device.
Samuel Antao86ace552016-04-27 22:40:57 +00006623 OMP_MAP_TO = 0x01,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006624 /// Allocate memory on the device and move data from device to host.
Samuel Antao86ace552016-04-27 22:40:57 +00006625 OMP_MAP_FROM = 0x02,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006626 /// Always perform the requested mapping action on the element, even
Samuel Antao86ace552016-04-27 22:40:57 +00006627 /// if it was already mapped before.
6628 OMP_MAP_ALWAYS = 0x04,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006629 /// Delete the element from the device environment, ignoring the
Samuel Antao86ace552016-04-27 22:40:57 +00006630 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00006631 OMP_MAP_DELETE = 0x08,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006632 /// The element being mapped is a pointer-pointee pair; both the
George Rokos065755d2017-11-07 18:27:04 +00006633 /// pointer and the pointee should be mapped.
6634 OMP_MAP_PTR_AND_OBJ = 0x10,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006635 /// This flags signals that the base address of an entry should be
George Rokos065755d2017-11-07 18:27:04 +00006636 /// passed to the target kernel as an argument.
6637 OMP_MAP_TARGET_PARAM = 0x20,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006638 /// Signal that the runtime library has to return the device pointer
George Rokos065755d2017-11-07 18:27:04 +00006639 /// in the current position for the data being mapped. Used when we have the
6640 /// use_device_ptr clause.
6641 OMP_MAP_RETURN_PARAM = 0x40,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006642 /// This flag signals that the reference being passed is a pointer to
Samuel Antaod486f842016-05-26 16:53:38 +00006643 /// private data.
George Rokos065755d2017-11-07 18:27:04 +00006644 OMP_MAP_PRIVATE = 0x80,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006645 /// Pass the element to the device by value.
George Rokos065755d2017-11-07 18:27:04 +00006646 OMP_MAP_LITERAL = 0x100,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006647 /// Implicit map
6648 OMP_MAP_IMPLICIT = 0x200,
Alexey Bataevb3638132018-07-19 16:34:13 +00006649 /// The 16 MSBs of the flags indicate whether the entry is member of some
6650 /// struct/class.
6651 OMP_MAP_MEMBER_OF = 0xffff000000000000,
6652 LLVM_MARK_AS_BITMASK_ENUM(/* LargestFlag = */ OMP_MAP_MEMBER_OF),
Samuel Antao86ace552016-04-27 22:40:57 +00006653 };
6654
Samuel Antaocc10b852016-07-28 14:23:26 +00006655 /// Class that associates information with a base pointer to be passed to the
6656 /// runtime library.
6657 class BasePointerInfo {
6658 /// The base pointer.
6659 llvm::Value *Ptr = nullptr;
6660 /// The base declaration that refers to this device pointer, or null if
6661 /// there is none.
6662 const ValueDecl *DevPtrDecl = nullptr;
6663
6664 public:
6665 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
6666 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
6667 llvm::Value *operator*() const { return Ptr; }
6668 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
6669 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
6670 };
6671
Alexey Bataevb3638132018-07-19 16:34:13 +00006672 using MapBaseValuesArrayTy = SmallVector<BasePointerInfo, 4>;
6673 using MapValuesArrayTy = SmallVector<llvm::Value *, 4>;
6674 using MapFlagsArrayTy = SmallVector<OpenMPOffloadMappingFlags, 4>;
6675
6676 /// Map between a struct and the its lowest & highest elements which have been
6677 /// mapped.
6678 /// [ValueDecl *] --> {LE(FieldIndex, Pointer),
6679 /// HE(FieldIndex, Pointer)}
6680 struct StructRangeInfoTy {
6681 std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> LowestElem = {
6682 0, Address::invalid()};
6683 std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> HighestElem = {
6684 0, Address::invalid()};
6685 Address Base = Address::invalid();
6686 };
Samuel Antao86ace552016-04-27 22:40:57 +00006687
6688private:
Alexey Bataevb3638132018-07-19 16:34:13 +00006689 /// Kind that defines how a device pointer has to be returned.
6690 struct MapInfo {
6691 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
6692 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
Kelvin Lief579432018-12-18 22:18:41 +00006693 ArrayRef<OpenMPMapModifierKind> MapModifiers;
Alexey Bataevb3638132018-07-19 16:34:13 +00006694 bool ReturnDevicePointer = false;
6695 bool IsImplicit = false;
6696
6697 MapInfo() = default;
6698 MapInfo(
6699 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Kelvin Lief579432018-12-18 22:18:41 +00006700 OpenMPMapClauseKind MapType,
6701 ArrayRef<OpenMPMapModifierKind> MapModifiers,
Alexey Bataevb3638132018-07-19 16:34:13 +00006702 bool ReturnDevicePointer, bool IsImplicit)
Kelvin Lief579432018-12-18 22:18:41 +00006703 : Components(Components), MapType(MapType), MapModifiers(MapModifiers),
Alexey Bataevb3638132018-07-19 16:34:13 +00006704 ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
6705 };
6706
6707 /// If use_device_ptr is used on a pointer which is a struct member and there
6708 /// is no map information about it, then emission of that entry is deferred
6709 /// until the whole struct has been processed.
6710 struct DeferredDevicePtrEntryTy {
6711 const Expr *IE = nullptr;
6712 const ValueDecl *VD = nullptr;
6713
6714 DeferredDevicePtrEntryTy(const Expr *IE, const ValueDecl *VD)
6715 : IE(IE), VD(VD) {}
6716 };
6717
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006718 /// Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00006719 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00006720
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006721 /// Function the directive is being generated for.
Samuel Antao86ace552016-04-27 22:40:57 +00006722 CodeGenFunction &CGF;
6723
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006724 /// Set of all first private variables in the current directive.
Samuel Antaod486f842016-05-26 16:53:38 +00006725 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
6726
Samuel Antao6890b092016-07-28 14:25:09 +00006727 /// Map between device pointer declarations and their expression components.
6728 /// The key value for declarations in 'this' is null.
6729 llvm::DenseMap<
6730 const ValueDecl *,
6731 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6732 DevPointersMap;
6733
Samuel Antao86ace552016-04-27 22:40:57 +00006734 llvm::Value *getExprTypeSize(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006735 QualType ExprTy = E->getType().getCanonicalType();
Samuel Antao86ace552016-04-27 22:40:57 +00006736
6737 // Reference types are ignored for mapping purposes.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006738 if (const auto *RefTy = ExprTy->getAs<ReferenceType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006739 ExprTy = RefTy->getPointeeType().getCanonicalType();
6740
6741 // Given that an array section is considered a built-in type, we need to
6742 // do the calculation based on the length of the section instead of relying
6743 // on CGF.getTypeSize(E->getType()).
6744 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6745 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6746 OAE->getBase()->IgnoreParenImpCasts())
6747 .getCanonicalType();
6748
6749 // If there is no length associated with the expression, that means we
6750 // are using the whole length of the base.
6751 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6752 return CGF.getTypeSize(BaseTy);
6753
6754 llvm::Value *ElemSize;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006755 if (const auto *PTy = BaseTy->getAs<PointerType>()) {
Samuel Antao86ace552016-04-27 22:40:57 +00006756 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006757 } else {
6758 const auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
Samuel Antao86ace552016-04-27 22:40:57 +00006759 assert(ATy && "Expecting array type if not a pointer type.");
6760 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6761 }
6762
6763 // If we don't have a length at this point, that is because we have an
6764 // array section with a single element.
6765 if (!OAE->getLength())
6766 return ElemSize;
6767
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006768 llvm::Value *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
Samuel Antao86ace552016-04-27 22:40:57 +00006769 LengthVal =
6770 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6771 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6772 }
6773 return CGF.getTypeSize(ExprTy);
6774 }
6775
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006776 /// Return the corresponding bits for a given map clause modifier. Add
Samuel Antao86ace552016-04-27 22:40:57 +00006777 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006778 /// map as the first one of a series of maps that relate to the same map
6779 /// expression.
Kelvin Lief579432018-12-18 22:18:41 +00006780 OpenMPOffloadMappingFlags getMapTypeBits(
6781 OpenMPMapClauseKind MapType, ArrayRef<OpenMPMapModifierKind> MapModifiers,
6782 bool IsImplicit, bool AddPtrFlag, bool AddIsTargetParamFlag) const {
Alexey Bataevb3638132018-07-19 16:34:13 +00006783 OpenMPOffloadMappingFlags Bits =
6784 IsImplicit ? OMP_MAP_IMPLICIT : OMP_MAP_NONE;
Samuel Antao86ace552016-04-27 22:40:57 +00006785 switch (MapType) {
6786 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006787 case OMPC_MAP_release:
6788 // alloc and release is the default behavior in the runtime library, i.e.
6789 // if we don't pass any bits alloc/release that is what the runtime is
6790 // going to do. Therefore, we don't need to signal anything for these two
6791 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006792 break;
6793 case OMPC_MAP_to:
Alexey Bataevb3638132018-07-19 16:34:13 +00006794 Bits |= OMP_MAP_TO;
Samuel Antao86ace552016-04-27 22:40:57 +00006795 break;
6796 case OMPC_MAP_from:
Alexey Bataevb3638132018-07-19 16:34:13 +00006797 Bits |= OMP_MAP_FROM;
Samuel Antao86ace552016-04-27 22:40:57 +00006798 break;
6799 case OMPC_MAP_tofrom:
Alexey Bataevb3638132018-07-19 16:34:13 +00006800 Bits |= OMP_MAP_TO | OMP_MAP_FROM;
Samuel Antao86ace552016-04-27 22:40:57 +00006801 break;
6802 case OMPC_MAP_delete:
Alexey Bataevb3638132018-07-19 16:34:13 +00006803 Bits |= OMP_MAP_DELETE;
Samuel Antao86ace552016-04-27 22:40:57 +00006804 break;
Alexey Bataevb3638132018-07-19 16:34:13 +00006805 case OMPC_MAP_unknown:
Samuel Antao86ace552016-04-27 22:40:57 +00006806 llvm_unreachable("Unexpected map type!");
Samuel Antao86ace552016-04-27 22:40:57 +00006807 }
6808 if (AddPtrFlag)
George Rokos065755d2017-11-07 18:27:04 +00006809 Bits |= OMP_MAP_PTR_AND_OBJ;
6810 if (AddIsTargetParamFlag)
6811 Bits |= OMP_MAP_TARGET_PARAM;
Kelvin Lief579432018-12-18 22:18:41 +00006812 if (llvm::find(MapModifiers, OMPC_MAP_MODIFIER_always)
6813 != MapModifiers.end())
Samuel Antao86ace552016-04-27 22:40:57 +00006814 Bits |= OMP_MAP_ALWAYS;
6815 return Bits;
6816 }
6817
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006818 /// Return true if the provided expression is a final array section. A
Samuel Antao86ace552016-04-27 22:40:57 +00006819 /// final array section, is one whose length can't be proved to be one.
6820 bool isFinalArraySectionExpression(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006821 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antao86ace552016-04-27 22:40:57 +00006822
6823 // It is not an array section and therefore not a unity-size one.
6824 if (!OASE)
6825 return false;
6826
6827 // An array section with no colon always refer to a single element.
6828 if (OASE->getColonLoc().isInvalid())
6829 return false;
6830
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006831 const Expr *Length = OASE->getLength();
Samuel Antao86ace552016-04-27 22:40:57 +00006832
6833 // If we don't have a length we have to check if the array has size 1
6834 // for this dimension. Also, we should always expect a length if the
6835 // base type is pointer.
6836 if (!Length) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006837 QualType BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6838 OASE->getBase()->IgnoreParenImpCasts())
6839 .getCanonicalType();
6840 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antao86ace552016-04-27 22:40:57 +00006841 return ATy->getSize().getSExtValue() != 1;
6842 // If we don't have a constant dimension length, we have to consider
6843 // the current section as having any size, so it is not necessarily
6844 // unitary. If it happen to be unity size, that's user fault.
6845 return true;
6846 }
6847
6848 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +00006849 Expr::EvalResult Result;
6850 if (!Length->EvaluateAsInt(Result, CGF.getContext()))
Samuel Antao86ace552016-04-27 22:40:57 +00006851 return true; // Can have more that size 1.
6852
Fangrui Song407659a2018-11-30 23:41:18 +00006853 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antao86ace552016-04-27 22:40:57 +00006854 return ConstLength.getSExtValue() != 1;
6855 }
6856
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006857 /// Generate the base pointers, section pointers, sizes and map type
Samuel Antao86ace552016-04-27 22:40:57 +00006858 /// bits for the provided map type, map modifier, and expression components.
6859 /// \a IsFirstComponent should be set to true if the provided set of
6860 /// components is the first associated with a capture.
6861 void generateInfoForComponentList(
Kelvin Lief579432018-12-18 22:18:41 +00006862 OpenMPMapClauseKind MapType,
6863 ArrayRef<OpenMPMapModifierKind> MapModifiers,
Samuel Antao86ace552016-04-27 22:40:57 +00006864 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006865 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006866 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
Alexey Bataevb3638132018-07-19 16:34:13 +00006867 StructRangeInfoTy &PartialStruct, bool IsFirstComponentList,
Alexey Bataeve82445f2018-09-20 13:54:02 +00006868 bool IsImplicit,
6869 ArrayRef<OMPClauseMappableExprCommon::MappableExprComponentListRef>
6870 OverlappedElements = llvm::None) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006871 // The following summarizes what has to be generated for each map and the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006872 // types below. The generated information is expressed in this order:
Samuel Antao86ace552016-04-27 22:40:57 +00006873 // base pointer, section pointer, size, flags
6874 // (to add to the ones that come from the map type and modifier).
6875 //
6876 // double d;
6877 // int i[100];
6878 // float *p;
6879 //
6880 // struct S1 {
6881 // int i;
6882 // float f[50];
6883 // }
6884 // struct S2 {
6885 // int i;
6886 // float f[50];
6887 // S1 s;
6888 // double *p;
6889 // struct S2 *ps;
6890 // }
6891 // S2 s;
6892 // S2 *ps;
6893 //
6894 // map(d)
Alexey Bataevb3638132018-07-19 16:34:13 +00006895 // &d, &d, sizeof(double), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006896 //
6897 // map(i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006898 // &i, &i, 100*sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006899 //
6900 // map(i[1:23])
Alexey Bataevb3638132018-07-19 16:34:13 +00006901 // &i(=&i[0]), &i[1], 23*sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006902 //
6903 // map(p)
Alexey Bataevb3638132018-07-19 16:34:13 +00006904 // &p, &p, sizeof(float*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006905 //
6906 // map(p[1:24])
Alexey Bataevb3638132018-07-19 16:34:13 +00006907 // p, &p[1], 24*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006908 //
6909 // map(s)
Alexey Bataevb3638132018-07-19 16:34:13 +00006910 // &s, &s, sizeof(S2), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006911 //
6912 // map(s.i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006913 // &s, &(s.i), sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006914 //
6915 // map(s.s.f)
Alexey Bataevb3638132018-07-19 16:34:13 +00006916 // &s, &(s.s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006917 //
6918 // map(s.p)
Alexey Bataevb3638132018-07-19 16:34:13 +00006919 // &s, &(s.p), sizeof(double*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006920 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006921 // map(to: s.p[:22])
6922 // &s, &(s.p), sizeof(double*), TARGET_PARAM (*)
6923 // &s, &(s.p), sizeof(double*), MEMBER_OF(1) (**)
6924 // &(s.p), &(s.p[0]), 22*sizeof(double),
6925 // MEMBER_OF(1) | PTR_AND_OBJ | TO (***)
6926 // (*) alloc space for struct members, only this is a target parameter
6927 // (**) map the pointer (nothing to be mapped in this example) (the compiler
6928 // optimizes this entry out, same in the examples below)
6929 // (***) map the pointee (map: to)
Samuel Antao86ace552016-04-27 22:40:57 +00006930 //
6931 // map(s.ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006932 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006933 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006934 // map(from: s.ps->s.i)
6935 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6936 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6937 // &(s.ps), &(s.ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006938 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006939 // map(to: s.ps->ps)
6940 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6941 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6942 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006943 //
6944 // map(s.ps->ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006945 // &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->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006949 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006950 // map(to: s.ps->ps->s.f[:22])
6951 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6952 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6953 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6954 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006955 //
6956 // map(ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006957 // &ps, &ps, sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006958 //
6959 // map(ps->i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006960 // ps, &(ps->i), sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006961 //
6962 // map(ps->s.f)
Alexey Bataevb3638132018-07-19 16:34:13 +00006963 // ps, &(ps->s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006964 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006965 // map(from: ps->p)
6966 // ps, &(ps->p), sizeof(double*), TARGET_PARAM | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006967 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006968 // map(to: ps->p[:22])
6969 // ps, &(ps->p), sizeof(double*), TARGET_PARAM
6970 // ps, &(ps->p), sizeof(double*), MEMBER_OF(1)
6971 // &(ps->p), &(ps->p[0]), 22*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006972 //
6973 // map(ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006974 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006975 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006976 // map(from: ps->ps->s.i)
6977 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6978 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6979 // &(ps->ps), &(ps->ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006980 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006981 // map(from: ps->ps->ps)
6982 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6983 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6984 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006985 //
6986 // map(ps->ps->ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006987 // 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->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006991 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006992 // map(to: ps->ps->ps->s.f[:22])
6993 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6994 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6995 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6996 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO
6997 //
6998 // map(to: s.f[:22]) map(from: s.p[:33])
6999 // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1) +
7000 // sizeof(double*) (**), TARGET_PARAM
7001 // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | TO
7002 // &s, &(s.p), sizeof(double*), MEMBER_OF(1)
7003 // &(s.p), &(s.p[0]), 33*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | FROM
7004 // (*) allocate contiguous space needed to fit all mapped members even if
7005 // we allocate space for members not mapped (in this example,
7006 // s.f[22..49] and s.s are not mapped, yet we must allocate space for
7007 // them as well because they fall between &s.f[0] and &s.p)
7008 //
7009 // map(from: s.f[:22]) map(to: ps->p[:33])
7010 // &s, &(s.f[0]), 22*sizeof(float), TARGET_PARAM | FROM
7011 // ps, &(ps->p), sizeof(S2*), TARGET_PARAM
7012 // ps, &(ps->p), sizeof(double*), MEMBER_OF(2) (*)
7013 // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(2) | PTR_AND_OBJ | TO
7014 // (*) the struct this entry pertains to is the 2nd element in the list of
7015 // arguments, hence MEMBER_OF(2)
7016 //
7017 // map(from: s.f[:22], s.s) map(to: ps->p[:33])
7018 // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1), TARGET_PARAM
7019 // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | FROM
7020 // &s, &(s.s), sizeof(struct S1), MEMBER_OF(1) | FROM
7021 // ps, &(ps->p), sizeof(S2*), TARGET_PARAM
7022 // ps, &(ps->p), sizeof(double*), MEMBER_OF(4) (*)
7023 // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(4) | PTR_AND_OBJ | TO
7024 // (*) the struct this entry pertains to is the 4th element in the list
7025 // of arguments, hence MEMBER_OF(4)
Samuel Antao86ace552016-04-27 22:40:57 +00007026
7027 // Track if the map information being generated is the first for a capture.
7028 bool IsCaptureFirstInfo = IsFirstComponentList;
Alexey Bataev92327c52018-03-26 16:40:55 +00007029 bool IsLink = false; // Is this variable a "declare target link"?
Samuel Antao86ace552016-04-27 22:40:57 +00007030
7031 // Scan the components from the base to the complete expression.
7032 auto CI = Components.rbegin();
7033 auto CE = Components.rend();
7034 auto I = CI;
7035
7036 // Track if the map information being generated is the first for a list of
7037 // components.
7038 bool IsExpressionFirstInfo = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00007039 Address BP = Address::invalid();
Patrick Lystere13b1e32019-01-02 19:28:48 +00007040 const Expr *AssocExpr = I->getAssociatedExpression();
7041 const auto *AE = dyn_cast<ArraySubscriptExpr>(AssocExpr);
7042 const auto *OASE = dyn_cast<OMPArraySectionExpr>(AssocExpr);
Samuel Antao86ace552016-04-27 22:40:57 +00007043
Patrick Lystere13b1e32019-01-02 19:28:48 +00007044 if (isa<MemberExpr>(AssocExpr)) {
Samuel Antao86ace552016-04-27 22:40:57 +00007045 // The base is the 'this' pointer. The content of the pointer is going
7046 // to be the base of the field being mapped.
Alexey Bataevb3638132018-07-19 16:34:13 +00007047 BP = CGF.LoadCXXThisAddress();
Patrick Lystere13b1e32019-01-02 19:28:48 +00007048 } else if ((AE && isa<CXXThisExpr>(AE->getBase()->IgnoreParenImpCasts())) ||
7049 (OASE &&
7050 isa<CXXThisExpr>(OASE->getBase()->IgnoreParenImpCasts()))) {
7051 BP = CGF.EmitOMPSharedLValue(AssocExpr).getAddress();
Samuel Antao86ace552016-04-27 22:40:57 +00007052 } else {
7053 // The base is the reference to the variable.
7054 // BP = &Var.
Patrick Lystere13b1e32019-01-02 19:28:48 +00007055 BP = CGF.EmitOMPSharedLValue(AssocExpr).getAddress();
Alexey Bataev92327c52018-03-26 16:40:55 +00007056 if (const auto *VD =
7057 dyn_cast_or_null<VarDecl>(I->getAssociatedDeclaration())) {
7058 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00007059 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataev2c1dffe2018-04-16 20:34:41 +00007060 if (*Res == OMPDeclareTargetDeclAttr::MT_Link) {
7061 IsLink = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00007062 BP = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
Alexey Bataev2c1dffe2018-04-16 20:34:41 +00007063 }
Alexey Bataev92327c52018-03-26 16:40:55 +00007064 }
Samuel Antao86ace552016-04-27 22:40:57 +00007065
7066 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00007067 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00007068 // reference. References are ignored for mapping purposes.
7069 QualType Ty =
7070 I->getAssociatedDeclaration()->getType().getNonReferenceType();
7071 if (Ty->isAnyPointerType() && std::next(I) != CE) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007072 BP = CGF.EmitLoadOfPointer(BP, Ty->castAs<PointerType>());
Samuel Antao86ace552016-04-27 22:40:57 +00007073
7074 // We do not need to generate individual map information for the
7075 // pointer, it can be associated with the combined storage.
7076 ++I;
7077 }
7078 }
7079
Alexey Bataevb3638132018-07-19 16:34:13 +00007080 // Track whether a component of the list should be marked as MEMBER_OF some
7081 // combined entry (for partial structs). Only the first PTR_AND_OBJ entry
7082 // in a component list should be marked as MEMBER_OF, all subsequent entries
7083 // do not belong to the base struct. E.g.
7084 // struct S2 s;
7085 // s.ps->ps->ps->f[:]
7086 // (1) (2) (3) (4)
7087 // ps(1) is a member pointer, ps(2) is a pointee of ps(1), so it is a
7088 // PTR_AND_OBJ entry; the PTR is ps(1), so MEMBER_OF the base struct. ps(3)
7089 // is the pointee of ps(2) which is not member of struct s, so it should not
7090 // be marked as such (it is still PTR_AND_OBJ).
7091 // The variable is initialized to false so that PTR_AND_OBJ entries which
7092 // are not struct members are not considered (e.g. array of pointers to
7093 // data).
7094 bool ShouldBeMemberOf = false;
7095
7096 // Variable keeping track of whether or not we have encountered a component
7097 // in the component list which is a member expression. Useful when we have a
7098 // pointer or a final array section, in which case it is the previous
7099 // component in the list which tells us whether we have a member expression.
7100 // E.g. X.f[:]
7101 // While processing the final array section "[:]" it is "f" which tells us
7102 // whether we are dealing with a member of a declared struct.
7103 const MemberExpr *EncounteredME = nullptr;
7104
Samuel Antao86ace552016-04-27 22:40:57 +00007105 for (; I != CE; ++I) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007106 // If the current component is member of a struct (parent struct) mark it.
7107 if (!EncounteredME) {
7108 EncounteredME = dyn_cast<MemberExpr>(I->getAssociatedExpression());
7109 // If we encounter a PTR_AND_OBJ entry from now on it should be marked
7110 // as MEMBER_OF the parent struct.
7111 if (EncounteredME)
7112 ShouldBeMemberOf = true;
7113 }
7114
Samuel Antao86ace552016-04-27 22:40:57 +00007115 auto Next = std::next(I);
7116
7117 // We need to generate the addresses and sizes if this is the last
7118 // component, if the component is a pointer or if it is an array section
7119 // whose length can't be proved to be one. If this is a pointer, it
7120 // becomes the base address for the following components.
7121
7122 // A final array section, is one whose length can't be proved to be one.
7123 bool IsFinalArraySection =
7124 isFinalArraySectionExpression(I->getAssociatedExpression());
7125
7126 // Get information on whether the element is a pointer. Have to do a
7127 // special treatment for array sections given that they are built-in
7128 // types.
7129 const auto *OASE =
7130 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
7131 bool IsPointer =
Alexey Bataevb3638132018-07-19 16:34:13 +00007132 (OASE && OMPArraySectionExpr::getBaseOriginalType(OASE)
7133 .getCanonicalType()
7134 ->isAnyPointerType()) ||
Samuel Antao86ace552016-04-27 22:40:57 +00007135 I->getAssociatedExpression()->getType()->isAnyPointerType();
7136
7137 if (Next == CE || IsPointer || IsFinalArraySection) {
Samuel Antao86ace552016-04-27 22:40:57 +00007138 // If this is not the last component, we expect the pointer to be
7139 // associated with an array expression or member expression.
7140 assert((Next == CE ||
7141 isa<MemberExpr>(Next->getAssociatedExpression()) ||
7142 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
7143 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
7144 "Unexpected expression");
7145
Alexey Bataevb3638132018-07-19 16:34:13 +00007146 Address LB =
7147 CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getAddress();
Samuel Antao86ace552016-04-27 22:40:57 +00007148
Alexey Bataevb3638132018-07-19 16:34:13 +00007149 // If this component is a pointer inside the base struct then we don't
7150 // need to create any entry for it - it will be combined with the object
7151 // it is pointing to into a single PTR_AND_OBJ entry.
7152 bool IsMemberPointer =
7153 IsPointer && EncounteredME &&
7154 (dyn_cast<MemberExpr>(I->getAssociatedExpression()) ==
7155 EncounteredME);
Alexey Bataeve82445f2018-09-20 13:54:02 +00007156 if (!OverlappedElements.empty()) {
7157 // Handle base element with the info for overlapped elements.
7158 assert(!PartialStruct.Base.isValid() && "The base element is set.");
7159 assert(Next == CE &&
7160 "Expected last element for the overlapped elements.");
7161 assert(!IsPointer &&
7162 "Unexpected base element with the pointer type.");
7163 // Mark the whole struct as the struct that requires allocation on the
7164 // device.
7165 PartialStruct.LowestElem = {0, LB};
7166 CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(
7167 I->getAssociatedExpression()->getType());
7168 Address HB = CGF.Builder.CreateConstGEP(
7169 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(LB,
7170 CGF.VoidPtrTy),
7171 TypeSize.getQuantity() - 1, CharUnits::One());
7172 PartialStruct.HighestElem = {
7173 std::numeric_limits<decltype(
7174 PartialStruct.HighestElem.first)>::max(),
7175 HB};
7176 PartialStruct.Base = BP;
7177 // Emit data for non-overlapped data.
7178 OpenMPOffloadMappingFlags Flags =
7179 OMP_MAP_MEMBER_OF |
Kelvin Lief579432018-12-18 22:18:41 +00007180 getMapTypeBits(MapType, MapModifiers, IsImplicit,
Alexey Bataeve82445f2018-09-20 13:54:02 +00007181 /*AddPtrFlag=*/false,
7182 /*AddIsTargetParamFlag=*/false);
7183 LB = BP;
7184 llvm::Value *Size = nullptr;
7185 // Do bitcopy of all non-overlapped structure elements.
7186 for (OMPClauseMappableExprCommon::MappableExprComponentListRef
7187 Component : OverlappedElements) {
7188 Address ComponentLB = Address::invalid();
7189 for (const OMPClauseMappableExprCommon::MappableComponent &MC :
7190 Component) {
7191 if (MC.getAssociatedDeclaration()) {
7192 ComponentLB =
7193 CGF.EmitOMPSharedLValue(MC.getAssociatedExpression())
7194 .getAddress();
7195 Size = CGF.Builder.CreatePtrDiff(
7196 CGF.EmitCastToVoidPtr(ComponentLB.getPointer()),
7197 CGF.EmitCastToVoidPtr(LB.getPointer()));
7198 break;
7199 }
7200 }
7201 BasePointers.push_back(BP.getPointer());
7202 Pointers.push_back(LB.getPointer());
7203 Sizes.push_back(Size);
7204 Types.push_back(Flags);
7205 LB = CGF.Builder.CreateConstGEP(ComponentLB, 1,
7206 CGF.getPointerSize());
7207 }
7208 BasePointers.push_back(BP.getPointer());
7209 Pointers.push_back(LB.getPointer());
7210 Size = CGF.Builder.CreatePtrDiff(
7211 CGF.EmitCastToVoidPtr(
7212 CGF.Builder.CreateConstGEP(HB, 1, CharUnits::One())
7213 .getPointer()),
7214 CGF.EmitCastToVoidPtr(LB.getPointer()));
7215 Sizes.push_back(Size);
7216 Types.push_back(Flags);
7217 break;
7218 }
7219 llvm::Value *Size = getExprTypeSize(I->getAssociatedExpression());
Alexey Bataevb3638132018-07-19 16:34:13 +00007220 if (!IsMemberPointer) {
7221 BasePointers.push_back(BP.getPointer());
7222 Pointers.push_back(LB.getPointer());
7223 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00007224
Alexey Bataevb3638132018-07-19 16:34:13 +00007225 // We need to add a pointer flag for each map that comes from the
7226 // same expression except for the first one. We also need to signal
7227 // this map is the first one that relates with the current capture
7228 // (there is a set of entries for each capture).
7229 OpenMPOffloadMappingFlags Flags = getMapTypeBits(
Kelvin Lief579432018-12-18 22:18:41 +00007230 MapType, MapModifiers, IsImplicit,
Alexey Bataevb3638132018-07-19 16:34:13 +00007231 !IsExpressionFirstInfo || IsLink, IsCaptureFirstInfo && !IsLink);
7232
7233 if (!IsExpressionFirstInfo) {
7234 // If we have a PTR_AND_OBJ pair where the OBJ is a pointer as well,
7235 // then we reset the TO/FROM/ALWAYS/DELETE flags.
7236 if (IsPointer)
7237 Flags &= ~(OMP_MAP_TO | OMP_MAP_FROM | OMP_MAP_ALWAYS |
7238 OMP_MAP_DELETE);
7239
7240 if (ShouldBeMemberOf) {
7241 // Set placeholder value MEMBER_OF=FFFF to indicate that the flag
7242 // should be later updated with the correct value of MEMBER_OF.
7243 Flags |= OMP_MAP_MEMBER_OF;
7244 // From now on, all subsequent PTR_AND_OBJ entries should not be
7245 // marked as MEMBER_OF.
7246 ShouldBeMemberOf = false;
7247 }
7248 }
7249
7250 Types.push_back(Flags);
Samuel Antao03a3cec2016-07-27 22:52:16 +00007251 }
7252
Alexey Bataevb3638132018-07-19 16:34:13 +00007253 // If we have encountered a member expression so far, keep track of the
7254 // mapped member. If the parent is "*this", then the value declaration
7255 // is nullptr.
7256 if (EncounteredME) {
7257 const auto *FD = dyn_cast<FieldDecl>(EncounteredME->getMemberDecl());
7258 unsigned FieldIndex = FD->getFieldIndex();
Samuel Antao03a3cec2016-07-27 22:52:16 +00007259
Alexey Bataevb3638132018-07-19 16:34:13 +00007260 // Update info about the lowest and highest elements for this struct
7261 if (!PartialStruct.Base.isValid()) {
7262 PartialStruct.LowestElem = {FieldIndex, LB};
7263 PartialStruct.HighestElem = {FieldIndex, LB};
7264 PartialStruct.Base = BP;
7265 } else if (FieldIndex < PartialStruct.LowestElem.first) {
7266 PartialStruct.LowestElem = {FieldIndex, LB};
7267 } else if (FieldIndex > PartialStruct.HighestElem.first) {
7268 PartialStruct.HighestElem = {FieldIndex, LB};
7269 }
7270 }
Samuel Antao86ace552016-04-27 22:40:57 +00007271
7272 // If we have a final array section, we are done with this expression.
7273 if (IsFinalArraySection)
7274 break;
7275
7276 // The pointer becomes the base for the next element.
7277 if (Next != CE)
7278 BP = LB;
7279
7280 IsExpressionFirstInfo = false;
7281 IsCaptureFirstInfo = false;
Samuel Antao86ace552016-04-27 22:40:57 +00007282 }
7283 }
7284 }
7285
Alexey Bataevb3638132018-07-19 16:34:13 +00007286 /// Return the adjusted map modifiers if the declaration a capture refers to
7287 /// appears in a first-private clause. This is expected to be used only with
7288 /// directives that start with 'target'.
7289 MappableExprsHandler::OpenMPOffloadMappingFlags
7290 getMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap) const {
7291 assert(Cap.capturesVariable() && "Expected capture by reference only!");
7292
7293 // A first private variable captured by reference will use only the
7294 // 'private ptr' and 'map to' flag. Return the right flags if the captured
7295 // declaration is known as first-private in this handler.
7296 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
7297 return MappableExprsHandler::OMP_MAP_PRIVATE |
7298 MappableExprsHandler::OMP_MAP_TO;
7299 return MappableExprsHandler::OMP_MAP_TO |
7300 MappableExprsHandler::OMP_MAP_FROM;
7301 }
7302
7303 static OpenMPOffloadMappingFlags getMemberOfFlag(unsigned Position) {
7304 // Member of is given by the 16 MSB of the flag, so rotate by 48 bits.
7305 return static_cast<OpenMPOffloadMappingFlags>(((uint64_t)Position + 1)
7306 << 48);
7307 }
7308
7309 static void setCorrectMemberOfFlag(OpenMPOffloadMappingFlags &Flags,
7310 OpenMPOffloadMappingFlags MemberOfFlag) {
7311 // If the entry is PTR_AND_OBJ but has not been marked with the special
7312 // placeholder value 0xFFFF in the MEMBER_OF field, then it should not be
7313 // marked as MEMBER_OF.
7314 if ((Flags & OMP_MAP_PTR_AND_OBJ) &&
7315 ((Flags & OMP_MAP_MEMBER_OF) != OMP_MAP_MEMBER_OF))
7316 return;
7317
7318 // Reset the placeholder value to prepare the flag for the assignment of the
7319 // proper MEMBER_OF value.
7320 Flags &= ~OMP_MAP_MEMBER_OF;
7321 Flags |= MemberOfFlag;
7322 }
7323
Alexey Bataeve82445f2018-09-20 13:54:02 +00007324 void getPlainLayout(const CXXRecordDecl *RD,
7325 llvm::SmallVectorImpl<const FieldDecl *> &Layout,
7326 bool AsBase) const {
7327 const CGRecordLayout &RL = CGF.getTypes().getCGRecordLayout(RD);
7328
7329 llvm::StructType *St =
7330 AsBase ? RL.getBaseSubobjectLLVMType() : RL.getLLVMType();
7331
7332 unsigned NumElements = St->getNumElements();
7333 llvm::SmallVector<
7334 llvm::PointerUnion<const CXXRecordDecl *, const FieldDecl *>, 4>
7335 RecordLayout(NumElements);
7336
7337 // Fill bases.
7338 for (const auto &I : RD->bases()) {
7339 if (I.isVirtual())
7340 continue;
7341 const auto *Base = I.getType()->getAsCXXRecordDecl();
7342 // Ignore empty bases.
7343 if (Base->isEmpty() || CGF.getContext()
7344 .getASTRecordLayout(Base)
7345 .getNonVirtualSize()
7346 .isZero())
7347 continue;
7348
7349 unsigned FieldIndex = RL.getNonVirtualBaseLLVMFieldNo(Base);
7350 RecordLayout[FieldIndex] = Base;
7351 }
7352 // Fill in virtual bases.
7353 for (const auto &I : RD->vbases()) {
7354 const auto *Base = I.getType()->getAsCXXRecordDecl();
7355 // Ignore empty bases.
7356 if (Base->isEmpty())
7357 continue;
7358 unsigned FieldIndex = RL.getVirtualBaseIndex(Base);
7359 if (RecordLayout[FieldIndex])
7360 continue;
7361 RecordLayout[FieldIndex] = Base;
7362 }
7363 // Fill in all the fields.
7364 assert(!RD->isUnion() && "Unexpected union.");
7365 for (const auto *Field : RD->fields()) {
7366 // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
7367 // will fill in later.)
7368 if (!Field->isBitField()) {
7369 unsigned FieldIndex = RL.getLLVMFieldNo(Field);
7370 RecordLayout[FieldIndex] = Field;
7371 }
7372 }
7373 for (const llvm::PointerUnion<const CXXRecordDecl *, const FieldDecl *>
7374 &Data : RecordLayout) {
7375 if (Data.isNull())
7376 continue;
7377 if (const auto *Base = Data.dyn_cast<const CXXRecordDecl *>())
7378 getPlainLayout(Base, Layout, /*AsBase=*/true);
7379 else
7380 Layout.push_back(Data.get<const FieldDecl *>());
7381 }
7382 }
7383
Alexey Bataevb3638132018-07-19 16:34:13 +00007384public:
7385 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
7386 : CurDir(Dir), CGF(CGF) {
7387 // Extract firstprivate clause information.
7388 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
7389 for (const auto *D : C->varlists())
7390 FirstPrivateDecls.insert(
7391 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
7392 // Extract device pointer clause information.
7393 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
7394 for (auto L : C->component_lists())
7395 DevPointersMap[L.first].push_back(L.second);
7396 }
7397
7398 /// Generate code for the combined entry if we have a partially mapped struct
7399 /// and take care of the mapping flags of the arguments corresponding to
7400 /// individual struct members.
7401 void emitCombinedEntry(MapBaseValuesArrayTy &BasePointers,
7402 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7403 MapFlagsArrayTy &Types, MapFlagsArrayTy &CurTypes,
7404 const StructRangeInfoTy &PartialStruct) const {
7405 // Base is the base of the struct
7406 BasePointers.push_back(PartialStruct.Base.getPointer());
7407 // Pointer is the address of the lowest element
7408 llvm::Value *LB = PartialStruct.LowestElem.second.getPointer();
7409 Pointers.push_back(LB);
7410 // Size is (addr of {highest+1} element) - (addr of lowest element)
7411 llvm::Value *HB = PartialStruct.HighestElem.second.getPointer();
7412 llvm::Value *HAddr = CGF.Builder.CreateConstGEP1_32(HB, /*Idx0=*/1);
7413 llvm::Value *CLAddr = CGF.Builder.CreatePointerCast(LB, CGF.VoidPtrTy);
7414 llvm::Value *CHAddr = CGF.Builder.CreatePointerCast(HAddr, CGF.VoidPtrTy);
7415 llvm::Value *Diff = CGF.Builder.CreatePtrDiff(CHAddr, CLAddr);
7416 llvm::Value *Size = CGF.Builder.CreateIntCast(Diff, CGF.SizeTy,
7417 /*isSinged=*/false);
7418 Sizes.push_back(Size);
7419 // Map type is always TARGET_PARAM
7420 Types.push_back(OMP_MAP_TARGET_PARAM);
7421 // Remove TARGET_PARAM flag from the first element
7422 (*CurTypes.begin()) &= ~OMP_MAP_TARGET_PARAM;
7423
7424 // All other current entries will be MEMBER_OF the combined entry
7425 // (except for PTR_AND_OBJ entries which do not have a placeholder value
7426 // 0xFFFF in the MEMBER_OF field).
7427 OpenMPOffloadMappingFlags MemberOfFlag =
7428 getMemberOfFlag(BasePointers.size() - 1);
7429 for (auto &M : CurTypes)
7430 setCorrectMemberOfFlag(M, MemberOfFlag);
7431 }
7432
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007433 /// Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00007434 /// types for the extracted mappable expressions. Also, for each item that
7435 /// relates with a device pointer, a pair of the relevant declaration and
7436 /// index where it occurs is appended to the device pointers info array.
7437 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007438 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7439 MapFlagsArrayTy &Types) const {
Samuel Antao86ace552016-04-27 22:40:57 +00007440 // We have to process the component lists that relate with the same
7441 // declaration in a single chunk so that we can generate the map flags
7442 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00007443 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00007444
7445 // Helper function to fill the information map for the different supported
7446 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00007447 auto &&InfoGen = [&Info](
7448 const ValueDecl *D,
7449 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
Kelvin Lief579432018-12-18 22:18:41 +00007450 OpenMPMapClauseKind MapType,
7451 ArrayRef<OpenMPMapModifierKind> MapModifiers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007452 bool ReturnDevicePointer, bool IsImplicit) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007453 const ValueDecl *VD =
7454 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Kelvin Lief579432018-12-18 22:18:41 +00007455 Info[VD].emplace_back(L, MapType, MapModifiers, ReturnDevicePointer,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007456 IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007457 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00007458
Paul Robinson78fb1322016-08-01 22:12:46 +00007459 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007460 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
7461 for (const auto &L : C->component_lists()) {
Kelvin Lief579432018-12-18 22:18:41 +00007462 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifiers(),
Alexey Bataevb3638132018-07-19 16:34:13 +00007463 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007464 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007465 for (const auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
7466 for (const auto &L : C->component_lists()) {
Kelvin Lief579432018-12-18 22:18:41 +00007467 InfoGen(L.first, L.second, OMPC_MAP_to, llvm::None,
Alexey Bataevb3638132018-07-19 16:34:13 +00007468 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007469 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007470 for (const auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
7471 for (const auto &L : C->component_lists()) {
Kelvin Lief579432018-12-18 22:18:41 +00007472 InfoGen(L.first, L.second, OMPC_MAP_from, llvm::None,
Alexey Bataevb3638132018-07-19 16:34:13 +00007473 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007474 }
Samuel Antao86ace552016-04-27 22:40:57 +00007475
Samuel Antaocc10b852016-07-28 14:23:26 +00007476 // Look at the use_device_ptr clause information and mark the existing map
7477 // entries as such. If there is no map information for an entry in the
7478 // use_device_ptr list, we create one with map type 'alloc' and zero size
Alexey Bataevb3638132018-07-19 16:34:13 +00007479 // section. It is the user fault if that was not mapped before. If there is
7480 // no map information and the pointer is a struct member, then we defer the
7481 // emission of that entry until the whole struct has been processed.
7482 llvm::MapVector<const ValueDecl *, SmallVector<DeferredDevicePtrEntryTy, 4>>
7483 DeferredInfo;
7484
Paul Robinson78fb1322016-08-01 22:12:46 +00007485 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataevb3638132018-07-19 16:34:13 +00007486 for (const auto *C :
7487 this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007488 for (const auto &L : C->component_lists()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007489 assert(!L.second.empty() && "Not expecting empty list of components!");
7490 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
7491 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007492 const Expr *IE = L.second.back().getAssociatedExpression();
Samuel Antaocc10b852016-07-28 14:23:26 +00007493 // If the first component is a member expression, we have to look into
7494 // 'this', which maps to null in the map of map information. Otherwise
7495 // look directly for the information.
7496 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
7497
7498 // We potentially have map information for this declaration already.
7499 // Look for the first set of components that refer to it.
7500 if (It != Info.end()) {
7501 auto CI = std::find_if(
7502 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
7503 return MI.Components.back().getAssociatedDeclaration() == VD;
7504 });
7505 // If we found a map entry, signal that the pointer has to be returned
7506 // and move on to the next declaration.
7507 if (CI != It->second.end()) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007508 CI->ReturnDevicePointer = true;
Samuel Antaocc10b852016-07-28 14:23:26 +00007509 continue;
7510 }
7511 }
7512
7513 // We didn't find any match in our map information - generate a zero
Alexey Bataevb3638132018-07-19 16:34:13 +00007514 // size array section - if the pointer is a struct member we defer this
7515 // action until the whole struct has been processed.
Paul Robinson78fb1322016-08-01 22:12:46 +00007516 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Alexey Bataevb3638132018-07-19 16:34:13 +00007517 if (isa<MemberExpr>(IE)) {
7518 // Insert the pointer into Info to be processed by
7519 // generateInfoForComponentList. Because it is a member pointer
7520 // without a pointee, no entry will be generated for it, therefore
7521 // we need to generate one after the whole struct has been processed.
7522 // Nonetheless, generateInfoForComponentList must be called to take
7523 // the pointer into account for the calculation of the range of the
7524 // partial struct.
Kelvin Lief579432018-12-18 22:18:41 +00007525 InfoGen(nullptr, L.second, OMPC_MAP_unknown, llvm::None,
Alexey Bataevb3638132018-07-19 16:34:13 +00007526 /*ReturnDevicePointer=*/false, C->isImplicit());
7527 DeferredInfo[nullptr].emplace_back(IE, VD);
7528 } else {
7529 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(
7530 this->CGF.EmitLValue(IE), IE->getExprLoc());
7531 BasePointers.emplace_back(Ptr, VD);
7532 Pointers.push_back(Ptr);
7533 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
7534 Types.push_back(OMP_MAP_RETURN_PARAM | OMP_MAP_TARGET_PARAM);
7535 }
Samuel Antaocc10b852016-07-28 14:23:26 +00007536 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007537 }
Samuel Antaocc10b852016-07-28 14:23:26 +00007538
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007539 for (const auto &M : Info) {
Samuel Antao86ace552016-04-27 22:40:57 +00007540 // We need to know when we generate information for the first component
7541 // associated with a capture, because the mapping flags depend on it.
7542 bool IsFirstComponentList = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00007543
7544 // Temporary versions of arrays
7545 MapBaseValuesArrayTy CurBasePointers;
7546 MapValuesArrayTy CurPointers;
7547 MapValuesArrayTy CurSizes;
7548 MapFlagsArrayTy CurTypes;
7549 StructRangeInfoTy PartialStruct;
7550
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007551 for (const MapInfo &L : M.second) {
Samuel Antao86ace552016-04-27 22:40:57 +00007552 assert(!L.Components.empty() &&
7553 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00007554
7555 // Remember the current base pointer index.
Alexey Bataevb3638132018-07-19 16:34:13 +00007556 unsigned CurrentBasePointersIdx = CurBasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00007557 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007558 this->generateInfoForComponentList(
Kelvin Lief579432018-12-18 22:18:41 +00007559 L.MapType, L.MapModifiers, L.Components, CurBasePointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007560 CurPointers, CurSizes, CurTypes, PartialStruct,
7561 IsFirstComponentList, L.IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007562
7563 // If this entry relates with a device pointer, set the relevant
7564 // declaration and add the 'return pointer' flag.
Alexey Bataevb3638132018-07-19 16:34:13 +00007565 if (L.ReturnDevicePointer) {
7566 assert(CurBasePointers.size() > CurrentBasePointersIdx &&
Samuel Antaocc10b852016-07-28 14:23:26 +00007567 "Unexpected number of mapped base pointers.");
7568
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007569 const ValueDecl *RelevantVD =
7570 L.Components.back().getAssociatedDeclaration();
Samuel Antaocc10b852016-07-28 14:23:26 +00007571 assert(RelevantVD &&
7572 "No relevant declaration related with device pointer??");
7573
Alexey Bataevb3638132018-07-19 16:34:13 +00007574 CurBasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
7575 CurTypes[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PARAM;
Samuel Antaocc10b852016-07-28 14:23:26 +00007576 }
Samuel Antao86ace552016-04-27 22:40:57 +00007577 IsFirstComponentList = false;
7578 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007579
7580 // Append any pending zero-length pointers which are struct members and
7581 // used with use_device_ptr.
7582 auto CI = DeferredInfo.find(M.first);
7583 if (CI != DeferredInfo.end()) {
7584 for (const DeferredDevicePtrEntryTy &L : CI->second) {
7585 llvm::Value *BasePtr = this->CGF.EmitLValue(L.IE).getPointer();
7586 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(
7587 this->CGF.EmitLValue(L.IE), L.IE->getExprLoc());
7588 CurBasePointers.emplace_back(BasePtr, L.VD);
7589 CurPointers.push_back(Ptr);
7590 CurSizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
7591 // Entry is PTR_AND_OBJ and RETURN_PARAM. Also, set the placeholder
7592 // value MEMBER_OF=FFFF so that the entry is later updated with the
7593 // correct value of MEMBER_OF.
7594 CurTypes.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_RETURN_PARAM |
7595 OMP_MAP_MEMBER_OF);
7596 }
7597 }
7598
7599 // If there is an entry in PartialStruct it means we have a struct with
7600 // individual members mapped. Emit an extra combined entry.
7601 if (PartialStruct.Base.isValid())
7602 emitCombinedEntry(BasePointers, Pointers, Sizes, Types, CurTypes,
7603 PartialStruct);
7604
7605 // We need to append the results of this capture to what we already have.
7606 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
7607 Pointers.append(CurPointers.begin(), CurPointers.end());
7608 Sizes.append(CurSizes.begin(), CurSizes.end());
7609 Types.append(CurTypes.begin(), CurTypes.end());
Samuel Antao86ace552016-04-27 22:40:57 +00007610 }
7611 }
7612
Alexey Bataev60705422018-10-30 15:50:12 +00007613 /// Emit capture info for lambdas for variables captured by reference.
Alexey Bataev969dbc02018-11-08 15:47:39 +00007614 void generateInfoForLambdaCaptures(
7615 const ValueDecl *VD, llvm::Value *Arg, MapBaseValuesArrayTy &BasePointers,
7616 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7617 MapFlagsArrayTy &Types,
7618 llvm::DenseMap<llvm::Value *, llvm::Value *> &LambdaPointers) const {
Alexey Bataev60705422018-10-30 15:50:12 +00007619 const auto *RD = VD->getType()
7620 .getCanonicalType()
7621 .getNonReferenceType()
7622 ->getAsCXXRecordDecl();
7623 if (!RD || !RD->isLambda())
7624 return;
7625 Address VDAddr = Address(Arg, CGF.getContext().getDeclAlign(VD));
7626 LValue VDLVal = CGF.MakeAddrLValue(
7627 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
7628 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
7629 FieldDecl *ThisCapture = nullptr;
7630 RD->getCaptureFields(Captures, ThisCapture);
7631 if (ThisCapture) {
7632 LValue ThisLVal =
7633 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
Alexey Bataev969dbc02018-11-08 15:47:39 +00007634 LValue ThisLValVal = CGF.EmitLValueForField(VDLVal, ThisCapture);
7635 LambdaPointers.try_emplace(ThisLVal.getPointer(), VDLVal.getPointer());
7636 BasePointers.push_back(ThisLVal.getPointer());
7637 Pointers.push_back(ThisLValVal.getPointer());
Alexey Bataev60705422018-10-30 15:50:12 +00007638 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
Alexey Bataev2dc07d02018-11-02 15:25:06 +00007639 Types.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
Alexey Bataev60705422018-10-30 15:50:12 +00007640 OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT);
7641 }
7642 for (const LambdaCapture &LC : RD->captures()) {
7643 if (LC.getCaptureKind() != LCK_ByRef)
7644 continue;
7645 const VarDecl *VD = LC.getCapturedVar();
7646 auto It = Captures.find(VD);
7647 assert(It != Captures.end() && "Found lambda capture without field.");
7648 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
Alexey Bataev969dbc02018-11-08 15:47:39 +00007649 LValue VarLValVal = CGF.EmitLValueForField(VDLVal, It->second);
7650 LambdaPointers.try_emplace(VarLVal.getPointer(), VDLVal.getPointer());
7651 BasePointers.push_back(VarLVal.getPointer());
7652 Pointers.push_back(VarLValVal.getPointer());
Alexey Bataev60705422018-10-30 15:50:12 +00007653 Sizes.push_back(CGF.getTypeSize(
7654 VD->getType().getCanonicalType().getNonReferenceType()));
Alexey Bataev2dc07d02018-11-02 15:25:06 +00007655 Types.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
Alexey Bataev60705422018-10-30 15:50:12 +00007656 OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT);
7657 }
7658 }
7659
7660 /// Set correct indices for lambdas captures.
Alexey Bataev969dbc02018-11-08 15:47:39 +00007661 void adjustMemberOfForLambdaCaptures(
7662 const llvm::DenseMap<llvm::Value *, llvm::Value *> &LambdaPointers,
7663 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
7664 MapFlagsArrayTy &Types) const {
Alexey Bataev60705422018-10-30 15:50:12 +00007665 for (unsigned I = 0, E = Types.size(); I < E; ++I) {
7666 // Set correct member_of idx for all implicit lambda captures.
Alexey Bataev2dc07d02018-11-02 15:25:06 +00007667 if (Types[I] != (OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
Alexey Bataev60705422018-10-30 15:50:12 +00007668 OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT))
7669 continue;
Alexey Bataev969dbc02018-11-08 15:47:39 +00007670 llvm::Value *BasePtr = LambdaPointers.lookup(*BasePointers[I]);
7671 assert(BasePtr && "Unable to find base lambda address.");
Alexey Bataev60705422018-10-30 15:50:12 +00007672 int TgtIdx = -1;
7673 for (unsigned J = I; J > 0; --J) {
7674 unsigned Idx = J - 1;
7675 if (Pointers[Idx] != BasePtr)
7676 continue;
7677 TgtIdx = Idx;
7678 break;
7679 }
7680 assert(TgtIdx != -1 && "Unable to find parent lambda.");
7681 // All other current entries will be MEMBER_OF the combined entry
7682 // (except for PTR_AND_OBJ entries which do not have a placeholder value
7683 // 0xFFFF in the MEMBER_OF field).
7684 OpenMPOffloadMappingFlags MemberOfFlag = getMemberOfFlag(TgtIdx);
7685 setCorrectMemberOfFlag(Types[I], MemberOfFlag);
7686 }
7687 }
7688
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007689 /// Generate the base pointers, section pointers, sizes and map types
Samuel Antao86ace552016-04-27 22:40:57 +00007690 /// associated to a given capture.
7691 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00007692 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007693 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007694 MapValuesArrayTy &Pointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007695 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
7696 StructRangeInfoTy &PartialStruct) const {
Samuel Antao86ace552016-04-27 22:40:57 +00007697 assert(!Cap->capturesVariableArrayType() &&
7698 "Not expecting to generate map info for a variable array type!");
7699
Samuel Antao6890b092016-07-28 14:25:09 +00007700 // We need to know when we generating information for the first component
Alexey Bataevb3638132018-07-19 16:34:13 +00007701 const ValueDecl *VD = Cap->capturesThis()
7702 ? nullptr
7703 : Cap->getCapturedVar()->getCanonicalDecl();
Samuel Antao86ace552016-04-27 22:40:57 +00007704
Samuel Antao6890b092016-07-28 14:25:09 +00007705 // If this declaration appears in a is_device_ptr clause we just have to
7706 // pass the pointer by value. If it is a reference to a declaration, we just
Alexey Bataevb3638132018-07-19 16:34:13 +00007707 // pass its value.
7708 if (DevPointersMap.count(VD)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007709 BasePointers.emplace_back(Arg, VD);
Samuel Antao6890b092016-07-28 14:25:09 +00007710 Pointers.push_back(Arg);
7711 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
George Rokos065755d2017-11-07 18:27:04 +00007712 Types.push_back(OMP_MAP_LITERAL | OMP_MAP_TARGET_PARAM);
Samuel Antao6890b092016-07-28 14:25:09 +00007713 return;
7714 }
7715
Alexey Bataeve82445f2018-09-20 13:54:02 +00007716 using MapData =
7717 std::tuple<OMPClauseMappableExprCommon::MappableExprComponentListRef,
Kelvin Lief579432018-12-18 22:18:41 +00007718 OpenMPMapClauseKind, ArrayRef<OpenMPMapModifierKind>, bool>;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007719 SmallVector<MapData, 4> DeclComponentLists;
Paul Robinson78fb1322016-08-01 22:12:46 +00007720 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeve82445f2018-09-20 13:54:02 +00007721 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007722 for (const auto &L : C->decl_component_lists(VD)) {
Samuel Antao86ace552016-04-27 22:40:57 +00007723 assert(L.first == VD &&
7724 "We got information for the wrong declaration??");
7725 assert(!L.second.empty() &&
7726 "Not expecting declaration with no component lists.");
Alexey Bataeve82445f2018-09-20 13:54:02 +00007727 DeclComponentLists.emplace_back(L.second, C->getMapType(),
Kelvin Lief579432018-12-18 22:18:41 +00007728 C->getMapTypeModifiers(),
Alexey Bataeve82445f2018-09-20 13:54:02 +00007729 C->isImplicit());
Samuel Antao86ace552016-04-27 22:40:57 +00007730 }
Alexey Bataeve82445f2018-09-20 13:54:02 +00007731 }
7732
7733 // Find overlapping elements (including the offset from the base element).
7734 llvm::SmallDenseMap<
7735 const MapData *,
7736 llvm::SmallVector<
7737 OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>,
7738 4>
7739 OverlappedData;
7740 size_t Count = 0;
7741 for (const MapData &L : DeclComponentLists) {
7742 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7743 OpenMPMapClauseKind MapType;
Kelvin Lief579432018-12-18 22:18:41 +00007744 ArrayRef<OpenMPMapModifierKind> MapModifiers;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007745 bool IsImplicit;
Kelvin Lief579432018-12-18 22:18:41 +00007746 std::tie(Components, MapType, MapModifiers, IsImplicit) = L;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007747 ++Count;
7748 for (const MapData &L1 : makeArrayRef(DeclComponentLists).slice(Count)) {
7749 OMPClauseMappableExprCommon::MappableExprComponentListRef Components1;
Kelvin Lief579432018-12-18 22:18:41 +00007750 std::tie(Components1, MapType, MapModifiers, IsImplicit) = L1;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007751 auto CI = Components.rbegin();
7752 auto CE = Components.rend();
7753 auto SI = Components1.rbegin();
7754 auto SE = Components1.rend();
7755 for (; CI != CE && SI != SE; ++CI, ++SI) {
7756 if (CI->getAssociatedExpression()->getStmtClass() !=
7757 SI->getAssociatedExpression()->getStmtClass())
7758 break;
7759 // Are we dealing with different variables/fields?
7760 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
7761 break;
7762 }
7763 // Found overlapping if, at least for one component, reached the head of
7764 // the components list.
7765 if (CI == CE || SI == SE) {
7766 assert((CI != CE || SI != SE) &&
7767 "Unexpected full match of the mapping components.");
7768 const MapData &BaseData = CI == CE ? L : L1;
7769 OMPClauseMappableExprCommon::MappableExprComponentListRef SubData =
7770 SI == SE ? Components : Components1;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007771 auto &OverlappedElements = OverlappedData.FindAndConstruct(&BaseData);
7772 OverlappedElements.getSecond().push_back(SubData);
7773 }
7774 }
7775 }
7776 // Sort the overlapped elements for each item.
7777 llvm::SmallVector<const FieldDecl *, 4> Layout;
7778 if (!OverlappedData.empty()) {
7779 if (const auto *CRD =
7780 VD->getType().getCanonicalType()->getAsCXXRecordDecl())
7781 getPlainLayout(CRD, Layout, /*AsBase=*/false);
7782 else {
7783 const auto *RD = VD->getType().getCanonicalType()->getAsRecordDecl();
7784 Layout.append(RD->field_begin(), RD->field_end());
7785 }
7786 }
7787 for (auto &Pair : OverlappedData) {
7788 llvm::sort(
7789 Pair.getSecond(),
7790 [&Layout](
7791 OMPClauseMappableExprCommon::MappableExprComponentListRef First,
7792 OMPClauseMappableExprCommon::MappableExprComponentListRef
7793 Second) {
7794 auto CI = First.rbegin();
7795 auto CE = First.rend();
7796 auto SI = Second.rbegin();
7797 auto SE = Second.rend();
7798 for (; CI != CE && SI != SE; ++CI, ++SI) {
7799 if (CI->getAssociatedExpression()->getStmtClass() !=
7800 SI->getAssociatedExpression()->getStmtClass())
7801 break;
7802 // Are we dealing with different variables/fields?
7803 if (CI->getAssociatedDeclaration() !=
7804 SI->getAssociatedDeclaration())
7805 break;
7806 }
Richard Trieu5061e832018-09-21 21:20:33 +00007807
7808 // Lists contain the same elements.
7809 if (CI == CE && SI == SE)
7810 return false;
7811
7812 // List with less elements is less than list with more elements.
7813 if (CI == CE || SI == SE)
7814 return CI == CE;
7815
Alexey Bataeve82445f2018-09-20 13:54:02 +00007816 const auto *FD1 = cast<FieldDecl>(CI->getAssociatedDeclaration());
7817 const auto *FD2 = cast<FieldDecl>(SI->getAssociatedDeclaration());
7818 if (FD1->getParent() == FD2->getParent())
7819 return FD1->getFieldIndex() < FD2->getFieldIndex();
7820 const auto It =
7821 llvm::find_if(Layout, [FD1, FD2](const FieldDecl *FD) {
7822 return FD == FD1 || FD == FD2;
7823 });
7824 return *It == FD1;
7825 });
7826 }
7827
7828 // Associated with a capture, because the mapping flags depend on it.
7829 // Go through all of the elements with the overlapped elements.
7830 for (const auto &Pair : OverlappedData) {
7831 const MapData &L = *Pair.getFirst();
7832 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7833 OpenMPMapClauseKind MapType;
Kelvin Lief579432018-12-18 22:18:41 +00007834 ArrayRef<OpenMPMapModifierKind> MapModifiers;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007835 bool IsImplicit;
Kelvin Lief579432018-12-18 22:18:41 +00007836 std::tie(Components, MapType, MapModifiers, IsImplicit) = L;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007837 ArrayRef<OMPClauseMappableExprCommon::MappableExprComponentListRef>
7838 OverlappedComponents = Pair.getSecond();
7839 bool IsFirstComponentList = true;
Kelvin Lief579432018-12-18 22:18:41 +00007840 generateInfoForComponentList(MapType, MapModifiers, Components,
Alexey Bataeve82445f2018-09-20 13:54:02 +00007841 BasePointers, Pointers, Sizes, Types,
7842 PartialStruct, IsFirstComponentList,
7843 IsImplicit, OverlappedComponents);
7844 }
7845 // Go through other elements without overlapped elements.
7846 bool IsFirstComponentList = OverlappedData.empty();
7847 for (const MapData &L : DeclComponentLists) {
7848 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7849 OpenMPMapClauseKind MapType;
Kelvin Lief579432018-12-18 22:18:41 +00007850 ArrayRef<OpenMPMapModifierKind> MapModifiers;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007851 bool IsImplicit;
Kelvin Lief579432018-12-18 22:18:41 +00007852 std::tie(Components, MapType, MapModifiers, IsImplicit) = L;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007853 auto It = OverlappedData.find(&L);
7854 if (It == OverlappedData.end())
Kelvin Lief579432018-12-18 22:18:41 +00007855 generateInfoForComponentList(MapType, MapModifiers, Components,
Alexey Bataeve82445f2018-09-20 13:54:02 +00007856 BasePointers, Pointers, Sizes, Types,
7857 PartialStruct, IsFirstComponentList,
7858 IsImplicit);
7859 IsFirstComponentList = false;
7860 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007861 }
Samuel Antao86ace552016-04-27 22:40:57 +00007862
Alexey Bataevb3638132018-07-19 16:34:13 +00007863 /// Generate the base pointers, section pointers, sizes and map types
7864 /// associated with the declare target link variables.
7865 void generateInfoForDeclareTargetLink(MapBaseValuesArrayTy &BasePointers,
7866 MapValuesArrayTy &Pointers,
7867 MapValuesArrayTy &Sizes,
7868 MapFlagsArrayTy &Types) const {
7869 // Map other list items in the map clause which are not captured variables
7870 // but "declare target link" global variables.,
7871 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) {
7872 for (const auto &L : C->component_lists()) {
7873 if (!L.first)
7874 continue;
7875 const auto *VD = dyn_cast<VarDecl>(L.first);
7876 if (!VD)
7877 continue;
7878 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00007879 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataevb3638132018-07-19 16:34:13 +00007880 if (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link)
7881 continue;
7882 StructRangeInfoTy PartialStruct;
7883 generateInfoForComponentList(
Kelvin Lief579432018-12-18 22:18:41 +00007884 C->getMapType(), C->getMapTypeModifiers(), L.second, BasePointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007885 Pointers, Sizes, Types, PartialStruct,
7886 /*IsFirstComponentList=*/true, C->isImplicit());
7887 assert(!PartialStruct.Base.isValid() &&
7888 "No partial structs for declare target link expected.");
7889 }
7890 }
Samuel Antao86ace552016-04-27 22:40:57 +00007891 }
Samuel Antaod486f842016-05-26 16:53:38 +00007892
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007893 /// Generate the default map information for a given capture \a CI,
Samuel Antaod486f842016-05-26 16:53:38 +00007894 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00007895 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
7896 const FieldDecl &RI, llvm::Value *CV,
7897 MapBaseValuesArrayTy &CurBasePointers,
7898 MapValuesArrayTy &CurPointers,
7899 MapValuesArrayTy &CurSizes,
Alexey Bataevb3638132018-07-19 16:34:13 +00007900 MapFlagsArrayTy &CurMapTypes) const {
Samuel Antaod486f842016-05-26 16:53:38 +00007901 // Do the default mapping.
7902 if (CI.capturesThis()) {
7903 CurBasePointers.push_back(CV);
7904 CurPointers.push_back(CV);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007905 const auto *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007906 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
7907 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00007908 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00007909 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007910 CurBasePointers.push_back(CV);
7911 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00007912 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007913 // We have to signal to the runtime captures passed by value that are
7914 // not pointers.
George Rokos065755d2017-11-07 18:27:04 +00007915 CurMapTypes.push_back(OMP_MAP_LITERAL);
Samuel Antaod486f842016-05-26 16:53:38 +00007916 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
7917 } else {
7918 // Pointers are implicitly mapped with a zero size and no flags
7919 // (other than first map that is added for all implicit maps).
Alexey Bataevb3638132018-07-19 16:34:13 +00007920 CurMapTypes.push_back(OMP_MAP_NONE);
Samuel Antaod486f842016-05-26 16:53:38 +00007921 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
7922 }
7923 } else {
7924 assert(CI.capturesVariable() && "Expected captured reference.");
7925 CurBasePointers.push_back(CV);
7926 CurPointers.push_back(CV);
7927
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007928 const auto *PtrTy = cast<ReferenceType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007929 QualType ElementType = PtrTy->getPointeeType();
7930 CurSizes.push_back(CGF.getTypeSize(ElementType));
7931 // The default map type for a scalar/complex type is 'to' because by
7932 // default the value doesn't have to be retrieved. For an aggregate
7933 // type, the default is 'tofrom'.
Alexey Bataevb3638132018-07-19 16:34:13 +00007934 CurMapTypes.push_back(getMapModifiersForPrivateClauses(CI));
Samuel Antaod486f842016-05-26 16:53:38 +00007935 }
George Rokos065755d2017-11-07 18:27:04 +00007936 // Every default map produces a single argument which is a target parameter.
7937 CurMapTypes.back() |= OMP_MAP_TARGET_PARAM;
Alexey Bataevb3638132018-07-19 16:34:13 +00007938
7939 // Add flag stating this is an implicit map.
7940 CurMapTypes.back() |= OMP_MAP_IMPLICIT;
Samuel Antaod486f842016-05-26 16:53:38 +00007941 }
Samuel Antao86ace552016-04-27 22:40:57 +00007942};
Samuel Antaodf158d52016-04-27 22:58:19 +00007943
7944enum OpenMPOffloadingReservedDeviceIDs {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007945 /// Device ID if the device was not defined, runtime should get it
Samuel Antaodf158d52016-04-27 22:58:19 +00007946 /// from environment variables in the spec.
7947 OMP_DEVICEID_UNDEF = -1,
7948};
7949} // anonymous namespace
7950
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007951/// Emit the arrays used to pass the captures and map information to the
Samuel Antaodf158d52016-04-27 22:58:19 +00007952/// offloading runtime library. If there is no map or capture information,
7953/// return nullptr by reference.
7954static void
Samuel Antaocc10b852016-07-28 14:23:26 +00007955emitOffloadingArrays(CodeGenFunction &CGF,
7956 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00007957 MappableExprsHandler::MapValuesArrayTy &Pointers,
7958 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00007959 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
7960 CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007961 CodeGenModule &CGM = CGF.CGM;
7962 ASTContext &Ctx = CGF.getContext();
Samuel Antaodf158d52016-04-27 22:58:19 +00007963
Samuel Antaocc10b852016-07-28 14:23:26 +00007964 // Reset the array information.
7965 Info.clearArrayInfo();
7966 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00007967
Samuel Antaocc10b852016-07-28 14:23:26 +00007968 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007969 // Detect if we have any capture size requiring runtime evaluation of the
7970 // size so that a constant array could be eventually used.
7971 bool hasRuntimeEvaluationCaptureSize = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007972 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00007973 if (!isa<llvm::Constant>(S)) {
7974 hasRuntimeEvaluationCaptureSize = true;
7975 break;
7976 }
7977
Samuel Antaocc10b852016-07-28 14:23:26 +00007978 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00007979 QualType PointerArrayType =
7980 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
7981 /*IndexTypeQuals=*/0);
7982
Samuel Antaocc10b852016-07-28 14:23:26 +00007983 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007984 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00007985 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007986 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
7987
7988 // If we don't have any VLA types or other types that require runtime
7989 // evaluation, we can use a constant array for the map sizes, otherwise we
7990 // need to fill up the arrays as we do for the pointers.
7991 if (hasRuntimeEvaluationCaptureSize) {
7992 QualType SizeArrayType = Ctx.getConstantArrayType(
7993 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
7994 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00007995 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007996 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
7997 } else {
7998 // We expect all the sizes to be constant, so we collect them to create
7999 // a constant array.
8000 SmallVector<llvm::Constant *, 16> ConstSizes;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008001 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00008002 ConstSizes.push_back(cast<llvm::Constant>(S));
8003
8004 auto *SizesArrayInit = llvm::ConstantArray::get(
8005 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
Alexey Bataev18fa2322018-05-02 14:20:50 +00008006 std::string Name = CGM.getOpenMPRuntime().getName({"offload_sizes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00008007 auto *SizesArrayGbl = new llvm::GlobalVariable(
8008 CGM.getModule(), SizesArrayInit->getType(),
8009 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00008010 SizesArrayInit, Name);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00008011 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00008012 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00008013 }
8014
8015 // The map types are always constant so we don't need to generate code to
8016 // fill arrays. Instead, we create an array constant.
Alexey Bataevb3638132018-07-19 16:34:13 +00008017 SmallVector<uint64_t, 4> Mapping(MapTypes.size(), 0);
8018 llvm::copy(MapTypes, Mapping.begin());
Samuel Antaodf158d52016-04-27 22:58:19 +00008019 llvm::Constant *MapTypesArrayInit =
Alexey Bataevb3638132018-07-19 16:34:13 +00008020 llvm::ConstantDataArray::get(CGF.Builder.getContext(), Mapping);
Alexey Bataev18fa2322018-05-02 14:20:50 +00008021 std::string MaptypesName =
8022 CGM.getOpenMPRuntime().getName({"offload_maptypes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00008023 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
8024 CGM.getModule(), MapTypesArrayInit->getType(),
8025 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00008026 MapTypesArrayInit, MaptypesName);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00008027 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00008028 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00008029
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008030 for (unsigned I = 0; I < Info.NumberOfPtrs; ++I) {
8031 llvm::Value *BPVal = *BasePointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00008032 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008033 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008034 Info.BasePointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00008035 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
8036 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00008037 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
8038 CGF.Builder.CreateStore(BPVal, BPAddr);
8039
Samuel Antaocc10b852016-07-28 14:23:26 +00008040 if (Info.requiresDevicePointerInfo())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008041 if (const ValueDecl *DevVD = BasePointers[I].getDevicePtrDecl())
Alexey Bataev43a919f2018-04-13 17:48:43 +00008042 Info.CaptureDeviceAddrMap.try_emplace(DevVD, BPAddr);
Samuel Antaocc10b852016-07-28 14:23:26 +00008043
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008044 llvm::Value *PVal = Pointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00008045 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008046 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008047 Info.PointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00008048 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
8049 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00008050 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
8051 CGF.Builder.CreateStore(PVal, PAddr);
8052
8053 if (hasRuntimeEvaluationCaptureSize) {
8054 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008055 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
8056 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008057 /*Idx0=*/0,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008058 /*Idx1=*/I);
Samuel Antaodf158d52016-04-27 22:58:19 +00008059 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
8060 CGF.Builder.CreateStore(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008061 CGF.Builder.CreateIntCast(Sizes[I], CGM.SizeTy, /*isSigned=*/true),
Samuel Antaodf158d52016-04-27 22:58:19 +00008062 SAddr);
8063 }
8064 }
8065 }
8066}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008067/// Emit the arguments to be passed to the runtime library based on the
Samuel Antaodf158d52016-04-27 22:58:19 +00008068/// arrays of pointers, sizes and map types.
8069static void emitOffloadingArraysArgument(
8070 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
8071 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008072 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008073 CodeGenModule &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00008074 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008075 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008076 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
8077 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008078 /*Idx0=*/0, /*Idx1=*/0);
8079 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008080 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
8081 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008082 /*Idx0=*/0,
8083 /*Idx1=*/0);
8084 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008085 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008086 /*Idx0=*/0, /*Idx1=*/0);
8087 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
George Rokos63bc9d62017-11-21 18:25:12 +00008088 llvm::ArrayType::get(CGM.Int64Ty, Info.NumberOfPtrs),
Samuel Antaocc10b852016-07-28 14:23:26 +00008089 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008090 /*Idx0=*/0,
8091 /*Idx1=*/0);
8092 } else {
8093 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
8094 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
8095 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
8096 MapTypesArrayArg =
George Rokos63bc9d62017-11-21 18:25:12 +00008097 llvm::ConstantPointerNull::get(CGM.Int64Ty->getPointerTo());
Samuel Antaodf158d52016-04-27 22:58:19 +00008098 }
Samuel Antao86ace552016-04-27 22:40:57 +00008099}
8100
Alexey Bataev7bb33532019-01-07 21:30:43 +00008101/// Checks if the expression is constant or does not have non-trivial function
8102/// calls.
8103static bool isTrivial(ASTContext &Ctx, const Expr * E) {
8104 // We can skip constant expressions.
8105 // We can skip expressions with trivial calls or simple expressions.
8106 return (E->isEvaluatable(Ctx, Expr::SE_AllowUndefinedBehavior) ||
8107 !E->hasNonTrivialCall(Ctx)) &&
8108 !E->HasSideEffects(Ctx, /*IncludePossibleEffects=*/true);
8109}
8110
8111/// Checks if the \p Body is the \a CompoundStmt and returns its child statement
8112/// iff there is only one that is not evaluatable at the compile time.
8113static const Stmt *getSingleCompoundChild(ASTContext &Ctx, const Stmt *Body) {
8114 if (const auto *C = dyn_cast<CompoundStmt>(Body)) {
8115 const Stmt *Child = nullptr;
8116 for (const Stmt *S : C->body()) {
8117 if (const auto *E = dyn_cast<Expr>(S)) {
8118 if (isTrivial(Ctx, E))
8119 continue;
8120 }
8121 // Some of the statements can be ignored.
8122 if (isa<AsmStmt>(S) || isa<NullStmt>(S) || isa<OMPFlushDirective>(S) ||
8123 isa<OMPBarrierDirective>(S) || isa<OMPTaskyieldDirective>(S))
8124 continue;
8125 // Analyze declarations.
8126 if (const auto *DS = dyn_cast<DeclStmt>(S)) {
8127 if (llvm::all_of(DS->decls(), [&Ctx](const Decl *D) {
8128 if (isa<EmptyDecl>(D) || isa<DeclContext>(D) ||
8129 isa<TypeDecl>(D) || isa<PragmaCommentDecl>(D) ||
8130 isa<PragmaDetectMismatchDecl>(D) || isa<UsingDecl>(D) ||
8131 isa<UsingDirectiveDecl>(D) ||
8132 isa<OMPDeclareReductionDecl>(D) ||
8133 isa<OMPThreadPrivateDecl>(D))
8134 return true;
8135 const auto *VD = dyn_cast<VarDecl>(D);
8136 if (!VD)
8137 return false;
8138 return VD->isConstexpr() ||
8139 ((VD->getType().isTrivialType(Ctx) ||
8140 VD->getType()->isReferenceType()) &&
8141 (!VD->hasInit() || isTrivial(Ctx, VD->getInit())));
8142 }))
8143 continue;
8144 }
8145 // Found multiple children - cannot get the one child only.
8146 if (Child)
8147 return Body;
8148 Child = S;
8149 }
8150 if (Child)
8151 return Child;
8152 }
8153 return Body;
8154}
8155
8156/// Check for inner distribute directive.
8157static const OMPExecutableDirective *
8158getNestedDistributeDirective(ASTContext &Ctx, const OMPExecutableDirective &D) {
8159 const auto *CS = D.getInnermostCapturedStmt();
8160 const auto *Body =
8161 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
8162 const Stmt *ChildStmt = getSingleCompoundChild(Ctx, Body);
8163
8164 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
8165 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
8166 switch (D.getDirectiveKind()) {
8167 case OMPD_target:
8168 if (isOpenMPDistributeDirective(DKind))
8169 return NestedDir;
8170 if (DKind == OMPD_teams) {
8171 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
8172 /*IgnoreCaptured=*/true);
8173 if (!Body)
8174 return nullptr;
8175 ChildStmt = getSingleCompoundChild(Ctx, Body);
8176 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
8177 DKind = NND->getDirectiveKind();
8178 if (isOpenMPDistributeDirective(DKind))
8179 return NND;
8180 }
8181 }
8182 return nullptr;
8183 case OMPD_target_teams:
8184 if (isOpenMPDistributeDirective(DKind))
8185 return NestedDir;
8186 return nullptr;
8187 case OMPD_target_parallel:
8188 case OMPD_target_simd:
8189 case OMPD_target_parallel_for:
8190 case OMPD_target_parallel_for_simd:
8191 return nullptr;
8192 case OMPD_target_teams_distribute:
8193 case OMPD_target_teams_distribute_simd:
8194 case OMPD_target_teams_distribute_parallel_for:
8195 case OMPD_target_teams_distribute_parallel_for_simd:
8196 case OMPD_parallel:
8197 case OMPD_for:
8198 case OMPD_parallel_for:
8199 case OMPD_parallel_sections:
8200 case OMPD_for_simd:
8201 case OMPD_parallel_for_simd:
8202 case OMPD_cancel:
8203 case OMPD_cancellation_point:
8204 case OMPD_ordered:
8205 case OMPD_threadprivate:
8206 case OMPD_task:
8207 case OMPD_simd:
8208 case OMPD_sections:
8209 case OMPD_section:
8210 case OMPD_single:
8211 case OMPD_master:
8212 case OMPD_critical:
8213 case OMPD_taskyield:
8214 case OMPD_barrier:
8215 case OMPD_taskwait:
8216 case OMPD_taskgroup:
8217 case OMPD_atomic:
8218 case OMPD_flush:
8219 case OMPD_teams:
8220 case OMPD_target_data:
8221 case OMPD_target_exit_data:
8222 case OMPD_target_enter_data:
8223 case OMPD_distribute:
8224 case OMPD_distribute_simd:
8225 case OMPD_distribute_parallel_for:
8226 case OMPD_distribute_parallel_for_simd:
8227 case OMPD_teams_distribute:
8228 case OMPD_teams_distribute_simd:
8229 case OMPD_teams_distribute_parallel_for:
8230 case OMPD_teams_distribute_parallel_for_simd:
8231 case OMPD_target_update:
8232 case OMPD_declare_simd:
8233 case OMPD_declare_target:
8234 case OMPD_end_declare_target:
8235 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008236 case OMPD_declare_mapper:
Alexey Bataev7bb33532019-01-07 21:30:43 +00008237 case OMPD_taskloop:
8238 case OMPD_taskloop_simd:
8239 case OMPD_requires:
8240 case OMPD_unknown:
8241 llvm_unreachable("Unexpected directive.");
8242 }
8243 }
8244
8245 return nullptr;
8246}
8247
8248void CGOpenMPRuntime::emitTargetNumIterationsCall(
8249 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *Device,
8250 const llvm::function_ref<llvm::Value *(
8251 CodeGenFunction &CGF, const OMPLoopDirective &D)> &SizeEmitter) {
8252 OpenMPDirectiveKind Kind = D.getDirectiveKind();
8253 const OMPExecutableDirective *TD = &D;
8254 // Get nested teams distribute kind directive, if any.
8255 if (!isOpenMPDistributeDirective(Kind) || !isOpenMPTeamsDirective(Kind))
8256 TD = getNestedDistributeDirective(CGM.getContext(), D);
8257 if (!TD)
8258 return;
8259 const auto *LD = cast<OMPLoopDirective>(TD);
8260 auto &&CodeGen = [LD, &Device, &SizeEmitter, this](CodeGenFunction &CGF,
8261 PrePostActionTy &) {
8262 llvm::Value *NumIterations = SizeEmitter(CGF, *LD);
8263
8264 // Emit device ID if any.
8265 llvm::Value *DeviceID;
8266 if (Device)
8267 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
8268 CGF.Int64Ty, /*isSigned=*/true);
8269 else
8270 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8271
8272 llvm::Value *Args[] = {DeviceID, NumIterations};
8273 CGF.EmitRuntimeCall(
8274 createRuntimeFunction(OMPRTL__kmpc_push_target_tripcount), Args);
8275 };
8276 emitInlinedDirective(CGF, OMPD_unknown, CodeGen);
8277}
8278
Samuel Antaobed3c462015-10-02 16:14:20 +00008279void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
8280 const OMPExecutableDirective &D,
8281 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00008282 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00008283 const Expr *IfCond, const Expr *Device) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00008284 if (!CGF.HaveInsertPoint())
8285 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00008286
Samuel Antaoee8fb302016-01-06 13:42:12 +00008287 assert(OutlinedFn && "Invalid outlined function!");
8288
Alexey Bataev8451efa2018-01-15 19:06:12 +00008289 const bool RequiresOuterTask = D.hasClausesOfKind<OMPDependClause>();
8290 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Alexey Bataev475a7442018-01-12 19:39:11 +00008291 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008292 auto &&ArgsCodegen = [&CS, &CapturedVars](CodeGenFunction &CGF,
8293 PrePostActionTy &) {
8294 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
8295 };
8296 emitInlinedDirective(CGF, OMPD_unknown, ArgsCodegen);
Samuel Antao86ace552016-04-27 22:40:57 +00008297
Alexey Bataev8451efa2018-01-15 19:06:12 +00008298 CodeGenFunction::OMPTargetDataInfo InputInfo;
8299 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00008300 // Fill up the pointer arrays and transfer execution to the device.
Alexey Bataev8451efa2018-01-15 19:06:12 +00008301 auto &&ThenGen = [this, Device, OutlinedFn, OutlinedFnID, &D, &InputInfo,
8302 &MapTypesArray, &CS, RequiresOuterTask,
8303 &CapturedVars](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobed3c462015-10-02 16:14:20 +00008304 // On top of the arrays that were filled up, the target offloading call
8305 // takes as arguments the device id as well as the host pointer. The host
8306 // pointer is used by the runtime library to identify the current target
8307 // region, so it only has to be unique and not necessarily point to
8308 // anything. It could be the pointer to the outlined function that
8309 // implements the target region, but we aren't using that so that the
8310 // compiler doesn't need to keep that, and could therefore inline the host
8311 // function if proven worthwhile during optimization.
8312
Samuel Antaoee8fb302016-01-06 13:42:12 +00008313 // From this point on, we need to have an ID of the target region defined.
8314 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00008315
8316 // Emit device ID if any.
8317 llvm::Value *DeviceID;
George Rokos63bc9d62017-11-21 18:25:12 +00008318 if (Device) {
Samuel Antaobed3c462015-10-02 16:14:20 +00008319 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008320 CGF.Int64Ty, /*isSigned=*/true);
8321 } else {
8322 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8323 }
Samuel Antaobed3c462015-10-02 16:14:20 +00008324
Samuel Antaodf158d52016-04-27 22:58:19 +00008325 // Emit the number of elements in the offloading arrays.
Alexey Bataev8451efa2018-01-15 19:06:12 +00008326 llvm::Value *PointerNum =
8327 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaodf158d52016-04-27 22:58:19 +00008328
Samuel Antaob68e2db2016-03-03 16:20:23 +00008329 // Return value of the runtime offloading call.
8330 llvm::Value *Return;
8331
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008332 llvm::Value *NumTeams = emitNumTeamsForTargetDirective(*this, CGF, D);
8333 llvm::Value *NumThreads = emitNumThreadsForTargetDirective(*this, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00008334
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008335 bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008336 // The target region is an outlined function launched by the runtime
8337 // via calls __tgt_target() or __tgt_target_teams().
8338 //
8339 // __tgt_target() launches a target region with one team and one thread,
8340 // executing a serial region. This master thread may in turn launch
8341 // more threads within its team upon encountering a parallel region,
8342 // however, no additional teams can be launched on the device.
8343 //
8344 // __tgt_target_teams() launches a target region with one or more teams,
8345 // each with one or more threads. This call is required for target
8346 // constructs such as:
8347 // 'target teams'
8348 // 'target' / 'teams'
8349 // 'target teams distribute parallel for'
8350 // 'target parallel'
8351 // and so on.
8352 //
8353 // Note that on the host and CPU targets, the runtime implementation of
8354 // these calls simply call the outlined function without forking threads.
8355 // The outlined functions themselves have runtime calls to
8356 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
8357 // the compiler in emitTeamsCall() and emitParallelCall().
8358 //
8359 // In contrast, on the NVPTX target, the implementation of
8360 // __tgt_target_teams() launches a GPU kernel with the requested number
8361 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00008362 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008363 // If we have NumTeams defined this means that we have an enclosed teams
8364 // region. Therefore we also expect to have NumThreads defined. These two
8365 // values should be defined in the presence of a teams directive,
8366 // regardless of having any clauses associated. If the user is using teams
8367 // but no clauses, these two values will be the default that should be
8368 // passed to the runtime library - a 32-bit integer with the value zero.
8369 assert(NumThreads && "Thread limit expression should be available along "
8370 "with number of teams.");
Alexey Bataev8451efa2018-01-15 19:06:12 +00008371 llvm::Value *OffloadingArgs[] = {DeviceID,
8372 OutlinedFnID,
8373 PointerNum,
8374 InputInfo.BasePointersArray.getPointer(),
8375 InputInfo.PointersArray.getPointer(),
8376 InputInfo.SizesArray.getPointer(),
8377 MapTypesArray,
8378 NumTeams,
8379 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00008380 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00008381 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_teams_nowait
8382 : OMPRTL__tgt_target_teams),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008383 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00008384 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00008385 llvm::Value *OffloadingArgs[] = {DeviceID,
8386 OutlinedFnID,
8387 PointerNum,
8388 InputInfo.BasePointersArray.getPointer(),
8389 InputInfo.PointersArray.getPointer(),
8390 InputInfo.SizesArray.getPointer(),
8391 MapTypesArray};
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008392 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00008393 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_nowait
8394 : OMPRTL__tgt_target),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008395 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00008396 }
Samuel Antaobed3c462015-10-02 16:14:20 +00008397
Alexey Bataev2a007e02017-10-02 14:20:58 +00008398 // Check the error code and execute the host version if required.
8399 llvm::BasicBlock *OffloadFailedBlock =
8400 CGF.createBasicBlock("omp_offload.failed");
8401 llvm::BasicBlock *OffloadContBlock =
8402 CGF.createBasicBlock("omp_offload.cont");
8403 llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
8404 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
8405
8406 CGF.EmitBlock(OffloadFailedBlock);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008407 if (RequiresOuterTask) {
8408 CapturedVars.clear();
8409 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
8410 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008411 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars);
Alexey Bataev2a007e02017-10-02 14:20:58 +00008412 CGF.EmitBranch(OffloadContBlock);
8413
8414 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00008415 };
8416
Samuel Antaoee8fb302016-01-06 13:42:12 +00008417 // Notify that the host version must be executed.
Alexey Bataev8451efa2018-01-15 19:06:12 +00008418 auto &&ElseGen = [this, &D, OutlinedFn, &CS, &CapturedVars,
8419 RequiresOuterTask](CodeGenFunction &CGF,
8420 PrePostActionTy &) {
8421 if (RequiresOuterTask) {
8422 CapturedVars.clear();
8423 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
8424 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008425 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008426 };
8427
8428 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray,
8429 &CapturedVars, RequiresOuterTask,
8430 &CS](CodeGenFunction &CGF, PrePostActionTy &) {
8431 // Fill up the arrays with all the captured variables.
8432 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
8433 MappableExprsHandler::MapValuesArrayTy Pointers;
8434 MappableExprsHandler::MapValuesArrayTy Sizes;
8435 MappableExprsHandler::MapFlagsArrayTy MapTypes;
8436
Alexey Bataev8451efa2018-01-15 19:06:12 +00008437 // Get mappable expression information.
8438 MappableExprsHandler MEHandler(D, CGF);
Alexey Bataev969dbc02018-11-08 15:47:39 +00008439 llvm::DenseMap<llvm::Value *, llvm::Value *> LambdaPointers;
Alexey Bataev8451efa2018-01-15 19:06:12 +00008440
8441 auto RI = CS.getCapturedRecordDecl()->field_begin();
8442 auto CV = CapturedVars.begin();
8443 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
8444 CE = CS.capture_end();
8445 CI != CE; ++CI, ++RI, ++CV) {
Alexey Bataevb3638132018-07-19 16:34:13 +00008446 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
8447 MappableExprsHandler::MapValuesArrayTy CurPointers;
8448 MappableExprsHandler::MapValuesArrayTy CurSizes;
8449 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
8450 MappableExprsHandler::StructRangeInfoTy PartialStruct;
Alexey Bataev8451efa2018-01-15 19:06:12 +00008451
8452 // VLA sizes are passed to the outlined region by copy and do not have map
8453 // information associated.
8454 if (CI->capturesVariableArrayType()) {
8455 CurBasePointers.push_back(*CV);
8456 CurPointers.push_back(*CV);
8457 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
8458 // Copy to the device as an argument. No need to retrieve it.
8459 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_LITERAL |
8460 MappableExprsHandler::OMP_MAP_TARGET_PARAM);
8461 } else {
8462 // If we have any information in the map clause, we use it, otherwise we
8463 // just do a default mapping.
8464 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00008465 CurSizes, CurMapTypes, PartialStruct);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008466 if (CurBasePointers.empty())
8467 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
8468 CurPointers, CurSizes, CurMapTypes);
Alexey Bataev60705422018-10-30 15:50:12 +00008469 // Generate correct mapping for variables captured by reference in
8470 // lambdas.
8471 if (CI->capturesVariable())
Alexey Bataev969dbc02018-11-08 15:47:39 +00008472 MEHandler.generateInfoForLambdaCaptures(
8473 CI->getCapturedVar(), *CV, CurBasePointers, CurPointers, CurSizes,
8474 CurMapTypes, LambdaPointers);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008475 }
8476 // We expect to have at least an element of information for this capture.
8477 assert(!CurBasePointers.empty() &&
8478 "Non-existing map pointer for capture!");
8479 assert(CurBasePointers.size() == CurPointers.size() &&
8480 CurBasePointers.size() == CurSizes.size() &&
8481 CurBasePointers.size() == CurMapTypes.size() &&
8482 "Inconsistent map information sizes!");
8483
Alexey Bataevb3638132018-07-19 16:34:13 +00008484 // If there is an entry in PartialStruct it means we have a struct with
8485 // individual members mapped. Emit an extra combined entry.
8486 if (PartialStruct.Base.isValid())
8487 MEHandler.emitCombinedEntry(BasePointers, Pointers, Sizes, MapTypes,
8488 CurMapTypes, PartialStruct);
8489
Alexey Bataev8451efa2018-01-15 19:06:12 +00008490 // We need to append the results of this capture to what we already have.
8491 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
8492 Pointers.append(CurPointers.begin(), CurPointers.end());
8493 Sizes.append(CurSizes.begin(), CurSizes.end());
8494 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
8495 }
Alexey Bataev60705422018-10-30 15:50:12 +00008496 // Adjust MEMBER_OF flags for the lambdas captures.
Alexey Bataev969dbc02018-11-08 15:47:39 +00008497 MEHandler.adjustMemberOfForLambdaCaptures(LambdaPointers, BasePointers,
8498 Pointers, MapTypes);
Alexey Bataev92327c52018-03-26 16:40:55 +00008499 // Map other list items in the map clause which are not captured variables
8500 // but "declare target link" global variables.
Alexey Bataevb3638132018-07-19 16:34:13 +00008501 MEHandler.generateInfoForDeclareTargetLink(BasePointers, Pointers, Sizes,
8502 MapTypes);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008503
8504 TargetDataInfo Info;
8505 // Fill up the arrays and create the arguments.
8506 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
8507 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
8508 Info.PointersArray, Info.SizesArray,
8509 Info.MapTypesArray, Info);
8510 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
8511 InputInfo.BasePointersArray =
8512 Address(Info.BasePointersArray, CGM.getPointerAlign());
8513 InputInfo.PointersArray =
8514 Address(Info.PointersArray, CGM.getPointerAlign());
8515 InputInfo.SizesArray = Address(Info.SizesArray, CGM.getPointerAlign());
8516 MapTypesArray = Info.MapTypesArray;
8517 if (RequiresOuterTask)
8518 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
8519 else
8520 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
8521 };
8522
8523 auto &&TargetElseGen = [this, &ElseGen, &D, RequiresOuterTask](
8524 CodeGenFunction &CGF, PrePostActionTy &) {
8525 if (RequiresOuterTask) {
8526 CodeGenFunction::OMPTargetDataInfo InputInfo;
8527 CGF.EmitOMPTargetTaskBasedDirective(D, ElseGen, InputInfo);
8528 } else {
8529 emitInlinedDirective(CGF, D.getDirectiveKind(), ElseGen);
8530 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00008531 };
8532
8533 // If we have a target function ID it means that we need to support
8534 // offloading, otherwise, just execute on the host. We need to execute on host
8535 // regardless of the conditional in the if clause if, e.g., the user do not
8536 // specify target triples.
8537 if (OutlinedFnID) {
Alexey Bataev8451efa2018-01-15 19:06:12 +00008538 if (IfCond) {
8539 emitOMPIfClause(CGF, IfCond, TargetThenGen, TargetElseGen);
8540 } else {
8541 RegionCodeGenTy ThenRCG(TargetThenGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00008542 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00008543 }
8544 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00008545 RegionCodeGenTy ElseRCG(TargetElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00008546 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00008547 }
Samuel Antaobed3c462015-10-02 16:14:20 +00008548}
Samuel Antaoee8fb302016-01-06 13:42:12 +00008549
8550void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
8551 StringRef ParentName) {
8552 if (!S)
8553 return;
8554
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008555 // Codegen OMP target directives that offload compute to the device.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008556 bool RequiresDeviceCodegen =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008557 isa<OMPExecutableDirective>(S) &&
8558 isOpenMPTargetExecutionDirective(
8559 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00008560
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008561 if (RequiresDeviceCodegen) {
8562 const auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008563 unsigned DeviceID;
8564 unsigned FileID;
8565 unsigned Line;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008566 getTargetEntryUniqueInfo(CGM.getContext(), E.getBeginLoc(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00008567 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008568
8569 // Is this a target region that should not be emitted as an entry point? If
8570 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00008571 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
8572 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008573 return;
8574
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008575 switch (E.getDirectiveKind()) {
8576 case OMPD_target:
8577 CodeGenFunction::EmitOMPTargetDeviceFunction(CGM, ParentName,
8578 cast<OMPTargetDirective>(E));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008579 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008580 case OMPD_target_parallel:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00008581 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008582 CGM, ParentName, cast<OMPTargetParallelDirective>(E));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00008583 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008584 case OMPD_target_teams:
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00008585 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008586 CGM, ParentName, cast<OMPTargetTeamsDirective>(E));
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00008587 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008588 case OMPD_target_teams_distribute:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008589 CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008590 CGM, ParentName, cast<OMPTargetTeamsDistributeDirective>(E));
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008591 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008592 case OMPD_target_teams_distribute_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008593 CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008594 CGM, ParentName, cast<OMPTargetTeamsDistributeSimdDirective>(E));
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008595 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008596 case OMPD_target_parallel_for:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008597 CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008598 CGM, ParentName, cast<OMPTargetParallelForDirective>(E));
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008599 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008600 case OMPD_target_parallel_for_simd:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008601 CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008602 CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(E));
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008603 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008604 case OMPD_target_simd:
Alexey Bataevf8365372017-11-17 17:57:25 +00008605 CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008606 CGM, ParentName, cast<OMPTargetSimdDirective>(E));
Alexey Bataevf8365372017-11-17 17:57:25 +00008607 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008608 case OMPD_target_teams_distribute_parallel_for:
Carlo Bertolli52978c32018-01-03 21:12:44 +00008609 CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
8610 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008611 cast<OMPTargetTeamsDistributeParallelForDirective>(E));
Carlo Bertolli52978c32018-01-03 21:12:44 +00008612 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008613 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00008614 CodeGenFunction::
8615 EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
8616 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008617 cast<OMPTargetTeamsDistributeParallelForSimdDirective>(E));
Alexey Bataev647dd842018-01-15 20:59:40 +00008618 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008619 case OMPD_parallel:
8620 case OMPD_for:
8621 case OMPD_parallel_for:
8622 case OMPD_parallel_sections:
8623 case OMPD_for_simd:
8624 case OMPD_parallel_for_simd:
8625 case OMPD_cancel:
8626 case OMPD_cancellation_point:
8627 case OMPD_ordered:
8628 case OMPD_threadprivate:
8629 case OMPD_task:
8630 case OMPD_simd:
8631 case OMPD_sections:
8632 case OMPD_section:
8633 case OMPD_single:
8634 case OMPD_master:
8635 case OMPD_critical:
8636 case OMPD_taskyield:
8637 case OMPD_barrier:
8638 case OMPD_taskwait:
8639 case OMPD_taskgroup:
8640 case OMPD_atomic:
8641 case OMPD_flush:
8642 case OMPD_teams:
8643 case OMPD_target_data:
8644 case OMPD_target_exit_data:
8645 case OMPD_target_enter_data:
8646 case OMPD_distribute:
8647 case OMPD_distribute_simd:
8648 case OMPD_distribute_parallel_for:
8649 case OMPD_distribute_parallel_for_simd:
8650 case OMPD_teams_distribute:
8651 case OMPD_teams_distribute_simd:
8652 case OMPD_teams_distribute_parallel_for:
8653 case OMPD_teams_distribute_parallel_for_simd:
8654 case OMPD_target_update:
8655 case OMPD_declare_simd:
8656 case OMPD_declare_target:
8657 case OMPD_end_declare_target:
8658 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008659 case OMPD_declare_mapper:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008660 case OMPD_taskloop:
8661 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008662 case OMPD_requires:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008663 case OMPD_unknown:
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008664 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
8665 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00008666 return;
8667 }
8668
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008669 if (const auto *E = dyn_cast<OMPExecutableDirective>(S)) {
Alexey Bataev475a7442018-01-12 19:39:11 +00008670 if (!E->hasAssociatedStmt() || !E->getAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00008671 return;
8672
8673 scanForTargetRegionsFunctions(
Alexey Bataev475a7442018-01-12 19:39:11 +00008674 E->getInnermostCapturedStmt()->getCapturedStmt(), ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008675 return;
8676 }
8677
8678 // If this is a lambda function, look into its body.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008679 if (const auto *L = dyn_cast<LambdaExpr>(S))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008680 S = L->getBody();
8681
8682 // Keep looking for target regions recursively.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008683 for (const Stmt *II : S->children())
Samuel Antaoee8fb302016-01-06 13:42:12 +00008684 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008685}
8686
8687bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008688 // If emitting code for the host, we do not process FD here. Instead we do
8689 // the normal code generation.
8690 if (!CGM.getLangOpts().OpenMPIsDevice)
8691 return false;
8692
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008693 const ValueDecl *VD = cast<ValueDecl>(GD.getDecl());
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008694 StringRef Name = CGM.getMangledName(GD);
8695 // Try to detect target regions in the function.
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008696 if (const auto *FD = dyn_cast<FunctionDecl>(VD))
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008697 scanForTargetRegionsFunctions(FD->getBody(), Name);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008698
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008699 // Do not to emit function if it is not marked as declare target.
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008700 return !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008701 AlreadyEmittedTargetFunctions.count(Name) == 0;
Samuel Antaoee8fb302016-01-06 13:42:12 +00008702}
8703
8704bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
8705 if (!CGM.getLangOpts().OpenMPIsDevice)
8706 return false;
8707
8708 // Check if there are Ctors/Dtors in this declaration and look for target
8709 // regions in it. We use the complete variant to produce the kernel name
8710 // mangling.
8711 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008712 if (const auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
8713 for (const CXXConstructorDecl *Ctor : RD->ctors()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008714 StringRef ParentName =
8715 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
8716 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
8717 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008718 if (const CXXDestructorDecl *Dtor = RD->getDestructor()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008719 StringRef ParentName =
8720 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
8721 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
8722 }
8723 }
8724
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008725 // Do not to emit variable if it is not marked as declare target.
Alexey Bataev92327c52018-03-26 16:40:55 +00008726 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00008727 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
8728 cast<VarDecl>(GD.getDecl()));
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008729 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Alexey Bataevd01b7492018-08-15 19:45:12 +00008730 DeferredGlobalVariables.insert(cast<VarDecl>(GD.getDecl()));
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008731 return true;
8732 }
8733 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00008734}
8735
Alexey Bataev03f270c2018-03-30 18:31:07 +00008736void CGOpenMPRuntime::registerTargetGlobalVariable(const VarDecl *VD,
8737 llvm::Constant *Addr) {
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008738 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
8739 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
8740 if (!Res) {
8741 if (CGM.getLangOpts().OpenMPIsDevice) {
8742 // Register non-target variables being emitted in device code (debug info
8743 // may cause this).
8744 StringRef VarName = CGM.getMangledName(VD);
8745 EmittedNonTargetVariables.try_emplace(VarName, Addr);
Alexey Bataev03f270c2018-03-30 18:31:07 +00008746 }
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008747 return;
Alexey Bataev03f270c2018-03-30 18:31:07 +00008748 }
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008749 // Register declare target variables.
8750 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags;
8751 StringRef VarName;
8752 CharUnits VarSize;
8753 llvm::GlobalValue::LinkageTypes Linkage;
8754 switch (*Res) {
8755 case OMPDeclareTargetDeclAttr::MT_To:
8756 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo;
8757 VarName = CGM.getMangledName(VD);
8758 if (VD->hasDefinition(CGM.getContext()) != VarDecl::DeclarationOnly) {
8759 VarSize = CGM.getContext().getTypeSizeInChars(VD->getType());
8760 assert(!VarSize.isZero() && "Expected non-zero size of the variable");
8761 } else {
8762 VarSize = CharUnits::Zero();
8763 }
8764 Linkage = CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false);
8765 // Temp solution to prevent optimizations of the internal variables.
8766 if (CGM.getLangOpts().OpenMPIsDevice && !VD->isExternallyVisible()) {
8767 std::string RefName = getName({VarName, "ref"});
8768 if (!CGM.GetGlobalValue(RefName)) {
8769 llvm::Constant *AddrRef =
8770 getOrCreateInternalVariable(Addr->getType(), RefName);
8771 auto *GVAddrRef = cast<llvm::GlobalVariable>(AddrRef);
8772 GVAddrRef->setConstant(/*Val=*/true);
8773 GVAddrRef->setLinkage(llvm::GlobalValue::InternalLinkage);
8774 GVAddrRef->setInitializer(Addr);
8775 CGM.addCompilerUsedGlobal(GVAddrRef);
8776 }
8777 }
8778 break;
8779 case OMPDeclareTargetDeclAttr::MT_Link:
8780 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink;
8781 if (CGM.getLangOpts().OpenMPIsDevice) {
8782 VarName = Addr->getName();
8783 Addr = nullptr;
8784 } else {
8785 VarName = getAddrOfDeclareTargetLink(VD).getName();
8786 Addr = cast<llvm::Constant>(getAddrOfDeclareTargetLink(VD).getPointer());
8787 }
8788 VarSize = CGM.getPointerSize();
8789 Linkage = llvm::GlobalValue::WeakAnyLinkage;
8790 break;
8791 }
8792 OffloadEntriesInfoManager.registerDeviceGlobalVarEntryInfo(
8793 VarName, Addr, VarSize, Flags, Linkage);
Alexey Bataev03f270c2018-03-30 18:31:07 +00008794}
8795
Samuel Antaoee8fb302016-01-06 13:42:12 +00008796bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008797 if (isa<FunctionDecl>(GD.getDecl()) ||
8798 isa<OMPDeclareReductionDecl>(GD.getDecl()))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008799 return emitTargetFunctions(GD);
8800
8801 return emitTargetGlobalVariable(GD);
8802}
8803
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008804void CGOpenMPRuntime::emitDeferredTargetDecls() const {
8805 for (const VarDecl *VD : DeferredGlobalVariables) {
8806 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00008807 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataevd01b7492018-08-15 19:45:12 +00008808 if (!Res)
8809 continue;
8810 if (*Res == OMPDeclareTargetDeclAttr::MT_To) {
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008811 CGM.EmitGlobal(VD);
Alexey Bataevd01b7492018-08-15 19:45:12 +00008812 } else {
8813 assert(*Res == OMPDeclareTargetDeclAttr::MT_Link &&
8814 "Expected to or link clauses.");
8815 (void)CGM.getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008816 }
8817 }
8818}
8819
Alexey Bataev60705422018-10-30 15:50:12 +00008820void CGOpenMPRuntime::adjustTargetSpecificDataForLambdas(
8821 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
8822 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
8823 " Expected target-based directive.");
8824}
8825
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008826CGOpenMPRuntime::DisableAutoDeclareTargetRAII::DisableAutoDeclareTargetRAII(
8827 CodeGenModule &CGM)
8828 : CGM(CGM) {
8829 if (CGM.getLangOpts().OpenMPIsDevice) {
8830 SavedShouldMarkAsGlobal = CGM.getOpenMPRuntime().ShouldMarkAsGlobal;
8831 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = false;
8832 }
8833}
8834
8835CGOpenMPRuntime::DisableAutoDeclareTargetRAII::~DisableAutoDeclareTargetRAII() {
8836 if (CGM.getLangOpts().OpenMPIsDevice)
8837 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = SavedShouldMarkAsGlobal;
8838}
8839
Alexey Bataev6d944102018-05-02 15:45:28 +00008840bool CGOpenMPRuntime::markAsGlobalTarget(GlobalDecl GD) {
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008841 if (!CGM.getLangOpts().OpenMPIsDevice || !ShouldMarkAsGlobal)
8842 return true;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008843
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008844 StringRef Name = CGM.getMangledName(GD);
Alexey Bataev6d944102018-05-02 15:45:28 +00008845 const auto *D = cast<FunctionDecl>(GD.getDecl());
Alexey Bataev34f8a702018-03-28 14:28:54 +00008846 // Do not to emit function if it is marked as declare target as it was already
8847 // emitted.
Alexey Bataev97b72212018-08-14 18:31:20 +00008848 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(D)) {
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008849 if (D->hasBody() && AlreadyEmittedTargetFunctions.count(Name) == 0) {
8850 if (auto *F = dyn_cast_or_null<llvm::Function>(CGM.GetGlobalValue(Name)))
Alexey Bataev34f8a702018-03-28 14:28:54 +00008851 return !F->isDeclaration();
8852 return false;
8853 }
8854 return true;
8855 }
8856
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008857 return !AlreadyEmittedTargetFunctions.insert(Name).second;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008858}
8859
Samuel Antaoee8fb302016-01-06 13:42:12 +00008860llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
8861 // If we have offloading in the current module, we need to emit the entries
8862 // now and register the offloading descriptor.
8863 createOffloadEntriesAndInfoMetadata();
8864
8865 // Create and register the offloading binary descriptors. This is the main
8866 // entity that captures all the information about offloading in the current
8867 // compilation unit.
8868 return createOffloadingBinaryDescriptorRegistration();
8869}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008870
8871void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
8872 const OMPExecutableDirective &D,
8873 SourceLocation Loc,
8874 llvm::Value *OutlinedFn,
8875 ArrayRef<llvm::Value *> CapturedVars) {
8876 if (!CGF.HaveInsertPoint())
8877 return;
8878
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008879 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008880 CodeGenFunction::RunCleanupsScope Scope(CGF);
8881
8882 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
8883 llvm::Value *Args[] = {
8884 RTLoc,
8885 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
8886 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
8887 llvm::SmallVector<llvm::Value *, 16> RealArgs;
8888 RealArgs.append(std::begin(Args), std::end(Args));
8889 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
8890
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008891 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008892 CGF.EmitRuntimeCall(RTLFn, RealArgs);
8893}
8894
8895void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00008896 const Expr *NumTeams,
8897 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008898 SourceLocation Loc) {
8899 if (!CGF.HaveInsertPoint())
8900 return;
8901
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008902 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008903
Carlo Bertollic6872252016-04-04 15:55:02 +00008904 llvm::Value *NumTeamsVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008905 NumTeams
Carlo Bertollic6872252016-04-04 15:55:02 +00008906 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
8907 CGF.CGM.Int32Ty, /* isSigned = */ true)
8908 : CGF.Builder.getInt32(0);
8909
8910 llvm::Value *ThreadLimitVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008911 ThreadLimit
Carlo Bertollic6872252016-04-04 15:55:02 +00008912 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
8913 CGF.CGM.Int32Ty, /* isSigned = */ true)
8914 : CGF.Builder.getInt32(0);
8915
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008916 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00008917 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
8918 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008919 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
8920 PushNumTeamsArgs);
8921}
Samuel Antaodf158d52016-04-27 22:58:19 +00008922
Samuel Antaocc10b852016-07-28 14:23:26 +00008923void CGOpenMPRuntime::emitTargetDataCalls(
8924 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8925 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008926 if (!CGF.HaveInsertPoint())
8927 return;
8928
Samuel Antaocc10b852016-07-28 14:23:26 +00008929 // Action used to replace the default codegen action and turn privatization
8930 // off.
8931 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00008932
8933 // Generate the code for the opening of the data environment. Capture all the
8934 // arguments of the runtime call by reference because they are used in the
8935 // closing of the region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008936 auto &&BeginThenGen = [this, &D, Device, &Info,
8937 &CodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008938 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00008939 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00008940 MappableExprsHandler::MapValuesArrayTy Pointers;
8941 MappableExprsHandler::MapValuesArrayTy Sizes;
8942 MappableExprsHandler::MapFlagsArrayTy MapTypes;
8943
8944 // Get map clause information.
8945 MappableExprsHandler MCHandler(D, CGF);
8946 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00008947
8948 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00008949 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008950
8951 llvm::Value *BasePointersArrayArg = nullptr;
8952 llvm::Value *PointersArrayArg = nullptr;
8953 llvm::Value *SizesArrayArg = nullptr;
8954 llvm::Value *MapTypesArrayArg = nullptr;
8955 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008956 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008957
8958 // Emit device ID if any.
8959 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008960 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008961 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008962 CGF.Int64Ty, /*isSigned=*/true);
8963 } else {
8964 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8965 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008966
8967 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008968 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00008969
8970 llvm::Value *OffloadingArgs[] = {
8971 DeviceID, PointerNum, BasePointersArrayArg,
8972 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008973 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_begin),
Samuel Antaodf158d52016-04-27 22:58:19 +00008974 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00008975
8976 // If device pointer privatization is required, emit the body of the region
8977 // here. It will have to be duplicated: with and without privatization.
8978 if (!Info.CaptureDeviceAddrMap.empty())
8979 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008980 };
8981
8982 // Generate code for the closing of the data region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008983 auto &&EndThenGen = [this, Device, &Info](CodeGenFunction &CGF,
8984 PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008985 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00008986
8987 llvm::Value *BasePointersArrayArg = nullptr;
8988 llvm::Value *PointersArrayArg = nullptr;
8989 llvm::Value *SizesArrayArg = nullptr;
8990 llvm::Value *MapTypesArrayArg = nullptr;
8991 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008992 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008993
8994 // Emit device ID if any.
8995 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008996 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008997 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008998 CGF.Int64Ty, /*isSigned=*/true);
8999 } else {
9000 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
9001 }
Samuel Antaodf158d52016-04-27 22:58:19 +00009002
9003 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009004 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00009005
9006 llvm::Value *OffloadingArgs[] = {
9007 DeviceID, PointerNum, BasePointersArrayArg,
9008 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009009 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_end),
Samuel Antaodf158d52016-04-27 22:58:19 +00009010 OffloadingArgs);
9011 };
9012
Samuel Antaocc10b852016-07-28 14:23:26 +00009013 // If we need device pointer privatization, we need to emit the body of the
9014 // region with no privatization in the 'else' branch of the conditional.
9015 // Otherwise, we don't have to do anything.
9016 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
9017 PrePostActionTy &) {
9018 if (!Info.CaptureDeviceAddrMap.empty()) {
9019 CodeGen.setAction(NoPrivAction);
9020 CodeGen(CGF);
9021 }
9022 };
9023
9024 // We don't have to do anything to close the region if the if clause evaluates
9025 // to false.
9026 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00009027
9028 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00009029 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00009030 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00009031 RegionCodeGenTy RCG(BeginThenGen);
9032 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00009033 }
9034
Samuel Antaocc10b852016-07-28 14:23:26 +00009035 // If we don't require privatization of device pointers, we emit the body in
9036 // between the runtime calls. This avoids duplicating the body code.
9037 if (Info.CaptureDeviceAddrMap.empty()) {
9038 CodeGen.setAction(NoPrivAction);
9039 CodeGen(CGF);
9040 }
Samuel Antaodf158d52016-04-27 22:58:19 +00009041
9042 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00009043 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00009044 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00009045 RegionCodeGenTy RCG(EndThenGen);
9046 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00009047 }
9048}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009049
Samuel Antao8d2d7302016-05-26 18:30:22 +00009050void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00009051 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
9052 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009053 if (!CGF.HaveInsertPoint())
9054 return;
9055
Samuel Antao8dd66282016-04-27 23:14:30 +00009056 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00009057 isa<OMPTargetExitDataDirective>(D) ||
9058 isa<OMPTargetUpdateDirective>(D)) &&
9059 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00009060
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009061 CodeGenFunction::OMPTargetDataInfo InputInfo;
9062 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009063 // Generate the code for the opening of the data environment.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009064 auto &&ThenGen = [this, &D, Device, &InputInfo,
9065 &MapTypesArray](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009066 // Emit device ID if any.
9067 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00009068 if (Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009069 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00009070 CGF.Int64Ty, /*isSigned=*/true);
9071 } else {
9072 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
9073 }
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009074
9075 // Emit the number of elements in the offloading arrays.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009076 llvm::Constant *PointerNum =
9077 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009078
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009079 llvm::Value *OffloadingArgs[] = {DeviceID,
9080 PointerNum,
9081 InputInfo.BasePointersArray.getPointer(),
9082 InputInfo.PointersArray.getPointer(),
9083 InputInfo.SizesArray.getPointer(),
9084 MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00009085
Samuel Antao8d2d7302016-05-26 18:30:22 +00009086 // Select the right runtime function call for each expected standalone
9087 // directive.
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00009088 const bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Samuel Antao8d2d7302016-05-26 18:30:22 +00009089 OpenMPRTLFunction RTLFn;
9090 switch (D.getDirectiveKind()) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00009091 case OMPD_target_enter_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00009092 RTLFn = HasNowait ? OMPRTL__tgt_target_data_begin_nowait
9093 : OMPRTL__tgt_target_data_begin;
Samuel Antao8d2d7302016-05-26 18:30:22 +00009094 break;
9095 case OMPD_target_exit_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00009096 RTLFn = HasNowait ? OMPRTL__tgt_target_data_end_nowait
9097 : OMPRTL__tgt_target_data_end;
Samuel Antao8d2d7302016-05-26 18:30:22 +00009098 break;
9099 case OMPD_target_update:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00009100 RTLFn = HasNowait ? OMPRTL__tgt_target_data_update_nowait
9101 : OMPRTL__tgt_target_data_update;
Samuel Antao8d2d7302016-05-26 18:30:22 +00009102 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009103 case OMPD_parallel:
9104 case OMPD_for:
9105 case OMPD_parallel_for:
9106 case OMPD_parallel_sections:
9107 case OMPD_for_simd:
9108 case OMPD_parallel_for_simd:
9109 case OMPD_cancel:
9110 case OMPD_cancellation_point:
9111 case OMPD_ordered:
9112 case OMPD_threadprivate:
9113 case OMPD_task:
9114 case OMPD_simd:
9115 case OMPD_sections:
9116 case OMPD_section:
9117 case OMPD_single:
9118 case OMPD_master:
9119 case OMPD_critical:
9120 case OMPD_taskyield:
9121 case OMPD_barrier:
9122 case OMPD_taskwait:
9123 case OMPD_taskgroup:
9124 case OMPD_atomic:
9125 case OMPD_flush:
9126 case OMPD_teams:
9127 case OMPD_target_data:
9128 case OMPD_distribute:
9129 case OMPD_distribute_simd:
9130 case OMPD_distribute_parallel_for:
9131 case OMPD_distribute_parallel_for_simd:
9132 case OMPD_teams_distribute:
9133 case OMPD_teams_distribute_simd:
9134 case OMPD_teams_distribute_parallel_for:
9135 case OMPD_teams_distribute_parallel_for_simd:
9136 case OMPD_declare_simd:
9137 case OMPD_declare_target:
9138 case OMPD_end_declare_target:
9139 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009140 case OMPD_declare_mapper:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009141 case OMPD_taskloop:
9142 case OMPD_taskloop_simd:
9143 case OMPD_target:
9144 case OMPD_target_simd:
9145 case OMPD_target_teams_distribute:
9146 case OMPD_target_teams_distribute_simd:
9147 case OMPD_target_teams_distribute_parallel_for:
9148 case OMPD_target_teams_distribute_parallel_for_simd:
9149 case OMPD_target_teams:
9150 case OMPD_target_parallel:
9151 case OMPD_target_parallel_for:
9152 case OMPD_target_parallel_for_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00009153 case OMPD_requires:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009154 case OMPD_unknown:
9155 llvm_unreachable("Unexpected standalone target data directive.");
9156 break;
Samuel Antao8d2d7302016-05-26 18:30:22 +00009157 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009158 CGF.EmitRuntimeCall(createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009159 };
9160
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009161 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray](
9162 CodeGenFunction &CGF, PrePostActionTy &) {
9163 // Fill up the arrays with all the mapped variables.
9164 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
9165 MappableExprsHandler::MapValuesArrayTy Pointers;
9166 MappableExprsHandler::MapValuesArrayTy Sizes;
9167 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009168
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009169 // Get map clause information.
9170 MappableExprsHandler MEHandler(D, CGF);
9171 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
9172
9173 TargetDataInfo Info;
9174 // Fill up the arrays and create the arguments.
9175 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
9176 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
9177 Info.PointersArray, Info.SizesArray,
9178 Info.MapTypesArray, Info);
9179 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
9180 InputInfo.BasePointersArray =
9181 Address(Info.BasePointersArray, CGM.getPointerAlign());
9182 InputInfo.PointersArray =
9183 Address(Info.PointersArray, CGM.getPointerAlign());
9184 InputInfo.SizesArray =
9185 Address(Info.SizesArray, CGM.getPointerAlign());
9186 MapTypesArray = Info.MapTypesArray;
9187 if (D.hasClausesOfKind<OMPDependClause>())
9188 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
9189 else
Alexey Bataev768f1f22018-01-09 19:59:25 +00009190 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009191 };
9192
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009193 if (IfCond) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009194 emitOMPIfClause(CGF, IfCond, TargetThenGen,
9195 [](CodeGenFunction &CGF, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009196 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009197 RegionCodeGenTy ThenRCG(TargetThenGen);
9198 ThenRCG(CGF);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009199 }
9200}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009201
9202namespace {
9203 /// Kind of parameter in a function with 'declare simd' directive.
9204 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
9205 /// Attribute set of the parameter.
9206 struct ParamAttrTy {
9207 ParamKindTy Kind = Vector;
9208 llvm::APSInt StrideOrArg;
9209 llvm::APSInt Alignment;
9210 };
9211} // namespace
9212
9213static unsigned evaluateCDTSize(const FunctionDecl *FD,
9214 ArrayRef<ParamAttrTy> ParamAttrs) {
9215 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
9216 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
9217 // of that clause. The VLEN value must be power of 2.
9218 // In other case the notion of the function`s "characteristic data type" (CDT)
9219 // is used to compute the vector length.
9220 // CDT is defined in the following order:
9221 // a) For non-void function, the CDT is the return type.
9222 // b) If the function has any non-uniform, non-linear parameters, then the
9223 // CDT is the type of the first such parameter.
9224 // c) If the CDT determined by a) or b) above is struct, union, or class
9225 // type which is pass-by-value (except for the type that maps to the
9226 // built-in complex data type), the characteristic data type is int.
9227 // d) If none of the above three cases is applicable, the CDT is int.
9228 // The VLEN is then determined based on the CDT and the size of vector
9229 // register of that ISA for which current vector version is generated. The
9230 // VLEN is computed using the formula below:
9231 // VLEN = sizeof(vector_register) / sizeof(CDT),
9232 // where vector register size specified in section 3.2.1 Registers and the
9233 // Stack Frame of original AMD64 ABI document.
9234 QualType RetType = FD->getReturnType();
9235 if (RetType.isNull())
9236 return 0;
9237 ASTContext &C = FD->getASTContext();
9238 QualType CDT;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009239 if (!RetType.isNull() && !RetType->isVoidType()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009240 CDT = RetType;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009241 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009242 unsigned Offset = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009243 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009244 if (ParamAttrs[Offset].Kind == Vector)
9245 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
9246 ++Offset;
9247 }
9248 if (CDT.isNull()) {
9249 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
9250 if (ParamAttrs[I + Offset].Kind == Vector) {
9251 CDT = FD->getParamDecl(I)->getType();
9252 break;
9253 }
9254 }
9255 }
9256 }
9257 if (CDT.isNull())
9258 CDT = C.IntTy;
9259 CDT = CDT->getCanonicalTypeUnqualified();
9260 if (CDT->isRecordType() || CDT->isUnionType())
9261 CDT = C.IntTy;
9262 return C.getTypeSize(CDT);
9263}
9264
9265static void
9266emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00009267 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009268 ArrayRef<ParamAttrTy> ParamAttrs,
9269 OMPDeclareSimdDeclAttr::BranchStateTy State) {
9270 struct ISADataTy {
9271 char ISA;
9272 unsigned VecRegSize;
9273 };
9274 ISADataTy ISAData[] = {
9275 {
9276 'b', 128
9277 }, // SSE
9278 {
9279 'c', 256
9280 }, // AVX
9281 {
9282 'd', 256
9283 }, // AVX2
9284 {
9285 'e', 512
9286 }, // AVX512
9287 };
9288 llvm::SmallVector<char, 2> Masked;
9289 switch (State) {
9290 case OMPDeclareSimdDeclAttr::BS_Undefined:
9291 Masked.push_back('N');
9292 Masked.push_back('M');
9293 break;
9294 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
9295 Masked.push_back('N');
9296 break;
9297 case OMPDeclareSimdDeclAttr::BS_Inbranch:
9298 Masked.push_back('M');
9299 break;
9300 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009301 for (char Mask : Masked) {
9302 for (const ISADataTy &Data : ISAData) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009303 SmallString<256> Buffer;
9304 llvm::raw_svector_ostream Out(Buffer);
9305 Out << "_ZGV" << Data.ISA << Mask;
9306 if (!VLENVal) {
9307 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
9308 evaluateCDTSize(FD, ParamAttrs));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009309 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009310 Out << VLENVal;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009311 }
9312 for (const ParamAttrTy &ParamAttr : ParamAttrs) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009313 switch (ParamAttr.Kind){
9314 case LinearWithVarStride:
9315 Out << 's' << ParamAttr.StrideOrArg;
9316 break;
9317 case Linear:
9318 Out << 'l';
9319 if (!!ParamAttr.StrideOrArg)
9320 Out << ParamAttr.StrideOrArg;
9321 break;
9322 case Uniform:
9323 Out << 'u';
9324 break;
9325 case Vector:
9326 Out << 'v';
9327 break;
9328 }
9329 if (!!ParamAttr.Alignment)
9330 Out << 'a' << ParamAttr.Alignment;
9331 }
9332 Out << '_' << Fn->getName();
9333 Fn->addFnAttr(Out.str());
9334 }
9335 }
9336}
9337
9338void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
9339 llvm::Function *Fn) {
9340 ASTContext &C = CGM.getContext();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009341 FD = FD->getMostRecentDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009342 // Map params to their positions in function decl.
9343 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
9344 if (isa<CXXMethodDecl>(FD))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009345 ParamPositions.try_emplace(FD, 0);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009346 unsigned ParamPos = ParamPositions.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009347 for (const ParmVarDecl *P : FD->parameters()) {
9348 ParamPositions.try_emplace(P->getCanonicalDecl(), ParamPos);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009349 ++ParamPos;
9350 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009351 while (FD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009352 for (const auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009353 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
9354 // Mark uniform parameters.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009355 for (const Expr *E : Attr->uniforms()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009356 E = E->IgnoreParenImpCasts();
9357 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009358 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009359 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009360 } else {
9361 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
9362 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009363 Pos = ParamPositions[PVD];
9364 }
9365 ParamAttrs[Pos].Kind = Uniform;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009366 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009367 // Get alignment info.
9368 auto NI = Attr->alignments_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009369 for (const Expr *E : Attr->aligneds()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009370 E = E->IgnoreParenImpCasts();
9371 unsigned Pos;
9372 QualType ParmTy;
9373 if (isa<CXXThisExpr>(E)) {
9374 Pos = ParamPositions[FD];
9375 ParmTy = E->getType();
9376 } else {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009377 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
9378 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009379 Pos = ParamPositions[PVD];
9380 ParmTy = PVD->getType();
9381 }
9382 ParamAttrs[Pos].Alignment =
9383 (*NI)
9384 ? (*NI)->EvaluateKnownConstInt(C)
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009385 : llvm::APSInt::getUnsigned(
9386 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
9387 .getQuantity());
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009388 ++NI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009389 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009390 // Mark linear parameters.
9391 auto SI = Attr->steps_begin();
9392 auto MI = Attr->modifiers_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009393 for (const Expr *E : Attr->linears()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009394 E = E->IgnoreParenImpCasts();
9395 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009396 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009397 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009398 } else {
9399 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
9400 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009401 Pos = ParamPositions[PVD];
9402 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009403 ParamAttrTy &ParamAttr = ParamAttrs[Pos];
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009404 ParamAttr.Kind = Linear;
9405 if (*SI) {
Fangrui Song407659a2018-11-30 23:41:18 +00009406 Expr::EvalResult Result;
9407 if (!(*SI)->EvaluateAsInt(Result, C, Expr::SE_AllowSideEffects)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009408 if (const auto *DRE =
9409 cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
9410 if (const auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009411 ParamAttr.Kind = LinearWithVarStride;
9412 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
9413 ParamPositions[StridePVD->getCanonicalDecl()]);
9414 }
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009415 }
Fangrui Song407659a2018-11-30 23:41:18 +00009416 } else {
9417 ParamAttr.StrideOrArg = Result.Val.getInt();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009418 }
9419 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009420 ++SI;
9421 ++MI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009422 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009423 llvm::APSInt VLENVal;
9424 if (const Expr *VLEN = Attr->getSimdlen())
9425 VLENVal = VLEN->EvaluateKnownConstInt(C);
9426 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
9427 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
9428 CGM.getTriple().getArch() == llvm::Triple::x86_64)
9429 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009430 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009431 FD = FD->getPreviousDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009432 }
9433}
Alexey Bataev8b427062016-05-25 12:36:08 +00009434
9435namespace {
9436/// Cleanup action for doacross support.
9437class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
9438public:
9439 static const int DoacrossFinArgs = 2;
9440
9441private:
9442 llvm::Value *RTLFn;
9443 llvm::Value *Args[DoacrossFinArgs];
9444
9445public:
9446 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
9447 : RTLFn(RTLFn) {
9448 assert(CallArgs.size() == DoacrossFinArgs);
9449 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
9450 }
9451 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
9452 if (!CGF.HaveInsertPoint())
9453 return;
9454 CGF.EmitRuntimeCall(RTLFn, Args);
9455 }
9456};
9457} // namespace
9458
9459void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
Alexey Bataevf138fda2018-08-13 19:04:24 +00009460 const OMPLoopDirective &D,
9461 ArrayRef<Expr *> NumIterations) {
Alexey Bataev8b427062016-05-25 12:36:08 +00009462 if (!CGF.HaveInsertPoint())
9463 return;
9464
9465 ASTContext &C = CGM.getContext();
9466 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
9467 RecordDecl *RD;
9468 if (KmpDimTy.isNull()) {
9469 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
9470 // kmp_int64 lo; // lower
9471 // kmp_int64 up; // upper
9472 // kmp_int64 st; // stride
9473 // };
9474 RD = C.buildImplicitRecord("kmp_dim");
9475 RD->startDefinition();
9476 addFieldToRecordDecl(C, RD, Int64Ty);
9477 addFieldToRecordDecl(C, RD, Int64Ty);
9478 addFieldToRecordDecl(C, RD, Int64Ty);
9479 RD->completeDefinition();
9480 KmpDimTy = C.getRecordType(RD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009481 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00009482 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009483 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00009484 llvm::APInt Size(/*numBits=*/32, NumIterations.size());
9485 QualType ArrayTy =
9486 C.getConstantArrayType(KmpDimTy, Size, ArrayType::Normal, 0);
Alexey Bataev8b427062016-05-25 12:36:08 +00009487
Alexey Bataevf138fda2018-08-13 19:04:24 +00009488 Address DimsAddr = CGF.CreateMemTemp(ArrayTy, "dims");
9489 CGF.EmitNullInitialization(DimsAddr, ArrayTy);
Alexey Bataev8b427062016-05-25 12:36:08 +00009490 enum { LowerFD = 0, UpperFD, StrideFD };
9491 // Fill dims with data.
Alexey Bataevf138fda2018-08-13 19:04:24 +00009492 for (unsigned I = 0, E = NumIterations.size(); I < E; ++I) {
9493 LValue DimsLVal =
9494 CGF.MakeAddrLValue(CGF.Builder.CreateConstArrayGEP(
9495 DimsAddr, I, C.getTypeSizeInChars(KmpDimTy)),
9496 KmpDimTy);
9497 // dims.upper = num_iterations;
9498 LValue UpperLVal = CGF.EmitLValueForField(
9499 DimsLVal, *std::next(RD->field_begin(), UpperFD));
9500 llvm::Value *NumIterVal =
9501 CGF.EmitScalarConversion(CGF.EmitScalarExpr(NumIterations[I]),
9502 D.getNumIterations()->getType(), Int64Ty,
9503 D.getNumIterations()->getExprLoc());
9504 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
9505 // dims.stride = 1;
9506 LValue StrideLVal = CGF.EmitLValueForField(
9507 DimsLVal, *std::next(RD->field_begin(), StrideFD));
9508 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
9509 StrideLVal);
9510 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009511
9512 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
9513 // kmp_int32 num_dims, struct kmp_dim * dims);
Alexey Bataevf138fda2018-08-13 19:04:24 +00009514 llvm::Value *Args[] = {
9515 emitUpdateLocation(CGF, D.getBeginLoc()),
9516 getThreadID(CGF, D.getBeginLoc()),
9517 llvm::ConstantInt::getSigned(CGM.Int32Ty, NumIterations.size()),
9518 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
9519 CGF.Builder
9520 .CreateConstArrayGEP(DimsAddr, 0, C.getTypeSizeInChars(KmpDimTy))
9521 .getPointer(),
9522 CGM.VoidPtrTy)};
Alexey Bataev8b427062016-05-25 12:36:08 +00009523
9524 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
9525 CGF.EmitRuntimeCall(RTLFn, Args);
9526 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009527 emitUpdateLocation(CGF, D.getEndLoc()), getThreadID(CGF, D.getEndLoc())};
Alexey Bataev8b427062016-05-25 12:36:08 +00009528 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
9529 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
9530 llvm::makeArrayRef(FiniArgs));
9531}
9532
9533void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
9534 const OMPDependClause *C) {
9535 QualType Int64Ty =
9536 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
Alexey Bataevf138fda2018-08-13 19:04:24 +00009537 llvm::APInt Size(/*numBits=*/32, C->getNumLoops());
9538 QualType ArrayTy = CGM.getContext().getConstantArrayType(
9539 Int64Ty, Size, ArrayType::Normal, 0);
9540 Address CntAddr = CGF.CreateMemTemp(ArrayTy, ".cnt.addr");
9541 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I) {
9542 const Expr *CounterVal = C->getLoopData(I);
9543 assert(CounterVal);
9544 llvm::Value *CntVal = CGF.EmitScalarConversion(
9545 CGF.EmitScalarExpr(CounterVal), CounterVal->getType(), Int64Ty,
9546 CounterVal->getExprLoc());
9547 CGF.EmitStoreOfScalar(
9548 CntVal,
9549 CGF.Builder.CreateConstArrayGEP(
9550 CntAddr, I, CGM.getContext().getTypeSizeInChars(Int64Ty)),
9551 /*Volatile=*/false, Int64Ty);
9552 }
9553 llvm::Value *Args[] = {
9554 emitUpdateLocation(CGF, C->getBeginLoc()),
9555 getThreadID(CGF, C->getBeginLoc()),
9556 CGF.Builder
9557 .CreateConstArrayGEP(CntAddr, 0,
9558 CGM.getContext().getTypeSizeInChars(Int64Ty))
9559 .getPointer()};
Alexey Bataev8b427062016-05-25 12:36:08 +00009560 llvm::Value *RTLFn;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009561 if (C->getDependencyKind() == OMPC_DEPEND_source) {
Alexey Bataev8b427062016-05-25 12:36:08 +00009562 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009563 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00009564 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
9565 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
9566 }
9567 CGF.EmitRuntimeCall(RTLFn, Args);
9568}
9569
Alexey Bataev7ef47a62018-02-22 18:33:31 +00009570void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, SourceLocation Loc,
9571 llvm::Value *Callee,
9572 ArrayRef<llvm::Value *> Args) const {
9573 assert(Loc.isValid() && "Outlined function call location must be valid.");
Alexey Bataev3c595a62017-08-14 15:01:03 +00009574 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
9575
9576 if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00009577 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00009578 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00009579 return;
9580 }
9581 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00009582 CGF.EmitRuntimeCall(Callee, Args);
9583}
9584
9585void CGOpenMPRuntime::emitOutlinedFunctionCall(
9586 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
9587 ArrayRef<llvm::Value *> Args) const {
Alexey Bataev7ef47a62018-02-22 18:33:31 +00009588 emitCall(CGF, Loc, OutlinedFn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00009589}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00009590
9591Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
9592 const VarDecl *NativeParam,
9593 const VarDecl *TargetParam) const {
9594 return CGF.GetAddrOfLocalVar(NativeParam);
9595}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009596
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00009597Address CGOpenMPRuntime::getAddressOfLocalVariable(CodeGenFunction &CGF,
9598 const VarDecl *VD) {
9599 return Address::invalid();
9600}
9601
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009602llvm::Value *CGOpenMPSIMDRuntime::emitParallelOutlinedFunction(
9603 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
9604 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
9605 llvm_unreachable("Not supported in SIMD-only mode");
9606}
9607
9608llvm::Value *CGOpenMPSIMDRuntime::emitTeamsOutlinedFunction(
9609 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
9610 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
9611 llvm_unreachable("Not supported in SIMD-only mode");
9612}
9613
9614llvm::Value *CGOpenMPSIMDRuntime::emitTaskOutlinedFunction(
9615 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
9616 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
9617 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
9618 bool Tied, unsigned &NumberOfParts) {
9619 llvm_unreachable("Not supported in SIMD-only mode");
9620}
9621
9622void CGOpenMPSIMDRuntime::emitParallelCall(CodeGenFunction &CGF,
9623 SourceLocation Loc,
9624 llvm::Value *OutlinedFn,
9625 ArrayRef<llvm::Value *> CapturedVars,
9626 const Expr *IfCond) {
9627 llvm_unreachable("Not supported in SIMD-only mode");
9628}
9629
9630void CGOpenMPSIMDRuntime::emitCriticalRegion(
9631 CodeGenFunction &CGF, StringRef CriticalName,
9632 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
9633 const Expr *Hint) {
9634 llvm_unreachable("Not supported in SIMD-only mode");
9635}
9636
9637void CGOpenMPSIMDRuntime::emitMasterRegion(CodeGenFunction &CGF,
9638 const RegionCodeGenTy &MasterOpGen,
9639 SourceLocation Loc) {
9640 llvm_unreachable("Not supported in SIMD-only mode");
9641}
9642
9643void CGOpenMPSIMDRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
9644 SourceLocation Loc) {
9645 llvm_unreachable("Not supported in SIMD-only mode");
9646}
9647
9648void CGOpenMPSIMDRuntime::emitTaskgroupRegion(
9649 CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen,
9650 SourceLocation Loc) {
9651 llvm_unreachable("Not supported in SIMD-only mode");
9652}
9653
9654void CGOpenMPSIMDRuntime::emitSingleRegion(
9655 CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen,
9656 SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars,
9657 ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs,
9658 ArrayRef<const Expr *> AssignmentOps) {
9659 llvm_unreachable("Not supported in SIMD-only mode");
9660}
9661
9662void CGOpenMPSIMDRuntime::emitOrderedRegion(CodeGenFunction &CGF,
9663 const RegionCodeGenTy &OrderedOpGen,
9664 SourceLocation Loc,
9665 bool IsThreads) {
9666 llvm_unreachable("Not supported in SIMD-only mode");
9667}
9668
9669void CGOpenMPSIMDRuntime::emitBarrierCall(CodeGenFunction &CGF,
9670 SourceLocation Loc,
9671 OpenMPDirectiveKind Kind,
9672 bool EmitChecks,
9673 bool ForceSimpleCall) {
9674 llvm_unreachable("Not supported in SIMD-only mode");
9675}
9676
9677void CGOpenMPSIMDRuntime::emitForDispatchInit(
9678 CodeGenFunction &CGF, SourceLocation Loc,
9679 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
9680 bool Ordered, const DispatchRTInput &DispatchValues) {
9681 llvm_unreachable("Not supported in SIMD-only mode");
9682}
9683
9684void CGOpenMPSIMDRuntime::emitForStaticInit(
9685 CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind,
9686 const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values) {
9687 llvm_unreachable("Not supported in SIMD-only mode");
9688}
9689
9690void CGOpenMPSIMDRuntime::emitDistributeStaticInit(
9691 CodeGenFunction &CGF, SourceLocation Loc,
9692 OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values) {
9693 llvm_unreachable("Not supported in SIMD-only mode");
9694}
9695
9696void CGOpenMPSIMDRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
9697 SourceLocation Loc,
9698 unsigned IVSize,
9699 bool IVSigned) {
9700 llvm_unreachable("Not supported in SIMD-only mode");
9701}
9702
9703void CGOpenMPSIMDRuntime::emitForStaticFinish(CodeGenFunction &CGF,
9704 SourceLocation Loc,
9705 OpenMPDirectiveKind DKind) {
9706 llvm_unreachable("Not supported in SIMD-only mode");
9707}
9708
9709llvm::Value *CGOpenMPSIMDRuntime::emitForNext(CodeGenFunction &CGF,
9710 SourceLocation Loc,
9711 unsigned IVSize, bool IVSigned,
9712 Address IL, Address LB,
9713 Address UB, Address ST) {
9714 llvm_unreachable("Not supported in SIMD-only mode");
9715}
9716
9717void CGOpenMPSIMDRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
9718 llvm::Value *NumThreads,
9719 SourceLocation Loc) {
9720 llvm_unreachable("Not supported in SIMD-only mode");
9721}
9722
9723void CGOpenMPSIMDRuntime::emitProcBindClause(CodeGenFunction &CGF,
9724 OpenMPProcBindClauseKind ProcBind,
9725 SourceLocation Loc) {
9726 llvm_unreachable("Not supported in SIMD-only mode");
9727}
9728
9729Address CGOpenMPSIMDRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
9730 const VarDecl *VD,
9731 Address VDAddr,
9732 SourceLocation Loc) {
9733 llvm_unreachable("Not supported in SIMD-only mode");
9734}
9735
9736llvm::Function *CGOpenMPSIMDRuntime::emitThreadPrivateVarDefinition(
9737 const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit,
9738 CodeGenFunction *CGF) {
9739 llvm_unreachable("Not supported in SIMD-only mode");
9740}
9741
9742Address CGOpenMPSIMDRuntime::getAddrOfArtificialThreadPrivate(
9743 CodeGenFunction &CGF, QualType VarType, StringRef Name) {
9744 llvm_unreachable("Not supported in SIMD-only mode");
9745}
9746
9747void CGOpenMPSIMDRuntime::emitFlush(CodeGenFunction &CGF,
9748 ArrayRef<const Expr *> Vars,
9749 SourceLocation Loc) {
9750 llvm_unreachable("Not supported in SIMD-only mode");
9751}
9752
9753void CGOpenMPSIMDRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
9754 const OMPExecutableDirective &D,
9755 llvm::Value *TaskFunction,
9756 QualType SharedsTy, Address Shareds,
9757 const Expr *IfCond,
9758 const OMPTaskDataTy &Data) {
9759 llvm_unreachable("Not supported in SIMD-only mode");
9760}
9761
9762void CGOpenMPSIMDRuntime::emitTaskLoopCall(
9763 CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D,
9764 llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
9765 const Expr *IfCond, const OMPTaskDataTy &Data) {
9766 llvm_unreachable("Not supported in SIMD-only mode");
9767}
9768
9769void CGOpenMPSIMDRuntime::emitReduction(
9770 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
9771 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
9772 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
9773 assert(Options.SimpleReduction && "Only simple reduction is expected.");
9774 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
9775 ReductionOps, Options);
9776}
9777
9778llvm::Value *CGOpenMPSIMDRuntime::emitTaskReductionInit(
9779 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
9780 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
9781 llvm_unreachable("Not supported in SIMD-only mode");
9782}
9783
9784void CGOpenMPSIMDRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
9785 SourceLocation Loc,
9786 ReductionCodeGen &RCG,
9787 unsigned N) {
9788 llvm_unreachable("Not supported in SIMD-only mode");
9789}
9790
9791Address CGOpenMPSIMDRuntime::getTaskReductionItem(CodeGenFunction &CGF,
9792 SourceLocation Loc,
9793 llvm::Value *ReductionsPtr,
9794 LValue SharedLVal) {
9795 llvm_unreachable("Not supported in SIMD-only mode");
9796}
9797
9798void CGOpenMPSIMDRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
9799 SourceLocation Loc) {
9800 llvm_unreachable("Not supported in SIMD-only mode");
9801}
9802
9803void CGOpenMPSIMDRuntime::emitCancellationPointCall(
9804 CodeGenFunction &CGF, SourceLocation Loc,
9805 OpenMPDirectiveKind CancelRegion) {
9806 llvm_unreachable("Not supported in SIMD-only mode");
9807}
9808
9809void CGOpenMPSIMDRuntime::emitCancelCall(CodeGenFunction &CGF,
9810 SourceLocation Loc, const Expr *IfCond,
9811 OpenMPDirectiveKind CancelRegion) {
9812 llvm_unreachable("Not supported in SIMD-only mode");
9813}
9814
9815void CGOpenMPSIMDRuntime::emitTargetOutlinedFunction(
9816 const OMPExecutableDirective &D, StringRef ParentName,
9817 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
9818 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
9819 llvm_unreachable("Not supported in SIMD-only mode");
9820}
9821
9822void CGOpenMPSIMDRuntime::emitTargetCall(CodeGenFunction &CGF,
9823 const OMPExecutableDirective &D,
9824 llvm::Value *OutlinedFn,
9825 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00009826 const Expr *IfCond, const Expr *Device) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009827 llvm_unreachable("Not supported in SIMD-only mode");
9828}
9829
9830bool CGOpenMPSIMDRuntime::emitTargetFunctions(GlobalDecl GD) {
9831 llvm_unreachable("Not supported in SIMD-only mode");
9832}
9833
9834bool CGOpenMPSIMDRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
9835 llvm_unreachable("Not supported in SIMD-only mode");
9836}
9837
9838bool CGOpenMPSIMDRuntime::emitTargetGlobal(GlobalDecl GD) {
9839 return false;
9840}
9841
9842llvm::Function *CGOpenMPSIMDRuntime::emitRegistrationFunction() {
9843 return nullptr;
9844}
9845
9846void CGOpenMPSIMDRuntime::emitTeamsCall(CodeGenFunction &CGF,
9847 const OMPExecutableDirective &D,
9848 SourceLocation Loc,
9849 llvm::Value *OutlinedFn,
9850 ArrayRef<llvm::Value *> CapturedVars) {
9851 llvm_unreachable("Not supported in SIMD-only mode");
9852}
9853
9854void CGOpenMPSIMDRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
9855 const Expr *NumTeams,
9856 const Expr *ThreadLimit,
9857 SourceLocation Loc) {
9858 llvm_unreachable("Not supported in SIMD-only mode");
9859}
9860
9861void CGOpenMPSIMDRuntime::emitTargetDataCalls(
9862 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
9863 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
9864 llvm_unreachable("Not supported in SIMD-only mode");
9865}
9866
9867void CGOpenMPSIMDRuntime::emitTargetDataStandAloneCall(
9868 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
9869 const Expr *Device) {
9870 llvm_unreachable("Not supported in SIMD-only mode");
9871}
9872
9873void CGOpenMPSIMDRuntime::emitDoacrossInit(CodeGenFunction &CGF,
Alexey Bataevf138fda2018-08-13 19:04:24 +00009874 const OMPLoopDirective &D,
9875 ArrayRef<Expr *> NumIterations) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009876 llvm_unreachable("Not supported in SIMD-only mode");
9877}
9878
9879void CGOpenMPSIMDRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
9880 const OMPDependClause *C) {
9881 llvm_unreachable("Not supported in SIMD-only mode");
9882}
9883
9884const VarDecl *
9885CGOpenMPSIMDRuntime::translateParameter(const FieldDecl *FD,
9886 const VarDecl *NativeParam) const {
9887 llvm_unreachable("Not supported in SIMD-only mode");
9888}
9889
9890Address
9891CGOpenMPSIMDRuntime::getParameterAddress(CodeGenFunction &CGF,
9892 const VarDecl *NativeParam,
9893 const VarDecl *TargetParam) const {
9894 llvm_unreachable("Not supported in SIMD-only mode");
9895}