blob: ad02ee6e21e05f079afc01265b0b64054c9825fd [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.
Alexey Bataev92e82f92015-11-23 13:33:42 +00005090 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
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;
Alexey Bataeveb482352015-12-18 05:05:56 +00005157 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005158 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005159 case OMPC_DEPEND_unknown:
5160 llvm_unreachable("Unknown task dependence type");
5161 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005162 LValue FlagsLVal = CGF.EmitLValueForField(
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005163 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
5164 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
5165 FlagsLVal);
5166 }
John McCall7f416cc2015-09-08 08:05:57 +00005167 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5168 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005169 CGF.VoidPtrTy);
5170 }
5171
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005172 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev62b63b12015-03-10 07:28:44 +00005173 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005174 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
5175 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
5176 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
5177 // list is not empty
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005178 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5179 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00005180 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
5181 llvm::Value *DepTaskArgs[7];
5182 if (NumDependencies) {
5183 DepTaskArgs[0] = UpLoc;
5184 DepTaskArgs[1] = ThreadID;
5185 DepTaskArgs[2] = NewTask;
5186 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
5187 DepTaskArgs[4] = DependenciesArray.getPointer();
5188 DepTaskArgs[5] = CGF.Builder.getInt32(0);
5189 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5190 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005191 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
5192 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005193 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005194 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005195 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005196 LValue PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005197 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
5198 }
John McCall7f416cc2015-09-08 08:05:57 +00005199 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005200 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00005201 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00005202 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00005203 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00005204 TaskArgs);
5205 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00005206 // Check if parent region is untied and build return for untied task;
5207 if (auto *Region =
5208 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5209 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00005210 };
John McCall7f416cc2015-09-08 08:05:57 +00005211
5212 llvm::Value *DepWaitTaskArgs[6];
5213 if (NumDependencies) {
5214 DepWaitTaskArgs[0] = UpLoc;
5215 DepWaitTaskArgs[1] = ThreadID;
5216 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
5217 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
5218 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
5219 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5220 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005221 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00005222 NumDependencies, &DepWaitTaskArgs,
5223 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005224 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005225 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
5226 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
5227 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
5228 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
5229 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00005230 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005231 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005232 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005233 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00005234 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
5235 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005236 Action.Enter(CGF);
5237 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00005238 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00005239 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005240 };
5241
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005242 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
5243 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005244 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
5245 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005246 RegionCodeGenTy RCG(CodeGen);
5247 CommonActionTy Action(
5248 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
5249 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
5250 RCG.setAction(Action);
5251 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00005252 };
John McCall7f416cc2015-09-08 08:05:57 +00005253
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005254 if (IfCond) {
Alexey Bataev1d677132015-04-22 13:57:31 +00005255 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005256 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005257 RegionCodeGenTy ThenRCG(ThenCodeGen);
5258 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00005259 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00005260}
5261
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005262void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
5263 const OMPLoopDirective &D,
5264 llvm::Value *TaskFunction,
5265 QualType SharedsTy, Address Shareds,
5266 const Expr *IfCond,
5267 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00005268 if (!CGF.HaveInsertPoint())
5269 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005270 TaskResultTy Result =
5271 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005272 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc()
Alexey Bataev7292c292016-04-25 12:22:29 +00005273 // libcall.
5274 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
5275 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
5276 // sched, kmp_uint64 grainsize, void *task_dup);
5277 llvm::Value *ThreadID = getThreadID(CGF, Loc);
5278 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
5279 llvm::Value *IfVal;
5280 if (IfCond) {
5281 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
5282 /*isSigned=*/true);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005283 } else {
Alexey Bataev7292c292016-04-25 12:22:29 +00005284 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005285 }
Alexey Bataev7292c292016-04-25 12:22:29 +00005286
5287 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005288 Result.TDBase,
5289 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005290 const auto *LBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005291 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
5292 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
5293 /*IsInitializer=*/true);
5294 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005295 Result.TDBase,
5296 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005297 const auto *UBVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005298 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
5299 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
5300 /*IsInitializer=*/true);
5301 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005302 Result.TDBase,
5303 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005304 const auto *StVar =
Alexey Bataev7292c292016-04-25 12:22:29 +00005305 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
5306 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
5307 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005308 // Store reductions address.
5309 LValue RedLVal = CGF.EmitLValueForField(
5310 Result.TDBase,
5311 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005312 if (Data.Reductions) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005313 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005314 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005315 CGF.EmitNullInitialization(RedLVal.getAddress(),
5316 CGF.getContext().VoidPtrTy);
5317 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005318 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00005319 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00005320 UpLoc,
5321 ThreadID,
5322 Result.NewTask,
5323 IfVal,
5324 LBLVal.getPointer(),
5325 UBLVal.getPointer(),
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005326 CGF.EmitLoadOfScalar(StLVal, Loc),
Alexey Bataevac6e4de2018-10-24 19:06:37 +00005327 llvm::ConstantInt::getSigned(
5328 CGF.IntTy, 1), // Always 1 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005329 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005330 CGF.IntTy, Data.Schedule.getPointer()
5331 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005332 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00005333 Data.Schedule.getPointer()
5334 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00005335 /*isSigned=*/false)
5336 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00005337 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5338 Result.TaskDupFn, CGF.VoidPtrTy)
5339 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00005340 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
5341}
5342
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005343/// Emit reduction operation for each element of array (required for
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005344/// array sections) LHS op = RHS.
5345/// \param Type Type of array.
5346/// \param LHSVar Variable on the left side of the reduction operation
5347/// (references element of array in original variable).
5348/// \param RHSVar Variable on the right side of the reduction operation
5349/// (references element of array in original variable).
5350/// \param RedOpGen Generator of reduction operation with use of LHSVar and
5351/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00005352static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005353 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
5354 const VarDecl *RHSVar,
5355 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
5356 const Expr *, const Expr *)> &RedOpGen,
5357 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
5358 const Expr *UpExpr = nullptr) {
5359 // Perform element-by-element initialization.
5360 QualType ElementTy;
5361 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
5362 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
5363
5364 // Drill down to the base element type on both arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005365 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
5366 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005367
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005368 llvm::Value *RHSBegin = RHSAddr.getPointer();
5369 llvm::Value *LHSBegin = LHSAddr.getPointer();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005370 // Cast from pointer to array type to pointer to single element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005371 llvm::Value *LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005372 // The basic structure here is a while-do loop.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005373 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
5374 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
5375 llvm::Value *IsEmpty =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005376 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
5377 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
5378
5379 // Enter the loop body, making that address the current address.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005380 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005381 CGF.EmitBlock(BodyBB);
5382
5383 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
5384
5385 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
5386 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
5387 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
5388 Address RHSElementCurrent =
5389 Address(RHSElementPHI,
5390 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5391
5392 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
5393 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
5394 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
5395 Address LHSElementCurrent =
5396 Address(LHSElementPHI,
5397 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
5398
5399 // Emit copy.
5400 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005401 Scope.addPrivate(LHSVar, [=]() { return LHSElementCurrent; });
5402 Scope.addPrivate(RHSVar, [=]() { return RHSElementCurrent; });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005403 Scope.Privatize();
5404 RedOpGen(CGF, XExpr, EExpr, UpExpr);
5405 Scope.ForceCleanup();
5406
5407 // Shift the address forward by one element.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005408 llvm::Value *LHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005409 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005410 llvm::Value *RHSElementNext = CGF.Builder.CreateConstGEP1_32(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005411 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
5412 // Check whether we've reached the end.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005413 llvm::Value *Done =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005414 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
5415 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
5416 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
5417 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
5418
5419 // Done.
5420 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
5421}
5422
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005423/// Emit reduction combiner. If the combiner is a simple expression emit it as
5424/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
5425/// UDR combiner function.
5426static void emitReductionCombiner(CodeGenFunction &CGF,
5427 const Expr *ReductionOp) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005428 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
5429 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
5430 if (const auto *DRE =
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005431 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005432 if (const auto *DRD =
5433 dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005434 std::pair<llvm::Function *, llvm::Function *> Reduction =
5435 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
5436 RValue Func = RValue::get(Reduction.first);
5437 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
5438 CGF.EmitIgnoredExpr(ReductionOp);
5439 return;
5440 }
5441 CGF.EmitIgnoredExpr(ReductionOp);
5442}
5443
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005444llvm::Value *CGOpenMPRuntime::emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005445 CodeGenModule &CGM, SourceLocation Loc, llvm::Type *ArgsType,
5446 ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs,
5447 ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005448 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005449
5450 // void reduction_func(void *LHSArg, void *RHSArg);
5451 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005452 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5453 ImplicitParamDecl::Other);
5454 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5455 ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005456 Args.push_back(&LHSArg);
5457 Args.push_back(&RHSArg);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005458 const auto &CGFI =
5459 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005460 std::string Name = getName({"omp", "reduction", "reduction_func"});
5461 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
5462 llvm::GlobalValue::InternalLinkage, Name,
5463 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005464 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005465 Fn->setDoesNotRecurse();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005466 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005467 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005468
5469 // Dst = (void*[n])(LHSArg);
5470 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00005471 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5472 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
5473 ArgsType), CGF.getPointerAlign());
5474 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5475 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
5476 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005477
5478 // ...
5479 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
5480 // ...
5481 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005482 auto IPriv = Privates.begin();
5483 unsigned Idx = 0;
5484 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005485 const auto *RHSVar =
5486 cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
5487 Scope.addPrivate(RHSVar, [&CGF, RHS, Idx, RHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005488 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005489 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005490 const auto *LHSVar =
5491 cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
5492 Scope.addPrivate(LHSVar, [&CGF, LHS, Idx, LHSVar]() {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005493 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00005494 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005495 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00005496 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005497 // Get array size and emit VLA type.
5498 ++Idx;
5499 Address Elem =
5500 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
5501 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005502 const VariableArrayType *VLA =
5503 CGF.getContext().getAsVariableArrayType(PrivTy);
5504 const auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005505 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00005506 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005507 CGF.EmitVariablyModifiedType(PrivTy);
5508 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005509 }
5510 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005511 IPriv = Privates.begin();
5512 auto ILHS = LHSExprs.begin();
5513 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005514 for (const Expr *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005515 if ((*IPriv)->getType()->isArrayType()) {
5516 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005517 const auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5518 const auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005519 EmitOMPAggregateReduction(
5520 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5521 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5522 emitReductionCombiner(CGF, E);
5523 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005524 } else {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005525 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00005526 emitReductionCombiner(CGF, E);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005527 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005528 ++IPriv;
5529 ++ILHS;
5530 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005531 }
5532 Scope.ForceCleanup();
5533 CGF.FinishFunction();
5534 return Fn;
5535}
5536
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005537void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
5538 const Expr *ReductionOp,
5539 const Expr *PrivateRef,
5540 const DeclRefExpr *LHS,
5541 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005542 if (PrivateRef->getType()->isArrayType()) {
5543 // Emit reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005544 const auto *LHSVar = cast<VarDecl>(LHS->getDecl());
5545 const auto *RHSVar = cast<VarDecl>(RHS->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005546 EmitOMPAggregateReduction(
5547 CGF, PrivateRef->getType(), LHSVar, RHSVar,
5548 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
5549 emitReductionCombiner(CGF, ReductionOp);
5550 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005551 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005552 // Emit reduction for array subscript or single variable.
5553 emitReductionCombiner(CGF, ReductionOp);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005554 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005555}
5556
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005557void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005558 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005559 ArrayRef<const Expr *> LHSExprs,
5560 ArrayRef<const Expr *> RHSExprs,
5561 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005562 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005563 if (!CGF.HaveInsertPoint())
5564 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005565
5566 bool WithNowait = Options.WithNowait;
5567 bool SimpleReduction = Options.SimpleReduction;
5568
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005569 // Next code should be emitted for reduction:
5570 //
5571 // static kmp_critical_name lock = { 0 };
5572 //
5573 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
5574 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
5575 // ...
5576 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
5577 // *(Type<n>-1*)rhs[<n>-1]);
5578 // }
5579 //
5580 // ...
5581 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
5582 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5583 // RedList, reduce_func, &<lock>)) {
5584 // case 1:
5585 // ...
5586 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5587 // ...
5588 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5589 // break;
5590 // case 2:
5591 // ...
5592 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5593 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00005594 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005595 // break;
5596 // default:;
5597 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005598 //
5599 // if SimpleReduction is true, only the next code is generated:
5600 // ...
5601 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5602 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005603
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005604 ASTContext &C = CGM.getContext();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005605
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005606 if (SimpleReduction) {
5607 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005608 auto IPriv = Privates.begin();
5609 auto ILHS = LHSExprs.begin();
5610 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005611 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005612 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5613 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005614 ++IPriv;
5615 ++ILHS;
5616 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00005617 }
5618 return;
5619 }
5620
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005621 // 1. Build a list of reduction variables.
5622 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005623 auto Size = RHSExprs.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005624 for (const Expr *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00005625 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005626 // Reserve place for array size.
5627 ++Size;
5628 }
5629 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005630 QualType ReductionArrayTy =
5631 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
5632 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00005633 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005634 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005635 auto IPriv = Privates.begin();
5636 unsigned Idx = 0;
5637 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00005638 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005639 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00005640 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005641 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00005642 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
5643 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00005644 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005645 // Store array size.
5646 ++Idx;
5647 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
5648 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00005649 llvm::Value *Size = CGF.Builder.CreateIntCast(
5650 CGF.getVLASize(
5651 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
Sander de Smalen891af03a2018-02-03 13:55:59 +00005652 .NumElts,
Alexey Bataev1189bd02016-01-26 12:20:39 +00005653 CGF.SizeTy, /*isSigned=*/false);
5654 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
5655 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005656 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005657 }
5658
5659 // 2. Emit reduce_func().
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005660 llvm::Value *ReductionFn = emitReductionFunction(
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005661 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(),
5662 Privates, LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005663
5664 // 3. Create static kmp_critical_name lock = { 0 };
Alexey Bataev18fa2322018-05-02 14:20:50 +00005665 std::string Name = getName({"reduction"});
5666 llvm::Value *Lock = getCriticalRegionLock(Name);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005667
5668 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
5669 // RedList, reduce_func, &<lock>);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005670 llvm::Value *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
5671 llvm::Value *ThreadId = getThreadID(CGF, Loc);
5672 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
5673 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Samuel Antao4c8035b2016-12-12 18:00:20 +00005674 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005675 llvm::Value *Args[] = {
5676 IdentTLoc, // ident_t *<loc>
5677 ThreadId, // i32 <gtid>
5678 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
5679 ReductionArrayTySize, // size_type sizeof(RedList)
5680 RL, // void *RedList
5681 ReductionFn, // void (*) (void *, void *) <reduce_func>
5682 Lock // kmp_critical_name *&<lock>
5683 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005684 llvm::Value *Res = CGF.EmitRuntimeCall(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005685 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5686 : OMPRTL__kmpc_reduce),
5687 Args);
5688
5689 // 5. Build switch(res)
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005690 llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5691 llvm::SwitchInst *SwInst =
5692 CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005693
5694 // 6. Build case 1:
5695 // ...
5696 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5697 // ...
5698 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5699 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005700 llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005701 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5702 CGF.EmitBlock(Case1BB);
5703
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005704 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5705 llvm::Value *EndArgs[] = {
5706 IdentTLoc, // ident_t *<loc>
5707 ThreadId, // i32 <gtid>
5708 Lock // kmp_critical_name *&<lock>
5709 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005710 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps](
5711 CodeGenFunction &CGF, PrePostActionTy &Action) {
5712 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005713 auto IPriv = Privates.begin();
5714 auto ILHS = LHSExprs.begin();
5715 auto IRHS = RHSExprs.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005716 for (const Expr *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005717 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5718 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005719 ++IPriv;
5720 ++ILHS;
5721 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005722 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005723 };
5724 RegionCodeGenTy RCG(CodeGen);
5725 CommonActionTy Action(
5726 nullptr, llvm::None,
5727 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5728 : OMPRTL__kmpc_end_reduce),
5729 EndArgs);
5730 RCG.setAction(Action);
5731 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005732
5733 CGF.EmitBranch(DefaultBB);
5734
5735 // 7. Build case 2:
5736 // ...
5737 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5738 // ...
5739 // break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005740 llvm::BasicBlock *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005741 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5742 CGF.EmitBlock(Case2BB);
5743
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005744 auto &&AtomicCodeGen = [Loc, Privates, LHSExprs, RHSExprs, ReductionOps](
5745 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005746 auto ILHS = LHSExprs.begin();
5747 auto IRHS = RHSExprs.begin();
5748 auto IPriv = Privates.begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005749 for (const Expr *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005750 const Expr *XExpr = nullptr;
5751 const Expr *EExpr = nullptr;
5752 const Expr *UpExpr = nullptr;
5753 BinaryOperatorKind BO = BO_Comma;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005754 if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005755 if (BO->getOpcode() == BO_Assign) {
5756 XExpr = BO->getLHS();
5757 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005758 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005759 }
5760 // Try to emit update expression as a simple atomic.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005761 const Expr *RHSExpr = UpExpr;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005762 if (RHSExpr) {
5763 // Analyze RHS part of the whole expression.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005764 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005765 RHSExpr->IgnoreParenImpCasts())) {
5766 // If this is a conditional operator, analyze its condition for
5767 // min/max reduction operator.
5768 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005769 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005770 if (const auto *BORHS =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005771 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5772 EExpr = BORHS->getRHS();
5773 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005774 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005775 }
5776 if (XExpr) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005777 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005778 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005779 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5780 const Expr *EExpr, const Expr *UpExpr) {
5781 LValue X = CGF.EmitLValue(XExpr);
5782 RValue E;
5783 if (EExpr)
5784 E = CGF.EmitAnyExpr(EExpr);
5785 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005786 X, E, BO, /*IsXLHSInRHSPart=*/true,
5787 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005788 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005789 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5790 PrivateScope.addPrivate(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005791 VD, [&CGF, VD, XRValue, Loc]() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005792 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5793 CGF.emitOMPSimpleStore(
5794 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5795 VD->getType().getNonReferenceType(), Loc);
5796 return LHSTemp;
5797 });
5798 (void)PrivateScope.Privatize();
5799 return CGF.EmitAnyExpr(UpExpr);
5800 });
5801 };
5802 if ((*IPriv)->getType()->isArrayType()) {
5803 // Emit atomic reduction for array section.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005804 const auto *RHSVar =
5805 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005806 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5807 AtomicRedGen, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005808 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005809 // Emit atomic reduction for array subscript or single variable.
5810 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005811 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005812 } else {
5813 // Emit as a critical region.
5814 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005815 const Expr *, const Expr *) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005816 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005817 std::string Name = RT.getName({"atomic_reduction"});
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005818 RT.emitCriticalRegion(
Alexey Bataev18fa2322018-05-02 14:20:50 +00005819 CGF, Name,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005820 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5821 Action.Enter(CGF);
5822 emitReductionCombiner(CGF, E);
5823 },
5824 Loc);
5825 };
5826 if ((*IPriv)->getType()->isArrayType()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005827 const auto *LHSVar =
5828 cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5829 const auto *RHSVar =
5830 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005831 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5832 CritRedGen);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005833 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005834 CritRedGen(CGF, nullptr, nullptr, nullptr);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005835 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005836 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005837 ++ILHS;
5838 ++IRHS;
5839 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005840 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005841 };
5842 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5843 if (!WithNowait) {
5844 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5845 llvm::Value *EndArgs[] = {
5846 IdentTLoc, // ident_t *<loc>
5847 ThreadId, // i32 <gtid>
5848 Lock // kmp_critical_name *&<lock>
5849 };
5850 CommonActionTy Action(nullptr, llvm::None,
5851 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5852 EndArgs);
5853 AtomicRCG.setAction(Action);
5854 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005855 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005856 AtomicRCG(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005857 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005858
5859 CGF.EmitBranch(DefaultBB);
5860 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5861}
5862
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005863/// Generates unique name for artificial threadprivate variables.
Alexey Bataev1c44e152018-03-06 18:59:43 +00005864/// Format is: <Prefix> "." <Decl_mangled_name> "_" "<Decl_start_loc_raw_enc>"
5865static std::string generateUniqueName(CodeGenModule &CGM, StringRef Prefix,
5866 const Expr *Ref) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005867 SmallString<256> Buffer;
5868 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev1c44e152018-03-06 18:59:43 +00005869 const clang::DeclRefExpr *DE;
5870 const VarDecl *D = ::getBaseDecl(Ref, DE);
5871 if (!D)
5872 D = cast<VarDecl>(cast<DeclRefExpr>(Ref)->getDecl());
5873 D = D->getCanonicalDecl();
Alexey Bataev18fa2322018-05-02 14:20:50 +00005874 std::string Name = CGM.getOpenMPRuntime().getName(
5875 {D->isLocalVarDeclOrParm() ? D->getName() : CGM.getMangledName(D)});
5876 Out << Prefix << Name << "_"
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005877 << D->getCanonicalDecl()->getBeginLoc().getRawEncoding();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005878 return Out.str();
5879}
5880
5881/// Emits reduction initializer function:
5882/// \code
5883/// void @.red_init(void* %arg) {
5884/// %0 = bitcast void* %arg to <type>*
5885/// store <type> <init>, <type>* %0
5886/// ret void
5887/// }
5888/// \endcode
5889static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5890 SourceLocation Loc,
5891 ReductionCodeGen &RCG, unsigned N) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005892 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005893 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005894 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5895 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005896 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005897 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005898 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005899 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005900 std::string Name = CGM.getOpenMPRuntime().getName({"red_init", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005901 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005902 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005903 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005904 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005905 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005906 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005907 Address PrivateAddr = CGF.EmitLoadOfPointer(
5908 CGF.GetAddrOfLocalVar(&Param),
5909 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5910 llvm::Value *Size = nullptr;
5911 // If the size of the reduction item is non-constant, load it from global
5912 // threadprivate variable.
5913 if (RCG.getSizes(N).second) {
5914 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5915 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005916 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005917 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5918 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005919 }
5920 RCG.emitAggregateType(CGF, N, Size);
5921 LValue SharedLVal;
5922 // If initializer uses initializer from declare reduction construct, emit a
5923 // pointer to the address of the original reduction item (reuired by reduction
5924 // initializer)
5925 if (RCG.usesReductionInitializer(N)) {
5926 Address SharedAddr =
5927 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5928 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00005929 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataev21dab122018-03-09 15:20:30 +00005930 SharedAddr = CGF.EmitLoadOfPointer(
5931 SharedAddr,
5932 CGM.getContext().VoidPtrTy.castAs<PointerType>()->getTypePtr());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005933 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5934 } else {
5935 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5936 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5937 CGM.getContext().VoidPtrTy);
5938 }
5939 // Emit the initializer:
5940 // %0 = bitcast void* %arg to <type>*
5941 // store <type> <init>, <type>* %0
5942 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5943 [](CodeGenFunction &) { return false; });
5944 CGF.FinishFunction();
5945 return Fn;
5946}
5947
5948/// Emits reduction combiner function:
5949/// \code
5950/// void @.red_comb(void* %arg0, void* %arg1) {
5951/// %lhs = bitcast void* %arg0 to <type>*
5952/// %rhs = bitcast void* %arg1 to <type>*
5953/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5954/// store <type> %2, <type>* %lhs
5955/// ret void
5956/// }
5957/// \endcode
5958static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5959 SourceLocation Loc,
5960 ReductionCodeGen &RCG, unsigned N,
5961 const Expr *ReductionOp,
5962 const Expr *LHS, const Expr *RHS,
5963 const Expr *PrivateRef) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005964 ASTContext &C = CGM.getContext();
5965 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5966 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005967 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005968 ImplicitParamDecl ParamInOut(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
5969 C.VoidPtrTy, ImplicitParamDecl::Other);
5970 ImplicitParamDecl ParamIn(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
5971 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005972 Args.emplace_back(&ParamInOut);
5973 Args.emplace_back(&ParamIn);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005974 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005975 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005976 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00005977 std::string Name = CGM.getOpenMPRuntime().getName({"red_comb", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005978 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00005979 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00005980 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00005981 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005982 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00005983 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005984 llvm::Value *Size = nullptr;
5985 // If the size of the reduction item is non-constant, load it from global
5986 // threadprivate variable.
5987 if (RCG.getSizes(N).second) {
5988 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5989 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00005990 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005991 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5992 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005993 }
5994 RCG.emitAggregateType(CGF, N, Size);
5995 // Remap lhs and rhs variables to the addresses of the function arguments.
5996 // %lhs = bitcast void* %arg0 to <type>*
5997 // %rhs = bitcast void* %arg1 to <type>*
5998 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00005999 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006000 // Pull out the pointer to the variable.
6001 Address PtrAddr = CGF.EmitLoadOfPointer(
6002 CGF.GetAddrOfLocalVar(&ParamInOut),
6003 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
6004 return CGF.Builder.CreateElementBitCast(
6005 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
6006 });
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006007 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006008 // Pull out the pointer to the variable.
6009 Address PtrAddr = CGF.EmitLoadOfPointer(
6010 CGF.GetAddrOfLocalVar(&ParamIn),
6011 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
6012 return CGF.Builder.CreateElementBitCast(
6013 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
6014 });
6015 PrivateScope.Privatize();
6016 // Emit the combiner body:
6017 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
6018 // store <type> %2, <type>* %lhs
6019 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
6020 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
6021 cast<DeclRefExpr>(RHS));
6022 CGF.FinishFunction();
6023 return Fn;
6024}
6025
6026/// Emits reduction finalizer function:
6027/// \code
6028/// void @.red_fini(void* %arg) {
6029/// %0 = bitcast void* %arg to <type>*
6030/// <destroy>(<type>* %0)
6031/// ret void
6032/// }
6033/// \endcode
6034static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
6035 SourceLocation Loc,
6036 ReductionCodeGen &RCG, unsigned N) {
6037 if (!RCG.needCleanups(N))
6038 return nullptr;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006039 ASTContext &C = CGM.getContext();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006040 FunctionArgList Args;
Alexey Bataev7cae94e2018-01-04 19:45:16 +00006041 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
6042 ImplicitParamDecl::Other);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006043 Args.emplace_back(&Param);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006044 const auto &FnInfo =
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006045 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006046 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
Alexey Bataev18fa2322018-05-02 14:20:50 +00006047 std::string Name = CGM.getOpenMPRuntime().getName({"red_fini", ""});
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006048 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00006049 Name, &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00006050 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
Alexey Bataevc0f879b2018-04-10 20:10:53 +00006051 Fn->setDoesNotRecurse();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006052 CodeGenFunction CGF(CGM);
Alexey Bataev7cae94e2018-01-04 19:45:16 +00006053 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006054 Address PrivateAddr = CGF.EmitLoadOfPointer(
6055 CGF.GetAddrOfLocalVar(&Param),
6056 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
6057 llvm::Value *Size = nullptr;
6058 // If the size of the reduction item is non-constant, load it from global
6059 // threadprivate variable.
6060 if (RCG.getSizes(N).second) {
6061 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
6062 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00006063 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00006064 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
6065 CGM.getContext().getSizeType(), Loc);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006066 }
6067 RCG.emitAggregateType(CGF, N, Size);
6068 // Emit the finalizer body:
6069 // <destroy>(<type>* %0)
6070 RCG.emitCleanups(CGF, N, PrivateAddr);
6071 CGF.FinishFunction();
6072 return Fn;
6073}
6074
6075llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
6076 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
6077 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
6078 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
6079 return nullptr;
6080
6081 // Build typedef struct:
6082 // kmp_task_red_input {
6083 // void *reduce_shar; // shared reduction item
6084 // size_t reduce_size; // size of data item
6085 // void *reduce_init; // data initialization routine
6086 // void *reduce_fini; // data finalization routine
6087 // void *reduce_comb; // data combiner routine
6088 // kmp_task_red_flags_t flags; // flags for additional info from compiler
6089 // } kmp_task_red_input_t;
6090 ASTContext &C = CGM.getContext();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006091 RecordDecl *RD = C.buildImplicitRecord("kmp_task_red_input_t");
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006092 RD->startDefinition();
6093 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6094 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
6095 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6096 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6097 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
6098 const FieldDecl *FlagsFD = addFieldToRecordDecl(
6099 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
6100 RD->completeDefinition();
6101 QualType RDType = C.getRecordType(RD);
6102 unsigned Size = Data.ReductionVars.size();
6103 llvm::APInt ArraySize(/*numBits=*/64, Size);
6104 QualType ArrayRDType = C.getConstantArrayType(
6105 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
6106 // kmp_task_red_input_t .rd_input.[Size];
6107 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
6108 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
6109 Data.ReductionOps);
6110 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
6111 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
6112 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
6113 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
6114 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
6115 TaskRedInput.getPointer(), Idxs,
6116 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
6117 ".rd_input.gep.");
6118 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
6119 // ElemLVal.reduce_shar = &Shareds[Cnt];
6120 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
6121 RCG.emitSharedLValue(CGF, Cnt);
6122 llvm::Value *CastedShared =
6123 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
6124 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
6125 RCG.emitAggregateType(CGF, Cnt);
6126 llvm::Value *SizeValInChars;
6127 llvm::Value *SizeVal;
6128 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
6129 // We use delayed creation/initialization for VLAs, array sections and
6130 // custom reduction initializations. It is required because runtime does not
6131 // provide the way to pass the sizes of VLAs/array sections to
6132 // initializer/combiner/finalizer functions and does not pass the pointer to
6133 // original reduction item to the initializer. Instead threadprivate global
6134 // variables are used to store these values and use them in the functions.
6135 bool DelayedCreation = !!SizeVal;
6136 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
6137 /*isSigned=*/false);
6138 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
6139 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
6140 // ElemLVal.reduce_init = init;
6141 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
6142 llvm::Value *InitAddr =
6143 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
6144 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
6145 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
6146 // ElemLVal.reduce_fini = fini;
6147 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
6148 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
6149 llvm::Value *FiniAddr = Fini
6150 ? CGF.EmitCastToVoidPtr(Fini)
6151 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
6152 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
6153 // ElemLVal.reduce_comb = comb;
6154 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
6155 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
6156 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
6157 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
6158 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
6159 // ElemLVal.flags = 0;
6160 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
6161 if (DelayedCreation) {
6162 CGF.EmitStoreOfScalar(
6163 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
6164 FlagsLVal);
6165 } else
6166 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
6167 }
6168 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
6169 // *data);
6170 llvm::Value *Args[] = {
6171 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6172 /*isSigned=*/true),
6173 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
6174 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
6175 CGM.VoidPtrTy)};
6176 return CGF.EmitRuntimeCall(
6177 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
6178}
6179
6180void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
6181 SourceLocation Loc,
6182 ReductionCodeGen &RCG,
6183 unsigned N) {
6184 auto Sizes = RCG.getSizes(N);
6185 // Emit threadprivate global variable if the type is non-constant
6186 // (Sizes.second = nullptr).
6187 if (Sizes.second) {
6188 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
6189 /*isSigned=*/false);
6190 Address SizeAddr = getAddrOfArtificialThreadPrivate(
6191 CGF, CGM.getContext().getSizeType(),
Alexey Bataev1c44e152018-03-06 18:59:43 +00006192 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006193 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
6194 }
6195 // Store address of the original reduction item if custom initializer is used.
6196 if (RCG.usesReductionInitializer(N)) {
6197 Address SharedAddr = getAddrOfArtificialThreadPrivate(
6198 CGF, CGM.getContext().VoidPtrTy,
Alexey Bataev1c44e152018-03-06 18:59:43 +00006199 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N)));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00006200 CGF.Builder.CreateStore(
6201 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6202 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
6203 SharedAddr, /*IsVolatile=*/false);
6204 }
6205}
6206
6207Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
6208 SourceLocation Loc,
6209 llvm::Value *ReductionsPtr,
6210 LValue SharedLVal) {
6211 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
6212 // *d);
6213 llvm::Value *Args[] = {
6214 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
6215 /*isSigned=*/true),
6216 ReductionsPtr,
6217 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
6218 CGM.VoidPtrTy)};
6219 return Address(
6220 CGF.EmitRuntimeCall(
6221 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
6222 SharedLVal.getAlignment());
6223}
6224
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006225void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
6226 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006227 if (!CGF.HaveInsertPoint())
6228 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006229 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
6230 // global_tid);
6231 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
6232 // Ignore return result until untied tasks are supported.
6233 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00006234 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
6235 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00006236}
6237
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006238void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006239 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006240 const RegionCodeGenTy &CodeGen,
6241 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006242 if (!CGF.HaveInsertPoint())
6243 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00006244 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00006245 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00006246}
6247
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006248namespace {
6249enum RTCancelKind {
6250 CancelNoreq = 0,
6251 CancelParallel = 1,
6252 CancelLoop = 2,
6253 CancelSections = 3,
6254 CancelTaskgroup = 4
6255};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00006256} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006257
6258static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
6259 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00006260 if (CancelRegion == OMPD_parallel)
6261 CancelKind = CancelParallel;
6262 else if (CancelRegion == OMPD_for)
6263 CancelKind = CancelLoop;
6264 else if (CancelRegion == OMPD_sections)
6265 CancelKind = CancelSections;
6266 else {
6267 assert(CancelRegion == OMPD_taskgroup);
6268 CancelKind = CancelTaskgroup;
6269 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006270 return CancelKind;
6271}
6272
6273void CGOpenMPRuntime::emitCancellationPointCall(
6274 CodeGenFunction &CGF, SourceLocation Loc,
6275 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006276 if (!CGF.HaveInsertPoint())
6277 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006278 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
6279 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006280 if (auto *OMPRegionInfo =
6281 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00006282 // For 'cancellation point taskgroup', the task region info may not have a
6283 // cancel. This may instead happen in another adjacent task.
6284 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006285 llvm::Value *Args[] = {
6286 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
6287 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006288 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006289 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006290 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
6291 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006292 // exit from construct;
6293 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006294 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6295 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6296 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006297 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6298 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006299 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006300 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev25e5b442015-09-15 12:52:43 +00006301 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00006302 CGF.EmitBranchThroughCleanup(CancelDest);
6303 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6304 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006305 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00006306}
6307
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006308void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00006309 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006310 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006311 if (!CGF.HaveInsertPoint())
6312 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006313 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
6314 // kmp_int32 cncl_kind);
6315 if (auto *OMPRegionInfo =
6316 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006317 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
6318 PrePostActionTy &) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006319 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00006320 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006321 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00006322 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
6323 // Ignore return result until untied tasks are supported.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006324 llvm::Value *Result = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006325 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00006326 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00006327 // exit from construct;
6328 // }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006329 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
6330 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
6331 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
Alexey Bataev87933c72015-09-18 08:07:34 +00006332 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
6333 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00006334 // exit from construct;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006335 CodeGenFunction::JumpDest CancelDest =
Alexey Bataev87933c72015-09-18 08:07:34 +00006336 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
6337 CGF.EmitBranchThroughCleanup(CancelDest);
6338 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
6339 };
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006340 if (IfCond) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006341 emitOMPIfClause(CGF, IfCond, ThenGen,
6342 [](CodeGenFunction &, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006343 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006344 RegionCodeGenTy ThenRCG(ThenGen);
6345 ThenRCG(CGF);
6346 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00006347 }
6348}
Samuel Antaobed3c462015-10-02 16:14:20 +00006349
Samuel Antaoee8fb302016-01-06 13:42:12 +00006350void CGOpenMPRuntime::emitTargetOutlinedFunction(
6351 const OMPExecutableDirective &D, StringRef ParentName,
6352 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006353 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00006354 assert(!ParentName.empty() && "Invalid target region parent name!");
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006355 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
6356 IsOffloadEntry, CodeGen);
6357}
6358
6359void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
6360 const OMPExecutableDirective &D, StringRef ParentName,
6361 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
6362 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00006363 // Create a unique name for the entry function using the source location
6364 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00006365 //
Samuel Antao2de62b02016-02-13 23:35:10 +00006366 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00006367 //
6368 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00006369 // mangled name of the function that encloses the target region and BB is the
6370 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00006371
6372 unsigned DeviceID;
6373 unsigned FileID;
6374 unsigned Line;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006375 getTargetEntryUniqueInfo(CGM.getContext(), D.getBeginLoc(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00006376 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006377 SmallString<64> EntryFnName;
6378 {
6379 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00006380 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
6381 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00006382 }
6383
Alexey Bataev475a7442018-01-12 19:39:11 +00006384 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00006385
Samuel Antaobed3c462015-10-02 16:14:20 +00006386 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006387 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00006388 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006389
Samuel Antao6d004262016-06-16 18:39:34 +00006390 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006391
6392 // If this target outline function is not an offload entry, we don't need to
6393 // register it.
6394 if (!IsOffloadEntry)
6395 return;
6396
6397 // The target region ID is used by the runtime library to identify the current
6398 // target region, so it only has to be unique and not necessarily point to
6399 // anything. It could be the pointer to the outlined function that implements
6400 // the target region, but we aren't using that so that the compiler doesn't
6401 // need to keep that, and could therefore inline the host function if proven
6402 // worthwhile during optimization. In the other hand, if emitting code for the
6403 // device, the ID has to be the function address so that it can retrieved from
6404 // the offloading entry and launched by the runtime library. We also mark the
6405 // outlined function to have external linkage in case we are emitting code for
6406 // the device, because these functions will be entry points to the device.
6407
6408 if (CGM.getLangOpts().OpenMPIsDevice) {
6409 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
Alexey Bataev9a700172018-05-08 14:16:57 +00006410 OutlinedFn->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
Rafael Espindolacbca4872018-01-11 22:15:12 +00006411 OutlinedFn->setDSOLocal(false);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006412 } else {
Alexey Bataevc15ea702018-05-09 18:02:37 +00006413 std::string Name = getName({EntryFnName, "region_id"});
Samuel Antaoee8fb302016-01-06 13:42:12 +00006414 OutlinedFnID = new llvm::GlobalVariable(
6415 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
Alexey Bataev9a700172018-05-08 14:16:57 +00006416 llvm::GlobalValue::WeakAnyLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00006417 llvm::Constant::getNullValue(CGM.Int8Ty), Name);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006418 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00006419
6420 // Register the information for the entry associated with this target region.
6421 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00006422 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
Alexey Bataev03f270c2018-03-30 18:31:07 +00006423 OffloadEntriesInfoManagerTy::OMPTargetRegionEntryTargetRegion);
Samuel Antaobed3c462015-10-02 16:14:20 +00006424}
6425
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006426/// discard all CompoundStmts intervening between two constructs
6427static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006428 while (const auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006429 Body = CS->body_front();
6430
6431 return Body;
6432}
6433
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006434/// Emit the number of teams for a target directive. Inspect the num_teams
6435/// clause associated with a teams construct combined or closely nested
6436/// with the target directive.
6437///
6438/// Emit a team of size one for directives such as 'target parallel' that
6439/// have no associated teams construct.
6440///
6441/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006442static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006443emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6444 CodeGenFunction &CGF,
6445 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006446 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6447 "teams directive expected to be "
6448 "emitted only for the host!");
6449
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006450 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006451
6452 // If the target directive is combined with a teams directive:
6453 // Return the value in the num_teams clause, if any.
6454 // Otherwise, return 0 to denote the runtime default.
6455 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
6456 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
6457 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006458 llvm::Value *NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
6459 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006460 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6461 /*IsSigned=*/true);
6462 }
6463
6464 // The default value is 0.
6465 return Bld.getInt32(0);
6466 }
6467
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006468 // If the target directive is combined with a parallel directive but not a
6469 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006470 if (isOpenMPParallelDirective(D.getDirectiveKind()))
6471 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006472
6473 // If the current target region has a teams region enclosed, we need to get
6474 // the number of teams to pass to the runtime function call. This is done
6475 // by generating the expression in a inlined region. This is required because
6476 // the expression is captured in the enclosing target environment when the
6477 // teams directive is not combined with target.
6478
Alexey Bataev475a7442018-01-12 19:39:11 +00006479 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006480
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006481 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006482 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006483 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006484 if (const auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006485 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6486 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6487 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
6488 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
6489 /*IsSigned=*/true);
6490 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006491
Alexey Bataev50a1c782017-12-01 21:31:08 +00006492 // If we have an enclosed teams directive but no num_teams clause we use
6493 // the default value 0.
6494 return Bld.getInt32(0);
6495 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006496 }
6497
6498 // No teams associated with the directive.
6499 return nullptr;
6500}
6501
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006502/// Emit the number of threads for a target directive. Inspect the
6503/// thread_limit clause associated with a teams construct combined or closely
6504/// nested with the target directive.
6505///
6506/// Emit the num_threads clause for directives such as 'target parallel' that
6507/// have no associated teams construct.
6508///
6509/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006510static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006511emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
6512 CodeGenFunction &CGF,
6513 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00006514 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
6515 "teams directive expected to be "
6516 "emitted only for the host!");
6517
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006518 CGBuilderTy &Bld = CGF.Builder;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006519
6520 //
6521 // If the target directive is combined with a teams directive:
6522 // Return the value in the thread_limit clause, if any.
6523 //
6524 // If the target directive is combined with a parallel directive:
6525 // Return the value in the num_threads clause, if any.
6526 //
6527 // If both clauses are set, select the minimum of the two.
6528 //
6529 // If neither teams or parallel combined directives set the number of threads
6530 // in a team, return 0 to denote the runtime default.
6531 //
6532 // If this is not a teams directive return nullptr.
6533
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006534 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
6535 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006536 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
6537 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006538 llvm::Value *ThreadLimitVal = nullptr;
6539
6540 if (const auto *ThreadLimitClause =
6541 D.getSingleClause<OMPThreadLimitClause>()) {
6542 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006543 llvm::Value *ThreadLimit =
6544 CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
6545 /*IgnoreResultAssign*/ true);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006546 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6547 /*IsSigned=*/true);
6548 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006549
6550 if (const auto *NumThreadsClause =
6551 D.getSingleClause<OMPNumThreadsClause>()) {
6552 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
6553 llvm::Value *NumThreads =
6554 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
6555 /*IgnoreResultAssign*/ true);
6556 NumThreadsVal =
6557 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
6558 }
6559
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006560 // Select the lesser of thread_limit and num_threads.
6561 if (NumThreadsVal)
6562 ThreadLimitVal = ThreadLimitVal
6563 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
6564 ThreadLimitVal),
6565 NumThreadsVal, ThreadLimitVal)
6566 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00006567
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006568 // Set default value passed to the runtime if either teams or a target
6569 // parallel type directive is found but no clause is specified.
6570 if (!ThreadLimitVal)
6571 ThreadLimitVal = DefaultThreadLimitVal;
6572
6573 return ThreadLimitVal;
6574 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00006575
Samuel Antaob68e2db2016-03-03 16:20:23 +00006576 // If the current target region has a teams region enclosed, we need to get
6577 // the thread limit to pass to the runtime function call. This is done
6578 // by generating the expression in a inlined region. This is required because
6579 // the expression is captured in the enclosing target environment when the
6580 // teams directive is not combined with target.
6581
Alexey Bataev475a7442018-01-12 19:39:11 +00006582 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006583
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006584 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>(
Carlo Bertolli6eee9062016-04-29 01:37:30 +00006585 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006586 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006587 if (const auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
Alexey Bataev50a1c782017-12-01 21:31:08 +00006588 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
6589 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
6590 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
6591 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
6592 /*IsSigned=*/true);
6593 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006594
Alexey Bataev50a1c782017-12-01 21:31:08 +00006595 // If we have an enclosed teams directive but no thread_limit clause we
6596 // use the default value 0.
6597 return CGF.Builder.getInt32(0);
6598 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00006599 }
6600
6601 // No teams associated with the directive.
6602 return nullptr;
6603}
6604
Samuel Antao86ace552016-04-27 22:40:57 +00006605namespace {
Alexey Bataevb3638132018-07-19 16:34:13 +00006606LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
6607
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006608// Utility to handle information from clauses associated with a given
Samuel Antao86ace552016-04-27 22:40:57 +00006609// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
6610// It provides a convenient interface to obtain the information and generate
6611// code for that information.
6612class MappableExprsHandler {
6613public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006614 /// Values for bit flags used to specify the mapping type for
Samuel Antao86ace552016-04-27 22:40:57 +00006615 /// offloading.
Alexey Bataevb3638132018-07-19 16:34:13 +00006616 enum OpenMPOffloadMappingFlags : uint64_t {
6617 /// No flags
6618 OMP_MAP_NONE = 0x0,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006619 /// Allocate memory on the device and move data from host to device.
Samuel Antao86ace552016-04-27 22:40:57 +00006620 OMP_MAP_TO = 0x01,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006621 /// Allocate memory on the device and move data from device to host.
Samuel Antao86ace552016-04-27 22:40:57 +00006622 OMP_MAP_FROM = 0x02,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006623 /// Always perform the requested mapping action on the element, even
Samuel Antao86ace552016-04-27 22:40:57 +00006624 /// if it was already mapped before.
6625 OMP_MAP_ALWAYS = 0x04,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006626 /// Delete the element from the device environment, ignoring the
Samuel Antao86ace552016-04-27 22:40:57 +00006627 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00006628 OMP_MAP_DELETE = 0x08,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006629 /// The element being mapped is a pointer-pointee pair; both the
George Rokos065755d2017-11-07 18:27:04 +00006630 /// pointer and the pointee should be mapped.
6631 OMP_MAP_PTR_AND_OBJ = 0x10,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006632 /// This flags signals that the base address of an entry should be
George Rokos065755d2017-11-07 18:27:04 +00006633 /// passed to the target kernel as an argument.
6634 OMP_MAP_TARGET_PARAM = 0x20,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006635 /// Signal that the runtime library has to return the device pointer
George Rokos065755d2017-11-07 18:27:04 +00006636 /// in the current position for the data being mapped. Used when we have the
6637 /// use_device_ptr clause.
6638 OMP_MAP_RETURN_PARAM = 0x40,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006639 /// This flag signals that the reference being passed is a pointer to
Samuel Antaod486f842016-05-26 16:53:38 +00006640 /// private data.
George Rokos065755d2017-11-07 18:27:04 +00006641 OMP_MAP_PRIVATE = 0x80,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006642 /// Pass the element to the device by value.
George Rokos065755d2017-11-07 18:27:04 +00006643 OMP_MAP_LITERAL = 0x100,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00006644 /// Implicit map
6645 OMP_MAP_IMPLICIT = 0x200,
Alexey Bataevb3638132018-07-19 16:34:13 +00006646 /// The 16 MSBs of the flags indicate whether the entry is member of some
6647 /// struct/class.
6648 OMP_MAP_MEMBER_OF = 0xffff000000000000,
6649 LLVM_MARK_AS_BITMASK_ENUM(/* LargestFlag = */ OMP_MAP_MEMBER_OF),
Samuel Antao86ace552016-04-27 22:40:57 +00006650 };
6651
Samuel Antaocc10b852016-07-28 14:23:26 +00006652 /// Class that associates information with a base pointer to be passed to the
6653 /// runtime library.
6654 class BasePointerInfo {
6655 /// The base pointer.
6656 llvm::Value *Ptr = nullptr;
6657 /// The base declaration that refers to this device pointer, or null if
6658 /// there is none.
6659 const ValueDecl *DevPtrDecl = nullptr;
6660
6661 public:
6662 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
6663 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
6664 llvm::Value *operator*() const { return Ptr; }
6665 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
6666 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
6667 };
6668
Alexey Bataevb3638132018-07-19 16:34:13 +00006669 using MapBaseValuesArrayTy = SmallVector<BasePointerInfo, 4>;
6670 using MapValuesArrayTy = SmallVector<llvm::Value *, 4>;
6671 using MapFlagsArrayTy = SmallVector<OpenMPOffloadMappingFlags, 4>;
6672
6673 /// Map between a struct and the its lowest & highest elements which have been
6674 /// mapped.
6675 /// [ValueDecl *] --> {LE(FieldIndex, Pointer),
6676 /// HE(FieldIndex, Pointer)}
6677 struct StructRangeInfoTy {
6678 std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> LowestElem = {
6679 0, Address::invalid()};
6680 std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> HighestElem = {
6681 0, Address::invalid()};
6682 Address Base = Address::invalid();
6683 };
Samuel Antao86ace552016-04-27 22:40:57 +00006684
6685private:
Alexey Bataevb3638132018-07-19 16:34:13 +00006686 /// Kind that defines how a device pointer has to be returned.
6687 struct MapInfo {
6688 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
6689 OpenMPMapClauseKind MapType = OMPC_MAP_unknown;
Kelvin Lief579432018-12-18 22:18:41 +00006690 ArrayRef<OpenMPMapModifierKind> MapModifiers;
Alexey Bataevb3638132018-07-19 16:34:13 +00006691 bool ReturnDevicePointer = false;
6692 bool IsImplicit = false;
6693
6694 MapInfo() = default;
6695 MapInfo(
6696 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Kelvin Lief579432018-12-18 22:18:41 +00006697 OpenMPMapClauseKind MapType,
6698 ArrayRef<OpenMPMapModifierKind> MapModifiers,
Alexey Bataevb3638132018-07-19 16:34:13 +00006699 bool ReturnDevicePointer, bool IsImplicit)
Kelvin Lief579432018-12-18 22:18:41 +00006700 : Components(Components), MapType(MapType), MapModifiers(MapModifiers),
Alexey Bataevb3638132018-07-19 16:34:13 +00006701 ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {}
6702 };
6703
6704 /// If use_device_ptr is used on a pointer which is a struct member and there
6705 /// is no map information about it, then emission of that entry is deferred
6706 /// until the whole struct has been processed.
6707 struct DeferredDevicePtrEntryTy {
6708 const Expr *IE = nullptr;
6709 const ValueDecl *VD = nullptr;
6710
6711 DeferredDevicePtrEntryTy(const Expr *IE, const ValueDecl *VD)
6712 : IE(IE), VD(VD) {}
6713 };
6714
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006715 /// Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00006716 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00006717
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006718 /// Function the directive is being generated for.
Samuel Antao86ace552016-04-27 22:40:57 +00006719 CodeGenFunction &CGF;
6720
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006721 /// Set of all first private variables in the current directive.
Samuel Antaod486f842016-05-26 16:53:38 +00006722 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
6723
Samuel Antao6890b092016-07-28 14:25:09 +00006724 /// Map between device pointer declarations and their expression components.
6725 /// The key value for declarations in 'this' is null.
6726 llvm::DenseMap<
6727 const ValueDecl *,
6728 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
6729 DevPointersMap;
6730
Samuel Antao86ace552016-04-27 22:40:57 +00006731 llvm::Value *getExprTypeSize(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006732 QualType ExprTy = E->getType().getCanonicalType();
Samuel Antao86ace552016-04-27 22:40:57 +00006733
6734 // Reference types are ignored for mapping purposes.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006735 if (const auto *RefTy = ExprTy->getAs<ReferenceType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006736 ExprTy = RefTy->getPointeeType().getCanonicalType();
6737
6738 // Given that an array section is considered a built-in type, we need to
6739 // do the calculation based on the length of the section instead of relying
6740 // on CGF.getTypeSize(E->getType()).
6741 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6742 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6743 OAE->getBase()->IgnoreParenImpCasts())
6744 .getCanonicalType();
6745
6746 // If there is no length associated with the expression, that means we
6747 // are using the whole length of the base.
6748 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6749 return CGF.getTypeSize(BaseTy);
6750
6751 llvm::Value *ElemSize;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006752 if (const auto *PTy = BaseTy->getAs<PointerType>()) {
Samuel Antao86ace552016-04-27 22:40:57 +00006753 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006754 } else {
6755 const auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
Samuel Antao86ace552016-04-27 22:40:57 +00006756 assert(ATy && "Expecting array type if not a pointer type.");
6757 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6758 }
6759
6760 // If we don't have a length at this point, that is because we have an
6761 // array section with a single element.
6762 if (!OAE->getLength())
6763 return ElemSize;
6764
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006765 llvm::Value *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
Samuel Antao86ace552016-04-27 22:40:57 +00006766 LengthVal =
6767 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6768 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6769 }
6770 return CGF.getTypeSize(ExprTy);
6771 }
6772
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006773 /// Return the corresponding bits for a given map clause modifier. Add
Samuel Antao86ace552016-04-27 22:40:57 +00006774 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006775 /// map as the first one of a series of maps that relate to the same map
6776 /// expression.
Kelvin Lief579432018-12-18 22:18:41 +00006777 OpenMPOffloadMappingFlags getMapTypeBits(
6778 OpenMPMapClauseKind MapType, ArrayRef<OpenMPMapModifierKind> MapModifiers,
6779 bool IsImplicit, bool AddPtrFlag, bool AddIsTargetParamFlag) const {
Alexey Bataevb3638132018-07-19 16:34:13 +00006780 OpenMPOffloadMappingFlags Bits =
6781 IsImplicit ? OMP_MAP_IMPLICIT : OMP_MAP_NONE;
Samuel Antao86ace552016-04-27 22:40:57 +00006782 switch (MapType) {
6783 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006784 case OMPC_MAP_release:
6785 // alloc and release is the default behavior in the runtime library, i.e.
6786 // if we don't pass any bits alloc/release that is what the runtime is
6787 // going to do. Therefore, we don't need to signal anything for these two
6788 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006789 break;
6790 case OMPC_MAP_to:
Alexey Bataevb3638132018-07-19 16:34:13 +00006791 Bits |= OMP_MAP_TO;
Samuel Antao86ace552016-04-27 22:40:57 +00006792 break;
6793 case OMPC_MAP_from:
Alexey Bataevb3638132018-07-19 16:34:13 +00006794 Bits |= OMP_MAP_FROM;
Samuel Antao86ace552016-04-27 22:40:57 +00006795 break;
6796 case OMPC_MAP_tofrom:
Alexey Bataevb3638132018-07-19 16:34:13 +00006797 Bits |= OMP_MAP_TO | OMP_MAP_FROM;
Samuel Antao86ace552016-04-27 22:40:57 +00006798 break;
6799 case OMPC_MAP_delete:
Alexey Bataevb3638132018-07-19 16:34:13 +00006800 Bits |= OMP_MAP_DELETE;
Samuel Antao86ace552016-04-27 22:40:57 +00006801 break;
Alexey Bataevb3638132018-07-19 16:34:13 +00006802 case OMPC_MAP_unknown:
Samuel Antao86ace552016-04-27 22:40:57 +00006803 llvm_unreachable("Unexpected map type!");
Samuel Antao86ace552016-04-27 22:40:57 +00006804 }
6805 if (AddPtrFlag)
George Rokos065755d2017-11-07 18:27:04 +00006806 Bits |= OMP_MAP_PTR_AND_OBJ;
6807 if (AddIsTargetParamFlag)
6808 Bits |= OMP_MAP_TARGET_PARAM;
Kelvin Lief579432018-12-18 22:18:41 +00006809 if (llvm::find(MapModifiers, OMPC_MAP_MODIFIER_always)
6810 != MapModifiers.end())
Samuel Antao86ace552016-04-27 22:40:57 +00006811 Bits |= OMP_MAP_ALWAYS;
6812 return Bits;
6813 }
6814
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006815 /// Return true if the provided expression is a final array section. A
Samuel Antao86ace552016-04-27 22:40:57 +00006816 /// final array section, is one whose length can't be proved to be one.
6817 bool isFinalArraySectionExpression(const Expr *E) const {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006818 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antao86ace552016-04-27 22:40:57 +00006819
6820 // It is not an array section and therefore not a unity-size one.
6821 if (!OASE)
6822 return false;
6823
6824 // An array section with no colon always refer to a single element.
6825 if (OASE->getColonLoc().isInvalid())
6826 return false;
6827
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006828 const Expr *Length = OASE->getLength();
Samuel Antao86ace552016-04-27 22:40:57 +00006829
6830 // If we don't have a length we have to check if the array has size 1
6831 // for this dimension. Also, we should always expect a length if the
6832 // base type is pointer.
6833 if (!Length) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00006834 QualType BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6835 OASE->getBase()->IgnoreParenImpCasts())
6836 .getCanonicalType();
6837 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antao86ace552016-04-27 22:40:57 +00006838 return ATy->getSize().getSExtValue() != 1;
6839 // If we don't have a constant dimension length, we have to consider
6840 // the current section as having any size, so it is not necessarily
6841 // unitary. If it happen to be unity size, that's user fault.
6842 return true;
6843 }
6844
6845 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +00006846 Expr::EvalResult Result;
6847 if (!Length->EvaluateAsInt(Result, CGF.getContext()))
Samuel Antao86ace552016-04-27 22:40:57 +00006848 return true; // Can have more that size 1.
6849
Fangrui Song407659a2018-11-30 23:41:18 +00006850 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antao86ace552016-04-27 22:40:57 +00006851 return ConstLength.getSExtValue() != 1;
6852 }
6853
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006854 /// Generate the base pointers, section pointers, sizes and map type
Samuel Antao86ace552016-04-27 22:40:57 +00006855 /// bits for the provided map type, map modifier, and expression components.
6856 /// \a IsFirstComponent should be set to true if the provided set of
6857 /// components is the first associated with a capture.
6858 void generateInfoForComponentList(
Kelvin Lief579432018-12-18 22:18:41 +00006859 OpenMPMapClauseKind MapType,
6860 ArrayRef<OpenMPMapModifierKind> MapModifiers,
Samuel Antao86ace552016-04-27 22:40:57 +00006861 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006862 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006863 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
Alexey Bataevb3638132018-07-19 16:34:13 +00006864 StructRangeInfoTy &PartialStruct, bool IsFirstComponentList,
Alexey Bataeve82445f2018-09-20 13:54:02 +00006865 bool IsImplicit,
6866 ArrayRef<OMPClauseMappableExprCommon::MappableExprComponentListRef>
6867 OverlappedElements = llvm::None) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006868 // The following summarizes what has to be generated for each map and the
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00006869 // types below. The generated information is expressed in this order:
Samuel Antao86ace552016-04-27 22:40:57 +00006870 // base pointer, section pointer, size, flags
6871 // (to add to the ones that come from the map type and modifier).
6872 //
6873 // double d;
6874 // int i[100];
6875 // float *p;
6876 //
6877 // struct S1 {
6878 // int i;
6879 // float f[50];
6880 // }
6881 // struct S2 {
6882 // int i;
6883 // float f[50];
6884 // S1 s;
6885 // double *p;
6886 // struct S2 *ps;
6887 // }
6888 // S2 s;
6889 // S2 *ps;
6890 //
6891 // map(d)
Alexey Bataevb3638132018-07-19 16:34:13 +00006892 // &d, &d, sizeof(double), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006893 //
6894 // map(i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006895 // &i, &i, 100*sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006896 //
6897 // map(i[1:23])
Alexey Bataevb3638132018-07-19 16:34:13 +00006898 // &i(=&i[0]), &i[1], 23*sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006899 //
6900 // map(p)
Alexey Bataevb3638132018-07-19 16:34:13 +00006901 // &p, &p, sizeof(float*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006902 //
6903 // map(p[1:24])
Alexey Bataevb3638132018-07-19 16:34:13 +00006904 // p, &p[1], 24*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006905 //
6906 // map(s)
Alexey Bataevb3638132018-07-19 16:34:13 +00006907 // &s, &s, sizeof(S2), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006908 //
6909 // map(s.i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006910 // &s, &(s.i), sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006911 //
6912 // map(s.s.f)
Alexey Bataevb3638132018-07-19 16:34:13 +00006913 // &s, &(s.s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006914 //
6915 // map(s.p)
Alexey Bataevb3638132018-07-19 16:34:13 +00006916 // &s, &(s.p), sizeof(double*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006917 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006918 // map(to: s.p[:22])
6919 // &s, &(s.p), sizeof(double*), TARGET_PARAM (*)
6920 // &s, &(s.p), sizeof(double*), MEMBER_OF(1) (**)
6921 // &(s.p), &(s.p[0]), 22*sizeof(double),
6922 // MEMBER_OF(1) | PTR_AND_OBJ | TO (***)
6923 // (*) alloc space for struct members, only this is a target parameter
6924 // (**) map the pointer (nothing to be mapped in this example) (the compiler
6925 // optimizes this entry out, same in the examples below)
6926 // (***) map the pointee (map: to)
Samuel Antao86ace552016-04-27 22:40:57 +00006927 //
6928 // map(s.ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006929 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006930 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006931 // map(from: s.ps->s.i)
6932 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6933 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6934 // &(s.ps), &(s.ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006935 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006936 // map(to: s.ps->ps)
6937 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6938 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6939 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006940 //
6941 // map(s.ps->ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006942 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6943 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6944 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6945 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006946 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006947 // map(to: s.ps->ps->s.f[:22])
6948 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM
6949 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1)
6950 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6951 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006952 //
6953 // map(ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006954 // &ps, &ps, sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006955 //
6956 // map(ps->i)
Alexey Bataevb3638132018-07-19 16:34:13 +00006957 // ps, &(ps->i), sizeof(int), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006958 //
6959 // map(ps->s.f)
Alexey Bataevb3638132018-07-19 16:34:13 +00006960 // ps, &(ps->s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006961 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006962 // map(from: ps->p)
6963 // ps, &(ps->p), sizeof(double*), TARGET_PARAM | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006964 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006965 // map(to: ps->p[:22])
6966 // ps, &(ps->p), sizeof(double*), TARGET_PARAM
6967 // ps, &(ps->p), sizeof(double*), MEMBER_OF(1)
6968 // &(ps->p), &(ps->p[0]), 22*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | TO
Samuel Antao86ace552016-04-27 22:40:57 +00006969 //
6970 // map(ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006971 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006972 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006973 // map(from: ps->ps->s.i)
6974 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6975 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6976 // &(ps->ps), &(ps->ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006977 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006978 // map(from: ps->ps->ps)
6979 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6980 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6981 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006982 //
6983 // map(ps->ps->ps->ps)
Alexey Bataevb3638132018-07-19 16:34:13 +00006984 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6985 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6986 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6987 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM
Samuel Antao86ace552016-04-27 22:40:57 +00006988 //
Alexey Bataevb3638132018-07-19 16:34:13 +00006989 // map(to: ps->ps->ps->s.f[:22])
6990 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM
6991 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1)
6992 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ
6993 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO
6994 //
6995 // map(to: s.f[:22]) map(from: s.p[:33])
6996 // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1) +
6997 // sizeof(double*) (**), TARGET_PARAM
6998 // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | TO
6999 // &s, &(s.p), sizeof(double*), MEMBER_OF(1)
7000 // &(s.p), &(s.p[0]), 33*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | FROM
7001 // (*) allocate contiguous space needed to fit all mapped members even if
7002 // we allocate space for members not mapped (in this example,
7003 // s.f[22..49] and s.s are not mapped, yet we must allocate space for
7004 // them as well because they fall between &s.f[0] and &s.p)
7005 //
7006 // map(from: s.f[:22]) map(to: ps->p[:33])
7007 // &s, &(s.f[0]), 22*sizeof(float), TARGET_PARAM | FROM
7008 // ps, &(ps->p), sizeof(S2*), TARGET_PARAM
7009 // ps, &(ps->p), sizeof(double*), MEMBER_OF(2) (*)
7010 // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(2) | PTR_AND_OBJ | TO
7011 // (*) the struct this entry pertains to is the 2nd element in the list of
7012 // arguments, hence MEMBER_OF(2)
7013 //
7014 // map(from: s.f[:22], s.s) map(to: ps->p[:33])
7015 // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1), TARGET_PARAM
7016 // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | FROM
7017 // &s, &(s.s), sizeof(struct S1), MEMBER_OF(1) | FROM
7018 // ps, &(ps->p), sizeof(S2*), TARGET_PARAM
7019 // ps, &(ps->p), sizeof(double*), MEMBER_OF(4) (*)
7020 // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(4) | PTR_AND_OBJ | TO
7021 // (*) the struct this entry pertains to is the 4th element in the list
7022 // of arguments, hence MEMBER_OF(4)
Samuel Antao86ace552016-04-27 22:40:57 +00007023
7024 // Track if the map information being generated is the first for a capture.
7025 bool IsCaptureFirstInfo = IsFirstComponentList;
Alexey Bataev92327c52018-03-26 16:40:55 +00007026 bool IsLink = false; // Is this variable a "declare target link"?
Samuel Antao86ace552016-04-27 22:40:57 +00007027
7028 // Scan the components from the base to the complete expression.
7029 auto CI = Components.rbegin();
7030 auto CE = Components.rend();
7031 auto I = CI;
7032
7033 // Track if the map information being generated is the first for a list of
7034 // components.
7035 bool IsExpressionFirstInfo = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00007036 Address BP = Address::invalid();
Patrick Lystere13b1e32019-01-02 19:28:48 +00007037 const Expr *AssocExpr = I->getAssociatedExpression();
7038 const auto *AE = dyn_cast<ArraySubscriptExpr>(AssocExpr);
7039 const auto *OASE = dyn_cast<OMPArraySectionExpr>(AssocExpr);
Samuel Antao86ace552016-04-27 22:40:57 +00007040
Patrick Lystere13b1e32019-01-02 19:28:48 +00007041 if (isa<MemberExpr>(AssocExpr)) {
Samuel Antao86ace552016-04-27 22:40:57 +00007042 // The base is the 'this' pointer. The content of the pointer is going
7043 // to be the base of the field being mapped.
Alexey Bataevb3638132018-07-19 16:34:13 +00007044 BP = CGF.LoadCXXThisAddress();
Patrick Lystere13b1e32019-01-02 19:28:48 +00007045 } else if ((AE && isa<CXXThisExpr>(AE->getBase()->IgnoreParenImpCasts())) ||
7046 (OASE &&
7047 isa<CXXThisExpr>(OASE->getBase()->IgnoreParenImpCasts()))) {
7048 BP = CGF.EmitOMPSharedLValue(AssocExpr).getAddress();
Samuel Antao86ace552016-04-27 22:40:57 +00007049 } else {
7050 // The base is the reference to the variable.
7051 // BP = &Var.
Patrick Lystere13b1e32019-01-02 19:28:48 +00007052 BP = CGF.EmitOMPSharedLValue(AssocExpr).getAddress();
Alexey Bataev92327c52018-03-26 16:40:55 +00007053 if (const auto *VD =
7054 dyn_cast_or_null<VarDecl>(I->getAssociatedDeclaration())) {
7055 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00007056 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataev2c1dffe2018-04-16 20:34:41 +00007057 if (*Res == OMPDeclareTargetDeclAttr::MT_Link) {
7058 IsLink = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00007059 BP = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
Alexey Bataev2c1dffe2018-04-16 20:34:41 +00007060 }
Alexey Bataev92327c52018-03-26 16:40:55 +00007061 }
Samuel Antao86ace552016-04-27 22:40:57 +00007062
7063 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00007064 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00007065 // reference. References are ignored for mapping purposes.
7066 QualType Ty =
7067 I->getAssociatedDeclaration()->getType().getNonReferenceType();
7068 if (Ty->isAnyPointerType() && std::next(I) != CE) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007069 BP = CGF.EmitLoadOfPointer(BP, Ty->castAs<PointerType>());
Samuel Antao86ace552016-04-27 22:40:57 +00007070
7071 // We do not need to generate individual map information for the
7072 // pointer, it can be associated with the combined storage.
7073 ++I;
7074 }
7075 }
7076
Alexey Bataevb3638132018-07-19 16:34:13 +00007077 // Track whether a component of the list should be marked as MEMBER_OF some
7078 // combined entry (for partial structs). Only the first PTR_AND_OBJ entry
7079 // in a component list should be marked as MEMBER_OF, all subsequent entries
7080 // do not belong to the base struct. E.g.
7081 // struct S2 s;
7082 // s.ps->ps->ps->f[:]
7083 // (1) (2) (3) (4)
7084 // ps(1) is a member pointer, ps(2) is a pointee of ps(1), so it is a
7085 // PTR_AND_OBJ entry; the PTR is ps(1), so MEMBER_OF the base struct. ps(3)
7086 // is the pointee of ps(2) which is not member of struct s, so it should not
7087 // be marked as such (it is still PTR_AND_OBJ).
7088 // The variable is initialized to false so that PTR_AND_OBJ entries which
7089 // are not struct members are not considered (e.g. array of pointers to
7090 // data).
7091 bool ShouldBeMemberOf = false;
7092
7093 // Variable keeping track of whether or not we have encountered a component
7094 // in the component list which is a member expression. Useful when we have a
7095 // pointer or a final array section, in which case it is the previous
7096 // component in the list which tells us whether we have a member expression.
7097 // E.g. X.f[:]
7098 // While processing the final array section "[:]" it is "f" which tells us
7099 // whether we are dealing with a member of a declared struct.
7100 const MemberExpr *EncounteredME = nullptr;
7101
Samuel Antao86ace552016-04-27 22:40:57 +00007102 for (; I != CE; ++I) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007103 // If the current component is member of a struct (parent struct) mark it.
7104 if (!EncounteredME) {
7105 EncounteredME = dyn_cast<MemberExpr>(I->getAssociatedExpression());
7106 // If we encounter a PTR_AND_OBJ entry from now on it should be marked
7107 // as MEMBER_OF the parent struct.
7108 if (EncounteredME)
7109 ShouldBeMemberOf = true;
7110 }
7111
Samuel Antao86ace552016-04-27 22:40:57 +00007112 auto Next = std::next(I);
7113
7114 // We need to generate the addresses and sizes if this is the last
7115 // component, if the component is a pointer or if it is an array section
7116 // whose length can't be proved to be one. If this is a pointer, it
7117 // becomes the base address for the following components.
7118
7119 // A final array section, is one whose length can't be proved to be one.
7120 bool IsFinalArraySection =
7121 isFinalArraySectionExpression(I->getAssociatedExpression());
7122
7123 // Get information on whether the element is a pointer. Have to do a
7124 // special treatment for array sections given that they are built-in
7125 // types.
7126 const auto *OASE =
7127 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
7128 bool IsPointer =
Alexey Bataevb3638132018-07-19 16:34:13 +00007129 (OASE && OMPArraySectionExpr::getBaseOriginalType(OASE)
7130 .getCanonicalType()
7131 ->isAnyPointerType()) ||
Samuel Antao86ace552016-04-27 22:40:57 +00007132 I->getAssociatedExpression()->getType()->isAnyPointerType();
7133
7134 if (Next == CE || IsPointer || IsFinalArraySection) {
Samuel Antao86ace552016-04-27 22:40:57 +00007135 // If this is not the last component, we expect the pointer to be
7136 // associated with an array expression or member expression.
7137 assert((Next == CE ||
7138 isa<MemberExpr>(Next->getAssociatedExpression()) ||
7139 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
7140 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
7141 "Unexpected expression");
7142
Alexey Bataevb3638132018-07-19 16:34:13 +00007143 Address LB =
7144 CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getAddress();
Samuel Antao86ace552016-04-27 22:40:57 +00007145
Alexey Bataevb3638132018-07-19 16:34:13 +00007146 // If this component is a pointer inside the base struct then we don't
7147 // need to create any entry for it - it will be combined with the object
7148 // it is pointing to into a single PTR_AND_OBJ entry.
7149 bool IsMemberPointer =
7150 IsPointer && EncounteredME &&
7151 (dyn_cast<MemberExpr>(I->getAssociatedExpression()) ==
7152 EncounteredME);
Alexey Bataeve82445f2018-09-20 13:54:02 +00007153 if (!OverlappedElements.empty()) {
7154 // Handle base element with the info for overlapped elements.
7155 assert(!PartialStruct.Base.isValid() && "The base element is set.");
7156 assert(Next == CE &&
7157 "Expected last element for the overlapped elements.");
7158 assert(!IsPointer &&
7159 "Unexpected base element with the pointer type.");
7160 // Mark the whole struct as the struct that requires allocation on the
7161 // device.
7162 PartialStruct.LowestElem = {0, LB};
7163 CharUnits TypeSize = CGF.getContext().getTypeSizeInChars(
7164 I->getAssociatedExpression()->getType());
7165 Address HB = CGF.Builder.CreateConstGEP(
7166 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(LB,
7167 CGF.VoidPtrTy),
7168 TypeSize.getQuantity() - 1, CharUnits::One());
7169 PartialStruct.HighestElem = {
7170 std::numeric_limits<decltype(
7171 PartialStruct.HighestElem.first)>::max(),
7172 HB};
7173 PartialStruct.Base = BP;
7174 // Emit data for non-overlapped data.
7175 OpenMPOffloadMappingFlags Flags =
7176 OMP_MAP_MEMBER_OF |
Kelvin Lief579432018-12-18 22:18:41 +00007177 getMapTypeBits(MapType, MapModifiers, IsImplicit,
Alexey Bataeve82445f2018-09-20 13:54:02 +00007178 /*AddPtrFlag=*/false,
7179 /*AddIsTargetParamFlag=*/false);
7180 LB = BP;
7181 llvm::Value *Size = nullptr;
7182 // Do bitcopy of all non-overlapped structure elements.
7183 for (OMPClauseMappableExprCommon::MappableExprComponentListRef
7184 Component : OverlappedElements) {
7185 Address ComponentLB = Address::invalid();
7186 for (const OMPClauseMappableExprCommon::MappableComponent &MC :
7187 Component) {
7188 if (MC.getAssociatedDeclaration()) {
7189 ComponentLB =
7190 CGF.EmitOMPSharedLValue(MC.getAssociatedExpression())
7191 .getAddress();
7192 Size = CGF.Builder.CreatePtrDiff(
7193 CGF.EmitCastToVoidPtr(ComponentLB.getPointer()),
7194 CGF.EmitCastToVoidPtr(LB.getPointer()));
7195 break;
7196 }
7197 }
7198 BasePointers.push_back(BP.getPointer());
7199 Pointers.push_back(LB.getPointer());
7200 Sizes.push_back(Size);
7201 Types.push_back(Flags);
7202 LB = CGF.Builder.CreateConstGEP(ComponentLB, 1,
7203 CGF.getPointerSize());
7204 }
7205 BasePointers.push_back(BP.getPointer());
7206 Pointers.push_back(LB.getPointer());
7207 Size = CGF.Builder.CreatePtrDiff(
7208 CGF.EmitCastToVoidPtr(
7209 CGF.Builder.CreateConstGEP(HB, 1, CharUnits::One())
7210 .getPointer()),
7211 CGF.EmitCastToVoidPtr(LB.getPointer()));
7212 Sizes.push_back(Size);
7213 Types.push_back(Flags);
7214 break;
7215 }
7216 llvm::Value *Size = getExprTypeSize(I->getAssociatedExpression());
Alexey Bataevb3638132018-07-19 16:34:13 +00007217 if (!IsMemberPointer) {
7218 BasePointers.push_back(BP.getPointer());
7219 Pointers.push_back(LB.getPointer());
7220 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00007221
Alexey Bataevb3638132018-07-19 16:34:13 +00007222 // We need to add a pointer flag for each map that comes from the
7223 // same expression except for the first one. We also need to signal
7224 // this map is the first one that relates with the current capture
7225 // (there is a set of entries for each capture).
7226 OpenMPOffloadMappingFlags Flags = getMapTypeBits(
Kelvin Lief579432018-12-18 22:18:41 +00007227 MapType, MapModifiers, IsImplicit,
Alexey Bataevb3638132018-07-19 16:34:13 +00007228 !IsExpressionFirstInfo || IsLink, IsCaptureFirstInfo && !IsLink);
7229
7230 if (!IsExpressionFirstInfo) {
7231 // If we have a PTR_AND_OBJ pair where the OBJ is a pointer as well,
7232 // then we reset the TO/FROM/ALWAYS/DELETE flags.
7233 if (IsPointer)
7234 Flags &= ~(OMP_MAP_TO | OMP_MAP_FROM | OMP_MAP_ALWAYS |
7235 OMP_MAP_DELETE);
7236
7237 if (ShouldBeMemberOf) {
7238 // Set placeholder value MEMBER_OF=FFFF to indicate that the flag
7239 // should be later updated with the correct value of MEMBER_OF.
7240 Flags |= OMP_MAP_MEMBER_OF;
7241 // From now on, all subsequent PTR_AND_OBJ entries should not be
7242 // marked as MEMBER_OF.
7243 ShouldBeMemberOf = false;
7244 }
7245 }
7246
7247 Types.push_back(Flags);
Samuel Antao03a3cec2016-07-27 22:52:16 +00007248 }
7249
Alexey Bataevb3638132018-07-19 16:34:13 +00007250 // If we have encountered a member expression so far, keep track of the
7251 // mapped member. If the parent is "*this", then the value declaration
7252 // is nullptr.
7253 if (EncounteredME) {
7254 const auto *FD = dyn_cast<FieldDecl>(EncounteredME->getMemberDecl());
7255 unsigned FieldIndex = FD->getFieldIndex();
Samuel Antao03a3cec2016-07-27 22:52:16 +00007256
Alexey Bataevb3638132018-07-19 16:34:13 +00007257 // Update info about the lowest and highest elements for this struct
7258 if (!PartialStruct.Base.isValid()) {
7259 PartialStruct.LowestElem = {FieldIndex, LB};
7260 PartialStruct.HighestElem = {FieldIndex, LB};
7261 PartialStruct.Base = BP;
7262 } else if (FieldIndex < PartialStruct.LowestElem.first) {
7263 PartialStruct.LowestElem = {FieldIndex, LB};
7264 } else if (FieldIndex > PartialStruct.HighestElem.first) {
7265 PartialStruct.HighestElem = {FieldIndex, LB};
7266 }
7267 }
Samuel Antao86ace552016-04-27 22:40:57 +00007268
7269 // If we have a final array section, we are done with this expression.
7270 if (IsFinalArraySection)
7271 break;
7272
7273 // The pointer becomes the base for the next element.
7274 if (Next != CE)
7275 BP = LB;
7276
7277 IsExpressionFirstInfo = false;
7278 IsCaptureFirstInfo = false;
Samuel Antao86ace552016-04-27 22:40:57 +00007279 }
7280 }
7281 }
7282
Alexey Bataevb3638132018-07-19 16:34:13 +00007283 /// Return the adjusted map modifiers if the declaration a capture refers to
7284 /// appears in a first-private clause. This is expected to be used only with
7285 /// directives that start with 'target'.
7286 MappableExprsHandler::OpenMPOffloadMappingFlags
7287 getMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap) const {
7288 assert(Cap.capturesVariable() && "Expected capture by reference only!");
7289
7290 // A first private variable captured by reference will use only the
7291 // 'private ptr' and 'map to' flag. Return the right flags if the captured
7292 // declaration is known as first-private in this handler.
7293 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
7294 return MappableExprsHandler::OMP_MAP_PRIVATE |
7295 MappableExprsHandler::OMP_MAP_TO;
7296 return MappableExprsHandler::OMP_MAP_TO |
7297 MappableExprsHandler::OMP_MAP_FROM;
7298 }
7299
7300 static OpenMPOffloadMappingFlags getMemberOfFlag(unsigned Position) {
7301 // Member of is given by the 16 MSB of the flag, so rotate by 48 bits.
7302 return static_cast<OpenMPOffloadMappingFlags>(((uint64_t)Position + 1)
7303 << 48);
7304 }
7305
7306 static void setCorrectMemberOfFlag(OpenMPOffloadMappingFlags &Flags,
7307 OpenMPOffloadMappingFlags MemberOfFlag) {
7308 // If the entry is PTR_AND_OBJ but has not been marked with the special
7309 // placeholder value 0xFFFF in the MEMBER_OF field, then it should not be
7310 // marked as MEMBER_OF.
7311 if ((Flags & OMP_MAP_PTR_AND_OBJ) &&
7312 ((Flags & OMP_MAP_MEMBER_OF) != OMP_MAP_MEMBER_OF))
7313 return;
7314
7315 // Reset the placeholder value to prepare the flag for the assignment of the
7316 // proper MEMBER_OF value.
7317 Flags &= ~OMP_MAP_MEMBER_OF;
7318 Flags |= MemberOfFlag;
7319 }
7320
Alexey Bataeve82445f2018-09-20 13:54:02 +00007321 void getPlainLayout(const CXXRecordDecl *RD,
7322 llvm::SmallVectorImpl<const FieldDecl *> &Layout,
7323 bool AsBase) const {
7324 const CGRecordLayout &RL = CGF.getTypes().getCGRecordLayout(RD);
7325
7326 llvm::StructType *St =
7327 AsBase ? RL.getBaseSubobjectLLVMType() : RL.getLLVMType();
7328
7329 unsigned NumElements = St->getNumElements();
7330 llvm::SmallVector<
7331 llvm::PointerUnion<const CXXRecordDecl *, const FieldDecl *>, 4>
7332 RecordLayout(NumElements);
7333
7334 // Fill bases.
7335 for (const auto &I : RD->bases()) {
7336 if (I.isVirtual())
7337 continue;
7338 const auto *Base = I.getType()->getAsCXXRecordDecl();
7339 // Ignore empty bases.
7340 if (Base->isEmpty() || CGF.getContext()
7341 .getASTRecordLayout(Base)
7342 .getNonVirtualSize()
7343 .isZero())
7344 continue;
7345
7346 unsigned FieldIndex = RL.getNonVirtualBaseLLVMFieldNo(Base);
7347 RecordLayout[FieldIndex] = Base;
7348 }
7349 // Fill in virtual bases.
7350 for (const auto &I : RD->vbases()) {
7351 const auto *Base = I.getType()->getAsCXXRecordDecl();
7352 // Ignore empty bases.
7353 if (Base->isEmpty())
7354 continue;
7355 unsigned FieldIndex = RL.getVirtualBaseIndex(Base);
7356 if (RecordLayout[FieldIndex])
7357 continue;
7358 RecordLayout[FieldIndex] = Base;
7359 }
7360 // Fill in all the fields.
7361 assert(!RD->isUnion() && "Unexpected union.");
7362 for (const auto *Field : RD->fields()) {
7363 // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
7364 // will fill in later.)
7365 if (!Field->isBitField()) {
7366 unsigned FieldIndex = RL.getLLVMFieldNo(Field);
7367 RecordLayout[FieldIndex] = Field;
7368 }
7369 }
7370 for (const llvm::PointerUnion<const CXXRecordDecl *, const FieldDecl *>
7371 &Data : RecordLayout) {
7372 if (Data.isNull())
7373 continue;
7374 if (const auto *Base = Data.dyn_cast<const CXXRecordDecl *>())
7375 getPlainLayout(Base, Layout, /*AsBase=*/true);
7376 else
7377 Layout.push_back(Data.get<const FieldDecl *>());
7378 }
7379 }
7380
Alexey Bataevb3638132018-07-19 16:34:13 +00007381public:
7382 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
7383 : CurDir(Dir), CGF(CGF) {
7384 // Extract firstprivate clause information.
7385 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
7386 for (const auto *D : C->varlists())
7387 FirstPrivateDecls.insert(
7388 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
7389 // Extract device pointer clause information.
7390 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
7391 for (auto L : C->component_lists())
7392 DevPointersMap[L.first].push_back(L.second);
7393 }
7394
7395 /// Generate code for the combined entry if we have a partially mapped struct
7396 /// and take care of the mapping flags of the arguments corresponding to
7397 /// individual struct members.
7398 void emitCombinedEntry(MapBaseValuesArrayTy &BasePointers,
7399 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7400 MapFlagsArrayTy &Types, MapFlagsArrayTy &CurTypes,
7401 const StructRangeInfoTy &PartialStruct) const {
7402 // Base is the base of the struct
7403 BasePointers.push_back(PartialStruct.Base.getPointer());
7404 // Pointer is the address of the lowest element
7405 llvm::Value *LB = PartialStruct.LowestElem.second.getPointer();
7406 Pointers.push_back(LB);
7407 // Size is (addr of {highest+1} element) - (addr of lowest element)
7408 llvm::Value *HB = PartialStruct.HighestElem.second.getPointer();
7409 llvm::Value *HAddr = CGF.Builder.CreateConstGEP1_32(HB, /*Idx0=*/1);
7410 llvm::Value *CLAddr = CGF.Builder.CreatePointerCast(LB, CGF.VoidPtrTy);
7411 llvm::Value *CHAddr = CGF.Builder.CreatePointerCast(HAddr, CGF.VoidPtrTy);
7412 llvm::Value *Diff = CGF.Builder.CreatePtrDiff(CHAddr, CLAddr);
7413 llvm::Value *Size = CGF.Builder.CreateIntCast(Diff, CGF.SizeTy,
7414 /*isSinged=*/false);
7415 Sizes.push_back(Size);
7416 // Map type is always TARGET_PARAM
7417 Types.push_back(OMP_MAP_TARGET_PARAM);
7418 // Remove TARGET_PARAM flag from the first element
7419 (*CurTypes.begin()) &= ~OMP_MAP_TARGET_PARAM;
7420
7421 // All other current entries will be MEMBER_OF the combined entry
7422 // (except for PTR_AND_OBJ entries which do not have a placeholder value
7423 // 0xFFFF in the MEMBER_OF field).
7424 OpenMPOffloadMappingFlags MemberOfFlag =
7425 getMemberOfFlag(BasePointers.size() - 1);
7426 for (auto &M : CurTypes)
7427 setCorrectMemberOfFlag(M, MemberOfFlag);
7428 }
7429
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007430 /// Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00007431 /// types for the extracted mappable expressions. Also, for each item that
7432 /// relates with a device pointer, a pair of the relevant declaration and
7433 /// index where it occurs is appended to the device pointers info array.
7434 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007435 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7436 MapFlagsArrayTy &Types) const {
Samuel Antao86ace552016-04-27 22:40:57 +00007437 // We have to process the component lists that relate with the same
7438 // declaration in a single chunk so that we can generate the map flags
7439 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00007440 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00007441
7442 // Helper function to fill the information map for the different supported
7443 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00007444 auto &&InfoGen = [&Info](
7445 const ValueDecl *D,
7446 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
Kelvin Lief579432018-12-18 22:18:41 +00007447 OpenMPMapClauseKind MapType,
7448 ArrayRef<OpenMPMapModifierKind> MapModifiers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007449 bool ReturnDevicePointer, bool IsImplicit) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007450 const ValueDecl *VD =
7451 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
Kelvin Lief579432018-12-18 22:18:41 +00007452 Info[VD].emplace_back(L, MapType, MapModifiers, ReturnDevicePointer,
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007453 IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007454 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00007455
Paul Robinson78fb1322016-08-01 22:12:46 +00007456 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007457 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
7458 for (const auto &L : C->component_lists()) {
Kelvin Lief579432018-12-18 22:18:41 +00007459 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifiers(),
Alexey Bataevb3638132018-07-19 16:34:13 +00007460 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007461 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007462 for (const auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
7463 for (const auto &L : C->component_lists()) {
Kelvin Lief579432018-12-18 22:18:41 +00007464 InfoGen(L.first, L.second, OMPC_MAP_to, llvm::None,
Alexey Bataevb3638132018-07-19 16:34:13 +00007465 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007466 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007467 for (const auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
7468 for (const auto &L : C->component_lists()) {
Kelvin Lief579432018-12-18 22:18:41 +00007469 InfoGen(L.first, L.second, OMPC_MAP_from, llvm::None,
Alexey Bataevb3638132018-07-19 16:34:13 +00007470 /*ReturnDevicePointer=*/false, C->isImplicit());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007471 }
Samuel Antao86ace552016-04-27 22:40:57 +00007472
Samuel Antaocc10b852016-07-28 14:23:26 +00007473 // Look at the use_device_ptr clause information and mark the existing map
7474 // entries as such. If there is no map information for an entry in the
7475 // use_device_ptr list, we create one with map type 'alloc' and zero size
Alexey Bataevb3638132018-07-19 16:34:13 +00007476 // section. It is the user fault if that was not mapped before. If there is
7477 // no map information and the pointer is a struct member, then we defer the
7478 // emission of that entry until the whole struct has been processed.
7479 llvm::MapVector<const ValueDecl *, SmallVector<DeferredDevicePtrEntryTy, 4>>
7480 DeferredInfo;
7481
Paul Robinson78fb1322016-08-01 22:12:46 +00007482 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataevb3638132018-07-19 16:34:13 +00007483 for (const auto *C :
7484 this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007485 for (const auto &L : C->component_lists()) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007486 assert(!L.second.empty() && "Not expecting empty list of components!");
7487 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
7488 VD = cast<ValueDecl>(VD->getCanonicalDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007489 const Expr *IE = L.second.back().getAssociatedExpression();
Samuel Antaocc10b852016-07-28 14:23:26 +00007490 // If the first component is a member expression, we have to look into
7491 // 'this', which maps to null in the map of map information. Otherwise
7492 // look directly for the information.
7493 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
7494
7495 // We potentially have map information for this declaration already.
7496 // Look for the first set of components that refer to it.
7497 if (It != Info.end()) {
7498 auto CI = std::find_if(
7499 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
7500 return MI.Components.back().getAssociatedDeclaration() == VD;
7501 });
7502 // If we found a map entry, signal that the pointer has to be returned
7503 // and move on to the next declaration.
7504 if (CI != It->second.end()) {
Alexey Bataevb3638132018-07-19 16:34:13 +00007505 CI->ReturnDevicePointer = true;
Samuel Antaocc10b852016-07-28 14:23:26 +00007506 continue;
7507 }
7508 }
7509
7510 // We didn't find any match in our map information - generate a zero
Alexey Bataevb3638132018-07-19 16:34:13 +00007511 // size array section - if the pointer is a struct member we defer this
7512 // action until the whole struct has been processed.
Paul Robinson78fb1322016-08-01 22:12:46 +00007513 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Alexey Bataevb3638132018-07-19 16:34:13 +00007514 if (isa<MemberExpr>(IE)) {
7515 // Insert the pointer into Info to be processed by
7516 // generateInfoForComponentList. Because it is a member pointer
7517 // without a pointee, no entry will be generated for it, therefore
7518 // we need to generate one after the whole struct has been processed.
7519 // Nonetheless, generateInfoForComponentList must be called to take
7520 // the pointer into account for the calculation of the range of the
7521 // partial struct.
Kelvin Lief579432018-12-18 22:18:41 +00007522 InfoGen(nullptr, L.second, OMPC_MAP_unknown, llvm::None,
Alexey Bataevb3638132018-07-19 16:34:13 +00007523 /*ReturnDevicePointer=*/false, C->isImplicit());
7524 DeferredInfo[nullptr].emplace_back(IE, VD);
7525 } else {
7526 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(
7527 this->CGF.EmitLValue(IE), IE->getExprLoc());
7528 BasePointers.emplace_back(Ptr, VD);
7529 Pointers.push_back(Ptr);
7530 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
7531 Types.push_back(OMP_MAP_RETURN_PARAM | OMP_MAP_TARGET_PARAM);
7532 }
Samuel Antaocc10b852016-07-28 14:23:26 +00007533 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007534 }
Samuel Antaocc10b852016-07-28 14:23:26 +00007535
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007536 for (const auto &M : Info) {
Samuel Antao86ace552016-04-27 22:40:57 +00007537 // We need to know when we generate information for the first component
7538 // associated with a capture, because the mapping flags depend on it.
7539 bool IsFirstComponentList = true;
Alexey Bataevb3638132018-07-19 16:34:13 +00007540
7541 // Temporary versions of arrays
7542 MapBaseValuesArrayTy CurBasePointers;
7543 MapValuesArrayTy CurPointers;
7544 MapValuesArrayTy CurSizes;
7545 MapFlagsArrayTy CurTypes;
7546 StructRangeInfoTy PartialStruct;
7547
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007548 for (const MapInfo &L : M.second) {
Samuel Antao86ace552016-04-27 22:40:57 +00007549 assert(!L.Components.empty() &&
7550 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00007551
7552 // Remember the current base pointer index.
Alexey Bataevb3638132018-07-19 16:34:13 +00007553 unsigned CurrentBasePointersIdx = CurBasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00007554 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Alexey Bataevf47c4b42017-09-26 13:47:31 +00007555 this->generateInfoForComponentList(
Kelvin Lief579432018-12-18 22:18:41 +00007556 L.MapType, L.MapModifiers, L.Components, CurBasePointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007557 CurPointers, CurSizes, CurTypes, PartialStruct,
7558 IsFirstComponentList, L.IsImplicit);
Samuel Antaocc10b852016-07-28 14:23:26 +00007559
7560 // If this entry relates with a device pointer, set the relevant
7561 // declaration and add the 'return pointer' flag.
Alexey Bataevb3638132018-07-19 16:34:13 +00007562 if (L.ReturnDevicePointer) {
7563 assert(CurBasePointers.size() > CurrentBasePointersIdx &&
Samuel Antaocc10b852016-07-28 14:23:26 +00007564 "Unexpected number of mapped base pointers.");
7565
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007566 const ValueDecl *RelevantVD =
7567 L.Components.back().getAssociatedDeclaration();
Samuel Antaocc10b852016-07-28 14:23:26 +00007568 assert(RelevantVD &&
7569 "No relevant declaration related with device pointer??");
7570
Alexey Bataevb3638132018-07-19 16:34:13 +00007571 CurBasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
7572 CurTypes[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PARAM;
Samuel Antaocc10b852016-07-28 14:23:26 +00007573 }
Samuel Antao86ace552016-04-27 22:40:57 +00007574 IsFirstComponentList = false;
7575 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007576
7577 // Append any pending zero-length pointers which are struct members and
7578 // used with use_device_ptr.
7579 auto CI = DeferredInfo.find(M.first);
7580 if (CI != DeferredInfo.end()) {
7581 for (const DeferredDevicePtrEntryTy &L : CI->second) {
7582 llvm::Value *BasePtr = this->CGF.EmitLValue(L.IE).getPointer();
7583 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar(
7584 this->CGF.EmitLValue(L.IE), L.IE->getExprLoc());
7585 CurBasePointers.emplace_back(BasePtr, L.VD);
7586 CurPointers.push_back(Ptr);
7587 CurSizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
7588 // Entry is PTR_AND_OBJ and RETURN_PARAM. Also, set the placeholder
7589 // value MEMBER_OF=FFFF so that the entry is later updated with the
7590 // correct value of MEMBER_OF.
7591 CurTypes.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_RETURN_PARAM |
7592 OMP_MAP_MEMBER_OF);
7593 }
7594 }
7595
7596 // If there is an entry in PartialStruct it means we have a struct with
7597 // individual members mapped. Emit an extra combined entry.
7598 if (PartialStruct.Base.isValid())
7599 emitCombinedEntry(BasePointers, Pointers, Sizes, Types, CurTypes,
7600 PartialStruct);
7601
7602 // We need to append the results of this capture to what we already have.
7603 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
7604 Pointers.append(CurPointers.begin(), CurPointers.end());
7605 Sizes.append(CurSizes.begin(), CurSizes.end());
7606 Types.append(CurTypes.begin(), CurTypes.end());
Samuel Antao86ace552016-04-27 22:40:57 +00007607 }
7608 }
7609
Alexey Bataev60705422018-10-30 15:50:12 +00007610 /// Emit capture info for lambdas for variables captured by reference.
Alexey Bataev969dbc02018-11-08 15:47:39 +00007611 void generateInfoForLambdaCaptures(
7612 const ValueDecl *VD, llvm::Value *Arg, MapBaseValuesArrayTy &BasePointers,
7613 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
7614 MapFlagsArrayTy &Types,
7615 llvm::DenseMap<llvm::Value *, llvm::Value *> &LambdaPointers) const {
Alexey Bataev60705422018-10-30 15:50:12 +00007616 const auto *RD = VD->getType()
7617 .getCanonicalType()
7618 .getNonReferenceType()
7619 ->getAsCXXRecordDecl();
7620 if (!RD || !RD->isLambda())
7621 return;
7622 Address VDAddr = Address(Arg, CGF.getContext().getDeclAlign(VD));
7623 LValue VDLVal = CGF.MakeAddrLValue(
7624 VDAddr, VD->getType().getCanonicalType().getNonReferenceType());
7625 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
7626 FieldDecl *ThisCapture = nullptr;
7627 RD->getCaptureFields(Captures, ThisCapture);
7628 if (ThisCapture) {
7629 LValue ThisLVal =
7630 CGF.EmitLValueForFieldInitialization(VDLVal, ThisCapture);
Alexey Bataev969dbc02018-11-08 15:47:39 +00007631 LValue ThisLValVal = CGF.EmitLValueForField(VDLVal, ThisCapture);
7632 LambdaPointers.try_emplace(ThisLVal.getPointer(), VDLVal.getPointer());
7633 BasePointers.push_back(ThisLVal.getPointer());
7634 Pointers.push_back(ThisLValVal.getPointer());
Alexey Bataev60705422018-10-30 15:50:12 +00007635 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
Alexey Bataev2dc07d02018-11-02 15:25:06 +00007636 Types.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
Alexey Bataev60705422018-10-30 15:50:12 +00007637 OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT);
7638 }
7639 for (const LambdaCapture &LC : RD->captures()) {
7640 if (LC.getCaptureKind() != LCK_ByRef)
7641 continue;
7642 const VarDecl *VD = LC.getCapturedVar();
7643 auto It = Captures.find(VD);
7644 assert(It != Captures.end() && "Found lambda capture without field.");
7645 LValue VarLVal = CGF.EmitLValueForFieldInitialization(VDLVal, It->second);
Alexey Bataev969dbc02018-11-08 15:47:39 +00007646 LValue VarLValVal = CGF.EmitLValueForField(VDLVal, It->second);
7647 LambdaPointers.try_emplace(VarLVal.getPointer(), VDLVal.getPointer());
7648 BasePointers.push_back(VarLVal.getPointer());
7649 Pointers.push_back(VarLValVal.getPointer());
Alexey Bataev60705422018-10-30 15:50:12 +00007650 Sizes.push_back(CGF.getTypeSize(
7651 VD->getType().getCanonicalType().getNonReferenceType()));
Alexey Bataev2dc07d02018-11-02 15:25:06 +00007652 Types.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
Alexey Bataev60705422018-10-30 15:50:12 +00007653 OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT);
7654 }
7655 }
7656
7657 /// Set correct indices for lambdas captures.
Alexey Bataev969dbc02018-11-08 15:47:39 +00007658 void adjustMemberOfForLambdaCaptures(
7659 const llvm::DenseMap<llvm::Value *, llvm::Value *> &LambdaPointers,
7660 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
7661 MapFlagsArrayTy &Types) const {
Alexey Bataev60705422018-10-30 15:50:12 +00007662 for (unsigned I = 0, E = Types.size(); I < E; ++I) {
7663 // Set correct member_of idx for all implicit lambda captures.
Alexey Bataev2dc07d02018-11-02 15:25:06 +00007664 if (Types[I] != (OMP_MAP_PTR_AND_OBJ | OMP_MAP_LITERAL |
Alexey Bataev60705422018-10-30 15:50:12 +00007665 OMP_MAP_MEMBER_OF | OMP_MAP_IMPLICIT))
7666 continue;
Alexey Bataev969dbc02018-11-08 15:47:39 +00007667 llvm::Value *BasePtr = LambdaPointers.lookup(*BasePointers[I]);
7668 assert(BasePtr && "Unable to find base lambda address.");
Alexey Bataev60705422018-10-30 15:50:12 +00007669 int TgtIdx = -1;
7670 for (unsigned J = I; J > 0; --J) {
7671 unsigned Idx = J - 1;
7672 if (Pointers[Idx] != BasePtr)
7673 continue;
7674 TgtIdx = Idx;
7675 break;
7676 }
7677 assert(TgtIdx != -1 && "Unable to find parent lambda.");
7678 // All other current entries will be MEMBER_OF the combined entry
7679 // (except for PTR_AND_OBJ entries which do not have a placeholder value
7680 // 0xFFFF in the MEMBER_OF field).
7681 OpenMPOffloadMappingFlags MemberOfFlag = getMemberOfFlag(TgtIdx);
7682 setCorrectMemberOfFlag(Types[I], MemberOfFlag);
7683 }
7684 }
7685
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007686 /// Generate the base pointers, section pointers, sizes and map types
Samuel Antao86ace552016-04-27 22:40:57 +00007687 /// associated to a given capture.
7688 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00007689 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007690 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00007691 MapValuesArrayTy &Pointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007692 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
7693 StructRangeInfoTy &PartialStruct) const {
Samuel Antao86ace552016-04-27 22:40:57 +00007694 assert(!Cap->capturesVariableArrayType() &&
7695 "Not expecting to generate map info for a variable array type!");
7696
Samuel Antao6890b092016-07-28 14:25:09 +00007697 // We need to know when we generating information for the first component
Alexey Bataevb3638132018-07-19 16:34:13 +00007698 const ValueDecl *VD = Cap->capturesThis()
7699 ? nullptr
7700 : Cap->getCapturedVar()->getCanonicalDecl();
Samuel Antao86ace552016-04-27 22:40:57 +00007701
Samuel Antao6890b092016-07-28 14:25:09 +00007702 // If this declaration appears in a is_device_ptr clause we just have to
7703 // pass the pointer by value. If it is a reference to a declaration, we just
Alexey Bataevb3638132018-07-19 16:34:13 +00007704 // pass its value.
7705 if (DevPointersMap.count(VD)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007706 BasePointers.emplace_back(Arg, VD);
Samuel Antao6890b092016-07-28 14:25:09 +00007707 Pointers.push_back(Arg);
7708 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
George Rokos065755d2017-11-07 18:27:04 +00007709 Types.push_back(OMP_MAP_LITERAL | OMP_MAP_TARGET_PARAM);
Samuel Antao6890b092016-07-28 14:25:09 +00007710 return;
7711 }
7712
Alexey Bataeve82445f2018-09-20 13:54:02 +00007713 using MapData =
7714 std::tuple<OMPClauseMappableExprCommon::MappableExprComponentListRef,
Kelvin Lief579432018-12-18 22:18:41 +00007715 OpenMPMapClauseKind, ArrayRef<OpenMPMapModifierKind>, bool>;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007716 SmallVector<MapData, 4> DeclComponentLists;
Paul Robinson78fb1322016-08-01 22:12:46 +00007717 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Alexey Bataeve82445f2018-09-20 13:54:02 +00007718 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007719 for (const auto &L : C->decl_component_lists(VD)) {
Samuel Antao86ace552016-04-27 22:40:57 +00007720 assert(L.first == VD &&
7721 "We got information for the wrong declaration??");
7722 assert(!L.second.empty() &&
7723 "Not expecting declaration with no component lists.");
Alexey Bataeve82445f2018-09-20 13:54:02 +00007724 DeclComponentLists.emplace_back(L.second, C->getMapType(),
Kelvin Lief579432018-12-18 22:18:41 +00007725 C->getMapTypeModifiers(),
Alexey Bataeve82445f2018-09-20 13:54:02 +00007726 C->isImplicit());
Samuel Antao86ace552016-04-27 22:40:57 +00007727 }
Alexey Bataeve82445f2018-09-20 13:54:02 +00007728 }
7729
7730 // Find overlapping elements (including the offset from the base element).
7731 llvm::SmallDenseMap<
7732 const MapData *,
7733 llvm::SmallVector<
7734 OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>,
7735 4>
7736 OverlappedData;
7737 size_t Count = 0;
7738 for (const MapData &L : DeclComponentLists) {
7739 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7740 OpenMPMapClauseKind MapType;
Kelvin Lief579432018-12-18 22:18:41 +00007741 ArrayRef<OpenMPMapModifierKind> MapModifiers;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007742 bool IsImplicit;
Kelvin Lief579432018-12-18 22:18:41 +00007743 std::tie(Components, MapType, MapModifiers, IsImplicit) = L;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007744 ++Count;
7745 for (const MapData &L1 : makeArrayRef(DeclComponentLists).slice(Count)) {
7746 OMPClauseMappableExprCommon::MappableExprComponentListRef Components1;
Kelvin Lief579432018-12-18 22:18:41 +00007747 std::tie(Components1, MapType, MapModifiers, IsImplicit) = L1;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007748 auto CI = Components.rbegin();
7749 auto CE = Components.rend();
7750 auto SI = Components1.rbegin();
7751 auto SE = Components1.rend();
7752 for (; CI != CE && SI != SE; ++CI, ++SI) {
7753 if (CI->getAssociatedExpression()->getStmtClass() !=
7754 SI->getAssociatedExpression()->getStmtClass())
7755 break;
7756 // Are we dealing with different variables/fields?
7757 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
7758 break;
7759 }
7760 // Found overlapping if, at least for one component, reached the head of
7761 // the components list.
7762 if (CI == CE || SI == SE) {
7763 assert((CI != CE || SI != SE) &&
7764 "Unexpected full match of the mapping components.");
7765 const MapData &BaseData = CI == CE ? L : L1;
7766 OMPClauseMappableExprCommon::MappableExprComponentListRef SubData =
7767 SI == SE ? Components : Components1;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007768 auto &OverlappedElements = OverlappedData.FindAndConstruct(&BaseData);
7769 OverlappedElements.getSecond().push_back(SubData);
7770 }
7771 }
7772 }
7773 // Sort the overlapped elements for each item.
7774 llvm::SmallVector<const FieldDecl *, 4> Layout;
7775 if (!OverlappedData.empty()) {
7776 if (const auto *CRD =
7777 VD->getType().getCanonicalType()->getAsCXXRecordDecl())
7778 getPlainLayout(CRD, Layout, /*AsBase=*/false);
7779 else {
7780 const auto *RD = VD->getType().getCanonicalType()->getAsRecordDecl();
7781 Layout.append(RD->field_begin(), RD->field_end());
7782 }
7783 }
7784 for (auto &Pair : OverlappedData) {
7785 llvm::sort(
7786 Pair.getSecond(),
7787 [&Layout](
7788 OMPClauseMappableExprCommon::MappableExprComponentListRef First,
7789 OMPClauseMappableExprCommon::MappableExprComponentListRef
7790 Second) {
7791 auto CI = First.rbegin();
7792 auto CE = First.rend();
7793 auto SI = Second.rbegin();
7794 auto SE = Second.rend();
7795 for (; CI != CE && SI != SE; ++CI, ++SI) {
7796 if (CI->getAssociatedExpression()->getStmtClass() !=
7797 SI->getAssociatedExpression()->getStmtClass())
7798 break;
7799 // Are we dealing with different variables/fields?
7800 if (CI->getAssociatedDeclaration() !=
7801 SI->getAssociatedDeclaration())
7802 break;
7803 }
Richard Trieu5061e832018-09-21 21:20:33 +00007804
7805 // Lists contain the same elements.
7806 if (CI == CE && SI == SE)
7807 return false;
7808
7809 // List with less elements is less than list with more elements.
7810 if (CI == CE || SI == SE)
7811 return CI == CE;
7812
Alexey Bataeve82445f2018-09-20 13:54:02 +00007813 const auto *FD1 = cast<FieldDecl>(CI->getAssociatedDeclaration());
7814 const auto *FD2 = cast<FieldDecl>(SI->getAssociatedDeclaration());
7815 if (FD1->getParent() == FD2->getParent())
7816 return FD1->getFieldIndex() < FD2->getFieldIndex();
7817 const auto It =
7818 llvm::find_if(Layout, [FD1, FD2](const FieldDecl *FD) {
7819 return FD == FD1 || FD == FD2;
7820 });
7821 return *It == FD1;
7822 });
7823 }
7824
7825 // Associated with a capture, because the mapping flags depend on it.
7826 // Go through all of the elements with the overlapped elements.
7827 for (const auto &Pair : OverlappedData) {
7828 const MapData &L = *Pair.getFirst();
7829 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7830 OpenMPMapClauseKind MapType;
Kelvin Lief579432018-12-18 22:18:41 +00007831 ArrayRef<OpenMPMapModifierKind> MapModifiers;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007832 bool IsImplicit;
Kelvin Lief579432018-12-18 22:18:41 +00007833 std::tie(Components, MapType, MapModifiers, IsImplicit) = L;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007834 ArrayRef<OMPClauseMappableExprCommon::MappableExprComponentListRef>
7835 OverlappedComponents = Pair.getSecond();
7836 bool IsFirstComponentList = true;
Kelvin Lief579432018-12-18 22:18:41 +00007837 generateInfoForComponentList(MapType, MapModifiers, Components,
Alexey Bataeve82445f2018-09-20 13:54:02 +00007838 BasePointers, Pointers, Sizes, Types,
7839 PartialStruct, IsFirstComponentList,
7840 IsImplicit, OverlappedComponents);
7841 }
7842 // Go through other elements without overlapped elements.
7843 bool IsFirstComponentList = OverlappedData.empty();
7844 for (const MapData &L : DeclComponentLists) {
7845 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
7846 OpenMPMapClauseKind MapType;
Kelvin Lief579432018-12-18 22:18:41 +00007847 ArrayRef<OpenMPMapModifierKind> MapModifiers;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007848 bool IsImplicit;
Kelvin Lief579432018-12-18 22:18:41 +00007849 std::tie(Components, MapType, MapModifiers, IsImplicit) = L;
Alexey Bataeve82445f2018-09-20 13:54:02 +00007850 auto It = OverlappedData.find(&L);
7851 if (It == OverlappedData.end())
Kelvin Lief579432018-12-18 22:18:41 +00007852 generateInfoForComponentList(MapType, MapModifiers, Components,
Alexey Bataeve82445f2018-09-20 13:54:02 +00007853 BasePointers, Pointers, Sizes, Types,
7854 PartialStruct, IsFirstComponentList,
7855 IsImplicit);
7856 IsFirstComponentList = false;
7857 }
Alexey Bataevb3638132018-07-19 16:34:13 +00007858 }
Samuel Antao86ace552016-04-27 22:40:57 +00007859
Alexey Bataevb3638132018-07-19 16:34:13 +00007860 /// Generate the base pointers, section pointers, sizes and map types
7861 /// associated with the declare target link variables.
7862 void generateInfoForDeclareTargetLink(MapBaseValuesArrayTy &BasePointers,
7863 MapValuesArrayTy &Pointers,
7864 MapValuesArrayTy &Sizes,
7865 MapFlagsArrayTy &Types) const {
7866 // Map other list items in the map clause which are not captured variables
7867 // but "declare target link" global variables.,
7868 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) {
7869 for (const auto &L : C->component_lists()) {
7870 if (!L.first)
7871 continue;
7872 const auto *VD = dyn_cast<VarDecl>(L.first);
7873 if (!VD)
7874 continue;
7875 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00007876 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataevb3638132018-07-19 16:34:13 +00007877 if (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link)
7878 continue;
7879 StructRangeInfoTy PartialStruct;
7880 generateInfoForComponentList(
Kelvin Lief579432018-12-18 22:18:41 +00007881 C->getMapType(), C->getMapTypeModifiers(), L.second, BasePointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00007882 Pointers, Sizes, Types, PartialStruct,
7883 /*IsFirstComponentList=*/true, C->isImplicit());
7884 assert(!PartialStruct.Base.isValid() &&
7885 "No partial structs for declare target link expected.");
7886 }
7887 }
Samuel Antao86ace552016-04-27 22:40:57 +00007888 }
Samuel Antaod486f842016-05-26 16:53:38 +00007889
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007890 /// Generate the default map information for a given capture \a CI,
Samuel Antaod486f842016-05-26 16:53:38 +00007891 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00007892 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
7893 const FieldDecl &RI, llvm::Value *CV,
7894 MapBaseValuesArrayTy &CurBasePointers,
7895 MapValuesArrayTy &CurPointers,
7896 MapValuesArrayTy &CurSizes,
Alexey Bataevb3638132018-07-19 16:34:13 +00007897 MapFlagsArrayTy &CurMapTypes) const {
Samuel Antaod486f842016-05-26 16:53:38 +00007898 // Do the default mapping.
7899 if (CI.capturesThis()) {
7900 CurBasePointers.push_back(CV);
7901 CurPointers.push_back(CV);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007902 const auto *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007903 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
7904 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00007905 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00007906 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007907 CurBasePointers.push_back(CV);
7908 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00007909 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00007910 // We have to signal to the runtime captures passed by value that are
7911 // not pointers.
George Rokos065755d2017-11-07 18:27:04 +00007912 CurMapTypes.push_back(OMP_MAP_LITERAL);
Samuel Antaod486f842016-05-26 16:53:38 +00007913 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
7914 } else {
7915 // Pointers are implicitly mapped with a zero size and no flags
7916 // (other than first map that is added for all implicit maps).
Alexey Bataevb3638132018-07-19 16:34:13 +00007917 CurMapTypes.push_back(OMP_MAP_NONE);
Samuel Antaod486f842016-05-26 16:53:38 +00007918 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
7919 }
7920 } else {
7921 assert(CI.capturesVariable() && "Expected captured reference.");
7922 CurBasePointers.push_back(CV);
7923 CurPointers.push_back(CV);
7924
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007925 const auto *PtrTy = cast<ReferenceType>(RI.getType().getTypePtr());
Samuel Antaod486f842016-05-26 16:53:38 +00007926 QualType ElementType = PtrTy->getPointeeType();
7927 CurSizes.push_back(CGF.getTypeSize(ElementType));
7928 // The default map type for a scalar/complex type is 'to' because by
7929 // default the value doesn't have to be retrieved. For an aggregate
7930 // type, the default is 'tofrom'.
Alexey Bataevb3638132018-07-19 16:34:13 +00007931 CurMapTypes.push_back(getMapModifiersForPrivateClauses(CI));
Samuel Antaod486f842016-05-26 16:53:38 +00007932 }
George Rokos065755d2017-11-07 18:27:04 +00007933 // Every default map produces a single argument which is a target parameter.
7934 CurMapTypes.back() |= OMP_MAP_TARGET_PARAM;
Alexey Bataevb3638132018-07-19 16:34:13 +00007935
7936 // Add flag stating this is an implicit map.
7937 CurMapTypes.back() |= OMP_MAP_IMPLICIT;
Samuel Antaod486f842016-05-26 16:53:38 +00007938 }
Samuel Antao86ace552016-04-27 22:40:57 +00007939};
Samuel Antaodf158d52016-04-27 22:58:19 +00007940
7941enum OpenMPOffloadingReservedDeviceIDs {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007942 /// Device ID if the device was not defined, runtime should get it
Samuel Antaodf158d52016-04-27 22:58:19 +00007943 /// from environment variables in the spec.
7944 OMP_DEVICEID_UNDEF = -1,
7945};
7946} // anonymous namespace
7947
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007948/// Emit the arrays used to pass the captures and map information to the
Samuel Antaodf158d52016-04-27 22:58:19 +00007949/// offloading runtime library. If there is no map or capture information,
7950/// return nullptr by reference.
7951static void
Samuel Antaocc10b852016-07-28 14:23:26 +00007952emitOffloadingArrays(CodeGenFunction &CGF,
7953 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00007954 MappableExprsHandler::MapValuesArrayTy &Pointers,
7955 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00007956 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
7957 CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007958 CodeGenModule &CGM = CGF.CGM;
7959 ASTContext &Ctx = CGF.getContext();
Samuel Antaodf158d52016-04-27 22:58:19 +00007960
Samuel Antaocc10b852016-07-28 14:23:26 +00007961 // Reset the array information.
7962 Info.clearArrayInfo();
7963 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00007964
Samuel Antaocc10b852016-07-28 14:23:26 +00007965 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007966 // Detect if we have any capture size requiring runtime evaluation of the
7967 // size so that a constant array could be eventually used.
7968 bool hasRuntimeEvaluationCaptureSize = false;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007969 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00007970 if (!isa<llvm::Constant>(S)) {
7971 hasRuntimeEvaluationCaptureSize = true;
7972 break;
7973 }
7974
Samuel Antaocc10b852016-07-28 14:23:26 +00007975 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00007976 QualType PointerArrayType =
7977 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
7978 /*IndexTypeQuals=*/0);
7979
Samuel Antaocc10b852016-07-28 14:23:26 +00007980 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007981 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00007982 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007983 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
7984
7985 // If we don't have any VLA types or other types that require runtime
7986 // evaluation, we can use a constant array for the map sizes, otherwise we
7987 // need to fill up the arrays as we do for the pointers.
7988 if (hasRuntimeEvaluationCaptureSize) {
7989 QualType SizeArrayType = Ctx.getConstantArrayType(
7990 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
7991 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00007992 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00007993 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
7994 } else {
7995 // We expect all the sizes to be constant, so we collect them to create
7996 // a constant array.
7997 SmallVector<llvm::Constant *, 16> ConstSizes;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00007998 for (llvm::Value *S : Sizes)
Samuel Antaodf158d52016-04-27 22:58:19 +00007999 ConstSizes.push_back(cast<llvm::Constant>(S));
8000
8001 auto *SizesArrayInit = llvm::ConstantArray::get(
8002 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
Alexey Bataev18fa2322018-05-02 14:20:50 +00008003 std::string Name = CGM.getOpenMPRuntime().getName({"offload_sizes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00008004 auto *SizesArrayGbl = new llvm::GlobalVariable(
8005 CGM.getModule(), SizesArrayInit->getType(),
8006 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00008007 SizesArrayInit, Name);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00008008 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00008009 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00008010 }
8011
8012 // The map types are always constant so we don't need to generate code to
8013 // fill arrays. Instead, we create an array constant.
Alexey Bataevb3638132018-07-19 16:34:13 +00008014 SmallVector<uint64_t, 4> Mapping(MapTypes.size(), 0);
8015 llvm::copy(MapTypes, Mapping.begin());
Samuel Antaodf158d52016-04-27 22:58:19 +00008016 llvm::Constant *MapTypesArrayInit =
Alexey Bataevb3638132018-07-19 16:34:13 +00008017 llvm::ConstantDataArray::get(CGF.Builder.getContext(), Mapping);
Alexey Bataev18fa2322018-05-02 14:20:50 +00008018 std::string MaptypesName =
8019 CGM.getOpenMPRuntime().getName({"offload_maptypes"});
Samuel Antaodf158d52016-04-27 22:58:19 +00008020 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
8021 CGM.getModule(), MapTypesArrayInit->getType(),
8022 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
Alexey Bataev18fa2322018-05-02 14:20:50 +00008023 MapTypesArrayInit, MaptypesName);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00008024 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00008025 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00008026
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008027 for (unsigned I = 0; I < Info.NumberOfPtrs; ++I) {
8028 llvm::Value *BPVal = *BasePointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00008029 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008030 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008031 Info.BasePointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00008032 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
8033 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00008034 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
8035 CGF.Builder.CreateStore(BPVal, BPAddr);
8036
Samuel Antaocc10b852016-07-28 14:23:26 +00008037 if (Info.requiresDevicePointerInfo())
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008038 if (const ValueDecl *DevVD = BasePointers[I].getDevicePtrDecl())
Alexey Bataev43a919f2018-04-13 17:48:43 +00008039 Info.CaptureDeviceAddrMap.try_emplace(DevVD, BPAddr);
Samuel Antaocc10b852016-07-28 14:23:26 +00008040
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008041 llvm::Value *PVal = Pointers[I];
Samuel Antaodf158d52016-04-27 22:58:19 +00008042 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008043 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008044 Info.PointersArray, 0, I);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00008045 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
8046 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00008047 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
8048 CGF.Builder.CreateStore(PVal, PAddr);
8049
8050 if (hasRuntimeEvaluationCaptureSize) {
8051 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008052 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
8053 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008054 /*Idx0=*/0,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008055 /*Idx1=*/I);
Samuel Antaodf158d52016-04-27 22:58:19 +00008056 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
8057 CGF.Builder.CreateStore(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008058 CGF.Builder.CreateIntCast(Sizes[I], CGM.SizeTy, /*isSigned=*/true),
Samuel Antaodf158d52016-04-27 22:58:19 +00008059 SAddr);
8060 }
8061 }
8062 }
8063}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008064/// Emit the arguments to be passed to the runtime library based on the
Samuel Antaodf158d52016-04-27 22:58:19 +00008065/// arrays of pointers, sizes and map types.
8066static void emitOffloadingArraysArgument(
8067 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
8068 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008069 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008070 CodeGenModule &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00008071 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008072 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008073 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
8074 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008075 /*Idx0=*/0, /*Idx1=*/0);
8076 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008077 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
8078 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008079 /*Idx0=*/0,
8080 /*Idx1=*/0);
8081 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00008082 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008083 /*Idx0=*/0, /*Idx1=*/0);
8084 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
George Rokos63bc9d62017-11-21 18:25:12 +00008085 llvm::ArrayType::get(CGM.Int64Ty, Info.NumberOfPtrs),
Samuel Antaocc10b852016-07-28 14:23:26 +00008086 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00008087 /*Idx0=*/0,
8088 /*Idx1=*/0);
8089 } else {
8090 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
8091 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
8092 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
8093 MapTypesArrayArg =
George Rokos63bc9d62017-11-21 18:25:12 +00008094 llvm::ConstantPointerNull::get(CGM.Int64Ty->getPointerTo());
Samuel Antaodf158d52016-04-27 22:58:19 +00008095 }
Samuel Antao86ace552016-04-27 22:40:57 +00008096}
8097
Alexey Bataev7bb33532019-01-07 21:30:43 +00008098/// Checks if the expression is constant or does not have non-trivial function
8099/// calls.
8100static bool isTrivial(ASTContext &Ctx, const Expr * E) {
8101 // We can skip constant expressions.
8102 // We can skip expressions with trivial calls or simple expressions.
8103 return (E->isEvaluatable(Ctx, Expr::SE_AllowUndefinedBehavior) ||
8104 !E->hasNonTrivialCall(Ctx)) &&
8105 !E->HasSideEffects(Ctx, /*IncludePossibleEffects=*/true);
8106}
8107
8108/// Checks if the \p Body is the \a CompoundStmt and returns its child statement
8109/// iff there is only one that is not evaluatable at the compile time.
8110static const Stmt *getSingleCompoundChild(ASTContext &Ctx, const Stmt *Body) {
8111 if (const auto *C = dyn_cast<CompoundStmt>(Body)) {
8112 const Stmt *Child = nullptr;
8113 for (const Stmt *S : C->body()) {
8114 if (const auto *E = dyn_cast<Expr>(S)) {
8115 if (isTrivial(Ctx, E))
8116 continue;
8117 }
8118 // Some of the statements can be ignored.
8119 if (isa<AsmStmt>(S) || isa<NullStmt>(S) || isa<OMPFlushDirective>(S) ||
8120 isa<OMPBarrierDirective>(S) || isa<OMPTaskyieldDirective>(S))
8121 continue;
8122 // Analyze declarations.
8123 if (const auto *DS = dyn_cast<DeclStmt>(S)) {
8124 if (llvm::all_of(DS->decls(), [&Ctx](const Decl *D) {
8125 if (isa<EmptyDecl>(D) || isa<DeclContext>(D) ||
8126 isa<TypeDecl>(D) || isa<PragmaCommentDecl>(D) ||
8127 isa<PragmaDetectMismatchDecl>(D) || isa<UsingDecl>(D) ||
8128 isa<UsingDirectiveDecl>(D) ||
8129 isa<OMPDeclareReductionDecl>(D) ||
8130 isa<OMPThreadPrivateDecl>(D))
8131 return true;
8132 const auto *VD = dyn_cast<VarDecl>(D);
8133 if (!VD)
8134 return false;
8135 return VD->isConstexpr() ||
8136 ((VD->getType().isTrivialType(Ctx) ||
8137 VD->getType()->isReferenceType()) &&
8138 (!VD->hasInit() || isTrivial(Ctx, VD->getInit())));
8139 }))
8140 continue;
8141 }
8142 // Found multiple children - cannot get the one child only.
8143 if (Child)
8144 return Body;
8145 Child = S;
8146 }
8147 if (Child)
8148 return Child;
8149 }
8150 return Body;
8151}
8152
8153/// Check for inner distribute directive.
8154static const OMPExecutableDirective *
8155getNestedDistributeDirective(ASTContext &Ctx, const OMPExecutableDirective &D) {
8156 const auto *CS = D.getInnermostCapturedStmt();
8157 const auto *Body =
8158 CS->getCapturedStmt()->IgnoreContainers(/*IgnoreCaptured=*/true);
8159 const Stmt *ChildStmt = getSingleCompoundChild(Ctx, Body);
8160
8161 if (const auto *NestedDir = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
8162 OpenMPDirectiveKind DKind = NestedDir->getDirectiveKind();
8163 switch (D.getDirectiveKind()) {
8164 case OMPD_target:
8165 if (isOpenMPDistributeDirective(DKind))
8166 return NestedDir;
8167 if (DKind == OMPD_teams) {
8168 Body = NestedDir->getInnermostCapturedStmt()->IgnoreContainers(
8169 /*IgnoreCaptured=*/true);
8170 if (!Body)
8171 return nullptr;
8172 ChildStmt = getSingleCompoundChild(Ctx, Body);
8173 if (const auto *NND = dyn_cast<OMPExecutableDirective>(ChildStmt)) {
8174 DKind = NND->getDirectiveKind();
8175 if (isOpenMPDistributeDirective(DKind))
8176 return NND;
8177 }
8178 }
8179 return nullptr;
8180 case OMPD_target_teams:
8181 if (isOpenMPDistributeDirective(DKind))
8182 return NestedDir;
8183 return nullptr;
8184 case OMPD_target_parallel:
8185 case OMPD_target_simd:
8186 case OMPD_target_parallel_for:
8187 case OMPD_target_parallel_for_simd:
8188 return nullptr;
8189 case OMPD_target_teams_distribute:
8190 case OMPD_target_teams_distribute_simd:
8191 case OMPD_target_teams_distribute_parallel_for:
8192 case OMPD_target_teams_distribute_parallel_for_simd:
8193 case OMPD_parallel:
8194 case OMPD_for:
8195 case OMPD_parallel_for:
8196 case OMPD_parallel_sections:
8197 case OMPD_for_simd:
8198 case OMPD_parallel_for_simd:
8199 case OMPD_cancel:
8200 case OMPD_cancellation_point:
8201 case OMPD_ordered:
8202 case OMPD_threadprivate:
8203 case OMPD_task:
8204 case OMPD_simd:
8205 case OMPD_sections:
8206 case OMPD_section:
8207 case OMPD_single:
8208 case OMPD_master:
8209 case OMPD_critical:
8210 case OMPD_taskyield:
8211 case OMPD_barrier:
8212 case OMPD_taskwait:
8213 case OMPD_taskgroup:
8214 case OMPD_atomic:
8215 case OMPD_flush:
8216 case OMPD_teams:
8217 case OMPD_target_data:
8218 case OMPD_target_exit_data:
8219 case OMPD_target_enter_data:
8220 case OMPD_distribute:
8221 case OMPD_distribute_simd:
8222 case OMPD_distribute_parallel_for:
8223 case OMPD_distribute_parallel_for_simd:
8224 case OMPD_teams_distribute:
8225 case OMPD_teams_distribute_simd:
8226 case OMPD_teams_distribute_parallel_for:
8227 case OMPD_teams_distribute_parallel_for_simd:
8228 case OMPD_target_update:
8229 case OMPD_declare_simd:
8230 case OMPD_declare_target:
8231 case OMPD_end_declare_target:
8232 case OMPD_declare_reduction:
8233 case OMPD_taskloop:
8234 case OMPD_taskloop_simd:
8235 case OMPD_requires:
8236 case OMPD_unknown:
8237 llvm_unreachable("Unexpected directive.");
8238 }
8239 }
8240
8241 return nullptr;
8242}
8243
8244void CGOpenMPRuntime::emitTargetNumIterationsCall(
8245 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *Device,
8246 const llvm::function_ref<llvm::Value *(
8247 CodeGenFunction &CGF, const OMPLoopDirective &D)> &SizeEmitter) {
8248 OpenMPDirectiveKind Kind = D.getDirectiveKind();
8249 const OMPExecutableDirective *TD = &D;
8250 // Get nested teams distribute kind directive, if any.
8251 if (!isOpenMPDistributeDirective(Kind) || !isOpenMPTeamsDirective(Kind))
8252 TD = getNestedDistributeDirective(CGM.getContext(), D);
8253 if (!TD)
8254 return;
8255 const auto *LD = cast<OMPLoopDirective>(TD);
8256 auto &&CodeGen = [LD, &Device, &SizeEmitter, this](CodeGenFunction &CGF,
8257 PrePostActionTy &) {
8258 llvm::Value *NumIterations = SizeEmitter(CGF, *LD);
8259
8260 // Emit device ID if any.
8261 llvm::Value *DeviceID;
8262 if (Device)
8263 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
8264 CGF.Int64Ty, /*isSigned=*/true);
8265 else
8266 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8267
8268 llvm::Value *Args[] = {DeviceID, NumIterations};
8269 CGF.EmitRuntimeCall(
8270 createRuntimeFunction(OMPRTL__kmpc_push_target_tripcount), Args);
8271 };
8272 emitInlinedDirective(CGF, OMPD_unknown, CodeGen);
8273}
8274
Samuel Antaobed3c462015-10-02 16:14:20 +00008275void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
8276 const OMPExecutableDirective &D,
8277 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00008278 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00008279 const Expr *IfCond, const Expr *Device) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00008280 if (!CGF.HaveInsertPoint())
8281 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00008282
Samuel Antaoee8fb302016-01-06 13:42:12 +00008283 assert(OutlinedFn && "Invalid outlined function!");
8284
Alexey Bataev8451efa2018-01-15 19:06:12 +00008285 const bool RequiresOuterTask = D.hasClausesOfKind<OMPDependClause>();
8286 llvm::SmallVector<llvm::Value *, 16> CapturedVars;
Alexey Bataev475a7442018-01-12 19:39:11 +00008287 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008288 auto &&ArgsCodegen = [&CS, &CapturedVars](CodeGenFunction &CGF,
8289 PrePostActionTy &) {
8290 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
8291 };
8292 emitInlinedDirective(CGF, OMPD_unknown, ArgsCodegen);
Samuel Antao86ace552016-04-27 22:40:57 +00008293
Alexey Bataev8451efa2018-01-15 19:06:12 +00008294 CodeGenFunction::OMPTargetDataInfo InputInfo;
8295 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobed3c462015-10-02 16:14:20 +00008296 // Fill up the pointer arrays and transfer execution to the device.
Alexey Bataev8451efa2018-01-15 19:06:12 +00008297 auto &&ThenGen = [this, Device, OutlinedFn, OutlinedFnID, &D, &InputInfo,
8298 &MapTypesArray, &CS, RequiresOuterTask,
8299 &CapturedVars](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobed3c462015-10-02 16:14:20 +00008300 // On top of the arrays that were filled up, the target offloading call
8301 // takes as arguments the device id as well as the host pointer. The host
8302 // pointer is used by the runtime library to identify the current target
8303 // region, so it only has to be unique and not necessarily point to
8304 // anything. It could be the pointer to the outlined function that
8305 // implements the target region, but we aren't using that so that the
8306 // compiler doesn't need to keep that, and could therefore inline the host
8307 // function if proven worthwhile during optimization.
8308
Samuel Antaoee8fb302016-01-06 13:42:12 +00008309 // From this point on, we need to have an ID of the target region defined.
8310 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00008311
8312 // Emit device ID if any.
8313 llvm::Value *DeviceID;
George Rokos63bc9d62017-11-21 18:25:12 +00008314 if (Device) {
Samuel Antaobed3c462015-10-02 16:14:20 +00008315 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008316 CGF.Int64Ty, /*isSigned=*/true);
8317 } else {
8318 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8319 }
Samuel Antaobed3c462015-10-02 16:14:20 +00008320
Samuel Antaodf158d52016-04-27 22:58:19 +00008321 // Emit the number of elements in the offloading arrays.
Alexey Bataev8451efa2018-01-15 19:06:12 +00008322 llvm::Value *PointerNum =
8323 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaodf158d52016-04-27 22:58:19 +00008324
Samuel Antaob68e2db2016-03-03 16:20:23 +00008325 // Return value of the runtime offloading call.
8326 llvm::Value *Return;
8327
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008328 llvm::Value *NumTeams = emitNumTeamsForTargetDirective(*this, CGF, D);
8329 llvm::Value *NumThreads = emitNumThreadsForTargetDirective(*this, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00008330
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008331 bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008332 // The target region is an outlined function launched by the runtime
8333 // via calls __tgt_target() or __tgt_target_teams().
8334 //
8335 // __tgt_target() launches a target region with one team and one thread,
8336 // executing a serial region. This master thread may in turn launch
8337 // more threads within its team upon encountering a parallel region,
8338 // however, no additional teams can be launched on the device.
8339 //
8340 // __tgt_target_teams() launches a target region with one or more teams,
8341 // each with one or more threads. This call is required for target
8342 // constructs such as:
8343 // 'target teams'
8344 // 'target' / 'teams'
8345 // 'target teams distribute parallel for'
8346 // 'target parallel'
8347 // and so on.
8348 //
8349 // Note that on the host and CPU targets, the runtime implementation of
8350 // these calls simply call the outlined function without forking threads.
8351 // The outlined functions themselves have runtime calls to
8352 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
8353 // the compiler in emitTeamsCall() and emitParallelCall().
8354 //
8355 // In contrast, on the NVPTX target, the implementation of
8356 // __tgt_target_teams() launches a GPU kernel with the requested number
8357 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00008358 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008359 // If we have NumTeams defined this means that we have an enclosed teams
8360 // region. Therefore we also expect to have NumThreads defined. These two
8361 // values should be defined in the presence of a teams directive,
8362 // regardless of having any clauses associated. If the user is using teams
8363 // but no clauses, these two values will be the default that should be
8364 // passed to the runtime library - a 32-bit integer with the value zero.
8365 assert(NumThreads && "Thread limit expression should be available along "
8366 "with number of teams.");
Alexey Bataev8451efa2018-01-15 19:06:12 +00008367 llvm::Value *OffloadingArgs[] = {DeviceID,
8368 OutlinedFnID,
8369 PointerNum,
8370 InputInfo.BasePointersArray.getPointer(),
8371 InputInfo.PointersArray.getPointer(),
8372 InputInfo.SizesArray.getPointer(),
8373 MapTypesArray,
8374 NumTeams,
8375 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00008376 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00008377 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_teams_nowait
8378 : OMPRTL__tgt_target_teams),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008379 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00008380 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00008381 llvm::Value *OffloadingArgs[] = {DeviceID,
8382 OutlinedFnID,
8383 PointerNum,
8384 InputInfo.BasePointersArray.getPointer(),
8385 InputInfo.PointersArray.getPointer(),
8386 InputInfo.SizesArray.getPointer(),
8387 MapTypesArray};
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008388 Return = CGF.EmitRuntimeCall(
Alexey Bataev8451efa2018-01-15 19:06:12 +00008389 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_nowait
8390 : OMPRTL__tgt_target),
Alexey Bataeva9f77c62017-12-13 21:04:20 +00008391 OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00008392 }
Samuel Antaobed3c462015-10-02 16:14:20 +00008393
Alexey Bataev2a007e02017-10-02 14:20:58 +00008394 // Check the error code and execute the host version if required.
8395 llvm::BasicBlock *OffloadFailedBlock =
8396 CGF.createBasicBlock("omp_offload.failed");
8397 llvm::BasicBlock *OffloadContBlock =
8398 CGF.createBasicBlock("omp_offload.cont");
8399 llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return);
8400 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
8401
8402 CGF.EmitBlock(OffloadFailedBlock);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008403 if (RequiresOuterTask) {
8404 CapturedVars.clear();
8405 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
8406 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008407 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars);
Alexey Bataev2a007e02017-10-02 14:20:58 +00008408 CGF.EmitBranch(OffloadContBlock);
8409
8410 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00008411 };
8412
Samuel Antaoee8fb302016-01-06 13:42:12 +00008413 // Notify that the host version must be executed.
Alexey Bataev8451efa2018-01-15 19:06:12 +00008414 auto &&ElseGen = [this, &D, OutlinedFn, &CS, &CapturedVars,
8415 RequiresOuterTask](CodeGenFunction &CGF,
8416 PrePostActionTy &) {
8417 if (RequiresOuterTask) {
8418 CapturedVars.clear();
8419 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars);
8420 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008421 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008422 };
8423
8424 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray,
8425 &CapturedVars, RequiresOuterTask,
8426 &CS](CodeGenFunction &CGF, PrePostActionTy &) {
8427 // Fill up the arrays with all the captured variables.
8428 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
8429 MappableExprsHandler::MapValuesArrayTy Pointers;
8430 MappableExprsHandler::MapValuesArrayTy Sizes;
8431 MappableExprsHandler::MapFlagsArrayTy MapTypes;
8432
Alexey Bataev8451efa2018-01-15 19:06:12 +00008433 // Get mappable expression information.
8434 MappableExprsHandler MEHandler(D, CGF);
Alexey Bataev969dbc02018-11-08 15:47:39 +00008435 llvm::DenseMap<llvm::Value *, llvm::Value *> LambdaPointers;
Alexey Bataev8451efa2018-01-15 19:06:12 +00008436
8437 auto RI = CS.getCapturedRecordDecl()->field_begin();
8438 auto CV = CapturedVars.begin();
8439 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
8440 CE = CS.capture_end();
8441 CI != CE; ++CI, ++RI, ++CV) {
Alexey Bataevb3638132018-07-19 16:34:13 +00008442 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
8443 MappableExprsHandler::MapValuesArrayTy CurPointers;
8444 MappableExprsHandler::MapValuesArrayTy CurSizes;
8445 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
8446 MappableExprsHandler::StructRangeInfoTy PartialStruct;
Alexey Bataev8451efa2018-01-15 19:06:12 +00008447
8448 // VLA sizes are passed to the outlined region by copy and do not have map
8449 // information associated.
8450 if (CI->capturesVariableArrayType()) {
8451 CurBasePointers.push_back(*CV);
8452 CurPointers.push_back(*CV);
8453 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
8454 // Copy to the device as an argument. No need to retrieve it.
8455 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_LITERAL |
8456 MappableExprsHandler::OMP_MAP_TARGET_PARAM);
8457 } else {
8458 // If we have any information in the map clause, we use it, otherwise we
8459 // just do a default mapping.
8460 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Alexey Bataevb3638132018-07-19 16:34:13 +00008461 CurSizes, CurMapTypes, PartialStruct);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008462 if (CurBasePointers.empty())
8463 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
8464 CurPointers, CurSizes, CurMapTypes);
Alexey Bataev60705422018-10-30 15:50:12 +00008465 // Generate correct mapping for variables captured by reference in
8466 // lambdas.
8467 if (CI->capturesVariable())
Alexey Bataev969dbc02018-11-08 15:47:39 +00008468 MEHandler.generateInfoForLambdaCaptures(
8469 CI->getCapturedVar(), *CV, CurBasePointers, CurPointers, CurSizes,
8470 CurMapTypes, LambdaPointers);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008471 }
8472 // We expect to have at least an element of information for this capture.
8473 assert(!CurBasePointers.empty() &&
8474 "Non-existing map pointer for capture!");
8475 assert(CurBasePointers.size() == CurPointers.size() &&
8476 CurBasePointers.size() == CurSizes.size() &&
8477 CurBasePointers.size() == CurMapTypes.size() &&
8478 "Inconsistent map information sizes!");
8479
Alexey Bataevb3638132018-07-19 16:34:13 +00008480 // If there is an entry in PartialStruct it means we have a struct with
8481 // individual members mapped. Emit an extra combined entry.
8482 if (PartialStruct.Base.isValid())
8483 MEHandler.emitCombinedEntry(BasePointers, Pointers, Sizes, MapTypes,
8484 CurMapTypes, PartialStruct);
8485
Alexey Bataev8451efa2018-01-15 19:06:12 +00008486 // We need to append the results of this capture to what we already have.
8487 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
8488 Pointers.append(CurPointers.begin(), CurPointers.end());
8489 Sizes.append(CurSizes.begin(), CurSizes.end());
8490 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
8491 }
Alexey Bataev60705422018-10-30 15:50:12 +00008492 // Adjust MEMBER_OF flags for the lambdas captures.
Alexey Bataev969dbc02018-11-08 15:47:39 +00008493 MEHandler.adjustMemberOfForLambdaCaptures(LambdaPointers, BasePointers,
8494 Pointers, MapTypes);
Alexey Bataev92327c52018-03-26 16:40:55 +00008495 // Map other list items in the map clause which are not captured variables
8496 // but "declare target link" global variables.
Alexey Bataevb3638132018-07-19 16:34:13 +00008497 MEHandler.generateInfoForDeclareTargetLink(BasePointers, Pointers, Sizes,
8498 MapTypes);
Alexey Bataev8451efa2018-01-15 19:06:12 +00008499
8500 TargetDataInfo Info;
8501 // Fill up the arrays and create the arguments.
8502 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
8503 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
8504 Info.PointersArray, Info.SizesArray,
8505 Info.MapTypesArray, Info);
8506 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
8507 InputInfo.BasePointersArray =
8508 Address(Info.BasePointersArray, CGM.getPointerAlign());
8509 InputInfo.PointersArray =
8510 Address(Info.PointersArray, CGM.getPointerAlign());
8511 InputInfo.SizesArray = Address(Info.SizesArray, CGM.getPointerAlign());
8512 MapTypesArray = Info.MapTypesArray;
8513 if (RequiresOuterTask)
8514 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
8515 else
8516 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
8517 };
8518
8519 auto &&TargetElseGen = [this, &ElseGen, &D, RequiresOuterTask](
8520 CodeGenFunction &CGF, PrePostActionTy &) {
8521 if (RequiresOuterTask) {
8522 CodeGenFunction::OMPTargetDataInfo InputInfo;
8523 CGF.EmitOMPTargetTaskBasedDirective(D, ElseGen, InputInfo);
8524 } else {
8525 emitInlinedDirective(CGF, D.getDirectiveKind(), ElseGen);
8526 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00008527 };
8528
8529 // If we have a target function ID it means that we need to support
8530 // offloading, otherwise, just execute on the host. We need to execute on host
8531 // regardless of the conditional in the if clause if, e.g., the user do not
8532 // specify target triples.
8533 if (OutlinedFnID) {
Alexey Bataev8451efa2018-01-15 19:06:12 +00008534 if (IfCond) {
8535 emitOMPIfClause(CGF, IfCond, TargetThenGen, TargetElseGen);
8536 } else {
8537 RegionCodeGenTy ThenRCG(TargetThenGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00008538 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00008539 }
8540 } else {
Alexey Bataev8451efa2018-01-15 19:06:12 +00008541 RegionCodeGenTy ElseRCG(TargetElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00008542 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00008543 }
Samuel Antaobed3c462015-10-02 16:14:20 +00008544}
Samuel Antaoee8fb302016-01-06 13:42:12 +00008545
8546void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
8547 StringRef ParentName) {
8548 if (!S)
8549 return;
8550
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008551 // Codegen OMP target directives that offload compute to the device.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008552 bool RequiresDeviceCodegen =
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008553 isa<OMPExecutableDirective>(S) &&
8554 isOpenMPTargetExecutionDirective(
8555 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00008556
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008557 if (RequiresDeviceCodegen) {
8558 const auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008559 unsigned DeviceID;
8560 unsigned FileID;
8561 unsigned Line;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008562 getTargetEntryUniqueInfo(CGM.getContext(), E.getBeginLoc(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00008563 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008564
8565 // Is this a target region that should not be emitted as an entry point? If
8566 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00008567 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
8568 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008569 return;
8570
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008571 switch (E.getDirectiveKind()) {
8572 case OMPD_target:
8573 CodeGenFunction::EmitOMPTargetDeviceFunction(CGM, ParentName,
8574 cast<OMPTargetDirective>(E));
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008575 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008576 case OMPD_target_parallel:
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00008577 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008578 CGM, ParentName, cast<OMPTargetParallelDirective>(E));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00008579 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008580 case OMPD_target_teams:
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00008581 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008582 CGM, ParentName, cast<OMPTargetTeamsDirective>(E));
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00008583 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008584 case OMPD_target_teams_distribute:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008585 CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008586 CGM, ParentName, cast<OMPTargetTeamsDistributeDirective>(E));
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008587 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008588 case OMPD_target_teams_distribute_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008589 CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008590 CGM, ParentName, cast<OMPTargetTeamsDistributeSimdDirective>(E));
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008591 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008592 case OMPD_target_parallel_for:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008593 CodeGenFunction::EmitOMPTargetParallelForDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008594 CGM, ParentName, cast<OMPTargetParallelForDirective>(E));
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008595 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008596 case OMPD_target_parallel_for_simd:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008597 CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008598 CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(E));
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008599 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008600 case OMPD_target_simd:
Alexey Bataevf8365372017-11-17 17:57:25 +00008601 CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008602 CGM, ParentName, cast<OMPTargetSimdDirective>(E));
Alexey Bataevf8365372017-11-17 17:57:25 +00008603 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008604 case OMPD_target_teams_distribute_parallel_for:
Carlo Bertolli52978c32018-01-03 21:12:44 +00008605 CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(
8606 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008607 cast<OMPTargetTeamsDistributeParallelForDirective>(E));
Carlo Bertolli52978c32018-01-03 21:12:44 +00008608 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008609 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00008610 CodeGenFunction::
8611 EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(
8612 CGM, ParentName,
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008613 cast<OMPTargetTeamsDistributeParallelForSimdDirective>(E));
Alexey Bataev647dd842018-01-15 20:59:40 +00008614 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008615 case OMPD_parallel:
8616 case OMPD_for:
8617 case OMPD_parallel_for:
8618 case OMPD_parallel_sections:
8619 case OMPD_for_simd:
8620 case OMPD_parallel_for_simd:
8621 case OMPD_cancel:
8622 case OMPD_cancellation_point:
8623 case OMPD_ordered:
8624 case OMPD_threadprivate:
8625 case OMPD_task:
8626 case OMPD_simd:
8627 case OMPD_sections:
8628 case OMPD_section:
8629 case OMPD_single:
8630 case OMPD_master:
8631 case OMPD_critical:
8632 case OMPD_taskyield:
8633 case OMPD_barrier:
8634 case OMPD_taskwait:
8635 case OMPD_taskgroup:
8636 case OMPD_atomic:
8637 case OMPD_flush:
8638 case OMPD_teams:
8639 case OMPD_target_data:
8640 case OMPD_target_exit_data:
8641 case OMPD_target_enter_data:
8642 case OMPD_distribute:
8643 case OMPD_distribute_simd:
8644 case OMPD_distribute_parallel_for:
8645 case OMPD_distribute_parallel_for_simd:
8646 case OMPD_teams_distribute:
8647 case OMPD_teams_distribute_simd:
8648 case OMPD_teams_distribute_parallel_for:
8649 case OMPD_teams_distribute_parallel_for_simd:
8650 case OMPD_target_update:
8651 case OMPD_declare_simd:
8652 case OMPD_declare_target:
8653 case OMPD_end_declare_target:
8654 case OMPD_declare_reduction:
8655 case OMPD_taskloop:
8656 case OMPD_taskloop_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008657 case OMPD_requires:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008658 case OMPD_unknown:
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00008659 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
8660 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00008661 return;
8662 }
8663
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008664 if (const auto *E = dyn_cast<OMPExecutableDirective>(S)) {
Alexey Bataev475a7442018-01-12 19:39:11 +00008665 if (!E->hasAssociatedStmt() || !E->getAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00008666 return;
8667
8668 scanForTargetRegionsFunctions(
Alexey Bataev475a7442018-01-12 19:39:11 +00008669 E->getInnermostCapturedStmt()->getCapturedStmt(), ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008670 return;
8671 }
8672
8673 // If this is a lambda function, look into its body.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008674 if (const auto *L = dyn_cast<LambdaExpr>(S))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008675 S = L->getBody();
8676
8677 // Keep looking for target regions recursively.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008678 for (const Stmt *II : S->children())
Samuel Antaoee8fb302016-01-06 13:42:12 +00008679 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008680}
8681
8682bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008683 // If emitting code for the host, we do not process FD here. Instead we do
8684 // the normal code generation.
8685 if (!CGM.getLangOpts().OpenMPIsDevice)
8686 return false;
8687
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008688 const ValueDecl *VD = cast<ValueDecl>(GD.getDecl());
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008689 StringRef Name = CGM.getMangledName(GD);
8690 // Try to detect target regions in the function.
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008691 if (const auto *FD = dyn_cast<FunctionDecl>(VD))
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008692 scanForTargetRegionsFunctions(FD->getBody(), Name);
Samuel Antaoee8fb302016-01-06 13:42:12 +00008693
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008694 // Do not to emit function if it is not marked as declare target.
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008695 return !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008696 AlreadyEmittedTargetFunctions.count(Name) == 0;
Samuel Antaoee8fb302016-01-06 13:42:12 +00008697}
8698
8699bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
8700 if (!CGM.getLangOpts().OpenMPIsDevice)
8701 return false;
8702
8703 // Check if there are Ctors/Dtors in this declaration and look for target
8704 // regions in it. We use the complete variant to produce the kernel name
8705 // mangling.
8706 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008707 if (const auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
8708 for (const CXXConstructorDecl *Ctor : RD->ctors()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008709 StringRef ParentName =
8710 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
8711 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
8712 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008713 if (const CXXDestructorDecl *Dtor = RD->getDestructor()) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00008714 StringRef ParentName =
8715 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
8716 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
8717 }
8718 }
8719
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008720 // Do not to emit variable if it is not marked as declare target.
Alexey Bataev92327c52018-03-26 16:40:55 +00008721 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00008722 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
8723 cast<VarDecl>(GD.getDecl()));
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008724 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Alexey Bataevd01b7492018-08-15 19:45:12 +00008725 DeferredGlobalVariables.insert(cast<VarDecl>(GD.getDecl()));
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008726 return true;
8727 }
8728 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00008729}
8730
Alexey Bataev03f270c2018-03-30 18:31:07 +00008731void CGOpenMPRuntime::registerTargetGlobalVariable(const VarDecl *VD,
8732 llvm::Constant *Addr) {
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008733 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
8734 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
8735 if (!Res) {
8736 if (CGM.getLangOpts().OpenMPIsDevice) {
8737 // Register non-target variables being emitted in device code (debug info
8738 // may cause this).
8739 StringRef VarName = CGM.getMangledName(VD);
8740 EmittedNonTargetVariables.try_emplace(VarName, Addr);
Alexey Bataev03f270c2018-03-30 18:31:07 +00008741 }
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008742 return;
Alexey Bataev03f270c2018-03-30 18:31:07 +00008743 }
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008744 // Register declare target variables.
8745 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags;
8746 StringRef VarName;
8747 CharUnits VarSize;
8748 llvm::GlobalValue::LinkageTypes Linkage;
8749 switch (*Res) {
8750 case OMPDeclareTargetDeclAttr::MT_To:
8751 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo;
8752 VarName = CGM.getMangledName(VD);
8753 if (VD->hasDefinition(CGM.getContext()) != VarDecl::DeclarationOnly) {
8754 VarSize = CGM.getContext().getTypeSizeInChars(VD->getType());
8755 assert(!VarSize.isZero() && "Expected non-zero size of the variable");
8756 } else {
8757 VarSize = CharUnits::Zero();
8758 }
8759 Linkage = CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false);
8760 // Temp solution to prevent optimizations of the internal variables.
8761 if (CGM.getLangOpts().OpenMPIsDevice && !VD->isExternallyVisible()) {
8762 std::string RefName = getName({VarName, "ref"});
8763 if (!CGM.GetGlobalValue(RefName)) {
8764 llvm::Constant *AddrRef =
8765 getOrCreateInternalVariable(Addr->getType(), RefName);
8766 auto *GVAddrRef = cast<llvm::GlobalVariable>(AddrRef);
8767 GVAddrRef->setConstant(/*Val=*/true);
8768 GVAddrRef->setLinkage(llvm::GlobalValue::InternalLinkage);
8769 GVAddrRef->setInitializer(Addr);
8770 CGM.addCompilerUsedGlobal(GVAddrRef);
8771 }
8772 }
8773 break;
8774 case OMPDeclareTargetDeclAttr::MT_Link:
8775 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink;
8776 if (CGM.getLangOpts().OpenMPIsDevice) {
8777 VarName = Addr->getName();
8778 Addr = nullptr;
8779 } else {
8780 VarName = getAddrOfDeclareTargetLink(VD).getName();
8781 Addr = cast<llvm::Constant>(getAddrOfDeclareTargetLink(VD).getPointer());
8782 }
8783 VarSize = CGM.getPointerSize();
8784 Linkage = llvm::GlobalValue::WeakAnyLinkage;
8785 break;
8786 }
8787 OffloadEntriesInfoManager.registerDeviceGlobalVarEntryInfo(
8788 VarName, Addr, VarSize, Flags, Linkage);
Alexey Bataev03f270c2018-03-30 18:31:07 +00008789}
8790
Samuel Antaoee8fb302016-01-06 13:42:12 +00008791bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
Alexey Bataeve6aa4692018-09-13 16:54:05 +00008792 if (isa<FunctionDecl>(GD.getDecl()) ||
8793 isa<OMPDeclareReductionDecl>(GD.getDecl()))
Samuel Antaoee8fb302016-01-06 13:42:12 +00008794 return emitTargetFunctions(GD);
8795
8796 return emitTargetGlobalVariable(GD);
8797}
8798
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008799void CGOpenMPRuntime::emitDeferredTargetDecls() const {
8800 for (const VarDecl *VD : DeferredGlobalVariables) {
8801 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00008802 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataevd01b7492018-08-15 19:45:12 +00008803 if (!Res)
8804 continue;
8805 if (*Res == OMPDeclareTargetDeclAttr::MT_To) {
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008806 CGM.EmitGlobal(VD);
Alexey Bataevd01b7492018-08-15 19:45:12 +00008807 } else {
8808 assert(*Res == OMPDeclareTargetDeclAttr::MT_Link &&
8809 "Expected to or link clauses.");
8810 (void)CGM.getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
Alexey Bataevbf8fe712018-08-07 16:14:36 +00008811 }
8812 }
8813}
8814
Alexey Bataev60705422018-10-30 15:50:12 +00008815void CGOpenMPRuntime::adjustTargetSpecificDataForLambdas(
8816 CodeGenFunction &CGF, const OMPExecutableDirective &D) const {
8817 assert(isOpenMPTargetExecutionDirective(D.getDirectiveKind()) &&
8818 " Expected target-based directive.");
8819}
8820
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008821CGOpenMPRuntime::DisableAutoDeclareTargetRAII::DisableAutoDeclareTargetRAII(
8822 CodeGenModule &CGM)
8823 : CGM(CGM) {
8824 if (CGM.getLangOpts().OpenMPIsDevice) {
8825 SavedShouldMarkAsGlobal = CGM.getOpenMPRuntime().ShouldMarkAsGlobal;
8826 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = false;
8827 }
8828}
8829
8830CGOpenMPRuntime::DisableAutoDeclareTargetRAII::~DisableAutoDeclareTargetRAII() {
8831 if (CGM.getLangOpts().OpenMPIsDevice)
8832 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = SavedShouldMarkAsGlobal;
8833}
8834
Alexey Bataev6d944102018-05-02 15:45:28 +00008835bool CGOpenMPRuntime::markAsGlobalTarget(GlobalDecl GD) {
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008836 if (!CGM.getLangOpts().OpenMPIsDevice || !ShouldMarkAsGlobal)
8837 return true;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008838
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008839 StringRef Name = CGM.getMangledName(GD);
Alexey Bataev6d944102018-05-02 15:45:28 +00008840 const auto *D = cast<FunctionDecl>(GD.getDecl());
Alexey Bataev34f8a702018-03-28 14:28:54 +00008841 // Do not to emit function if it is marked as declare target as it was already
8842 // emitted.
Alexey Bataev97b72212018-08-14 18:31:20 +00008843 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(D)) {
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008844 if (D->hasBody() && AlreadyEmittedTargetFunctions.count(Name) == 0) {
8845 if (auto *F = dyn_cast_or_null<llvm::Function>(CGM.GetGlobalValue(Name)))
Alexey Bataev34f8a702018-03-28 14:28:54 +00008846 return !F->isDeclaration();
8847 return false;
8848 }
8849 return true;
8850 }
8851
Alexey Bataev2a6f3f52018-11-07 19:11:14 +00008852 return !AlreadyEmittedTargetFunctions.insert(Name).second;
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00008853}
8854
Samuel Antaoee8fb302016-01-06 13:42:12 +00008855llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
8856 // If we have offloading in the current module, we need to emit the entries
8857 // now and register the offloading descriptor.
8858 createOffloadEntriesAndInfoMetadata();
8859
8860 // Create and register the offloading binary descriptors. This is the main
8861 // entity that captures all the information about offloading in the current
8862 // compilation unit.
8863 return createOffloadingBinaryDescriptorRegistration();
8864}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008865
8866void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
8867 const OMPExecutableDirective &D,
8868 SourceLocation Loc,
8869 llvm::Value *OutlinedFn,
8870 ArrayRef<llvm::Value *> CapturedVars) {
8871 if (!CGF.HaveInsertPoint())
8872 return;
8873
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008874 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008875 CodeGenFunction::RunCleanupsScope Scope(CGF);
8876
8877 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
8878 llvm::Value *Args[] = {
8879 RTLoc,
8880 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
8881 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
8882 llvm::SmallVector<llvm::Value *, 16> RealArgs;
8883 RealArgs.append(std::begin(Args), std::end(Args));
8884 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
8885
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008886 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008887 CGF.EmitRuntimeCall(RTLFn, RealArgs);
8888}
8889
8890void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00008891 const Expr *NumTeams,
8892 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008893 SourceLocation Loc) {
8894 if (!CGF.HaveInsertPoint())
8895 return;
8896
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008897 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008898
Carlo Bertollic6872252016-04-04 15:55:02 +00008899 llvm::Value *NumTeamsVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008900 NumTeams
Carlo Bertollic6872252016-04-04 15:55:02 +00008901 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
8902 CGF.CGM.Int32Ty, /* isSigned = */ true)
8903 : CGF.Builder.getInt32(0);
8904
8905 llvm::Value *ThreadLimitVal =
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008906 ThreadLimit
Carlo Bertollic6872252016-04-04 15:55:02 +00008907 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
8908 CGF.CGM.Int32Ty, /* isSigned = */ true)
8909 : CGF.Builder.getInt32(0);
8910
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008911 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00008912 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
8913 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00008914 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
8915 PushNumTeamsArgs);
8916}
Samuel Antaodf158d52016-04-27 22:58:19 +00008917
Samuel Antaocc10b852016-07-28 14:23:26 +00008918void CGOpenMPRuntime::emitTargetDataCalls(
8919 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
8920 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008921 if (!CGF.HaveInsertPoint())
8922 return;
8923
Samuel Antaocc10b852016-07-28 14:23:26 +00008924 // Action used to replace the default codegen action and turn privatization
8925 // off.
8926 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00008927
8928 // Generate the code for the opening of the data environment. Capture all the
8929 // arguments of the runtime call by reference because they are used in the
8930 // closing of the region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008931 auto &&BeginThenGen = [this, &D, Device, &Info,
8932 &CodeGen](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008933 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00008934 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00008935 MappableExprsHandler::MapValuesArrayTy Pointers;
8936 MappableExprsHandler::MapValuesArrayTy Sizes;
8937 MappableExprsHandler::MapFlagsArrayTy MapTypes;
8938
8939 // Get map clause information.
8940 MappableExprsHandler MCHandler(D, CGF);
8941 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00008942
8943 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00008944 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008945
8946 llvm::Value *BasePointersArrayArg = nullptr;
8947 llvm::Value *PointersArrayArg = nullptr;
8948 llvm::Value *SizesArrayArg = nullptr;
8949 llvm::Value *MapTypesArrayArg = nullptr;
8950 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008951 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008952
8953 // Emit device ID if any.
8954 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008955 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008956 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008957 CGF.Int64Ty, /*isSigned=*/true);
8958 } else {
8959 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8960 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008961
8962 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008963 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00008964
8965 llvm::Value *OffloadingArgs[] = {
8966 DeviceID, PointerNum, BasePointersArrayArg,
8967 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008968 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_begin),
Samuel Antaodf158d52016-04-27 22:58:19 +00008969 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00008970
8971 // If device pointer privatization is required, emit the body of the region
8972 // here. It will have to be duplicated: with and without privatization.
8973 if (!Info.CaptureDeviceAddrMap.empty())
8974 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00008975 };
8976
8977 // Generate code for the closing of the data region.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008978 auto &&EndThenGen = [this, Device, &Info](CodeGenFunction &CGF,
8979 PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00008980 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00008981
8982 llvm::Value *BasePointersArrayArg = nullptr;
8983 llvm::Value *PointersArrayArg = nullptr;
8984 llvm::Value *SizesArrayArg = nullptr;
8985 llvm::Value *MapTypesArrayArg = nullptr;
8986 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00008987 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00008988
8989 // Emit device ID if any.
8990 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00008991 if (Device) {
Samuel Antaodf158d52016-04-27 22:58:19 +00008992 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00008993 CGF.Int64Ty, /*isSigned=*/true);
8994 } else {
8995 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
8996 }
Samuel Antaodf158d52016-04-27 22:58:19 +00008997
8998 // Emit the number of elements in the offloading arrays.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00008999 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00009000
9001 llvm::Value *OffloadingArgs[] = {
9002 DeviceID, PointerNum, BasePointersArrayArg,
9003 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009004 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_end),
Samuel Antaodf158d52016-04-27 22:58:19 +00009005 OffloadingArgs);
9006 };
9007
Samuel Antaocc10b852016-07-28 14:23:26 +00009008 // If we need device pointer privatization, we need to emit the body of the
9009 // region with no privatization in the 'else' branch of the conditional.
9010 // Otherwise, we don't have to do anything.
9011 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
9012 PrePostActionTy &) {
9013 if (!Info.CaptureDeviceAddrMap.empty()) {
9014 CodeGen.setAction(NoPrivAction);
9015 CodeGen(CGF);
9016 }
9017 };
9018
9019 // We don't have to do anything to close the region if the if clause evaluates
9020 // to false.
9021 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00009022
9023 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00009024 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00009025 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00009026 RegionCodeGenTy RCG(BeginThenGen);
9027 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00009028 }
9029
Samuel Antaocc10b852016-07-28 14:23:26 +00009030 // If we don't require privatization of device pointers, we emit the body in
9031 // between the runtime calls. This avoids duplicating the body code.
9032 if (Info.CaptureDeviceAddrMap.empty()) {
9033 CodeGen.setAction(NoPrivAction);
9034 CodeGen(CGF);
9035 }
Samuel Antaodf158d52016-04-27 22:58:19 +00009036
9037 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00009038 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00009039 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00009040 RegionCodeGenTy RCG(EndThenGen);
9041 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00009042 }
9043}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009044
Samuel Antao8d2d7302016-05-26 18:30:22 +00009045void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00009046 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
9047 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009048 if (!CGF.HaveInsertPoint())
9049 return;
9050
Samuel Antao8dd66282016-04-27 23:14:30 +00009051 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00009052 isa<OMPTargetExitDataDirective>(D) ||
9053 isa<OMPTargetUpdateDirective>(D)) &&
9054 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00009055
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009056 CodeGenFunction::OMPTargetDataInfo InputInfo;
9057 llvm::Value *MapTypesArray = nullptr;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009058 // Generate the code for the opening of the data environment.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009059 auto &&ThenGen = [this, &D, Device, &InputInfo,
9060 &MapTypesArray](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009061 // Emit device ID if any.
9062 llvm::Value *DeviceID = nullptr;
George Rokos63bc9d62017-11-21 18:25:12 +00009063 if (Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009064 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
George Rokos63bc9d62017-11-21 18:25:12 +00009065 CGF.Int64Ty, /*isSigned=*/true);
9066 } else {
9067 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
9068 }
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009069
9070 // Emit the number of elements in the offloading arrays.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009071 llvm::Constant *PointerNum =
9072 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009073
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009074 llvm::Value *OffloadingArgs[] = {DeviceID,
9075 PointerNum,
9076 InputInfo.BasePointersArray.getPointer(),
9077 InputInfo.PointersArray.getPointer(),
9078 InputInfo.SizesArray.getPointer(),
9079 MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00009080
Samuel Antao8d2d7302016-05-26 18:30:22 +00009081 // Select the right runtime function call for each expected standalone
9082 // directive.
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00009083 const bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>();
Samuel Antao8d2d7302016-05-26 18:30:22 +00009084 OpenMPRTLFunction RTLFn;
9085 switch (D.getDirectiveKind()) {
Samuel Antao8d2d7302016-05-26 18:30:22 +00009086 case OMPD_target_enter_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00009087 RTLFn = HasNowait ? OMPRTL__tgt_target_data_begin_nowait
9088 : OMPRTL__tgt_target_data_begin;
Samuel Antao8d2d7302016-05-26 18:30:22 +00009089 break;
9090 case OMPD_target_exit_data:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00009091 RTLFn = HasNowait ? OMPRTL__tgt_target_data_end_nowait
9092 : OMPRTL__tgt_target_data_end;
Samuel Antao8d2d7302016-05-26 18:30:22 +00009093 break;
9094 case OMPD_target_update:
Alexey Bataev0cc6b8e2017-12-14 17:00:17 +00009095 RTLFn = HasNowait ? OMPRTL__tgt_target_data_update_nowait
9096 : OMPRTL__tgt_target_data_update;
Samuel Antao8d2d7302016-05-26 18:30:22 +00009097 break;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009098 case OMPD_parallel:
9099 case OMPD_for:
9100 case OMPD_parallel_for:
9101 case OMPD_parallel_sections:
9102 case OMPD_for_simd:
9103 case OMPD_parallel_for_simd:
9104 case OMPD_cancel:
9105 case OMPD_cancellation_point:
9106 case OMPD_ordered:
9107 case OMPD_threadprivate:
9108 case OMPD_task:
9109 case OMPD_simd:
9110 case OMPD_sections:
9111 case OMPD_section:
9112 case OMPD_single:
9113 case OMPD_master:
9114 case OMPD_critical:
9115 case OMPD_taskyield:
9116 case OMPD_barrier:
9117 case OMPD_taskwait:
9118 case OMPD_taskgroup:
9119 case OMPD_atomic:
9120 case OMPD_flush:
9121 case OMPD_teams:
9122 case OMPD_target_data:
9123 case OMPD_distribute:
9124 case OMPD_distribute_simd:
9125 case OMPD_distribute_parallel_for:
9126 case OMPD_distribute_parallel_for_simd:
9127 case OMPD_teams_distribute:
9128 case OMPD_teams_distribute_simd:
9129 case OMPD_teams_distribute_parallel_for:
9130 case OMPD_teams_distribute_parallel_for_simd:
9131 case OMPD_declare_simd:
9132 case OMPD_declare_target:
9133 case OMPD_end_declare_target:
9134 case OMPD_declare_reduction:
9135 case OMPD_taskloop:
9136 case OMPD_taskloop_simd:
9137 case OMPD_target:
9138 case OMPD_target_simd:
9139 case OMPD_target_teams_distribute:
9140 case OMPD_target_teams_distribute_simd:
9141 case OMPD_target_teams_distribute_parallel_for:
9142 case OMPD_target_teams_distribute_parallel_for_simd:
9143 case OMPD_target_teams:
9144 case OMPD_target_parallel:
9145 case OMPD_target_parallel_for:
9146 case OMPD_target_parallel_for_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00009147 case OMPD_requires:
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009148 case OMPD_unknown:
9149 llvm_unreachable("Unexpected standalone target data directive.");
9150 break;
Samuel Antao8d2d7302016-05-26 18:30:22 +00009151 }
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009152 CGF.EmitRuntimeCall(createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009153 };
9154
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009155 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray](
9156 CodeGenFunction &CGF, PrePostActionTy &) {
9157 // Fill up the arrays with all the mapped variables.
9158 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
9159 MappableExprsHandler::MapValuesArrayTy Pointers;
9160 MappableExprsHandler::MapValuesArrayTy Sizes;
9161 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009162
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009163 // Get map clause information.
9164 MappableExprsHandler MEHandler(D, CGF);
9165 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
9166
9167 TargetDataInfo Info;
9168 // Fill up the arrays and create the arguments.
9169 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
9170 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
9171 Info.PointersArray, Info.SizesArray,
9172 Info.MapTypesArray, Info);
9173 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs;
9174 InputInfo.BasePointersArray =
9175 Address(Info.BasePointersArray, CGM.getPointerAlign());
9176 InputInfo.PointersArray =
9177 Address(Info.PointersArray, CGM.getPointerAlign());
9178 InputInfo.SizesArray =
9179 Address(Info.SizesArray, CGM.getPointerAlign());
9180 MapTypesArray = Info.MapTypesArray;
9181 if (D.hasClausesOfKind<OMPDependClause>())
9182 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo);
9183 else
Alexey Bataev768f1f22018-01-09 19:59:25 +00009184 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen);
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009185 };
9186
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009187 if (IfCond) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009188 emitOMPIfClause(CGF, IfCond, TargetThenGen,
9189 [](CodeGenFunction &CGF, PrePostActionTy &) {});
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009190 } else {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009191 RegionCodeGenTy ThenRCG(TargetThenGen);
9192 ThenRCG(CGF);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00009193 }
9194}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009195
9196namespace {
9197 /// Kind of parameter in a function with 'declare simd' directive.
9198 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
9199 /// Attribute set of the parameter.
9200 struct ParamAttrTy {
9201 ParamKindTy Kind = Vector;
9202 llvm::APSInt StrideOrArg;
9203 llvm::APSInt Alignment;
9204 };
9205} // namespace
9206
9207static unsigned evaluateCDTSize(const FunctionDecl *FD,
9208 ArrayRef<ParamAttrTy> ParamAttrs) {
9209 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
9210 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
9211 // of that clause. The VLEN value must be power of 2.
9212 // In other case the notion of the function`s "characteristic data type" (CDT)
9213 // is used to compute the vector length.
9214 // CDT is defined in the following order:
9215 // a) For non-void function, the CDT is the return type.
9216 // b) If the function has any non-uniform, non-linear parameters, then the
9217 // CDT is the type of the first such parameter.
9218 // c) If the CDT determined by a) or b) above is struct, union, or class
9219 // type which is pass-by-value (except for the type that maps to the
9220 // built-in complex data type), the characteristic data type is int.
9221 // d) If none of the above three cases is applicable, the CDT is int.
9222 // The VLEN is then determined based on the CDT and the size of vector
9223 // register of that ISA for which current vector version is generated. The
9224 // VLEN is computed using the formula below:
9225 // VLEN = sizeof(vector_register) / sizeof(CDT),
9226 // where vector register size specified in section 3.2.1 Registers and the
9227 // Stack Frame of original AMD64 ABI document.
9228 QualType RetType = FD->getReturnType();
9229 if (RetType.isNull())
9230 return 0;
9231 ASTContext &C = FD->getASTContext();
9232 QualType CDT;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009233 if (!RetType.isNull() && !RetType->isVoidType()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009234 CDT = RetType;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009235 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009236 unsigned Offset = 0;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009237 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009238 if (ParamAttrs[Offset].Kind == Vector)
9239 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
9240 ++Offset;
9241 }
9242 if (CDT.isNull()) {
9243 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
9244 if (ParamAttrs[I + Offset].Kind == Vector) {
9245 CDT = FD->getParamDecl(I)->getType();
9246 break;
9247 }
9248 }
9249 }
9250 }
9251 if (CDT.isNull())
9252 CDT = C.IntTy;
9253 CDT = CDT->getCanonicalTypeUnqualified();
9254 if (CDT->isRecordType() || CDT->isUnionType())
9255 CDT = C.IntTy;
9256 return C.getTypeSize(CDT);
9257}
9258
9259static void
9260emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00009261 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009262 ArrayRef<ParamAttrTy> ParamAttrs,
9263 OMPDeclareSimdDeclAttr::BranchStateTy State) {
9264 struct ISADataTy {
9265 char ISA;
9266 unsigned VecRegSize;
9267 };
9268 ISADataTy ISAData[] = {
9269 {
9270 'b', 128
9271 }, // SSE
9272 {
9273 'c', 256
9274 }, // AVX
9275 {
9276 'd', 256
9277 }, // AVX2
9278 {
9279 'e', 512
9280 }, // AVX512
9281 };
9282 llvm::SmallVector<char, 2> Masked;
9283 switch (State) {
9284 case OMPDeclareSimdDeclAttr::BS_Undefined:
9285 Masked.push_back('N');
9286 Masked.push_back('M');
9287 break;
9288 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
9289 Masked.push_back('N');
9290 break;
9291 case OMPDeclareSimdDeclAttr::BS_Inbranch:
9292 Masked.push_back('M');
9293 break;
9294 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009295 for (char Mask : Masked) {
9296 for (const ISADataTy &Data : ISAData) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009297 SmallString<256> Buffer;
9298 llvm::raw_svector_ostream Out(Buffer);
9299 Out << "_ZGV" << Data.ISA << Mask;
9300 if (!VLENVal) {
9301 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
9302 evaluateCDTSize(FD, ParamAttrs));
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009303 } else {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009304 Out << VLENVal;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009305 }
9306 for (const ParamAttrTy &ParamAttr : ParamAttrs) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009307 switch (ParamAttr.Kind){
9308 case LinearWithVarStride:
9309 Out << 's' << ParamAttr.StrideOrArg;
9310 break;
9311 case Linear:
9312 Out << 'l';
9313 if (!!ParamAttr.StrideOrArg)
9314 Out << ParamAttr.StrideOrArg;
9315 break;
9316 case Uniform:
9317 Out << 'u';
9318 break;
9319 case Vector:
9320 Out << 'v';
9321 break;
9322 }
9323 if (!!ParamAttr.Alignment)
9324 Out << 'a' << ParamAttr.Alignment;
9325 }
9326 Out << '_' << Fn->getName();
9327 Fn->addFnAttr(Out.str());
9328 }
9329 }
9330}
9331
9332void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
9333 llvm::Function *Fn) {
9334 ASTContext &C = CGM.getContext();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009335 FD = FD->getMostRecentDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009336 // Map params to their positions in function decl.
9337 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
9338 if (isa<CXXMethodDecl>(FD))
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009339 ParamPositions.try_emplace(FD, 0);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009340 unsigned ParamPos = ParamPositions.size();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009341 for (const ParmVarDecl *P : FD->parameters()) {
9342 ParamPositions.try_emplace(P->getCanonicalDecl(), ParamPos);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009343 ++ParamPos;
9344 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009345 while (FD) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009346 for (const auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009347 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
9348 // Mark uniform parameters.
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009349 for (const Expr *E : Attr->uniforms()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009350 E = E->IgnoreParenImpCasts();
9351 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009352 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009353 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009354 } else {
9355 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
9356 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009357 Pos = ParamPositions[PVD];
9358 }
9359 ParamAttrs[Pos].Kind = Uniform;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009360 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009361 // Get alignment info.
9362 auto NI = Attr->alignments_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009363 for (const Expr *E : Attr->aligneds()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009364 E = E->IgnoreParenImpCasts();
9365 unsigned Pos;
9366 QualType ParmTy;
9367 if (isa<CXXThisExpr>(E)) {
9368 Pos = ParamPositions[FD];
9369 ParmTy = E->getType();
9370 } else {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009371 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
9372 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009373 Pos = ParamPositions[PVD];
9374 ParmTy = PVD->getType();
9375 }
9376 ParamAttrs[Pos].Alignment =
9377 (*NI)
9378 ? (*NI)->EvaluateKnownConstInt(C)
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009379 : llvm::APSInt::getUnsigned(
9380 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
9381 .getQuantity());
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009382 ++NI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009383 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009384 // Mark linear parameters.
9385 auto SI = Attr->steps_begin();
9386 auto MI = Attr->modifiers_begin();
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009387 for (const Expr *E : Attr->linears()) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009388 E = E->IgnoreParenImpCasts();
9389 unsigned Pos;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009390 if (isa<CXXThisExpr>(E)) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009391 Pos = ParamPositions[FD];
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009392 } else {
9393 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
9394 ->getCanonicalDecl();
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009395 Pos = ParamPositions[PVD];
9396 }
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009397 ParamAttrTy &ParamAttr = ParamAttrs[Pos];
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009398 ParamAttr.Kind = Linear;
9399 if (*SI) {
Fangrui Song407659a2018-11-30 23:41:18 +00009400 Expr::EvalResult Result;
9401 if (!(*SI)->EvaluateAsInt(Result, C, Expr::SE_AllowSideEffects)) {
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009402 if (const auto *DRE =
9403 cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
9404 if (const auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009405 ParamAttr.Kind = LinearWithVarStride;
9406 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
9407 ParamPositions[StridePVD->getCanonicalDecl()]);
9408 }
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009409 }
Fangrui Song407659a2018-11-30 23:41:18 +00009410 } else {
9411 ParamAttr.StrideOrArg = Result.Val.getInt();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009412 }
9413 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009414 ++SI;
9415 ++MI;
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009416 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009417 llvm::APSInt VLENVal;
9418 if (const Expr *VLEN = Attr->getSimdlen())
9419 VLENVal = VLEN->EvaluateKnownConstInt(C);
9420 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
9421 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
9422 CGM.getTriple().getArch() == llvm::Triple::x86_64)
9423 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009424 }
Alexey Bataev20cf67c2018-03-02 18:07:00 +00009425 FD = FD->getPreviousDecl();
Alexey Bataevc7a82b42016-05-06 09:40:08 +00009426 }
9427}
Alexey Bataev8b427062016-05-25 12:36:08 +00009428
9429namespace {
9430/// Cleanup action for doacross support.
9431class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
9432public:
9433 static const int DoacrossFinArgs = 2;
9434
9435private:
9436 llvm::Value *RTLFn;
9437 llvm::Value *Args[DoacrossFinArgs];
9438
9439public:
9440 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
9441 : RTLFn(RTLFn) {
9442 assert(CallArgs.size() == DoacrossFinArgs);
9443 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
9444 }
9445 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
9446 if (!CGF.HaveInsertPoint())
9447 return;
9448 CGF.EmitRuntimeCall(RTLFn, Args);
9449 }
9450};
9451} // namespace
9452
9453void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
Alexey Bataevf138fda2018-08-13 19:04:24 +00009454 const OMPLoopDirective &D,
9455 ArrayRef<Expr *> NumIterations) {
Alexey Bataev8b427062016-05-25 12:36:08 +00009456 if (!CGF.HaveInsertPoint())
9457 return;
9458
9459 ASTContext &C = CGM.getContext();
9460 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
9461 RecordDecl *RD;
9462 if (KmpDimTy.isNull()) {
9463 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
9464 // kmp_int64 lo; // lower
9465 // kmp_int64 up; // upper
9466 // kmp_int64 st; // stride
9467 // };
9468 RD = C.buildImplicitRecord("kmp_dim");
9469 RD->startDefinition();
9470 addFieldToRecordDecl(C, RD, Int64Ty);
9471 addFieldToRecordDecl(C, RD, Int64Ty);
9472 addFieldToRecordDecl(C, RD, Int64Ty);
9473 RD->completeDefinition();
9474 KmpDimTy = C.getRecordType(RD);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009475 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00009476 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009477 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00009478 llvm::APInt Size(/*numBits=*/32, NumIterations.size());
9479 QualType ArrayTy =
9480 C.getConstantArrayType(KmpDimTy, Size, ArrayType::Normal, 0);
Alexey Bataev8b427062016-05-25 12:36:08 +00009481
Alexey Bataevf138fda2018-08-13 19:04:24 +00009482 Address DimsAddr = CGF.CreateMemTemp(ArrayTy, "dims");
9483 CGF.EmitNullInitialization(DimsAddr, ArrayTy);
Alexey Bataev8b427062016-05-25 12:36:08 +00009484 enum { LowerFD = 0, UpperFD, StrideFD };
9485 // Fill dims with data.
Alexey Bataevf138fda2018-08-13 19:04:24 +00009486 for (unsigned I = 0, E = NumIterations.size(); I < E; ++I) {
9487 LValue DimsLVal =
9488 CGF.MakeAddrLValue(CGF.Builder.CreateConstArrayGEP(
9489 DimsAddr, I, C.getTypeSizeInChars(KmpDimTy)),
9490 KmpDimTy);
9491 // dims.upper = num_iterations;
9492 LValue UpperLVal = CGF.EmitLValueForField(
9493 DimsLVal, *std::next(RD->field_begin(), UpperFD));
9494 llvm::Value *NumIterVal =
9495 CGF.EmitScalarConversion(CGF.EmitScalarExpr(NumIterations[I]),
9496 D.getNumIterations()->getType(), Int64Ty,
9497 D.getNumIterations()->getExprLoc());
9498 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
9499 // dims.stride = 1;
9500 LValue StrideLVal = CGF.EmitLValueForField(
9501 DimsLVal, *std::next(RD->field_begin(), StrideFD));
9502 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
9503 StrideLVal);
9504 }
Alexey Bataev8b427062016-05-25 12:36:08 +00009505
9506 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
9507 // kmp_int32 num_dims, struct kmp_dim * dims);
Alexey Bataevf138fda2018-08-13 19:04:24 +00009508 llvm::Value *Args[] = {
9509 emitUpdateLocation(CGF, D.getBeginLoc()),
9510 getThreadID(CGF, D.getBeginLoc()),
9511 llvm::ConstantInt::getSigned(CGM.Int32Ty, NumIterations.size()),
9512 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
9513 CGF.Builder
9514 .CreateConstArrayGEP(DimsAddr, 0, C.getTypeSizeInChars(KmpDimTy))
9515 .getPointer(),
9516 CGM.VoidPtrTy)};
Alexey Bataev8b427062016-05-25 12:36:08 +00009517
9518 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
9519 CGF.EmitRuntimeCall(RTLFn, Args);
9520 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009521 emitUpdateLocation(CGF, D.getEndLoc()), getThreadID(CGF, D.getEndLoc())};
Alexey Bataev8b427062016-05-25 12:36:08 +00009522 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
9523 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
9524 llvm::makeArrayRef(FiniArgs));
9525}
9526
9527void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
9528 const OMPDependClause *C) {
9529 QualType Int64Ty =
9530 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
Alexey Bataevf138fda2018-08-13 19:04:24 +00009531 llvm::APInt Size(/*numBits=*/32, C->getNumLoops());
9532 QualType ArrayTy = CGM.getContext().getConstantArrayType(
9533 Int64Ty, Size, ArrayType::Normal, 0);
9534 Address CntAddr = CGF.CreateMemTemp(ArrayTy, ".cnt.addr");
9535 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I) {
9536 const Expr *CounterVal = C->getLoopData(I);
9537 assert(CounterVal);
9538 llvm::Value *CntVal = CGF.EmitScalarConversion(
9539 CGF.EmitScalarExpr(CounterVal), CounterVal->getType(), Int64Ty,
9540 CounterVal->getExprLoc());
9541 CGF.EmitStoreOfScalar(
9542 CntVal,
9543 CGF.Builder.CreateConstArrayGEP(
9544 CntAddr, I, CGM.getContext().getTypeSizeInChars(Int64Ty)),
9545 /*Volatile=*/false, Int64Ty);
9546 }
9547 llvm::Value *Args[] = {
9548 emitUpdateLocation(CGF, C->getBeginLoc()),
9549 getThreadID(CGF, C->getBeginLoc()),
9550 CGF.Builder
9551 .CreateConstArrayGEP(CntAddr, 0,
9552 CGM.getContext().getTypeSizeInChars(Int64Ty))
9553 .getPointer()};
Alexey Bataev8b427062016-05-25 12:36:08 +00009554 llvm::Value *RTLFn;
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009555 if (C->getDependencyKind() == OMPC_DEPEND_source) {
Alexey Bataev8b427062016-05-25 12:36:08 +00009556 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
Alexey Bataeva4fa0b82018-04-16 17:59:34 +00009557 } else {
Alexey Bataev8b427062016-05-25 12:36:08 +00009558 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
9559 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
9560 }
9561 CGF.EmitRuntimeCall(RTLFn, Args);
9562}
9563
Alexey Bataev7ef47a62018-02-22 18:33:31 +00009564void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, SourceLocation Loc,
9565 llvm::Value *Callee,
9566 ArrayRef<llvm::Value *> Args) const {
9567 assert(Loc.isValid() && "Outlined function call location must be valid.");
Alexey Bataev3c595a62017-08-14 15:01:03 +00009568 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
9569
9570 if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00009571 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00009572 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00009573 return;
9574 }
9575 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00009576 CGF.EmitRuntimeCall(Callee, Args);
9577}
9578
9579void CGOpenMPRuntime::emitOutlinedFunctionCall(
9580 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
9581 ArrayRef<llvm::Value *> Args) const {
Alexey Bataev7ef47a62018-02-22 18:33:31 +00009582 emitCall(CGF, Loc, OutlinedFn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00009583}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00009584
9585Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
9586 const VarDecl *NativeParam,
9587 const VarDecl *TargetParam) const {
9588 return CGF.GetAddrOfLocalVar(NativeParam);
9589}
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009590
Gheorghe-Teodor Bercead3dcf2f2018-03-14 14:17:45 +00009591Address CGOpenMPRuntime::getAddressOfLocalVariable(CodeGenFunction &CGF,
9592 const VarDecl *VD) {
9593 return Address::invalid();
9594}
9595
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009596llvm::Value *CGOpenMPSIMDRuntime::emitParallelOutlinedFunction(
9597 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
9598 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
9599 llvm_unreachable("Not supported in SIMD-only mode");
9600}
9601
9602llvm::Value *CGOpenMPSIMDRuntime::emitTeamsOutlinedFunction(
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::emitTaskOutlinedFunction(
9609 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
9610 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
9611 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
9612 bool Tied, unsigned &NumberOfParts) {
9613 llvm_unreachable("Not supported in SIMD-only mode");
9614}
9615
9616void CGOpenMPSIMDRuntime::emitParallelCall(CodeGenFunction &CGF,
9617 SourceLocation Loc,
9618 llvm::Value *OutlinedFn,
9619 ArrayRef<llvm::Value *> CapturedVars,
9620 const Expr *IfCond) {
9621 llvm_unreachable("Not supported in SIMD-only mode");
9622}
9623
9624void CGOpenMPSIMDRuntime::emitCriticalRegion(
9625 CodeGenFunction &CGF, StringRef CriticalName,
9626 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc,
9627 const Expr *Hint) {
9628 llvm_unreachable("Not supported in SIMD-only mode");
9629}
9630
9631void CGOpenMPSIMDRuntime::emitMasterRegion(CodeGenFunction &CGF,
9632 const RegionCodeGenTy &MasterOpGen,
9633 SourceLocation Loc) {
9634 llvm_unreachable("Not supported in SIMD-only mode");
9635}
9636
9637void CGOpenMPSIMDRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
9638 SourceLocation Loc) {
9639 llvm_unreachable("Not supported in SIMD-only mode");
9640}
9641
9642void CGOpenMPSIMDRuntime::emitTaskgroupRegion(
9643 CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen,
9644 SourceLocation Loc) {
9645 llvm_unreachable("Not supported in SIMD-only mode");
9646}
9647
9648void CGOpenMPSIMDRuntime::emitSingleRegion(
9649 CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen,
9650 SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars,
9651 ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs,
9652 ArrayRef<const Expr *> AssignmentOps) {
9653 llvm_unreachable("Not supported in SIMD-only mode");
9654}
9655
9656void CGOpenMPSIMDRuntime::emitOrderedRegion(CodeGenFunction &CGF,
9657 const RegionCodeGenTy &OrderedOpGen,
9658 SourceLocation Loc,
9659 bool IsThreads) {
9660 llvm_unreachable("Not supported in SIMD-only mode");
9661}
9662
9663void CGOpenMPSIMDRuntime::emitBarrierCall(CodeGenFunction &CGF,
9664 SourceLocation Loc,
9665 OpenMPDirectiveKind Kind,
9666 bool EmitChecks,
9667 bool ForceSimpleCall) {
9668 llvm_unreachable("Not supported in SIMD-only mode");
9669}
9670
9671void CGOpenMPSIMDRuntime::emitForDispatchInit(
9672 CodeGenFunction &CGF, SourceLocation Loc,
9673 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
9674 bool Ordered, const DispatchRTInput &DispatchValues) {
9675 llvm_unreachable("Not supported in SIMD-only mode");
9676}
9677
9678void CGOpenMPSIMDRuntime::emitForStaticInit(
9679 CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind,
9680 const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values) {
9681 llvm_unreachable("Not supported in SIMD-only mode");
9682}
9683
9684void CGOpenMPSIMDRuntime::emitDistributeStaticInit(
9685 CodeGenFunction &CGF, SourceLocation Loc,
9686 OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values) {
9687 llvm_unreachable("Not supported in SIMD-only mode");
9688}
9689
9690void CGOpenMPSIMDRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
9691 SourceLocation Loc,
9692 unsigned IVSize,
9693 bool IVSigned) {
9694 llvm_unreachable("Not supported in SIMD-only mode");
9695}
9696
9697void CGOpenMPSIMDRuntime::emitForStaticFinish(CodeGenFunction &CGF,
9698 SourceLocation Loc,
9699 OpenMPDirectiveKind DKind) {
9700 llvm_unreachable("Not supported in SIMD-only mode");
9701}
9702
9703llvm::Value *CGOpenMPSIMDRuntime::emitForNext(CodeGenFunction &CGF,
9704 SourceLocation Loc,
9705 unsigned IVSize, bool IVSigned,
9706 Address IL, Address LB,
9707 Address UB, Address ST) {
9708 llvm_unreachable("Not supported in SIMD-only mode");
9709}
9710
9711void CGOpenMPSIMDRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
9712 llvm::Value *NumThreads,
9713 SourceLocation Loc) {
9714 llvm_unreachable("Not supported in SIMD-only mode");
9715}
9716
9717void CGOpenMPSIMDRuntime::emitProcBindClause(CodeGenFunction &CGF,
9718 OpenMPProcBindClauseKind ProcBind,
9719 SourceLocation Loc) {
9720 llvm_unreachable("Not supported in SIMD-only mode");
9721}
9722
9723Address CGOpenMPSIMDRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
9724 const VarDecl *VD,
9725 Address VDAddr,
9726 SourceLocation Loc) {
9727 llvm_unreachable("Not supported in SIMD-only mode");
9728}
9729
9730llvm::Function *CGOpenMPSIMDRuntime::emitThreadPrivateVarDefinition(
9731 const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit,
9732 CodeGenFunction *CGF) {
9733 llvm_unreachable("Not supported in SIMD-only mode");
9734}
9735
9736Address CGOpenMPSIMDRuntime::getAddrOfArtificialThreadPrivate(
9737 CodeGenFunction &CGF, QualType VarType, StringRef Name) {
9738 llvm_unreachable("Not supported in SIMD-only mode");
9739}
9740
9741void CGOpenMPSIMDRuntime::emitFlush(CodeGenFunction &CGF,
9742 ArrayRef<const Expr *> Vars,
9743 SourceLocation Loc) {
9744 llvm_unreachable("Not supported in SIMD-only mode");
9745}
9746
9747void CGOpenMPSIMDRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
9748 const OMPExecutableDirective &D,
9749 llvm::Value *TaskFunction,
9750 QualType SharedsTy, Address Shareds,
9751 const Expr *IfCond,
9752 const OMPTaskDataTy &Data) {
9753 llvm_unreachable("Not supported in SIMD-only mode");
9754}
9755
9756void CGOpenMPSIMDRuntime::emitTaskLoopCall(
9757 CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D,
9758 llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds,
9759 const Expr *IfCond, const OMPTaskDataTy &Data) {
9760 llvm_unreachable("Not supported in SIMD-only mode");
9761}
9762
9763void CGOpenMPSIMDRuntime::emitReduction(
9764 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates,
9765 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
9766 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) {
9767 assert(Options.SimpleReduction && "Only simple reduction is expected.");
9768 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs,
9769 ReductionOps, Options);
9770}
9771
9772llvm::Value *CGOpenMPSIMDRuntime::emitTaskReductionInit(
9773 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
9774 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
9775 llvm_unreachable("Not supported in SIMD-only mode");
9776}
9777
9778void CGOpenMPSIMDRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
9779 SourceLocation Loc,
9780 ReductionCodeGen &RCG,
9781 unsigned N) {
9782 llvm_unreachable("Not supported in SIMD-only mode");
9783}
9784
9785Address CGOpenMPSIMDRuntime::getTaskReductionItem(CodeGenFunction &CGF,
9786 SourceLocation Loc,
9787 llvm::Value *ReductionsPtr,
9788 LValue SharedLVal) {
9789 llvm_unreachable("Not supported in SIMD-only mode");
9790}
9791
9792void CGOpenMPSIMDRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
9793 SourceLocation Loc) {
9794 llvm_unreachable("Not supported in SIMD-only mode");
9795}
9796
9797void CGOpenMPSIMDRuntime::emitCancellationPointCall(
9798 CodeGenFunction &CGF, SourceLocation Loc,
9799 OpenMPDirectiveKind CancelRegion) {
9800 llvm_unreachable("Not supported in SIMD-only mode");
9801}
9802
9803void CGOpenMPSIMDRuntime::emitCancelCall(CodeGenFunction &CGF,
9804 SourceLocation Loc, const Expr *IfCond,
9805 OpenMPDirectiveKind CancelRegion) {
9806 llvm_unreachable("Not supported in SIMD-only mode");
9807}
9808
9809void CGOpenMPSIMDRuntime::emitTargetOutlinedFunction(
9810 const OMPExecutableDirective &D, StringRef ParentName,
9811 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
9812 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
9813 llvm_unreachable("Not supported in SIMD-only mode");
9814}
9815
9816void CGOpenMPSIMDRuntime::emitTargetCall(CodeGenFunction &CGF,
9817 const OMPExecutableDirective &D,
9818 llvm::Value *OutlinedFn,
9819 llvm::Value *OutlinedFnID,
Alexey Bataev8451efa2018-01-15 19:06:12 +00009820 const Expr *IfCond, const Expr *Device) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009821 llvm_unreachable("Not supported in SIMD-only mode");
9822}
9823
9824bool CGOpenMPSIMDRuntime::emitTargetFunctions(GlobalDecl GD) {
9825 llvm_unreachable("Not supported in SIMD-only mode");
9826}
9827
9828bool CGOpenMPSIMDRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
9829 llvm_unreachable("Not supported in SIMD-only mode");
9830}
9831
9832bool CGOpenMPSIMDRuntime::emitTargetGlobal(GlobalDecl GD) {
9833 return false;
9834}
9835
9836llvm::Function *CGOpenMPSIMDRuntime::emitRegistrationFunction() {
9837 return nullptr;
9838}
9839
9840void CGOpenMPSIMDRuntime::emitTeamsCall(CodeGenFunction &CGF,
9841 const OMPExecutableDirective &D,
9842 SourceLocation Loc,
9843 llvm::Value *OutlinedFn,
9844 ArrayRef<llvm::Value *> CapturedVars) {
9845 llvm_unreachable("Not supported in SIMD-only mode");
9846}
9847
9848void CGOpenMPSIMDRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
9849 const Expr *NumTeams,
9850 const Expr *ThreadLimit,
9851 SourceLocation Loc) {
9852 llvm_unreachable("Not supported in SIMD-only mode");
9853}
9854
9855void CGOpenMPSIMDRuntime::emitTargetDataCalls(
9856 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
9857 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
9858 llvm_unreachable("Not supported in SIMD-only mode");
9859}
9860
9861void CGOpenMPSIMDRuntime::emitTargetDataStandAloneCall(
9862 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
9863 const Expr *Device) {
9864 llvm_unreachable("Not supported in SIMD-only mode");
9865}
9866
9867void CGOpenMPSIMDRuntime::emitDoacrossInit(CodeGenFunction &CGF,
Alexey Bataevf138fda2018-08-13 19:04:24 +00009868 const OMPLoopDirective &D,
9869 ArrayRef<Expr *> NumIterations) {
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00009870 llvm_unreachable("Not supported in SIMD-only mode");
9871}
9872
9873void CGOpenMPSIMDRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
9874 const OMPDependClause *C) {
9875 llvm_unreachable("Not supported in SIMD-only mode");
9876}
9877
9878const VarDecl *
9879CGOpenMPSIMDRuntime::translateParameter(const FieldDecl *FD,
9880 const VarDecl *NativeParam) const {
9881 llvm_unreachable("Not supported in SIMD-only mode");
9882}
9883
9884Address
9885CGOpenMPSIMDRuntime::getParameterAddress(CodeGenFunction &CGF,
9886 const VarDecl *NativeParam,
9887 const VarDecl *TargetParam) const {
9888 llvm_unreachable("Not supported in SIMD-only mode");
9889}