blob: 7ca76f8cb7a1f3bacc49a6f26600e25d81c907b1 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===----- CGOpenMPRuntime.cpp - Interface to OpenMP Runtimes -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides a class for OpenMP runtime code generation.
11//
12//===----------------------------------------------------------------------===//
13
Samuel Antaoee8fb302016-01-06 13:42:12 +000014#include "CGCXXABI.h"
15#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000016#include "CGOpenMPRuntime.h"
17#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"
Alexey Bataev9959db52014-05-06 10:08:46 +000021#include "llvm/ADT/ArrayRef.h"
Alexey Bataev0f87dbe2017-08-14 17:56:13 +000022#include "llvm/ADT/BitmaskEnum.h"
Teresa Johnsonffc4e242016-11-11 05:35:12 +000023#include "llvm/Bitcode/BitcodeReader.h"
Alexey Bataevd74d0602014-10-13 06:02:40 +000024#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000025#include "llvm/IR/DerivedTypes.h"
26#include "llvm/IR/GlobalValue.h"
27#include "llvm/IR/Value.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000028#include "llvm/Support/Format.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000029#include "llvm/Support/raw_ostream.h"
Alexey Bataev23b69422014-06-18 07:08:49 +000030#include <cassert>
Alexey Bataev9959db52014-05-06 10:08:46 +000031
32using namespace clang;
33using namespace CodeGen;
34
Benjamin Kramerc52193f2014-10-10 13:57:57 +000035namespace {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000036/// \brief Base class for handling code generation inside OpenMP regions.
Alexey Bataev18095712014-10-10 12:19:54 +000037class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
38public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000039 /// \brief Kinds of OpenMP regions used in codegen.
40 enum CGOpenMPRegionKind {
41 /// \brief Region with outlined function for standalone 'parallel'
42 /// directive.
43 ParallelOutlinedRegion,
44 /// \brief Region with outlined function for standalone 'task' directive.
45 TaskOutlinedRegion,
46 /// \brief Region for constructs that do not require function outlining,
47 /// like 'for', 'sections', 'atomic' etc. directives.
48 InlinedRegion,
Samuel Antaobed3c462015-10-02 16:14:20 +000049 /// \brief Region with outlined function for standalone 'target' directive.
50 TargetRegion,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000051 };
Alexey Bataev18095712014-10-10 12:19:54 +000052
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000053 CGOpenMPRegionInfo(const CapturedStmt &CS,
54 const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000055 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
56 bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000057 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
Alexey Bataev25e5b442015-09-15 12:52:43 +000058 CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000059
60 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000061 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
62 bool HasCancel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +000063 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
Alexey Bataev25e5b442015-09-15 12:52:43 +000064 Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000065
66 /// \brief Get a variable or parameter for storing global thread id
Alexey Bataev18095712014-10-10 12:19:54 +000067 /// inside OpenMP construct.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000068 virtual const VarDecl *getThreadIDVariable() const = 0;
Alexey Bataev18095712014-10-10 12:19:54 +000069
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000070 /// \brief Emit the captured statement body.
Hans Wennborg7eb54642015-09-10 17:07:54 +000071 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000072
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000073 /// \brief Get an LValue for the current ThreadID variable.
Alexey Bataev62b63b12015-03-10 07:28:44 +000074 /// \return LValue for thread id variable. This LValue always has type int32*.
75 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
Alexey Bataev18095712014-10-10 12:19:54 +000076
Alexey Bataev48591dd2016-04-20 04:01:36 +000077 virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {}
78
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000079 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000080
Alexey Bataev81c7ea02015-07-03 09:56:58 +000081 OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
82
Alexey Bataev25e5b442015-09-15 12:52:43 +000083 bool hasCancel() const { return HasCancel; }
84
Alexey Bataev18095712014-10-10 12:19:54 +000085 static bool classof(const CGCapturedStmtInfo *Info) {
86 return Info->getKind() == CR_OpenMP;
87 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000088
Alexey Bataev48591dd2016-04-20 04:01:36 +000089 ~CGOpenMPRegionInfo() override = default;
90
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000091protected:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000092 CGOpenMPRegionKind RegionKind;
Hans Wennborg45c74392016-01-12 20:54:36 +000093 RegionCodeGenTy CodeGen;
Alexey Bataev81c7ea02015-07-03 09:56:58 +000094 OpenMPDirectiveKind Kind;
Alexey Bataev25e5b442015-09-15 12:52:43 +000095 bool HasCancel;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000096};
Alexey Bataev18095712014-10-10 12:19:54 +000097
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000098/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +000099class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000100public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000101 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000102 const RegionCodeGenTy &CodeGen,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000103 OpenMPDirectiveKind Kind, bool HasCancel,
104 StringRef HelperName)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000105 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
106 HasCancel),
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000107 ThreadIDVar(ThreadIDVar), HelperName(HelperName) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000108 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
109 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000110
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000111 /// \brief Get a variable or parameter for storing global thread id
112 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000113 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000114
Alexey Bataev18095712014-10-10 12:19:54 +0000115 /// \brief Get the name of the capture helper.
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000116 StringRef getHelperName() const override { return HelperName; }
Alexey Bataev18095712014-10-10 12:19:54 +0000117
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000118 static bool classof(const CGCapturedStmtInfo *Info) {
119 return CGOpenMPRegionInfo::classof(Info) &&
120 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
121 ParallelOutlinedRegion;
122 }
123
Alexey Bataev18095712014-10-10 12:19:54 +0000124private:
125 /// \brief A variable or parameter storing global thread id for OpenMP
126 /// constructs.
127 const VarDecl *ThreadIDVar;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000128 StringRef HelperName;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000129};
130
Alexey Bataev62b63b12015-03-10 07:28:44 +0000131/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000132class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000133public:
Alexey Bataev48591dd2016-04-20 04:01:36 +0000134 class UntiedTaskActionTy final : public PrePostActionTy {
135 bool Untied;
136 const VarDecl *PartIDVar;
137 const RegionCodeGenTy UntiedCodeGen;
138 llvm::SwitchInst *UntiedSwitch = nullptr;
139
140 public:
141 UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
142 const RegionCodeGenTy &UntiedCodeGen)
143 : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
144 void Enter(CodeGenFunction &CGF) override {
145 if (Untied) {
146 // Emit task switching point.
147 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
148 CGF.GetAddrOfLocalVar(PartIDVar),
149 PartIDVar->getType()->castAs<PointerType>());
150 auto *Res = CGF.EmitLoadOfScalar(PartIdLVal, SourceLocation());
151 auto *DoneBB = CGF.createBasicBlock(".untied.done.");
152 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) {
163 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
164 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
Alexey Bataev62b63b12015-03-10 07:28:44 +0000191 /// \brief Get a variable or parameter for storing global thread id
192 /// 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
195 /// \brief 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
Alexey Bataev62b63b12015-03-10 07:28:44 +0000198 /// \brief Get the name of the capture helper.
199 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:
212 /// \brief A variable or parameter storing global thread id for OpenMP
213 /// 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
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000219/// \brief API for inlined captured statement code generation in OpenMP
220/// 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
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000230 // \brief 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
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000245 /// \brief 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
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000260 /// \brief Get a variable or parameter for storing global thread id
261 /// 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
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000268 /// \brief Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000269 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000270 if (auto *OuterRegionInfo = getOldCSI())
271 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000272 llvm_unreachable("No helper name for inlined OpenMP construct");
273 }
274
Alexey Bataev48591dd2016-04-20 04:01:36 +0000275 void emitUntiedSwitch(CodeGenFunction &CGF) override {
276 if (OuterRegionInfo)
277 OuterRegionInfo->emitUntiedSwitch(CGF);
278 }
279
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000280 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
281
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000282 static bool classof(const CGCapturedStmtInfo *Info) {
283 return CGOpenMPRegionInfo::classof(Info) &&
284 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
285 }
286
Alexey Bataev48591dd2016-04-20 04:01:36 +0000287 ~CGOpenMPInlinedRegionInfo() override = default;
288
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000289private:
290 /// \brief CodeGen info about outer OpenMP region.
291 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
292 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000293};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000294
Samuel Antaobed3c462015-10-02 16:14:20 +0000295/// \brief API for captured statement code generation in OpenMP target
296/// constructs. For this captures, implicit parameters are used instead of the
Samuel Antaoee8fb302016-01-06 13:42:12 +0000297/// captured fields. The name of the target region has to be unique in a given
298/// application so it is provided by the client, because only the client has
299/// the information to generate that.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000300class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
Samuel Antaobed3c462015-10-02 16:14:20 +0000301public:
302 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000303 const RegionCodeGenTy &CodeGen, StringRef HelperName)
Samuel Antaobed3c462015-10-02 16:14:20 +0000304 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000305 /*HasCancel=*/false),
306 HelperName(HelperName) {}
Samuel Antaobed3c462015-10-02 16:14:20 +0000307
308 /// \brief This is unused for target regions because each starts executing
309 /// with a single thread.
310 const VarDecl *getThreadIDVariable() const override { return nullptr; }
311
312 /// \brief Get the name of the capture helper.
Samuel Antaoee8fb302016-01-06 13:42:12 +0000313 StringRef getHelperName() const override { return HelperName; }
Samuel Antaobed3c462015-10-02 16:14:20 +0000314
315 static bool classof(const CGCapturedStmtInfo *Info) {
316 return CGOpenMPRegionInfo::classof(Info) &&
317 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
318 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000319
320private:
321 StringRef HelperName;
Samuel Antaobed3c462015-10-02 16:14:20 +0000322};
323
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000324static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000325 llvm_unreachable("No codegen for expressions");
326}
327/// \brief API for generation of expressions captured in a innermost OpenMP
328/// region.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000329class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000330public:
331 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
332 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
333 OMPD_unknown,
334 /*HasCancel=*/false),
335 PrivScope(CGF) {
336 // Make sure the globals captured in the provided statement are local by
337 // using the privatization logic. We assume the same variable is not
338 // captured more than once.
339 for (auto &C : CS.captures()) {
340 if (!C.capturesVariable() && !C.capturesVariableByCopy())
341 continue;
342
343 const VarDecl *VD = C.getCapturedVar();
344 if (VD->isLocalVarDeclOrParm())
345 continue;
346
347 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
348 /*RefersToEnclosingVariableOrCapture=*/false,
349 VD->getType().getNonReferenceType(), VK_LValue,
350 SourceLocation());
351 PrivScope.addPrivate(VD, [&CGF, &DRE]() -> Address {
352 return CGF.EmitLValue(&DRE).getAddress();
353 });
354 }
355 (void)PrivScope.Privatize();
356 }
357
358 /// \brief Lookup the captured field decl for a variable.
359 const FieldDecl *lookup(const VarDecl *VD) const override {
360 if (auto *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
361 return FD;
362 return nullptr;
363 }
364
365 /// \brief Emit the captured statement body.
366 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
367 llvm_unreachable("No body for expressions");
368 }
369
370 /// \brief Get a variable or parameter for storing global thread id
371 /// inside OpenMP construct.
372 const VarDecl *getThreadIDVariable() const override {
373 llvm_unreachable("No thread id for expressions");
374 }
375
376 /// \brief Get the name of the capture helper.
377 StringRef getHelperName() const override {
378 llvm_unreachable("No helper name for expressions");
379 }
380
381 static bool classof(const CGCapturedStmtInfo *Info) { return false; }
382
383private:
384 /// Private scope to capture global variables.
385 CodeGenFunction::OMPPrivateScope PrivScope;
386};
387
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000388/// \brief RAII for emitting code of OpenMP constructs.
389class InlinedOpenMPRegionRAII {
390 CodeGenFunction &CGF;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000391 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
392 FieldDecl *LambdaThisCaptureField = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000393
394public:
395 /// \brief Constructs region for combined constructs.
396 /// \param CodeGen Code generation sequence for combined directives. Includes
397 /// a list of functions used for code generation of implicitly inlined
398 /// regions.
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000399 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000400 OpenMPDirectiveKind Kind, bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000401 : CGF(CGF) {
402 // Start emission for the construct.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000403 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
404 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000405 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
406 LambdaThisCaptureField = CGF.LambdaThisCaptureField;
407 CGF.LambdaThisCaptureField = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000408 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000409
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000410 ~InlinedOpenMPRegionRAII() {
411 // Restore original CapturedStmtInfo only if we're done with code emission.
412 auto *OldCSI =
413 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
414 delete CGF.CapturedStmtInfo;
415 CGF.CapturedStmtInfo = OldCSI;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000416 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
417 CGF.LambdaThisCaptureField = LambdaThisCaptureField;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000418 }
419};
420
Alexey Bataev50b3c952016-02-19 10:38:26 +0000421/// \brief Values for bit flags used in the ident_t to describe the fields.
422/// All enumeric elements are named and described in accordance with the code
423/// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000424enum OpenMPLocationFlags : unsigned {
Alexey Bataev50b3c952016-02-19 10:38:26 +0000425 /// \brief Use trampoline for internal microtask.
426 OMP_IDENT_IMD = 0x01,
427 /// \brief Use c-style ident structure.
428 OMP_IDENT_KMPC = 0x02,
429 /// \brief Atomic reduction option for kmpc_reduce.
430 OMP_ATOMIC_REDUCE = 0x10,
431 /// \brief Explicit 'barrier' directive.
432 OMP_IDENT_BARRIER_EXPL = 0x20,
433 /// \brief Implicit barrier in code.
434 OMP_IDENT_BARRIER_IMPL = 0x40,
435 /// \brief Implicit barrier in 'for' directive.
436 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
437 /// \brief Implicit barrier in 'sections' directive.
438 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
439 /// \brief Implicit barrier in 'single' directive.
Alexey Bataev0f87dbe2017-08-14 17:56:13 +0000440 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140,
441 /// Call of __kmp_for_static_init for static loop.
442 OMP_IDENT_WORK_LOOP = 0x200,
443 /// Call of __kmp_for_static_init for sections.
444 OMP_IDENT_WORK_SECTIONS = 0x400,
445 /// Call of __kmp_for_static_init for distribute.
446 OMP_IDENT_WORK_DISTRIBUTE = 0x800,
447 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_IDENT_WORK_DISTRIBUTE)
Alexey Bataev50b3c952016-02-19 10:38:26 +0000448};
449
450/// \brief Describes ident structure that describes a source location.
451/// All descriptions are taken from
452/// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
453/// Original structure:
454/// typedef struct ident {
455/// kmp_int32 reserved_1; /**< might be used in Fortran;
456/// see above */
457/// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
458/// KMP_IDENT_KMPC identifies this union
459/// member */
460/// kmp_int32 reserved_2; /**< not really used in Fortran any more;
461/// see above */
462///#if USE_ITT_BUILD
463/// /* but currently used for storing
464/// region-specific ITT */
465/// /* contextual information. */
466///#endif /* USE_ITT_BUILD */
467/// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
468/// C++ */
469/// char const *psource; /**< String describing the source location.
470/// The string is composed of semi-colon separated
471// fields which describe the source file,
472/// the function and a pair of line numbers that
473/// delimit the construct.
474/// */
475/// } ident_t;
476enum IdentFieldIndex {
477 /// \brief might be used in Fortran
478 IdentField_Reserved_1,
479 /// \brief OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
480 IdentField_Flags,
481 /// \brief Not really used in Fortran any more
482 IdentField_Reserved_2,
483 /// \brief Source[4] in Fortran, do not use for C++
484 IdentField_Reserved_3,
485 /// \brief String describing the source location. The string is composed of
486 /// semi-colon separated fields which describe the source file, the function
487 /// and a pair of line numbers that delimit the construct.
488 IdentField_PSource
489};
490
491/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
492/// the enum sched_type in kmp.h).
493enum OpenMPSchedType {
494 /// \brief Lower bound for default (unordered) versions.
495 OMP_sch_lower = 32,
496 OMP_sch_static_chunked = 33,
497 OMP_sch_static = 34,
498 OMP_sch_dynamic_chunked = 35,
499 OMP_sch_guided_chunked = 36,
500 OMP_sch_runtime = 37,
501 OMP_sch_auto = 38,
Alexey Bataev6cff6242016-05-30 13:05:14 +0000502 /// static with chunk adjustment (e.g., simd)
Samuel Antao4c8035b2016-12-12 18:00:20 +0000503 OMP_sch_static_balanced_chunked = 45,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000504 /// \brief Lower bound for 'ordered' versions.
505 OMP_ord_lower = 64,
506 OMP_ord_static_chunked = 65,
507 OMP_ord_static = 66,
508 OMP_ord_dynamic_chunked = 67,
509 OMP_ord_guided_chunked = 68,
510 OMP_ord_runtime = 69,
511 OMP_ord_auto = 70,
512 OMP_sch_default = OMP_sch_static,
Carlo Bertollifc35ad22016-03-07 16:04:49 +0000513 /// \brief dist_schedule types
514 OMP_dist_sch_static_chunked = 91,
515 OMP_dist_sch_static = 92,
Alexey Bataev9ebd7422016-05-10 09:57:36 +0000516 /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
517 /// Set if the monotonic schedule modifier was present.
518 OMP_sch_modifier_monotonic = (1 << 29),
519 /// Set if the nonmonotonic schedule modifier was present.
520 OMP_sch_modifier_nonmonotonic = (1 << 30),
Alexey Bataev50b3c952016-02-19 10:38:26 +0000521};
522
523enum OpenMPRTLFunction {
524 /// \brief Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
525 /// kmpc_micro microtask, ...);
526 OMPRTL__kmpc_fork_call,
527 /// \brief Call to void *__kmpc_threadprivate_cached(ident_t *loc,
528 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
529 OMPRTL__kmpc_threadprivate_cached,
530 /// \brief Call to void __kmpc_threadprivate_register( ident_t *,
531 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
532 OMPRTL__kmpc_threadprivate_register,
533 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
534 OMPRTL__kmpc_global_thread_num,
535 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
536 // kmp_critical_name *crit);
537 OMPRTL__kmpc_critical,
538 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
539 // global_tid, kmp_critical_name *crit, uintptr_t hint);
540 OMPRTL__kmpc_critical_with_hint,
541 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
542 // kmp_critical_name *crit);
543 OMPRTL__kmpc_end_critical,
544 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
545 // global_tid);
546 OMPRTL__kmpc_cancel_barrier,
547 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
548 OMPRTL__kmpc_barrier,
549 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
550 OMPRTL__kmpc_for_static_fini,
551 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
552 // global_tid);
553 OMPRTL__kmpc_serialized_parallel,
554 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
555 // global_tid);
556 OMPRTL__kmpc_end_serialized_parallel,
557 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
558 // kmp_int32 num_threads);
559 OMPRTL__kmpc_push_num_threads,
560 // Call to void __kmpc_flush(ident_t *loc);
561 OMPRTL__kmpc_flush,
562 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
563 OMPRTL__kmpc_master,
564 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
565 OMPRTL__kmpc_end_master,
566 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
567 // int end_part);
568 OMPRTL__kmpc_omp_taskyield,
569 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
570 OMPRTL__kmpc_single,
571 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
572 OMPRTL__kmpc_end_single,
573 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
574 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
575 // kmp_routine_entry_t *task_entry);
576 OMPRTL__kmpc_omp_task_alloc,
577 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
578 // new_task);
579 OMPRTL__kmpc_omp_task,
580 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
581 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
582 // kmp_int32 didit);
583 OMPRTL__kmpc_copyprivate,
584 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
585 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
586 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
587 OMPRTL__kmpc_reduce,
588 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
589 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
590 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
591 // *lck);
592 OMPRTL__kmpc_reduce_nowait,
593 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
594 // kmp_critical_name *lck);
595 OMPRTL__kmpc_end_reduce,
596 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
597 // kmp_critical_name *lck);
598 OMPRTL__kmpc_end_reduce_nowait,
599 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
600 // kmp_task_t * new_task);
601 OMPRTL__kmpc_omp_task_begin_if0,
602 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
603 // kmp_task_t * new_task);
604 OMPRTL__kmpc_omp_task_complete_if0,
605 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
606 OMPRTL__kmpc_ordered,
607 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
608 OMPRTL__kmpc_end_ordered,
609 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
610 // global_tid);
611 OMPRTL__kmpc_omp_taskwait,
612 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
613 OMPRTL__kmpc_taskgroup,
614 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
615 OMPRTL__kmpc_end_taskgroup,
616 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
617 // int proc_bind);
618 OMPRTL__kmpc_push_proc_bind,
619 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
620 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
621 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
622 OMPRTL__kmpc_omp_task_with_deps,
623 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
624 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
625 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
626 OMPRTL__kmpc_omp_wait_deps,
627 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
628 // global_tid, kmp_int32 cncl_kind);
629 OMPRTL__kmpc_cancellationpoint,
630 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
631 // kmp_int32 cncl_kind);
632 OMPRTL__kmpc_cancel,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000633 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
634 // kmp_int32 num_teams, kmp_int32 thread_limit);
635 OMPRTL__kmpc_push_num_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000636 // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
637 // microtask, ...);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000638 OMPRTL__kmpc_fork_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000639 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
640 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
641 // sched, kmp_uint64 grainsize, void *task_dup);
642 OMPRTL__kmpc_taskloop,
Alexey Bataev8b427062016-05-25 12:36:08 +0000643 // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
644 // num_dims, struct kmp_dim *dims);
645 OMPRTL__kmpc_doacross_init,
646 // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
647 OMPRTL__kmpc_doacross_fini,
648 // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
649 // *vec);
650 OMPRTL__kmpc_doacross_post,
651 // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
652 // *vec);
653 OMPRTL__kmpc_doacross_wait,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000654 // Call to void *__kmpc_task_reduction_init(int gtid, int num_data, void
655 // *data);
656 OMPRTL__kmpc_task_reduction_init,
657 // Call to void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
658 // *d);
659 OMPRTL__kmpc_task_reduction_get_th_data,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000660
661 //
662 // Offloading related calls
663 //
664 // Call to int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
665 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
666 // *arg_types);
667 OMPRTL__tgt_target,
Samuel Antaob68e2db2016-03-03 16:20:23 +0000668 // Call to int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
669 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
670 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
671 OMPRTL__tgt_target_teams,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000672 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
673 OMPRTL__tgt_register_lib,
674 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
675 OMPRTL__tgt_unregister_lib,
Samuel Antaodf158d52016-04-27 22:58:19 +0000676 // Call to void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
677 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
678 OMPRTL__tgt_target_data_begin,
679 // Call to void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
680 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
681 OMPRTL__tgt_target_data_end,
Samuel Antao8d2d7302016-05-26 18:30:22 +0000682 // Call to void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
683 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
684 OMPRTL__tgt_target_data_update,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000685};
686
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000687/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
688/// region.
689class CleanupTy final : public EHScopeStack::Cleanup {
690 PrePostActionTy *Action;
691
692public:
693 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
694 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
695 if (!CGF.HaveInsertPoint())
696 return;
697 Action->Exit(CGF);
698 }
699};
700
Hans Wennborg7eb54642015-09-10 17:07:54 +0000701} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000702
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000703void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
704 CodeGenFunction::RunCleanupsScope Scope(CGF);
705 if (PrePostAction) {
706 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
707 Callback(CodeGen, CGF, *PrePostAction);
708 } else {
709 PrePostActionTy Action;
710 Callback(CodeGen, CGF, Action);
711 }
712}
713
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000714/// Check if the combiner is a call to UDR combiner and if it is so return the
715/// UDR decl used for reduction.
716static const OMPDeclareReductionDecl *
717getReductionInit(const Expr *ReductionOp) {
718 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
719 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
720 if (auto *DRE =
721 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
722 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
723 return DRD;
724 return nullptr;
725}
726
727static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
728 const OMPDeclareReductionDecl *DRD,
729 const Expr *InitOp,
730 Address Private, Address Original,
731 QualType Ty) {
732 if (DRD->getInitializer()) {
733 std::pair<llvm::Function *, llvm::Function *> Reduction =
734 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
735 auto *CE = cast<CallExpr>(InitOp);
736 auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
737 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
738 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
739 auto *LHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
740 auto *RHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
741 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
742 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
743 [=]() -> Address { return Private; });
744 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
745 [=]() -> Address { return Original; });
746 (void)PrivateScope.Privatize();
747 RValue Func = RValue::get(Reduction.second);
748 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
749 CGF.EmitIgnoredExpr(InitOp);
750 } else {
751 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
752 auto *GV = new llvm::GlobalVariable(
753 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
754 llvm::GlobalValue::PrivateLinkage, Init, ".init");
755 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
756 RValue InitRVal;
757 switch (CGF.getEvaluationKind(Ty)) {
758 case TEK_Scalar:
759 InitRVal = CGF.EmitLoadOfLValue(LV, SourceLocation());
760 break;
761 case TEK_Complex:
762 InitRVal =
763 RValue::getComplex(CGF.EmitLoadOfComplex(LV, SourceLocation()));
764 break;
765 case TEK_Aggregate:
766 InitRVal = RValue::getAggregate(LV.getAddress());
767 break;
768 }
769 OpaqueValueExpr OVE(SourceLocation(), Ty, VK_RValue);
770 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
771 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
772 /*IsInitializer=*/false);
773 }
774}
775
776/// \brief Emit initialization of arrays of complex types.
777/// \param DestAddr Address of the array.
778/// \param Type Type of array.
779/// \param Init Initial expression of array.
780/// \param SrcAddr Address of the original array.
781static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
782 QualType Type, const Expr *Init,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000783 const OMPDeclareReductionDecl *DRD,
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000784 Address SrcAddr = Address::invalid()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000785 // Perform element-by-element initialization.
786 QualType ElementTy;
787
788 // Drill down to the base element type on both arrays.
789 auto ArrayTy = Type->getAsArrayTypeUnsafe();
790 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
791 DestAddr =
792 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
793 if (DRD)
794 SrcAddr =
795 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
796
797 llvm::Value *SrcBegin = nullptr;
798 if (DRD)
799 SrcBegin = SrcAddr.getPointer();
800 auto DestBegin = DestAddr.getPointer();
801 // Cast from pointer to array type to pointer to single element.
802 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
803 // The basic structure here is a while-do loop.
804 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
805 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
806 auto IsEmpty =
807 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
808 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
809
810 // Enter the loop body, making that address the current address.
811 auto EntryBB = CGF.Builder.GetInsertBlock();
812 CGF.EmitBlock(BodyBB);
813
814 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
815
816 llvm::PHINode *SrcElementPHI = nullptr;
817 Address SrcElementCurrent = Address::invalid();
818 if (DRD) {
819 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
820 "omp.arraycpy.srcElementPast");
821 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
822 SrcElementCurrent =
823 Address(SrcElementPHI,
824 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
825 }
826 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
827 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
828 DestElementPHI->addIncoming(DestBegin, EntryBB);
829 Address DestElementCurrent =
830 Address(DestElementPHI,
831 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
832
833 // Emit copy.
834 {
835 CodeGenFunction::RunCleanupsScope InitScope(CGF);
836 if (DRD && (DRD->getInitializer() || !Init)) {
837 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
838 SrcElementCurrent, ElementTy);
839 } else
840 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
841 /*IsInitializer=*/false);
842 }
843
844 if (DRD) {
845 // Shift the address forward by one element.
846 auto SrcElementNext = CGF.Builder.CreateConstGEP1_32(
847 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
848 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
849 }
850
851 // Shift the address forward by one element.
852 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
853 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
854 // Check whether we've reached the end.
855 auto Done =
856 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
857 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
858 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
859
860 // Done.
861 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
862}
863
864LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
865 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
866 return CGF.EmitOMPArraySectionExpr(OASE);
867 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(E))
868 return CGF.EmitLValue(ASE);
869 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
870 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
871 CGF.CapturedStmtInfo &&
872 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
873 E->getType(), VK_LValue, E->getExprLoc());
874 // Store the address of the original variable associated with the LHS
875 // implicit variable.
876 return CGF.EmitLValue(&DRE);
877}
878
879LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
880 const Expr *E) {
881 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
882 return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
883 return LValue();
884}
885
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000886void ReductionCodeGen::emitAggregateInitialization(
887 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
888 const OMPDeclareReductionDecl *DRD) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000889 // Emit VarDecl with copy init for arrays.
890 // Get the address of the original variable captured in current
891 // captured region.
892 auto *PrivateVD =
893 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000894 EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
895 DRD ? ClausesData[N].ReductionOp : PrivateVD->getInit(),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000896 DRD, SharedLVal.getAddress());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000897}
898
899ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
900 ArrayRef<const Expr *> Privates,
901 ArrayRef<const Expr *> ReductionOps) {
902 ClausesData.reserve(Shareds.size());
903 SharedAddresses.reserve(Shareds.size());
904 Sizes.reserve(Shareds.size());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000905 BaseDecls.reserve(Shareds.size());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000906 auto IPriv = Privates.begin();
907 auto IRed = ReductionOps.begin();
908 for (const auto *Ref : Shareds) {
909 ClausesData.emplace_back(Ref, *IPriv, *IRed);
910 std::advance(IPriv, 1);
911 std::advance(IRed, 1);
912 }
913}
914
915void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
916 assert(SharedAddresses.size() == N &&
917 "Number of generated lvalues must be exactly N.");
918 SharedAddresses.emplace_back(emitSharedLValue(CGF, ClausesData[N].Ref),
919 emitSharedLValueUB(CGF, ClausesData[N].Ref));
920}
921
922void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
923 auto *PrivateVD =
924 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
925 QualType PrivateType = PrivateVD->getType();
926 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
927 if (!AsArraySection && !PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000928 Sizes.emplace_back(
929 CGF.getTypeSize(
930 SharedAddresses[N].first.getType().getNonReferenceType()),
931 nullptr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000932 return;
933 }
934 llvm::Value *Size;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000935 llvm::Value *SizeInChars;
936 llvm::Type *ElemType =
937 cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
938 ->getElementType();
939 auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000940 if (AsArraySection) {
941 Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
942 SharedAddresses[N].first.getPointer());
943 Size = CGF.Builder.CreateNUWAdd(
944 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000945 SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000946 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000947 SizeInChars = CGF.getTypeSize(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000948 SharedAddresses[N].first.getType().getNonReferenceType());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000949 Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000950 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000951 Sizes.emplace_back(SizeInChars, Size);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000952 CodeGenFunction::OpaqueValueMapping OpaqueMap(
953 CGF,
954 cast<OpaqueValueExpr>(
955 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
956 RValue::get(Size));
957 CGF.EmitVariablyModifiedType(PrivateType);
958}
959
960void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
961 llvm::Value *Size) {
962 auto *PrivateVD =
963 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
964 QualType PrivateType = PrivateVD->getType();
965 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
966 if (!AsArraySection && !PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000967 assert(!Size && !Sizes[N].second &&
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000968 "Size should be nullptr for non-variably modified redution "
969 "items.");
970 return;
971 }
972 CodeGenFunction::OpaqueValueMapping OpaqueMap(
973 CGF,
974 cast<OpaqueValueExpr>(
975 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
976 RValue::get(Size));
977 CGF.EmitVariablyModifiedType(PrivateType);
978}
979
980void ReductionCodeGen::emitInitialization(
981 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
982 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
983 assert(SharedAddresses.size() > N && "No variable was generated");
984 auto *PrivateVD =
985 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
986 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
987 QualType PrivateType = PrivateVD->getType();
988 PrivateAddr = CGF.Builder.CreateElementBitCast(
989 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
990 QualType SharedType = SharedAddresses[N].first.getType();
991 SharedLVal = CGF.MakeAddrLValue(
992 CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
993 CGF.ConvertTypeForMem(SharedType)),
994 SharedType, SharedAddresses[N].first.getBaseInfo());
995 if (isa<OMPArraySectionExpr>(ClausesData[N].Ref) ||
996 CGF.getContext().getAsArrayType(PrivateVD->getType())) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000997 emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000998 } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
999 emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
1000 PrivateAddr, SharedLVal.getAddress(),
1001 SharedLVal.getType());
1002 } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
1003 !CGF.isTrivialInitializer(PrivateVD->getInit())) {
1004 CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
1005 PrivateVD->getType().getQualifiers(),
1006 /*IsInitializer=*/false);
1007 }
1008}
1009
1010bool ReductionCodeGen::needCleanups(unsigned N) {
1011 auto *PrivateVD =
1012 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1013 QualType PrivateType = PrivateVD->getType();
1014 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1015 return DTorKind != QualType::DK_none;
1016}
1017
1018void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
1019 Address PrivateAddr) {
1020 auto *PrivateVD =
1021 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1022 QualType PrivateType = PrivateVD->getType();
1023 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1024 if (needCleanups(N)) {
1025 PrivateAddr = CGF.Builder.CreateElementBitCast(
1026 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1027 CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
1028 }
1029}
1030
1031static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1032 LValue BaseLV) {
1033 BaseTy = BaseTy.getNonReferenceType();
1034 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1035 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1036 if (auto *PtrTy = BaseTy->getAs<PointerType>())
1037 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
1038 else {
1039 BaseLV = CGF.EmitLoadOfReferenceLValue(BaseLV.getAddress(),
1040 BaseTy->castAs<ReferenceType>());
1041 }
1042 BaseTy = BaseTy->getPointeeType();
1043 }
1044 return CGF.MakeAddrLValue(
1045 CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
1046 CGF.ConvertTypeForMem(ElTy)),
1047 BaseLV.getType(), BaseLV.getBaseInfo());
1048}
1049
1050static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1051 llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
1052 llvm::Value *Addr) {
1053 Address Tmp = Address::invalid();
1054 Address TopTmp = Address::invalid();
1055 Address MostTopTmp = Address::invalid();
1056 BaseTy = BaseTy.getNonReferenceType();
1057 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1058 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1059 Tmp = CGF.CreateMemTemp(BaseTy);
1060 if (TopTmp.isValid())
1061 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
1062 else
1063 MostTopTmp = Tmp;
1064 TopTmp = Tmp;
1065 BaseTy = BaseTy->getPointeeType();
1066 }
1067 llvm::Type *Ty = BaseLVType;
1068 if (Tmp.isValid())
1069 Ty = Tmp.getElementType();
1070 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
1071 if (Tmp.isValid()) {
1072 CGF.Builder.CreateStore(Addr, Tmp);
1073 return MostTopTmp;
1074 }
1075 return Address(Addr, BaseLVAlignment);
1076}
1077
1078Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
1079 Address PrivateAddr) {
1080 const DeclRefExpr *DE;
1081 const VarDecl *OrigVD = nullptr;
1082 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(ClausesData[N].Ref)) {
1083 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
1084 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
1085 Base = TempOASE->getBase()->IgnoreParenImpCasts();
1086 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1087 Base = TempASE->getBase()->IgnoreParenImpCasts();
1088 DE = cast<DeclRefExpr>(Base);
1089 OrigVD = cast<VarDecl>(DE->getDecl());
1090 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(ClausesData[N].Ref)) {
1091 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
1092 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1093 Base = TempASE->getBase()->IgnoreParenImpCasts();
1094 DE = cast<DeclRefExpr>(Base);
1095 OrigVD = cast<VarDecl>(DE->getDecl());
1096 }
1097 if (OrigVD) {
1098 BaseDecls.emplace_back(OrigVD);
1099 auto OriginalBaseLValue = CGF.EmitLValue(DE);
1100 LValue BaseLValue =
1101 loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1102 OriginalBaseLValue);
1103 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1104 BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
1105 llvm::Value *Ptr =
1106 CGF.Builder.CreateGEP(PrivateAddr.getPointer(), Adjustment);
1107 return castToBase(CGF, OrigVD->getType(),
1108 SharedAddresses[N].first.getType(),
1109 OriginalBaseLValue.getPointer()->getType(),
1110 OriginalBaseLValue.getAlignment(), Ptr);
1111 }
1112 BaseDecls.emplace_back(
1113 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1114 return PrivateAddr;
1115}
1116
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001117bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
1118 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
1119 return DRD && DRD->getInitializer();
1120}
1121
Alexey Bataev18095712014-10-10 12:19:54 +00001122LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00001123 return CGF.EmitLoadOfPointerLValue(
1124 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1125 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +00001126}
1127
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001128void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001129 if (!CGF.HaveInsertPoint())
1130 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001131 // 1.2.2 OpenMP Language Terminology
1132 // Structured block - An executable statement with a single entry at the
1133 // top and a single exit at the bottom.
1134 // The point of exit cannot be a branch out of the structured block.
1135 // longjmp() and throw() must not violate the entry/exit criteria.
1136 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001137 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001138 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001139}
1140
Alexey Bataev62b63b12015-03-10 07:28:44 +00001141LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1142 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001143 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1144 getThreadIDVariable()->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001145 LValueBaseInfo(AlignmentSource::Decl, false));
Alexey Bataev62b63b12015-03-10 07:28:44 +00001146}
1147
Alexey Bataev9959db52014-05-06 10:08:46 +00001148CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001149 : CGM(CGM), OffloadEntriesInfoManager(CGM) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001150 IdentTy = llvm::StructType::create(
1151 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
1152 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Serge Guelton1d993272017-05-09 19:31:30 +00001153 CGM.Int8PtrTy /* psource */);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001154 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +00001155
1156 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +00001157}
1158
Alexey Bataev91797552015-03-18 04:13:55 +00001159void CGOpenMPRuntime::clear() {
1160 InternalVars.clear();
1161}
1162
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001163static llvm::Function *
1164emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1165 const Expr *CombinerInitializer, const VarDecl *In,
1166 const VarDecl *Out, bool IsCombiner) {
1167 // void .omp_combiner.(Ty *in, Ty *out);
1168 auto &C = CGM.getContext();
1169 QualType PtrTy = C.getPointerType(Ty).withRestrict();
1170 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001171 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001172 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001173 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001174 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001175 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001176 Args.push_back(&OmpInParm);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001177 auto &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001178 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001179 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1180 auto *Fn = llvm::Function::Create(
1181 FnTy, llvm::GlobalValue::InternalLinkage,
1182 IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
1183 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001184 Fn->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001185 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001186 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001187 CodeGenFunction CGF(CGM);
1188 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1189 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
1190 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
1191 CodeGenFunction::OMPPrivateScope Scope(CGF);
1192 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
1193 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
1194 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1195 .getAddress();
1196 });
1197 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
1198 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
1199 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1200 .getAddress();
1201 });
1202 (void)Scope.Privatize();
1203 CGF.EmitIgnoredExpr(CombinerInitializer);
1204 Scope.ForceCleanup();
1205 CGF.FinishFunction();
1206 return Fn;
1207}
1208
1209void CGOpenMPRuntime::emitUserDefinedReduction(
1210 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1211 if (UDRMap.count(D) > 0)
1212 return;
1213 auto &C = CGM.getContext();
1214 if (!In || !Out) {
1215 In = &C.Idents.get("omp_in");
1216 Out = &C.Idents.get("omp_out");
1217 }
1218 llvm::Function *Combiner = emitCombinerOrInitializer(
1219 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
1220 cast<VarDecl>(D->lookup(Out).front()),
1221 /*IsCombiner=*/true);
1222 llvm::Function *Initializer = nullptr;
1223 if (auto *Init = D->getInitializer()) {
1224 if (!Priv || !Orig) {
1225 Priv = &C.Idents.get("omp_priv");
1226 Orig = &C.Idents.get("omp_orig");
1227 }
1228 Initializer = emitCombinerOrInitializer(
1229 CGM, D->getType(), Init, cast<VarDecl>(D->lookup(Orig).front()),
1230 cast<VarDecl>(D->lookup(Priv).front()),
1231 /*IsCombiner=*/false);
1232 }
1233 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
1234 if (CGF) {
1235 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1236 Decls.second.push_back(D);
1237 }
1238}
1239
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001240std::pair<llvm::Function *, llvm::Function *>
1241CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1242 auto I = UDRMap.find(D);
1243 if (I != UDRMap.end())
1244 return I->second;
1245 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1246 return UDRMap.lookup(D);
1247}
1248
John McCall7f416cc2015-09-08 08:05:57 +00001249// Layout information for ident_t.
1250static CharUnits getIdentAlign(CodeGenModule &CGM) {
1251 return CGM.getPointerAlign();
1252}
1253static CharUnits getIdentSize(CodeGenModule &CGM) {
1254 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
1255 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
1256}
Alexey Bataev50b3c952016-02-19 10:38:26 +00001257static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
John McCall7f416cc2015-09-08 08:05:57 +00001258 // All the fields except the last are i32, so this works beautifully.
1259 return unsigned(Field) * CharUnits::fromQuantity(4);
1260}
1261static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001262 IdentFieldIndex Field,
John McCall7f416cc2015-09-08 08:05:57 +00001263 const llvm::Twine &Name = "") {
1264 auto Offset = getOffsetOfIdentField(Field);
1265 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
1266}
1267
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001268static llvm::Value *emitParallelOrTeamsOutlinedFunction(
1269 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1270 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1271 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001272 assert(ThreadIDVar->getType()->isPointerType() &&
1273 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +00001274 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00001275 bool HasCancel = false;
1276 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
1277 HasCancel = OPD->hasCancel();
1278 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
1279 HasCancel = OPSD->hasCancel();
1280 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
1281 HasCancel = OPFD->hasCancel();
1282 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001283 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +00001284 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001285 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +00001286}
1287
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001288llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
1289 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1290 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1291 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1292 return emitParallelOrTeamsOutlinedFunction(
1293 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1294}
1295
1296llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1297 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1298 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1299 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1300 return emitParallelOrTeamsOutlinedFunction(
1301 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1302}
1303
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001304llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
1305 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +00001306 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1307 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1308 bool Tied, unsigned &NumberOfParts) {
1309 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1310 PrePostActionTy &) {
1311 auto *ThreadID = getThreadID(CGF, D.getLocStart());
1312 auto *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
1313 llvm::Value *TaskArgs[] = {
1314 UpLoc, ThreadID,
1315 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1316 TaskTVar->getType()->castAs<PointerType>())
1317 .getPointer()};
1318 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1319 };
1320 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1321 UntiedCodeGen);
1322 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001323 assert(!ThreadIDVar->getType()->isPointerType() &&
1324 "thread id variable must be of type kmp_int32 for tasks");
1325 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
Alexey Bataev7292c292016-04-25 12:22:29 +00001326 auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001327 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +00001328 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1329 InnermostKind,
1330 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +00001331 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev48591dd2016-04-20 04:01:36 +00001332 auto *Res = CGF.GenerateCapturedStmtFunction(*CS);
1333 if (!Tied)
1334 NumberOfParts = Action.getNumberOfParts();
1335 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001336}
1337
Alexey Bataev50b3c952016-02-19 10:38:26 +00001338Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +00001339 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +00001340 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +00001341 if (!Entry) {
1342 if (!DefaultOpenMPPSource) {
1343 // Initialize default location for psource field of ident_t structure of
1344 // all ident_t objects. Format is ";file;function;line;column;;".
1345 // Taken from
1346 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1347 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +00001348 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001349 DefaultOpenMPPSource =
1350 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1351 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001352
John McCall23c9dc62016-11-28 22:18:27 +00001353 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001354 auto fields = builder.beginStruct(IdentTy);
1355 fields.addInt(CGM.Int32Ty, 0);
1356 fields.addInt(CGM.Int32Ty, Flags);
1357 fields.addInt(CGM.Int32Ty, 0);
1358 fields.addInt(CGM.Int32Ty, 0);
1359 fields.add(DefaultOpenMPPSource);
1360 auto DefaultOpenMPLocation =
1361 fields.finishAndCreateGlobal("", Align, /*isConstant*/ true,
1362 llvm::GlobalValue::PrivateLinkage);
1363 DefaultOpenMPLocation->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1364
John McCall7f416cc2015-09-08 08:05:57 +00001365 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +00001366 }
John McCall7f416cc2015-09-08 08:05:57 +00001367 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +00001368}
1369
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001370llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1371 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001372 unsigned Flags) {
1373 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +00001374 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001375 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +00001376 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +00001377 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001378
1379 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1380
John McCall7f416cc2015-09-08 08:05:57 +00001381 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001382 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1383 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +00001384 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
1385
Alexander Musmanc6388682014-12-15 07:07:06 +00001386 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1387 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +00001388 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +00001389 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +00001390 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
1391 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +00001392 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +00001393 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001394 LocValue = AI;
1395
1396 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1397 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001398 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +00001399 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +00001400 }
1401
1402 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +00001403 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +00001404
Alexey Bataevf002aca2014-05-30 05:48:40 +00001405 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
1406 if (OMPDebugLoc == nullptr) {
1407 SmallString<128> Buffer2;
1408 llvm::raw_svector_ostream OS2(Buffer2);
1409 // Build debug location
1410 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1411 OS2 << ";" << PLoc.getFilename() << ";";
1412 if (const FunctionDecl *FD =
1413 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
1414 OS2 << FD->getQualifiedNameAsString();
1415 }
1416 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1417 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1418 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +00001419 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001420 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +00001421 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
1422
John McCall7f416cc2015-09-08 08:05:57 +00001423 // Our callers always pass this to a runtime function, so for
1424 // convenience, go ahead and return a naked pointer.
1425 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001426}
1427
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001428llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1429 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001430 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1431
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001432 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001433 // Check whether we've already cached a load of the thread id in this
1434 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001435 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001436 if (I != OpenMPLocThreadIDMap.end()) {
1437 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001438 if (ThreadID != nullptr)
1439 return ThreadID;
1440 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001441 if (auto *OMPRegionInfo =
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001442 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001443 if (OMPRegionInfo->getThreadIDVariable()) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001444 // Check if this an outlined function with thread id passed as argument.
1445 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001446 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
1447 // If value loaded in entry block, cache it and use it everywhere in
1448 // function.
1449 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1450 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1451 Elem.second.ThreadID = ThreadID;
1452 }
1453 return ThreadID;
Alexey Bataevd6c57552014-07-25 07:55:17 +00001454 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001455 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001456
1457 // This is not an outlined function region - need to call __kmpc_int32
1458 // kmpc_global_thread_num(ident_t *loc).
1459 // Generate thread id value and cache this value for use across the
1460 // function.
1461 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1462 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
1463 ThreadID =
1464 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1465 emitUpdateLocation(CGF, Loc));
1466 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1467 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001468 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +00001469}
1470
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001471void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001472 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001473 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1474 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001475 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1476 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
1477 UDRMap.erase(D);
1478 }
1479 FunctionUDRMap.erase(CGF.CurFn);
1480 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001481}
1482
1483llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001484 if (!IdentTy) {
1485 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001486 return llvm::PointerType::getUnqual(IdentTy);
1487}
1488
1489llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001490 if (!Kmpc_MicroTy) {
1491 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1492 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1493 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1494 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1495 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001496 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1497}
1498
1499llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001500CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001501 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001502 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001503 case OMPRTL__kmpc_fork_call: {
1504 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1505 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001506 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1507 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001508 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001509 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001510 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1511 break;
1512 }
1513 case OMPRTL__kmpc_global_thread_num: {
1514 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001515 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001516 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001517 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001518 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1519 break;
1520 }
Alexey Bataev97720002014-11-11 04:05:39 +00001521 case OMPRTL__kmpc_threadprivate_cached: {
1522 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1523 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1524 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1525 CGM.VoidPtrTy, CGM.SizeTy,
1526 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1527 llvm::FunctionType *FnTy =
1528 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1529 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1530 break;
1531 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001532 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001533 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1534 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001535 llvm::Type *TypeParams[] = {
1536 getIdentTyPointerTy(), CGM.Int32Ty,
1537 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1538 llvm::FunctionType *FnTy =
1539 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1540 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1541 break;
1542 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001543 case OMPRTL__kmpc_critical_with_hint: {
1544 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1545 // kmp_critical_name *crit, uintptr_t hint);
1546 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1547 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1548 CGM.IntPtrTy};
1549 llvm::FunctionType *FnTy =
1550 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1551 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1552 break;
1553 }
Alexey Bataev97720002014-11-11 04:05:39 +00001554 case OMPRTL__kmpc_threadprivate_register: {
1555 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1556 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1557 // typedef void *(*kmpc_ctor)(void *);
1558 auto KmpcCtorTy =
1559 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1560 /*isVarArg*/ false)->getPointerTo();
1561 // typedef void *(*kmpc_cctor)(void *, void *);
1562 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1563 auto KmpcCopyCtorTy =
1564 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1565 /*isVarArg*/ false)->getPointerTo();
1566 // typedef void (*kmpc_dtor)(void *);
1567 auto KmpcDtorTy =
1568 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1569 ->getPointerTo();
1570 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1571 KmpcCopyCtorTy, KmpcDtorTy};
1572 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1573 /*isVarArg*/ false);
1574 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1575 break;
1576 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001577 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001578 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1579 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001580 llvm::Type *TypeParams[] = {
1581 getIdentTyPointerTy(), CGM.Int32Ty,
1582 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1583 llvm::FunctionType *FnTy =
1584 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1585 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1586 break;
1587 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001588 case OMPRTL__kmpc_cancel_barrier: {
1589 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1590 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001591 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1592 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001593 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1594 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001595 break;
1596 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001597 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001598 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001599 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1600 llvm::FunctionType *FnTy =
1601 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1602 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1603 break;
1604 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001605 case OMPRTL__kmpc_for_static_fini: {
1606 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1607 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1608 llvm::FunctionType *FnTy =
1609 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1610 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1611 break;
1612 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001613 case OMPRTL__kmpc_push_num_threads: {
1614 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1615 // kmp_int32 num_threads)
1616 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1617 CGM.Int32Ty};
1618 llvm::FunctionType *FnTy =
1619 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1620 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1621 break;
1622 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001623 case OMPRTL__kmpc_serialized_parallel: {
1624 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1625 // global_tid);
1626 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1627 llvm::FunctionType *FnTy =
1628 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1629 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1630 break;
1631 }
1632 case OMPRTL__kmpc_end_serialized_parallel: {
1633 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1634 // global_tid);
1635 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1636 llvm::FunctionType *FnTy =
1637 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1638 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1639 break;
1640 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001641 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001642 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001643 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1644 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001645 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001646 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1647 break;
1648 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001649 case OMPRTL__kmpc_master: {
1650 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1651 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1652 llvm::FunctionType *FnTy =
1653 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1654 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1655 break;
1656 }
1657 case OMPRTL__kmpc_end_master: {
1658 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1659 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1660 llvm::FunctionType *FnTy =
1661 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1662 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1663 break;
1664 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001665 case OMPRTL__kmpc_omp_taskyield: {
1666 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1667 // int end_part);
1668 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1669 llvm::FunctionType *FnTy =
1670 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1671 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1672 break;
1673 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001674 case OMPRTL__kmpc_single: {
1675 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1676 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1677 llvm::FunctionType *FnTy =
1678 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1679 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1680 break;
1681 }
1682 case OMPRTL__kmpc_end_single: {
1683 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1684 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1685 llvm::FunctionType *FnTy =
1686 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1687 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1688 break;
1689 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001690 case OMPRTL__kmpc_omp_task_alloc: {
1691 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1692 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1693 // kmp_routine_entry_t *task_entry);
1694 assert(KmpRoutineEntryPtrTy != nullptr &&
1695 "Type kmp_routine_entry_t must be created.");
1696 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1697 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1698 // Return void * and then cast to particular kmp_task_t type.
1699 llvm::FunctionType *FnTy =
1700 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1701 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1702 break;
1703 }
1704 case OMPRTL__kmpc_omp_task: {
1705 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1706 // *new_task);
1707 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1708 CGM.VoidPtrTy};
1709 llvm::FunctionType *FnTy =
1710 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1711 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1712 break;
1713 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001714 case OMPRTL__kmpc_copyprivate: {
1715 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001716 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001717 // kmp_int32 didit);
1718 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1719 auto *CpyFnTy =
1720 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001721 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001722 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1723 CGM.Int32Ty};
1724 llvm::FunctionType *FnTy =
1725 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1726 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1727 break;
1728 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001729 case OMPRTL__kmpc_reduce: {
1730 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1731 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1732 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1733 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1734 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1735 /*isVarArg=*/false);
1736 llvm::Type *TypeParams[] = {
1737 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1738 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1739 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1740 llvm::FunctionType *FnTy =
1741 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1742 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1743 break;
1744 }
1745 case OMPRTL__kmpc_reduce_nowait: {
1746 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1747 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1748 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1749 // *lck);
1750 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1751 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1752 /*isVarArg=*/false);
1753 llvm::Type *TypeParams[] = {
1754 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1755 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1756 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1757 llvm::FunctionType *FnTy =
1758 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1759 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1760 break;
1761 }
1762 case OMPRTL__kmpc_end_reduce: {
1763 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1764 // kmp_critical_name *lck);
1765 llvm::Type *TypeParams[] = {
1766 getIdentTyPointerTy(), CGM.Int32Ty,
1767 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1768 llvm::FunctionType *FnTy =
1769 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1770 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1771 break;
1772 }
1773 case OMPRTL__kmpc_end_reduce_nowait: {
1774 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1775 // kmp_critical_name *lck);
1776 llvm::Type *TypeParams[] = {
1777 getIdentTyPointerTy(), CGM.Int32Ty,
1778 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1779 llvm::FunctionType *FnTy =
1780 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1781 RTLFn =
1782 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1783 break;
1784 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001785 case OMPRTL__kmpc_omp_task_begin_if0: {
1786 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1787 // *new_task);
1788 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1789 CGM.VoidPtrTy};
1790 llvm::FunctionType *FnTy =
1791 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1792 RTLFn =
1793 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1794 break;
1795 }
1796 case OMPRTL__kmpc_omp_task_complete_if0: {
1797 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1798 // *new_task);
1799 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1800 CGM.VoidPtrTy};
1801 llvm::FunctionType *FnTy =
1802 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1803 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1804 /*Name=*/"__kmpc_omp_task_complete_if0");
1805 break;
1806 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001807 case OMPRTL__kmpc_ordered: {
1808 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1809 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1810 llvm::FunctionType *FnTy =
1811 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1812 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1813 break;
1814 }
1815 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001816 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001817 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1818 llvm::FunctionType *FnTy =
1819 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1820 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1821 break;
1822 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001823 case OMPRTL__kmpc_omp_taskwait: {
1824 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1825 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1826 llvm::FunctionType *FnTy =
1827 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1828 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1829 break;
1830 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001831 case OMPRTL__kmpc_taskgroup: {
1832 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1833 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1834 llvm::FunctionType *FnTy =
1835 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1836 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1837 break;
1838 }
1839 case OMPRTL__kmpc_end_taskgroup: {
1840 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1841 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1842 llvm::FunctionType *FnTy =
1843 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1844 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1845 break;
1846 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001847 case OMPRTL__kmpc_push_proc_bind: {
1848 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1849 // int proc_bind)
1850 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1851 llvm::FunctionType *FnTy =
1852 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1853 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1854 break;
1855 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001856 case OMPRTL__kmpc_omp_task_with_deps: {
1857 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1858 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1859 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1860 llvm::Type *TypeParams[] = {
1861 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1862 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1863 llvm::FunctionType *FnTy =
1864 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1865 RTLFn =
1866 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1867 break;
1868 }
1869 case OMPRTL__kmpc_omp_wait_deps: {
1870 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1871 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1872 // kmp_depend_info_t *noalias_dep_list);
1873 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1874 CGM.Int32Ty, CGM.VoidPtrTy,
1875 CGM.Int32Ty, CGM.VoidPtrTy};
1876 llvm::FunctionType *FnTy =
1877 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1878 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1879 break;
1880 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001881 case OMPRTL__kmpc_cancellationpoint: {
1882 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1883 // global_tid, kmp_int32 cncl_kind)
1884 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1885 llvm::FunctionType *FnTy =
1886 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1887 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1888 break;
1889 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001890 case OMPRTL__kmpc_cancel: {
1891 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1892 // kmp_int32 cncl_kind)
1893 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1894 llvm::FunctionType *FnTy =
1895 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1896 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1897 break;
1898 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001899 case OMPRTL__kmpc_push_num_teams: {
1900 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1901 // kmp_int32 num_teams, kmp_int32 num_threads)
1902 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1903 CGM.Int32Ty};
1904 llvm::FunctionType *FnTy =
1905 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1906 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1907 break;
1908 }
1909 case OMPRTL__kmpc_fork_teams: {
1910 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1911 // microtask, ...);
1912 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1913 getKmpc_MicroPointerTy()};
1914 llvm::FunctionType *FnTy =
1915 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1916 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1917 break;
1918 }
Alexey Bataev7292c292016-04-25 12:22:29 +00001919 case OMPRTL__kmpc_taskloop: {
1920 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
1921 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
1922 // sched, kmp_uint64 grainsize, void *task_dup);
1923 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1924 CGM.IntTy,
1925 CGM.VoidPtrTy,
1926 CGM.IntTy,
1927 CGM.Int64Ty->getPointerTo(),
1928 CGM.Int64Ty->getPointerTo(),
1929 CGM.Int64Ty,
1930 CGM.IntTy,
1931 CGM.IntTy,
1932 CGM.Int64Ty,
1933 CGM.VoidPtrTy};
1934 llvm::FunctionType *FnTy =
1935 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1936 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
1937 break;
1938 }
Alexey Bataev8b427062016-05-25 12:36:08 +00001939 case OMPRTL__kmpc_doacross_init: {
1940 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
1941 // num_dims, struct kmp_dim *dims);
1942 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1943 CGM.Int32Ty,
1944 CGM.Int32Ty,
1945 CGM.VoidPtrTy};
1946 llvm::FunctionType *FnTy =
1947 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1948 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
1949 break;
1950 }
1951 case OMPRTL__kmpc_doacross_fini: {
1952 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
1953 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1954 llvm::FunctionType *FnTy =
1955 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1956 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
1957 break;
1958 }
1959 case OMPRTL__kmpc_doacross_post: {
1960 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
1961 // *vec);
1962 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1963 CGM.Int64Ty->getPointerTo()};
1964 llvm::FunctionType *FnTy =
1965 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1966 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
1967 break;
1968 }
1969 case OMPRTL__kmpc_doacross_wait: {
1970 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
1971 // *vec);
1972 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1973 CGM.Int64Ty->getPointerTo()};
1974 llvm::FunctionType *FnTy =
1975 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1976 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
1977 break;
1978 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001979 case OMPRTL__kmpc_task_reduction_init: {
1980 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
1981 // *data);
1982 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
1983 llvm::FunctionType *FnTy =
1984 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1985 RTLFn =
1986 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
1987 break;
1988 }
1989 case OMPRTL__kmpc_task_reduction_get_th_data: {
1990 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
1991 // *d);
1992 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
1993 llvm::FunctionType *FnTy =
1994 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1995 RTLFn = CGM.CreateRuntimeFunction(
1996 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
1997 break;
1998 }
Samuel Antaobed3c462015-10-02 16:14:20 +00001999 case OMPRTL__tgt_target: {
2000 // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
2001 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
2002 // *arg_types);
2003 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2004 CGM.VoidPtrTy,
2005 CGM.Int32Ty,
2006 CGM.VoidPtrPtrTy,
2007 CGM.VoidPtrPtrTy,
2008 CGM.SizeTy->getPointerTo(),
2009 CGM.Int32Ty->getPointerTo()};
2010 llvm::FunctionType *FnTy =
2011 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2012 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2013 break;
2014 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00002015 case OMPRTL__tgt_target_teams: {
2016 // Build int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
2017 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2018 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
2019 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2020 CGM.VoidPtrTy,
2021 CGM.Int32Ty,
2022 CGM.VoidPtrPtrTy,
2023 CGM.VoidPtrPtrTy,
2024 CGM.SizeTy->getPointerTo(),
2025 CGM.Int32Ty->getPointerTo(),
2026 CGM.Int32Ty,
2027 CGM.Int32Ty};
2028 llvm::FunctionType *FnTy =
2029 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2030 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2031 break;
2032 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002033 case OMPRTL__tgt_register_lib: {
2034 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2035 QualType ParamTy =
2036 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2037 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2038 llvm::FunctionType *FnTy =
2039 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2040 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2041 break;
2042 }
2043 case OMPRTL__tgt_unregister_lib: {
2044 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2045 QualType ParamTy =
2046 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2047 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2048 llvm::FunctionType *FnTy =
2049 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2050 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2051 break;
2052 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002053 case OMPRTL__tgt_target_data_begin: {
2054 // Build void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
2055 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2056 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2057 CGM.Int32Ty,
2058 CGM.VoidPtrPtrTy,
2059 CGM.VoidPtrPtrTy,
2060 CGM.SizeTy->getPointerTo(),
2061 CGM.Int32Ty->getPointerTo()};
2062 llvm::FunctionType *FnTy =
2063 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2064 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2065 break;
2066 }
2067 case OMPRTL__tgt_target_data_end: {
2068 // Build void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
2069 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2070 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2071 CGM.Int32Ty,
2072 CGM.VoidPtrPtrTy,
2073 CGM.VoidPtrPtrTy,
2074 CGM.SizeTy->getPointerTo(),
2075 CGM.Int32Ty->getPointerTo()};
2076 llvm::FunctionType *FnTy =
2077 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2078 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2079 break;
2080 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002081 case OMPRTL__tgt_target_data_update: {
2082 // Build void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
2083 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2084 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2085 CGM.Int32Ty,
2086 CGM.VoidPtrPtrTy,
2087 CGM.VoidPtrPtrTy,
2088 CGM.SizeTy->getPointerTo(),
2089 CGM.Int32Ty->getPointerTo()};
2090 llvm::FunctionType *FnTy =
2091 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2092 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2093 break;
2094 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002095 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002096 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002097 return RTLFn;
2098}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002099
Alexander Musman21212e42015-03-13 10:38:23 +00002100llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2101 bool IVSigned) {
2102 assert((IVSize == 32 || IVSize == 64) &&
2103 "IV size is not compatible with the omp runtime");
2104 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2105 : "__kmpc_for_static_init_4u")
2106 : (IVSigned ? "__kmpc_for_static_init_8"
2107 : "__kmpc_for_static_init_8u");
2108 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2109 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2110 llvm::Type *TypeParams[] = {
2111 getIdentTyPointerTy(), // loc
2112 CGM.Int32Ty, // tid
2113 CGM.Int32Ty, // schedtype
2114 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2115 PtrTy, // p_lower
2116 PtrTy, // p_upper
2117 PtrTy, // p_stride
2118 ITy, // incr
2119 ITy // chunk
2120 };
2121 llvm::FunctionType *FnTy =
2122 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2123 return CGM.CreateRuntimeFunction(FnTy, Name);
2124}
2125
Alexander Musman92bdaab2015-03-12 13:37:50 +00002126llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2127 bool IVSigned) {
2128 assert((IVSize == 32 || IVSize == 64) &&
2129 "IV size is not compatible with the omp runtime");
2130 auto Name =
2131 IVSize == 32
2132 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2133 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
2134 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2135 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2136 CGM.Int32Ty, // tid
2137 CGM.Int32Ty, // schedtype
2138 ITy, // lower
2139 ITy, // upper
2140 ITy, // stride
2141 ITy // chunk
2142 };
2143 llvm::FunctionType *FnTy =
2144 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2145 return CGM.CreateRuntimeFunction(FnTy, Name);
2146}
2147
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002148llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2149 bool IVSigned) {
2150 assert((IVSize == 32 || IVSize == 64) &&
2151 "IV size is not compatible with the omp runtime");
2152 auto Name =
2153 IVSize == 32
2154 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2155 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2156 llvm::Type *TypeParams[] = {
2157 getIdentTyPointerTy(), // loc
2158 CGM.Int32Ty, // tid
2159 };
2160 llvm::FunctionType *FnTy =
2161 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2162 return CGM.CreateRuntimeFunction(FnTy, Name);
2163}
2164
Alexander Musman92bdaab2015-03-12 13:37:50 +00002165llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2166 bool IVSigned) {
2167 assert((IVSize == 32 || IVSize == 64) &&
2168 "IV size is not compatible with the omp runtime");
2169 auto Name =
2170 IVSize == 32
2171 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2172 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
2173 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2174 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2175 llvm::Type *TypeParams[] = {
2176 getIdentTyPointerTy(), // loc
2177 CGM.Int32Ty, // tid
2178 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2179 PtrTy, // p_lower
2180 PtrTy, // p_upper
2181 PtrTy // p_stride
2182 };
2183 llvm::FunctionType *FnTy =
2184 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2185 return CGM.CreateRuntimeFunction(FnTy, Name);
2186}
2187
Alexey Bataev97720002014-11-11 04:05:39 +00002188llvm::Constant *
2189CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002190 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2191 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002192 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002193 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002194 Twine(CGM.getMangledName(VD)) + ".cache.");
2195}
2196
John McCall7f416cc2015-09-08 08:05:57 +00002197Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2198 const VarDecl *VD,
2199 Address VDAddr,
2200 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002201 if (CGM.getLangOpts().OpenMPUseTLS &&
2202 CGM.getContext().getTargetInfo().isTLSSupported())
2203 return VDAddr;
2204
John McCall7f416cc2015-09-08 08:05:57 +00002205 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002206 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002207 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2208 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002209 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2210 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002211 return Address(CGF.EmitRuntimeCall(
2212 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2213 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002214}
2215
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002216void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002217 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002218 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2219 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2220 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002221 auto OMPLoc = emitUpdateLocation(CGF, Loc);
2222 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002223 OMPLoc);
2224 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2225 // to register constructor/destructor for variable.
2226 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00002227 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2228 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002229 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002230 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002231 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002232}
2233
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002234llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002235 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002236 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002237 if (CGM.getLangOpts().OpenMPUseTLS &&
2238 CGM.getContext().getTargetInfo().isTLSSupported())
2239 return nullptr;
2240
Alexey Bataev97720002014-11-11 04:05:39 +00002241 VD = VD->getDefinition(CGM.getContext());
2242 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
2243 ThreadPrivateWithDefinition.insert(VD);
2244 QualType ASTTy = VD->getType();
2245
2246 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
2247 auto Init = VD->getAnyInitializer();
2248 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2249 // Generate function that re-emits the declaration's initializer into the
2250 // threadprivate copy of the variable VD
2251 CodeGenFunction CtorCGF(CGM);
2252 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002253 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
2254 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002255 Args.push_back(&Dst);
2256
John McCallc56a8b32016-03-11 04:30:31 +00002257 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2258 CGM.getContext().VoidPtrTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002259 auto FTy = CGM.getTypes().GetFunctionType(FI);
2260 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002261 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002262 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
2263 Args, SourceLocation());
2264 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002265 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002266 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002267 Address Arg = Address(ArgVal, VDAddr.getAlignment());
2268 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
2269 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002270 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2271 /*IsInitializer=*/true);
2272 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002273 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002274 CGM.getContext().VoidPtrTy, Dst.getLocation());
2275 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2276 CtorCGF.FinishFunction();
2277 Ctor = Fn;
2278 }
2279 if (VD->getType().isDestructedType() != QualType::DK_none) {
2280 // Generate function that emits destructor call for the threadprivate copy
2281 // of the variable VD
2282 CodeGenFunction DtorCGF(CGM);
2283 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002284 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
2285 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002286 Args.push_back(&Dst);
2287
John McCallc56a8b32016-03-11 04:30:31 +00002288 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2289 CGM.getContext().VoidTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002290 auto FTy = CGM.getTypes().GetFunctionType(FI);
2291 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002292 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002293 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002294 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
2295 SourceLocation());
Adrian Prantl1858c662016-04-24 22:22:29 +00002296 // Create a scope with an artificial location for the body of this function.
2297 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002298 auto ArgVal = DtorCGF.EmitLoadOfScalar(
2299 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002300 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2301 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002302 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2303 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2304 DtorCGF.FinishFunction();
2305 Dtor = Fn;
2306 }
2307 // Do not emit init function if it is not required.
2308 if (!Ctor && !Dtor)
2309 return nullptr;
2310
2311 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
2312 auto CopyCtorTy =
2313 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2314 /*isVarArg=*/false)->getPointerTo();
2315 // Copying constructor for the threadprivate variable.
2316 // Must be NULL - reserved by runtime, but currently it requires that this
2317 // parameter is always NULL. Otherwise it fires assertion.
2318 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2319 if (Ctor == nullptr) {
2320 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2321 /*isVarArg=*/false)->getPointerTo();
2322 Ctor = llvm::Constant::getNullValue(CtorTy);
2323 }
2324 if (Dtor == nullptr) {
2325 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2326 /*isVarArg=*/false)->getPointerTo();
2327 Dtor = llvm::Constant::getNullValue(DtorTy);
2328 }
2329 if (!CGF) {
2330 auto InitFunctionTy =
2331 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
2332 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002333 InitFunctionTy, ".__omp_threadprivate_init_.",
2334 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002335 CodeGenFunction InitCGF(CGM);
2336 FunctionArgList ArgList;
2337 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2338 CGM.getTypes().arrangeNullaryFunction(), ArgList,
2339 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002340 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002341 InitCGF.FinishFunction();
2342 return InitFunction;
2343 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002344 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002345 }
2346 return nullptr;
2347}
2348
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002349Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2350 QualType VarType,
2351 StringRef Name) {
2352 llvm::Twine VarName(Name, ".artificial.");
2353 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
2354 llvm::Value *GAddr = getOrCreateInternalVariable(VarLVType, VarName);
2355 llvm::Value *Args[] = {
2356 emitUpdateLocation(CGF, SourceLocation()),
2357 getThreadID(CGF, SourceLocation()),
2358 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2359 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2360 /*IsSigned=*/false),
2361 getOrCreateInternalVariable(CGM.VoidPtrPtrTy, VarName + ".cache.")};
2362 return Address(
2363 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2364 CGF.EmitRuntimeCall(
2365 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2366 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2367 CGM.getPointerAlign());
2368}
2369
Alexey Bataev1d677132015-04-22 13:57:31 +00002370/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
2371/// function. Here is the logic:
2372/// if (Cond) {
2373/// ThenGen();
2374/// } else {
2375/// ElseGen();
2376/// }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002377void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2378 const RegionCodeGenTy &ThenGen,
2379 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002380 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2381
2382 // If the condition constant folds and can be elided, try to avoid emitting
2383 // the condition and the dead arm of the if/else.
2384 bool CondConstant;
2385 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002386 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002387 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002388 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002389 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002390 return;
2391 }
2392
2393 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2394 // emit the conditional branch.
2395 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
2396 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
2397 auto ContBlock = CGF.createBasicBlock("omp_if.end");
2398 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2399
2400 // Emit the 'then' code.
2401 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002402 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002403 CGF.EmitBranch(ContBlock);
2404 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002405 // There is no need to emit line number for unconditional branch.
2406 (void)ApplyDebugLocation::CreateEmpty(CGF);
2407 CGF.EmitBlock(ElseBlock);
2408 ElseGen(CGF);
2409 // There is no need to emit line number for unconditional branch.
2410 (void)ApplyDebugLocation::CreateEmpty(CGF);
2411 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002412 // Emit the continuation block for code after the if.
2413 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002414}
2415
Alexey Bataev1d677132015-04-22 13:57:31 +00002416void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2417 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002418 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002419 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002420 if (!CGF.HaveInsertPoint())
2421 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00002422 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002423 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2424 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002425 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002426 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002427 llvm::Value *Args[] = {
2428 RTLoc,
2429 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002430 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002431 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2432 RealArgs.append(std::begin(Args), std::end(Args));
2433 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2434
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002435 auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002436 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2437 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002438 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2439 PrePostActionTy &) {
2440 auto &RT = CGF.CGM.getOpenMPRuntime();
2441 auto ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00002442 // Build calls:
2443 // __kmpc_serialized_parallel(&Loc, GTid);
2444 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002445 CGF.EmitRuntimeCall(
2446 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002447
Alexey Bataev1d677132015-04-22 13:57:31 +00002448 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002449 auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00002450 Address ZeroAddr =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002451 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
2452 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00002453 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00002454 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2455 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2456 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2457 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002458 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002459
Alexey Bataev1d677132015-04-22 13:57:31 +00002460 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002461 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00002462 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002463 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2464 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002465 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002466 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00002467 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002468 else {
2469 RegionCodeGenTy ThenRCG(ThenGen);
2470 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002471 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002472}
2473
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002474// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002475// thread-ID variable (it is passed in a first argument of the outlined function
2476// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2477// regular serial code region, get thread ID by calling kmp_int32
2478// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2479// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002480Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2481 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002482 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002483 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002484 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002485 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002486
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002487 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002488 auto Int32Ty =
2489 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2490 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2491 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002492 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002493
2494 return ThreadIDTemp;
2495}
2496
Alexey Bataev97720002014-11-11 04:05:39 +00002497llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002498CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002499 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002500 SmallString<256> Buffer;
2501 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002502 Out << Name;
2503 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00002504 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
2505 if (Elem.second) {
2506 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002507 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002508 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002509 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002510
David Blaikie13156b62014-11-19 03:06:06 +00002511 return Elem.second = new llvm::GlobalVariable(
2512 CGM.getModule(), Ty, /*IsConstant*/ false,
2513 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2514 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002515}
2516
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002517llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00002518 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002519 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002520}
2521
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002522namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002523/// Common pre(post)-action for different OpenMP constructs.
2524class CommonActionTy final : public PrePostActionTy {
2525 llvm::Value *EnterCallee;
2526 ArrayRef<llvm::Value *> EnterArgs;
2527 llvm::Value *ExitCallee;
2528 ArrayRef<llvm::Value *> ExitArgs;
2529 bool Conditional;
2530 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002531
2532public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002533 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2534 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2535 bool Conditional = false)
2536 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2537 ExitArgs(ExitArgs), Conditional(Conditional) {}
2538 void Enter(CodeGenFunction &CGF) override {
2539 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2540 if (Conditional) {
2541 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2542 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2543 ContBlock = CGF.createBasicBlock("omp_if.end");
2544 // Generate the branch (If-stmt)
2545 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2546 CGF.EmitBlock(ThenBlock);
2547 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002548 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002549 void Done(CodeGenFunction &CGF) {
2550 // Emit the rest of blocks/branches
2551 CGF.EmitBranch(ContBlock);
2552 CGF.EmitBlock(ContBlock, true);
2553 }
2554 void Exit(CodeGenFunction &CGF) override {
2555 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002556 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002557};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002558} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002559
2560void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2561 StringRef CriticalName,
2562 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002563 SourceLocation Loc, const Expr *Hint) {
2564 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002565 // CriticalOpGen();
2566 // __kmpc_end_critical(ident_t *, gtid, Lock);
2567 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002568 if (!CGF.HaveInsertPoint())
2569 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002570 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2571 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002572 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2573 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002574 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002575 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2576 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2577 }
2578 CommonActionTy Action(
2579 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2580 : OMPRTL__kmpc_critical),
2581 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2582 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002583 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002584}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002585
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002586void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002587 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002588 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002589 if (!CGF.HaveInsertPoint())
2590 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002591 // if(__kmpc_master(ident_t *, gtid)) {
2592 // MasterOpGen();
2593 // __kmpc_end_master(ident_t *, gtid);
2594 // }
2595 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002596 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002597 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2598 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2599 /*Conditional=*/true);
2600 MasterOpGen.setAction(Action);
2601 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2602 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002603}
2604
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002605void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2606 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002607 if (!CGF.HaveInsertPoint())
2608 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00002609 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2610 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002611 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00002612 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002613 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002614 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2615 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00002616}
2617
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002618void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2619 const RegionCodeGenTy &TaskgroupOpGen,
2620 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002621 if (!CGF.HaveInsertPoint())
2622 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002623 // __kmpc_taskgroup(ident_t *, gtid);
2624 // TaskgroupOpGen();
2625 // __kmpc_end_taskgroup(ident_t *, gtid);
2626 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002627 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2628 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2629 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2630 Args);
2631 TaskgroupOpGen.setAction(Action);
2632 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002633}
2634
John McCall7f416cc2015-09-08 08:05:57 +00002635/// Given an array of pointers to variables, project the address of a
2636/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002637static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2638 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00002639 // Pull out the pointer to the variable.
2640 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002641 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00002642 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2643
2644 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002645 Addr = CGF.Builder.CreateElementBitCast(
2646 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002647 return Addr;
2648}
2649
Alexey Bataeva63048e2015-03-23 06:18:07 +00002650static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00002651 CodeGenModule &CGM, llvm::Type *ArgsType,
2652 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
2653 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002654 auto &C = CGM.getContext();
2655 // void copy_func(void *LHSArg, void *RHSArg);
2656 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002657 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
2658 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002659 Args.push_back(&LHSArg);
2660 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00002661 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002662 auto *Fn = llvm::Function::Create(
2663 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2664 ".omp.copyprivate.copy_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002665 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002666 CodeGenFunction CGF(CGM);
2667 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00002668 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002669 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00002670 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2671 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2672 ArgsType), CGF.getPointerAlign());
2673 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2674 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2675 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002676 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2677 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2678 // ...
2679 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00002680 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002681 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2682 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2683
2684 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2685 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2686
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002687 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2688 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00002689 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002690 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002691 CGF.FinishFunction();
2692 return Fn;
2693}
2694
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002695void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002696 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00002697 SourceLocation Loc,
2698 ArrayRef<const Expr *> CopyprivateVars,
2699 ArrayRef<const Expr *> SrcExprs,
2700 ArrayRef<const Expr *> DstExprs,
2701 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002702 if (!CGF.HaveInsertPoint())
2703 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002704 assert(CopyprivateVars.size() == SrcExprs.size() &&
2705 CopyprivateVars.size() == DstExprs.size() &&
2706 CopyprivateVars.size() == AssignmentOps.size());
2707 auto &C = CGM.getContext();
2708 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002709 // if(__kmpc_single(ident_t *, gtid)) {
2710 // SingleOpGen();
2711 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002712 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002713 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002714 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2715 // <copy_func>, did_it);
2716
John McCall7f416cc2015-09-08 08:05:57 +00002717 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00002718 if (!CopyprivateVars.empty()) {
2719 // int32 did_it = 0;
2720 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2721 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00002722 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002723 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002724 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002725 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002726 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
2727 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
2728 /*Conditional=*/true);
2729 SingleOpGen.setAction(Action);
2730 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2731 if (DidIt.isValid()) {
2732 // did_it = 1;
2733 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2734 }
2735 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002736 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2737 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00002738 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002739 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2740 auto CopyprivateArrayTy =
2741 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2742 /*IndexTypeQuals=*/0);
2743 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00002744 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00002745 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2746 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002747 Address Elem = CGF.Builder.CreateConstArrayGEP(
2748 CopyprivateList, I, CGF.getPointerSize());
2749 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00002750 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002751 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2752 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002753 }
2754 // Build function that copies private values from single region to all other
2755 // threads in the corresponding parallel region.
2756 auto *CpyFn = emitCopyprivateCopyFunction(
2757 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00002758 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev1189bd02016-01-26 12:20:39 +00002759 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00002760 Address CL =
2761 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2762 CGF.VoidPtrTy);
2763 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002764 llvm::Value *Args[] = {
2765 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2766 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00002767 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00002768 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00002769 CpyFn, // void (*) (void *, void *) <copy_func>
2770 DidItVal // i32 did_it
2771 };
2772 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2773 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002774}
2775
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002776void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2777 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00002778 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002779 if (!CGF.HaveInsertPoint())
2780 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002781 // __kmpc_ordered(ident_t *, gtid);
2782 // OrderedOpGen();
2783 // __kmpc_end_ordered(ident_t *, gtid);
2784 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00002785 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002786 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002787 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
2788 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2789 Args);
2790 OrderedOpGen.setAction(Action);
2791 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2792 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002793 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002794 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002795}
2796
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002797void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002798 OpenMPDirectiveKind Kind, bool EmitChecks,
2799 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002800 if (!CGF.HaveInsertPoint())
2801 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002802 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002803 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002804 unsigned Flags;
2805 if (Kind == OMPD_for)
2806 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2807 else if (Kind == OMPD_sections)
2808 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2809 else if (Kind == OMPD_single)
2810 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2811 else if (Kind == OMPD_barrier)
2812 Flags = OMP_IDENT_BARRIER_EXPL;
2813 else
2814 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002815 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2816 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002817 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2818 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002819 if (auto *OMPRegionInfo =
2820 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00002821 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002822 auto *Result = CGF.EmitRuntimeCall(
2823 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002824 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002825 // if (__kmpc_cancel_barrier()) {
2826 // exit from construct;
2827 // }
2828 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2829 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2830 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2831 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2832 CGF.EmitBlock(ExitBB);
2833 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002834 auto CancelDestination =
2835 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002836 CGF.EmitBranchThroughCleanup(CancelDestination);
2837 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2838 }
2839 return;
2840 }
2841 }
2842 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002843}
2844
Alexander Musmanc6388682014-12-15 07:07:06 +00002845/// \brief Map the OpenMP loop schedule to the runtime enumeration.
2846static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002847 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002848 switch (ScheduleKind) {
2849 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002850 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2851 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00002852 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002853 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002854 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002855 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002856 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002857 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2858 case OMPC_SCHEDULE_auto:
2859 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00002860 case OMPC_SCHEDULE_unknown:
2861 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002862 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00002863 }
2864 llvm_unreachable("Unexpected runtime schedule");
2865}
2866
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002867/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
2868static OpenMPSchedType
2869getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2870 // only static is allowed for dist_schedule
2871 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
2872}
2873
Alexander Musmanc6388682014-12-15 07:07:06 +00002874bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2875 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002876 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00002877 return Schedule == OMP_sch_static;
2878}
2879
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002880bool CGOpenMPRuntime::isStaticNonchunked(
2881 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2882 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2883 return Schedule == OMP_dist_sch_static;
2884}
2885
2886
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002887bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002888 auto Schedule =
2889 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002890 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2891 return Schedule != OMP_sch_static;
2892}
2893
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002894static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
2895 OpenMPScheduleClauseModifier M1,
2896 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00002897 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002898 switch (M1) {
2899 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002900 Modifier = OMP_sch_modifier_monotonic;
2901 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002902 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002903 Modifier = OMP_sch_modifier_nonmonotonic;
2904 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002905 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002906 if (Schedule == OMP_sch_static_chunked)
2907 Schedule = OMP_sch_static_balanced_chunked;
2908 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002909 case OMPC_SCHEDULE_MODIFIER_last:
2910 case OMPC_SCHEDULE_MODIFIER_unknown:
2911 break;
2912 }
2913 switch (M2) {
2914 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002915 Modifier = OMP_sch_modifier_monotonic;
2916 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002917 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002918 Modifier = OMP_sch_modifier_nonmonotonic;
2919 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002920 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002921 if (Schedule == OMP_sch_static_chunked)
2922 Schedule = OMP_sch_static_balanced_chunked;
2923 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002924 case OMPC_SCHEDULE_MODIFIER_last:
2925 case OMPC_SCHEDULE_MODIFIER_unknown:
2926 break;
2927 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00002928 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002929}
2930
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002931void CGOpenMPRuntime::emitForDispatchInit(
2932 CodeGenFunction &CGF, SourceLocation Loc,
2933 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
2934 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002935 if (!CGF.HaveInsertPoint())
2936 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002937 OpenMPSchedType Schedule = getRuntimeSchedule(
2938 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00002939 assert(Ordered ||
2940 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00002941 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
2942 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00002943 // Call __kmpc_dispatch_init(
2944 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2945 // kmp_int[32|64] lower, kmp_int[32|64] upper,
2946 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002947
John McCall7f416cc2015-09-08 08:05:57 +00002948 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002949 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
2950 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00002951 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002952 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2953 CGF.Builder.getInt32(addMonoNonMonoModifier(
2954 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002955 DispatchValues.LB, // Lower
2956 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002957 CGF.Builder.getIntN(IVSize, 1), // Stride
2958 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00002959 };
2960 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2961}
2962
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002963static void emitForStaticInitCall(
2964 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
2965 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
2966 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002967 const CGOpenMPRuntime::StaticRTInput &Values) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002968 if (!CGF.HaveInsertPoint())
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002969 return;
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002970
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002971 assert(!Values.Ordered);
2972 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
2973 Schedule == OMP_sch_static_balanced_chunked ||
2974 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
2975 Schedule == OMP_dist_sch_static ||
2976 Schedule == OMP_dist_sch_static_chunked);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002977
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00002978 // Call __kmpc_for_static_init(
2979 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2980 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2981 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2982 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
2983 llvm::Value *Chunk = Values.Chunk;
2984 if (Chunk == nullptr) {
2985 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
2986 Schedule == OMP_dist_sch_static) &&
2987 "expected static non-chunked schedule");
2988 // If the Chunk was not specified in the clause - use default value 1.
2989 Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
2990 } else {
2991 assert((Schedule == OMP_sch_static_chunked ||
2992 Schedule == OMP_sch_static_balanced_chunked ||
2993 Schedule == OMP_ord_static_chunked ||
2994 Schedule == OMP_dist_sch_static_chunked) &&
2995 "expected static chunked schedule");
2996 }
2997 llvm::Value *Args[] = {
2998 UpdateLocation,
2999 ThreadId,
3000 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1,
3001 M2)), // Schedule type
3002 Values.IL.getPointer(), // &isLastIter
3003 Values.LB.getPointer(), // &LB
3004 Values.UB.getPointer(), // &UB
3005 Values.ST.getPointer(), // &Stride
3006 CGF.Builder.getIntN(Values.IVSize, 1), // Incr
3007 Chunk // Chunk
3008 };
3009 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003010}
3011
John McCall7f416cc2015-09-08 08:05:57 +00003012void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3013 SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003014 OpenMPDirectiveKind DKind,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003015 const OpenMPScheduleTy &ScheduleKind,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003016 const StaticRTInput &Values) {
3017 OpenMPSchedType ScheduleNum = getRuntimeSchedule(
3018 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
3019 assert(isOpenMPWorksharingDirective(DKind) &&
3020 "Expected loop-based or sections-based directive.");
3021 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc,
3022 isOpenMPLoopDirective(DKind)
3023 ? OMP_IDENT_WORK_LOOP
3024 : OMP_IDENT_WORK_SECTIONS);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003025 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003026 auto *StaticInitFunction =
3027 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003028 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003029 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003030}
John McCall7f416cc2015-09-08 08:05:57 +00003031
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003032void CGOpenMPRuntime::emitDistributeStaticInit(
3033 CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003034 OpenMPDistScheduleClauseKind SchedKind,
3035 const CGOpenMPRuntime::StaticRTInput &Values) {
3036 OpenMPSchedType ScheduleNum =
3037 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
3038 auto *UpdatedLocation =
3039 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003040 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003041 auto *StaticInitFunction =
3042 createForStaticInitFunction(Values.IVSize, Values.IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003043 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3044 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
Alexey Bataev0f87dbe2017-08-14 17:56:13 +00003045 OMPC_SCHEDULE_MODIFIER_unknown, Values);
Alexander Musmanc6388682014-12-15 07:07:06 +00003046}
3047
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003048void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
3049 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003050 if (!CGF.HaveInsertPoint())
3051 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003052 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003053 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003054 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3055 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003056}
3057
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003058void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3059 SourceLocation Loc,
3060 unsigned IVSize,
3061 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003062 if (!CGF.HaveInsertPoint())
3063 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003064 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003065 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003066 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3067}
3068
Alexander Musman92bdaab2015-03-12 13:37:50 +00003069llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3070 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003071 bool IVSigned, Address IL,
3072 Address LB, Address UB,
3073 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003074 // Call __kmpc_dispatch_next(
3075 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3076 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3077 // kmp_int[32|64] *p_stride);
3078 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003079 emitUpdateLocation(CGF, Loc),
3080 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003081 IL.getPointer(), // &isLastIter
3082 LB.getPointer(), // &Lower
3083 UB.getPointer(), // &Upper
3084 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003085 };
3086 llvm::Value *Call =
3087 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3088 return CGF.EmitScalarConversion(
3089 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003090 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003091}
3092
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003093void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3094 llvm::Value *NumThreads,
3095 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003096 if (!CGF.HaveInsertPoint())
3097 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003098 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3099 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003100 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003101 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003102 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3103 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003104}
3105
Alexey Bataev7f210c62015-06-18 13:40:03 +00003106void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3107 OpenMPProcBindClauseKind ProcBind,
3108 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003109 if (!CGF.HaveInsertPoint())
3110 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003111 // Constants for proc bind value accepted by the runtime.
3112 enum ProcBindTy {
3113 ProcBindFalse = 0,
3114 ProcBindTrue,
3115 ProcBindMaster,
3116 ProcBindClose,
3117 ProcBindSpread,
3118 ProcBindIntel,
3119 ProcBindDefault
3120 } RuntimeProcBind;
3121 switch (ProcBind) {
3122 case OMPC_PROC_BIND_master:
3123 RuntimeProcBind = ProcBindMaster;
3124 break;
3125 case OMPC_PROC_BIND_close:
3126 RuntimeProcBind = ProcBindClose;
3127 break;
3128 case OMPC_PROC_BIND_spread:
3129 RuntimeProcBind = ProcBindSpread;
3130 break;
3131 case OMPC_PROC_BIND_unknown:
3132 llvm_unreachable("Unsupported proc_bind value.");
3133 }
3134 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3135 llvm::Value *Args[] = {
3136 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3137 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3138 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3139}
3140
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003141void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3142 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003143 if (!CGF.HaveInsertPoint())
3144 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003145 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003146 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3147 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003148}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003149
Alexey Bataev62b63b12015-03-10 07:28:44 +00003150namespace {
3151/// \brief Indexes of fields for type kmp_task_t.
3152enum KmpTaskTFields {
3153 /// \brief List of shared variables.
3154 KmpTaskTShareds,
3155 /// \brief Task routine.
3156 KmpTaskTRoutine,
3157 /// \brief Partition id for the untied tasks.
3158 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003159 /// Function with call of destructors for private variables.
3160 Data1,
3161 /// Task priority.
3162 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003163 /// (Taskloops only) Lower bound.
3164 KmpTaskTLowerBound,
3165 /// (Taskloops only) Upper bound.
3166 KmpTaskTUpperBound,
3167 /// (Taskloops only) Stride.
3168 KmpTaskTStride,
3169 /// (Taskloops only) Is last iteration flag.
3170 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003171 /// (Taskloops only) Reduction data.
3172 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003173};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003174} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003175
Samuel Antaoee8fb302016-01-06 13:42:12 +00003176bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
3177 // FIXME: Add other entries type when they become supported.
3178 return OffloadEntriesTargetRegion.empty();
3179}
3180
3181/// \brief Initialize target region entry.
3182void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3183 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3184 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003185 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003186 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3187 "only required for the device "
3188 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003189 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003190 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
3191 /*Flags=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003192 ++OffloadingEntriesNum;
3193}
3194
3195void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3196 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3197 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003198 llvm::Constant *Addr, llvm::Constant *ID,
3199 int32_t Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003200 // If we are emitting code for a target, the entry is already initialized,
3201 // only has to be registered.
3202 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003203 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00003204 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003205 auto &Entry =
3206 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003207 assert(Entry.isValid() && "Entry not initialized!");
3208 Entry.setAddress(Addr);
3209 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003210 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003211 return;
3212 } else {
Samuel Antaof83efdb2017-01-05 16:02:49 +00003213 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003214 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003215 }
3216}
3217
3218bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003219 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3220 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003221 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3222 if (PerDevice == OffloadEntriesTargetRegion.end())
3223 return false;
3224 auto PerFile = PerDevice->second.find(FileID);
3225 if (PerFile == PerDevice->second.end())
3226 return false;
3227 auto PerParentName = PerFile->second.find(ParentName);
3228 if (PerParentName == PerFile->second.end())
3229 return false;
3230 auto PerLine = PerParentName->second.find(LineNum);
3231 if (PerLine == PerParentName->second.end())
3232 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003233 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003234 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003235 return false;
3236 return true;
3237}
3238
3239void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3240 const OffloadTargetRegionEntryInfoActTy &Action) {
3241 // Scan all target region entries and perform the provided action.
3242 for (auto &D : OffloadEntriesTargetRegion)
3243 for (auto &F : D.second)
3244 for (auto &P : F.second)
3245 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003246 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003247}
3248
3249/// \brief Create a Ctor/Dtor-like function whose body is emitted through
3250/// \a Codegen. This is used to emit the two functions that register and
3251/// unregister the descriptor of the current compilation unit.
3252static llvm::Function *
3253createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
3254 const RegionCodeGenTy &Codegen) {
3255 auto &C = CGM.getContext();
3256 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003257 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003258 Args.push_back(&DummyPtr);
3259
3260 CodeGenFunction CGF(CGM);
John McCallc56a8b32016-03-11 04:30:31 +00003261 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003262 auto FTy = CGM.getTypes().GetFunctionType(FI);
3263 auto *Fn =
3264 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
3265 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
3266 Codegen(CGF);
3267 CGF.FinishFunction();
3268 return Fn;
3269}
3270
3271llvm::Function *
3272CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
3273
3274 // If we don't have entries or if we are emitting code for the device, we
3275 // don't need to do anything.
3276 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3277 return nullptr;
3278
3279 auto &M = CGM.getModule();
3280 auto &C = CGM.getContext();
3281
3282 // Get list of devices we care about
3283 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
3284
3285 // We should be creating an offloading descriptor only if there are devices
3286 // specified.
3287 assert(!Devices.empty() && "No OpenMP offloading devices??");
3288
3289 // Create the external variables that will point to the begin and end of the
3290 // host entries section. These will be defined by the linker.
3291 auto *OffloadEntryTy =
3292 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
3293 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
3294 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003295 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003296 ".omp_offloading.entries_begin");
3297 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
3298 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003299 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003300 ".omp_offloading.entries_end");
3301
3302 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003303 auto *DeviceImageTy = cast<llvm::StructType>(
3304 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003305 ConstantInitBuilder DeviceImagesBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003306 auto DeviceImagesEntries = DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003307
3308 for (unsigned i = 0; i < Devices.size(); ++i) {
3309 StringRef T = Devices[i].getTriple();
3310 auto *ImgBegin = new llvm::GlobalVariable(
3311 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003312 /*Initializer=*/nullptr,
3313 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003314 auto *ImgEnd = new llvm::GlobalVariable(
3315 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003316 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003317
John McCall6c9f1fdb2016-11-19 08:17:24 +00003318 auto Dev = DeviceImagesEntries.beginStruct(DeviceImageTy);
3319 Dev.add(ImgBegin);
3320 Dev.add(ImgEnd);
3321 Dev.add(HostEntriesBegin);
3322 Dev.add(HostEntriesEnd);
John McCallf1788632016-11-28 22:18:30 +00003323 Dev.finishAndAddTo(DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003324 }
3325
3326 // Create device images global array.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003327 llvm::GlobalVariable *DeviceImages =
3328 DeviceImagesEntries.finishAndCreateGlobal(".omp_offloading.device_images",
3329 CGM.getPointerAlign(),
3330 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003331 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003332
3333 // This is a Zero array to be used in the creation of the constant expressions
3334 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3335 llvm::Constant::getNullValue(CGM.Int32Ty)};
3336
3337 // Create the target region descriptor.
3338 auto *BinaryDescriptorTy = cast<llvm::StructType>(
3339 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003340 ConstantInitBuilder DescBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003341 auto DescInit = DescBuilder.beginStruct(BinaryDescriptorTy);
3342 DescInit.addInt(CGM.Int32Ty, Devices.size());
3343 DescInit.add(llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3344 DeviceImages,
3345 Index));
3346 DescInit.add(HostEntriesBegin);
3347 DescInit.add(HostEntriesEnd);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003348
John McCall6c9f1fdb2016-11-19 08:17:24 +00003349 auto *Desc = DescInit.finishAndCreateGlobal(".omp_offloading.descriptor",
3350 CGM.getPointerAlign(),
3351 /*isConstant=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003352
3353 // Emit code to register or unregister the descriptor at execution
3354 // startup or closing, respectively.
3355
3356 // Create a variable to drive the registration and unregistration of the
3357 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3358 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
3359 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00003360 IdentInfo, C.CharTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003361
3362 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003363 CGM, ".omp_offloading.descriptor_unreg",
3364 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00003365 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3366 Desc);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003367 });
3368 auto *RegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003369 CGM, ".omp_offloading.descriptor_reg",
3370 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00003371 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib),
3372 Desc);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003373 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3374 });
George Rokos29d0f002017-05-27 03:03:13 +00003375 if (CGM.supportsCOMDAT()) {
3376 // It is sufficient to call registration function only once, so create a
3377 // COMDAT group for registration/unregistration functions and associated
3378 // data. That would reduce startup time and code size. Registration
3379 // function serves as a COMDAT group key.
3380 auto ComdatKey = M.getOrInsertComdat(RegFn->getName());
3381 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3382 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3383 RegFn->setComdat(ComdatKey);
3384 UnRegFn->setComdat(ComdatKey);
3385 DeviceImages->setComdat(ComdatKey);
3386 Desc->setComdat(ComdatKey);
3387 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003388 return RegFn;
3389}
3390
Samuel Antao2de62b02016-02-13 23:35:10 +00003391void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003392 llvm::Constant *Addr, uint64_t Size,
3393 int32_t Flags) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003394 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003395 auto *TgtOffloadEntryType = cast<llvm::StructType>(
3396 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
3397 llvm::LLVMContext &C = CGM.getModule().getContext();
3398 llvm::Module &M = CGM.getModule();
3399
3400 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00003401 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003402
3403 // Create constant string with the name.
3404 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3405
3406 llvm::GlobalVariable *Str =
3407 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
3408 llvm::GlobalValue::InternalLinkage, StrPtrInit,
3409 ".omp_offloading.entry_name");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003410 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003411 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
3412
John McCall6c9f1fdb2016-11-19 08:17:24 +00003413 // We can't have any padding between symbols, so we need to have 1-byte
3414 // alignment.
3415 auto Align = CharUnits::fromQuantity(1);
3416
Samuel Antaoee8fb302016-01-06 13:42:12 +00003417 // Create the entry struct.
John McCall23c9dc62016-11-28 22:18:27 +00003418 ConstantInitBuilder EntryBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003419 auto EntryInit = EntryBuilder.beginStruct(TgtOffloadEntryType);
3420 EntryInit.add(AddrPtr);
3421 EntryInit.add(StrPtr);
3422 EntryInit.addInt(CGM.SizeTy, Size);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003423 EntryInit.addInt(CGM.Int32Ty, Flags);
3424 EntryInit.addInt(CGM.Int32Ty, 0);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003425 llvm::GlobalVariable *Entry =
3426 EntryInit.finishAndCreateGlobal(".omp_offloading.entry",
3427 Align,
3428 /*constant*/ true,
3429 llvm::GlobalValue::ExternalLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003430
3431 // The entry has to be created in the section the linker expects it to be.
3432 Entry->setSection(".omp_offloading.entries");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003433}
3434
3435void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3436 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003437 // can easily figure out what to emit. The produced metadata looks like
3438 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003439 //
3440 // !omp_offload.info = !{!1, ...}
3441 //
3442 // Right now we only generate metadata for function that contain target
3443 // regions.
3444
3445 // If we do not have entries, we dont need to do anything.
3446 if (OffloadEntriesInfoManager.empty())
3447 return;
3448
3449 llvm::Module &M = CGM.getModule();
3450 llvm::LLVMContext &C = M.getContext();
3451 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
3452 OrderedEntries(OffloadEntriesInfoManager.size());
3453
3454 // Create the offloading info metadata node.
3455 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
3456
Simon Pilgrim2c518802017-03-30 14:13:19 +00003457 // Auxiliary methods to create metadata values and strings.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003458 auto getMDInt = [&](unsigned v) {
3459 return llvm::ConstantAsMetadata::get(
3460 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
3461 };
3462
3463 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
3464
3465 // Create function that emits metadata for each target region entry;
3466 auto &&TargetRegionMetadataEmitter = [&](
3467 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003468 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3469 llvm::SmallVector<llvm::Metadata *, 32> Ops;
3470 // Generate metadata for target regions. Each entry of this metadata
3471 // contains:
3472 // - Entry 0 -> Kind of this type of metadata (0).
3473 // - Entry 1 -> Device ID of the file where the entry was identified.
3474 // - Entry 2 -> File ID of the file where the entry was identified.
3475 // - Entry 3 -> Mangled name of the function where the entry was identified.
3476 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00003477 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003478 // The first element of the metadata node is the kind.
3479 Ops.push_back(getMDInt(E.getKind()));
3480 Ops.push_back(getMDInt(DeviceID));
3481 Ops.push_back(getMDInt(FileID));
3482 Ops.push_back(getMDString(ParentName));
3483 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003484 Ops.push_back(getMDInt(E.getOrder()));
3485
3486 // Save this entry in the right position of the ordered entries array.
3487 OrderedEntries[E.getOrder()] = &E;
3488
3489 // Add metadata to the named metadata node.
3490 MD->addOperand(llvm::MDNode::get(C, Ops));
3491 };
3492
3493 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3494 TargetRegionMetadataEmitter);
3495
3496 for (auto *E : OrderedEntries) {
3497 assert(E && "All ordered entries must exist!");
3498 if (auto *CE =
3499 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3500 E)) {
3501 assert(CE->getID() && CE->getAddress() &&
3502 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00003503 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003504 } else
3505 llvm_unreachable("Unsupported entry kind.");
3506 }
3507}
3508
3509/// \brief Loads all the offload entries information from the host IR
3510/// metadata.
3511void CGOpenMPRuntime::loadOffloadInfoMetadata() {
3512 // If we are in target mode, load the metadata from the host IR. This code has
3513 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
3514
3515 if (!CGM.getLangOpts().OpenMPIsDevice)
3516 return;
3517
3518 if (CGM.getLangOpts().OMPHostIRFile.empty())
3519 return;
3520
3521 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
3522 if (Buf.getError())
3523 return;
3524
3525 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00003526 auto ME = expectedToErrorOrAndEmitErrors(
3527 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003528
3529 if (ME.getError())
3530 return;
3531
3532 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
3533 if (!MD)
3534 return;
3535
3536 for (auto I : MD->operands()) {
3537 llvm::MDNode *MN = cast<llvm::MDNode>(I);
3538
3539 auto getMDInt = [&](unsigned Idx) {
3540 llvm::ConstantAsMetadata *V =
3541 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
3542 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
3543 };
3544
3545 auto getMDString = [&](unsigned Idx) {
3546 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
3547 return V->getString();
3548 };
3549
3550 switch (getMDInt(0)) {
3551 default:
3552 llvm_unreachable("Unexpected metadata!");
3553 break;
3554 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3555 OFFLOAD_ENTRY_INFO_TARGET_REGION:
3556 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
3557 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
3558 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00003559 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003560 break;
3561 }
3562 }
3563}
3564
Alexey Bataev62b63b12015-03-10 07:28:44 +00003565void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
3566 if (!KmpRoutineEntryPtrTy) {
3567 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
3568 auto &C = CGM.getContext();
3569 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
3570 FunctionProtoType::ExtProtoInfo EPI;
3571 KmpRoutineEntryPtrQTy = C.getPointerType(
3572 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
3573 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
3574 }
3575}
3576
Alexey Bataevc71a4092015-09-11 10:29:41 +00003577static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
3578 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003579 auto *Field = FieldDecl::Create(
3580 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
3581 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
3582 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
3583 Field->setAccess(AS_public);
3584 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003585 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003586}
3587
Samuel Antaoee8fb302016-01-06 13:42:12 +00003588QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
3589
3590 // Make sure the type of the entry is already created. This is the type we
3591 // have to create:
3592 // struct __tgt_offload_entry{
3593 // void *addr; // Pointer to the offload entry info.
3594 // // (function or global)
3595 // char *name; // Name of the function or global.
3596 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00003597 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
3598 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003599 // };
3600 if (TgtOffloadEntryQTy.isNull()) {
3601 ASTContext &C = CGM.getContext();
3602 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
3603 RD->startDefinition();
3604 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3605 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
3606 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00003607 addFieldToRecordDecl(
3608 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3609 addFieldToRecordDecl(
3610 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003611 RD->completeDefinition();
3612 TgtOffloadEntryQTy = C.getRecordType(RD);
3613 }
3614 return TgtOffloadEntryQTy;
3615}
3616
3617QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
3618 // These are the types we need to build:
3619 // struct __tgt_device_image{
3620 // void *ImageStart; // Pointer to the target code start.
3621 // void *ImageEnd; // Pointer to the target code end.
3622 // // We also add the host entries to the device image, as it may be useful
3623 // // for the target runtime to have access to that information.
3624 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
3625 // // the entries.
3626 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3627 // // entries (non inclusive).
3628 // };
3629 if (TgtDeviceImageQTy.isNull()) {
3630 ASTContext &C = CGM.getContext();
3631 auto *RD = C.buildImplicitRecord("__tgt_device_image");
3632 RD->startDefinition();
3633 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3634 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3635 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3636 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3637 RD->completeDefinition();
3638 TgtDeviceImageQTy = C.getRecordType(RD);
3639 }
3640 return TgtDeviceImageQTy;
3641}
3642
3643QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
3644 // struct __tgt_bin_desc{
3645 // int32_t NumDevices; // Number of devices supported.
3646 // __tgt_device_image *DeviceImages; // Arrays of device images
3647 // // (one per device).
3648 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
3649 // // entries.
3650 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3651 // // entries (non inclusive).
3652 // };
3653 if (TgtBinaryDescriptorQTy.isNull()) {
3654 ASTContext &C = CGM.getContext();
3655 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
3656 RD->startDefinition();
3657 addFieldToRecordDecl(
3658 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3659 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
3660 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3661 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3662 RD->completeDefinition();
3663 TgtBinaryDescriptorQTy = C.getRecordType(RD);
3664 }
3665 return TgtBinaryDescriptorQTy;
3666}
3667
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003668namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00003669struct PrivateHelpersTy {
3670 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
3671 const VarDecl *PrivateElemInit)
3672 : Original(Original), PrivateCopy(PrivateCopy),
3673 PrivateElemInit(PrivateElemInit) {}
3674 const VarDecl *Original;
3675 const VarDecl *PrivateCopy;
3676 const VarDecl *PrivateElemInit;
3677};
3678typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00003679} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003680
Alexey Bataev9e034042015-05-05 04:05:12 +00003681static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00003682createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003683 if (!Privates.empty()) {
3684 auto &C = CGM.getContext();
3685 // Build struct .kmp_privates_t. {
3686 // /* private vars */
3687 // };
3688 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
3689 RD->startDefinition();
3690 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00003691 auto *VD = Pair.second.Original;
3692 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003693 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00003694 auto *FD = addFieldToRecordDecl(C, RD, Type);
3695 if (VD->hasAttrs()) {
3696 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
3697 E(VD->getAttrs().end());
3698 I != E; ++I)
3699 FD->addAttr(*I);
3700 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003701 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003702 RD->completeDefinition();
3703 return RD;
3704 }
3705 return nullptr;
3706}
3707
Alexey Bataev9e034042015-05-05 04:05:12 +00003708static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00003709createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
3710 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003711 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003712 auto &C = CGM.getContext();
3713 // Build struct kmp_task_t {
3714 // void * shareds;
3715 // kmp_routine_entry_t routine;
3716 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00003717 // kmp_cmplrdata_t data1;
3718 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00003719 // For taskloops additional fields:
3720 // kmp_uint64 lb;
3721 // kmp_uint64 ub;
3722 // kmp_int64 st;
3723 // kmp_int32 liter;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003724 // void * reductions;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003725 // };
Alexey Bataevad537bb2016-05-30 09:06:50 +00003726 auto *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
3727 UD->startDefinition();
3728 addFieldToRecordDecl(C, UD, KmpInt32Ty);
3729 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
3730 UD->completeDefinition();
3731 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003732 auto *RD = C.buildImplicitRecord("kmp_task_t");
3733 RD->startDefinition();
3734 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3735 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
3736 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00003737 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3738 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003739 if (isOpenMPTaskLoopDirective(Kind)) {
3740 QualType KmpUInt64Ty =
3741 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3742 QualType KmpInt64Ty =
3743 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3744 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3745 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3746 addFieldToRecordDecl(C, RD, KmpInt64Ty);
3747 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003748 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003749 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003750 RD->completeDefinition();
3751 return RD;
3752}
3753
3754static RecordDecl *
3755createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003756 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003757 auto &C = CGM.getContext();
3758 // Build struct kmp_task_t_with_privates {
3759 // kmp_task_t task_data;
3760 // .kmp_privates_t. privates;
3761 // };
3762 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
3763 RD->startDefinition();
3764 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003765 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
3766 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
3767 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003768 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003769 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003770}
3771
3772/// \brief Emit a proxy function which accepts kmp_task_t as the second
3773/// argument.
3774/// \code
3775/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003776/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00003777/// For taskloops:
3778/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003779/// tt->reductions, tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003780/// return 0;
3781/// }
3782/// \endcode
3783static llvm::Value *
3784emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00003785 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
3786 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003787 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003788 QualType SharedsPtrTy, llvm::Value *TaskFunction,
3789 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003790 auto &C = CGM.getContext();
3791 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003792 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3793 ImplicitParamDecl::Other);
3794 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3795 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3796 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003797 Args.push_back(&GtidArg);
3798 Args.push_back(&TaskTypeArg);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003799 auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003800 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003801 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
3802 auto *TaskEntry =
3803 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
3804 ".omp_task_entry.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003805 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003806 CodeGenFunction CGF(CGM);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003807 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
3808
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003809 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00003810 // tt,
3811 // For taskloops:
3812 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3813 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003814 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00003815 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003816 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3817 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3818 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003819 auto *KmpTaskTWithPrivatesQTyRD =
3820 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003821 LValue Base =
3822 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003823 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3824 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3825 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003826 auto *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003827
3828 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3829 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003830 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003831 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003832 CGF.ConvertTypeForMem(SharedsPtrTy));
3833
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003834 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3835 llvm::Value *PrivatesParam;
3836 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3837 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3838 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003839 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003840 } else
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003841 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003842
Alexey Bataev7292c292016-04-25 12:22:29 +00003843 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
3844 TaskPrivatesMap,
3845 CGF.Builder
3846 .CreatePointerBitCastOrAddrSpaceCast(
3847 TDBase.getAddress(), CGF.VoidPtrTy)
3848 .getPointer()};
3849 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
3850 std::end(CommonArgs));
3851 if (isOpenMPTaskLoopDirective(Kind)) {
3852 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
3853 auto LBLVal = CGF.EmitLValueForField(Base, *LBFI);
3854 auto *LBParam = CGF.EmitLoadOfLValue(LBLVal, Loc).getScalarVal();
3855 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
3856 auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
3857 auto *UBParam = CGF.EmitLoadOfLValue(UBLVal, Loc).getScalarVal();
3858 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
3859 auto StLVal = CGF.EmitLValueForField(Base, *StFI);
3860 auto *StParam = CGF.EmitLoadOfLValue(StLVal, Loc).getScalarVal();
3861 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3862 auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
3863 auto *LIParam = CGF.EmitLoadOfLValue(LILVal, Loc).getScalarVal();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003864 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
3865 auto RLVal = CGF.EmitLValueForField(Base, *RFI);
3866 auto *RParam = CGF.EmitLoadOfLValue(RLVal, Loc).getScalarVal();
Alexey Bataev7292c292016-04-25 12:22:29 +00003867 CallArgs.push_back(LBParam);
3868 CallArgs.push_back(UBParam);
3869 CallArgs.push_back(StParam);
3870 CallArgs.push_back(LIParam);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003871 CallArgs.push_back(RParam);
Alexey Bataev7292c292016-04-25 12:22:29 +00003872 }
3873 CallArgs.push_back(SharedsParam);
3874
Alexey Bataev3c595a62017-08-14 15:01:03 +00003875 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
3876 CallArgs);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003877 CGF.EmitStoreThroughLValue(
3878 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00003879 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00003880 CGF.FinishFunction();
3881 return TaskEntry;
3882}
3883
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003884static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
3885 SourceLocation Loc,
3886 QualType KmpInt32Ty,
3887 QualType KmpTaskTWithPrivatesPtrQTy,
3888 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003889 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003890 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003891 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3892 ImplicitParamDecl::Other);
3893 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3894 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3895 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003896 Args.push_back(&GtidArg);
3897 Args.push_back(&TaskTypeArg);
3898 FunctionType::ExtInfo Info;
3899 auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003900 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003901 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
3902 auto *DestructorFn =
3903 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
3904 ".omp_task_destructor.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003905 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
3906 DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003907 CodeGenFunction CGF(CGM);
3908 CGF.disableDebugInfo();
3909 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
3910 Args);
3911
Alexey Bataev31300ed2016-02-04 11:27:03 +00003912 LValue Base = CGF.EmitLoadOfPointerLValue(
3913 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3914 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003915 auto *KmpTaskTWithPrivatesQTyRD =
3916 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3917 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003918 Base = CGF.EmitLValueForField(Base, *FI);
3919 for (auto *Field :
3920 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
3921 if (auto DtorKind = Field->getType().isDestructedType()) {
3922 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
3923 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
3924 }
3925 }
3926 CGF.FinishFunction();
3927 return DestructorFn;
3928}
3929
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003930/// \brief Emit a privates mapping function for correct handling of private and
3931/// firstprivate variables.
3932/// \code
3933/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
3934/// **noalias priv1,..., <tyn> **noalias privn) {
3935/// *priv1 = &.privates.priv1;
3936/// ...;
3937/// *privn = &.privates.privn;
3938/// }
3939/// \endcode
3940static llvm::Value *
3941emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00003942 ArrayRef<const Expr *> PrivateVars,
3943 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00003944 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003945 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003946 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003947 auto &C = CGM.getContext();
3948 FunctionArgList Args;
3949 ImplicitParamDecl TaskPrivatesArg(
3950 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003951 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
3952 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003953 Args.push_back(&TaskPrivatesArg);
3954 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
3955 unsigned Counter = 1;
3956 for (auto *E: PrivateVars) {
3957 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003958 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3959 C.getPointerType(C.getPointerType(E->getType()))
3960 .withConst()
3961 .withRestrict(),
3962 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003963 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3964 PrivateVarsPos[VD] = Counter;
3965 ++Counter;
3966 }
3967 for (auto *E : FirstprivateVars) {
3968 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003969 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3970 C.getPointerType(C.getPointerType(E->getType()))
3971 .withConst()
3972 .withRestrict(),
3973 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003974 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3975 PrivateVarsPos[VD] = Counter;
3976 ++Counter;
3977 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003978 for (auto *E: LastprivateVars) {
3979 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003980 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3981 C.getPointerType(C.getPointerType(E->getType()))
3982 .withConst()
3983 .withRestrict(),
3984 ImplicitParamDecl::Other));
Alexey Bataevf93095a2016-05-05 08:46:22 +00003985 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3986 PrivateVarsPos[VD] = Counter;
3987 ++Counter;
3988 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003989 auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003990 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003991 auto *TaskPrivatesMapTy =
3992 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
3993 auto *TaskPrivatesMap = llvm::Function::Create(
3994 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
3995 ".omp_task_privates_map.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003996 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
3997 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00003998 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00003999 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00004000 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004001 CodeGenFunction CGF(CGM);
4002 CGF.disableDebugInfo();
4003 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
4004 TaskPrivatesMapFnInfo, Args);
4005
4006 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00004007 LValue Base = CGF.EmitLoadOfPointerLValue(
4008 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
4009 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004010 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
4011 Counter = 0;
4012 for (auto *Field : PrivatesQTyRD->fields()) {
4013 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
4014 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00004015 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00004016 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
4017 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00004018 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004019 ++Counter;
4020 }
4021 CGF.FinishFunction();
4022 return TaskPrivatesMap;
4023}
4024
Alexey Bataev9e034042015-05-05 04:05:12 +00004025static int array_pod_sort_comparator(const PrivateDataTy *P1,
4026 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004027 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
4028}
4029
Alexey Bataevf93095a2016-05-05 08:46:22 +00004030/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00004031static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004032 const OMPExecutableDirective &D,
4033 Address KmpTaskSharedsPtr, LValue TDBase,
4034 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4035 QualType SharedsTy, QualType SharedsPtrTy,
4036 const OMPTaskDataTy &Data,
4037 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
4038 auto &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004039 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4040 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
4041 LValue SrcBase;
4042 if (!Data.FirstprivateVars.empty()) {
4043 SrcBase = CGF.MakeAddrLValue(
4044 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4045 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4046 SharedsTy);
4047 }
4048 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
4049 cast<CapturedStmt>(*D.getAssociatedStmt()));
4050 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
4051 for (auto &&Pair : Privates) {
4052 auto *VD = Pair.second.PrivateCopy;
4053 auto *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004054 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4055 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004056 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004057 if (auto *Elem = Pair.second.PrivateElemInit) {
4058 auto *OriginalVD = Pair.second.Original;
4059 auto *SharedField = CapturesInfo.lookup(OriginalVD);
4060 auto SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4061 SharedRefLValue = CGF.MakeAddrLValue(
4062 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004063 SharedRefLValue.getType(),
4064 LValueBaseInfo(AlignmentSource::Decl,
4065 SharedRefLValue.getBaseInfo().getMayAlias()));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004066 QualType Type = OriginalVD->getType();
4067 if (Type->isArrayType()) {
4068 // Initialize firstprivate array.
4069 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4070 // Perform simple memcpy.
4071 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
4072 SharedRefLValue.getAddress(), Type);
4073 } else {
4074 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00004075 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00004076 CGF.EmitOMPAggregateAssign(
4077 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4078 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4079 Address SrcElement) {
4080 // Clean up any temporaries needed by the initialization.
4081 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4082 InitScope.addPrivate(
4083 Elem, [SrcElement]() -> Address { return SrcElement; });
4084 (void)InitScope.Privatize();
4085 // Emit initialization for single element.
4086 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4087 CGF, &CapturesInfo);
4088 CGF.EmitAnyExprToMem(Init, DestElement,
4089 Init->getType().getQualifiers(),
4090 /*IsInitializer=*/false);
4091 });
4092 }
4093 } else {
4094 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4095 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4096 return SharedRefLValue.getAddress();
4097 });
4098 (void)InitScope.Privatize();
4099 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4100 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4101 /*capturedByInit=*/false);
4102 }
4103 } else
4104 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
4105 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004106 ++FI;
4107 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004108}
4109
4110/// Check if duplication function is required for taskloops.
4111static bool checkInitIsRequired(CodeGenFunction &CGF,
4112 ArrayRef<PrivateDataTy> Privates) {
4113 bool InitRequired = false;
4114 for (auto &&Pair : Privates) {
4115 auto *VD = Pair.second.PrivateCopy;
4116 auto *Init = VD->getAnyInitializer();
4117 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4118 !CGF.isTrivialInitializer(Init));
4119 }
4120 return InitRequired;
4121}
4122
4123
4124/// Emit task_dup function (for initialization of
4125/// private/firstprivate/lastprivate vars and last_iter flag)
4126/// \code
4127/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4128/// lastpriv) {
4129/// // setup lastprivate flag
4130/// task_dst->last = lastpriv;
4131/// // could be constructor calls here...
4132/// }
4133/// \endcode
4134static llvm::Value *
4135emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4136 const OMPExecutableDirective &D,
4137 QualType KmpTaskTWithPrivatesPtrQTy,
4138 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4139 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4140 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4141 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
4142 auto &C = CGM.getContext();
4143 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004144 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4145 KmpTaskTWithPrivatesPtrQTy,
4146 ImplicitParamDecl::Other);
4147 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4148 KmpTaskTWithPrivatesPtrQTy,
4149 ImplicitParamDecl::Other);
4150 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4151 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004152 Args.push_back(&DstArg);
4153 Args.push_back(&SrcArg);
4154 Args.push_back(&LastprivArg);
4155 auto &TaskDupFnInfo =
4156 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
4157 auto *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
4158 auto *TaskDup =
4159 llvm::Function::Create(TaskDupTy, llvm::GlobalValue::InternalLinkage,
4160 ".omp_task_dup.", &CGM.getModule());
4161 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskDup, TaskDupFnInfo);
4162 CodeGenFunction CGF(CGM);
4163 CGF.disableDebugInfo();
4164 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args);
4165
4166 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4167 CGF.GetAddrOfLocalVar(&DstArg),
4168 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4169 // task_dst->liter = lastpriv;
4170 if (WithLastIter) {
4171 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4172 LValue Base = CGF.EmitLValueForField(
4173 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4174 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4175 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4176 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4177 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4178 }
4179
4180 // Emit initial values for private copies (if any).
4181 assert(!Privates.empty());
4182 Address KmpTaskSharedsPtr = Address::invalid();
4183 if (!Data.FirstprivateVars.empty()) {
4184 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4185 CGF.GetAddrOfLocalVar(&SrcArg),
4186 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4187 LValue Base = CGF.EmitLValueForField(
4188 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4189 KmpTaskSharedsPtr = Address(
4190 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4191 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4192 KmpTaskTShareds)),
4193 Loc),
4194 CGF.getNaturalTypeAlignment(SharedsTy));
4195 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004196 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4197 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004198 CGF.FinishFunction();
4199 return TaskDup;
4200}
4201
Alexey Bataev8a831592016-05-10 10:36:51 +00004202/// Checks if destructor function is required to be generated.
4203/// \return true if cleanups are required, false otherwise.
4204static bool
4205checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4206 bool NeedsCleanup = false;
4207 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4208 auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4209 for (auto *FD : PrivateRD->fields()) {
4210 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4211 if (NeedsCleanup)
4212 break;
4213 }
4214 return NeedsCleanup;
4215}
4216
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004217CGOpenMPRuntime::TaskResultTy
4218CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4219 const OMPExecutableDirective &D,
4220 llvm::Value *TaskFunction, QualType SharedsTy,
4221 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004222 auto &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004223 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004224 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004225 auto I = Data.PrivateCopies.begin();
4226 for (auto *E : Data.PrivateVars) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004227 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4228 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004229 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004230 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4231 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004232 ++I;
4233 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004234 I = Data.FirstprivateCopies.begin();
4235 auto IElemInitRef = Data.FirstprivateInits.begin();
4236 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev9e034042015-05-05 04:05:12 +00004237 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4238 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004239 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004240 PrivateHelpersTy(
4241 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4242 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
Richard Trieucc3949d2016-02-18 22:34:54 +00004243 ++I;
4244 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004245 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004246 I = Data.LastprivateCopies.begin();
4247 for (auto *E : Data.LastprivateVars) {
4248 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4249 Privates.push_back(std::make_pair(
4250 C.getDeclAlign(VD),
4251 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4252 /*PrivateElemInit=*/nullptr)));
4253 ++I;
4254 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004255 llvm::array_pod_sort(Privates.begin(), Privates.end(),
4256 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004257 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
4258 // Build type kmp_routine_entry_t (if not built yet).
4259 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004260 // Build type kmp_task_t (if not built yet).
4261 if (KmpTaskTQTy.isNull()) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004262 KmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4263 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004264 }
4265 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004266 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004267 auto *KmpTaskTWithPrivatesQTyRD =
4268 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
4269 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
4270 QualType KmpTaskTWithPrivatesPtrQTy =
4271 C.getPointerType(KmpTaskTWithPrivatesQTy);
4272 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4273 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004274 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004275 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4276
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004277 // Emit initial values for private copies (if any).
4278 llvm::Value *TaskPrivatesMap = nullptr;
4279 auto *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00004280 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004281 if (!Privates.empty()) {
4282 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004283 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4284 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4285 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004286 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4287 TaskPrivatesMap, TaskPrivatesMapTy);
4288 } else {
4289 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4290 cast<llvm::PointerType>(TaskPrivatesMapTy));
4291 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004292 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4293 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004294 auto *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004295 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4296 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4297 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004298
4299 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4300 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4301 // kmp_routine_entry_t *task_entry);
4302 // Task flags. Format is taken from
4303 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4304 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004305 enum {
4306 TiedFlag = 0x1,
4307 FinalFlag = 0x2,
4308 DestructorsFlag = 0x8,
4309 PriorityFlag = 0x20
4310 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004311 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004312 bool NeedsCleanup = false;
4313 if (!Privates.empty()) {
4314 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4315 if (NeedsCleanup)
4316 Flags = Flags | DestructorsFlag;
4317 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004318 if (Data.Priority.getInt())
4319 Flags = Flags | PriorityFlag;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004320 auto *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004321 Data.Final.getPointer()
4322 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00004323 CGF.Builder.getInt32(FinalFlag),
4324 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004325 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004326 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00004327 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004328 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4329 getThreadID(CGF, Loc), TaskFlags,
4330 KmpTaskTWithPrivatesTySize, SharedsSize,
4331 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4332 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00004333 auto *NewTask = CGF.EmitRuntimeCall(
4334 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004335 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4336 NewTask, KmpTaskTWithPrivatesPtrTy);
4337 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4338 KmpTaskTWithPrivatesQTy);
4339 LValue TDBase =
4340 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004341 // Fill the data in the resulting kmp_task_t record.
4342 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00004343 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004344 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00004345 KmpTaskSharedsPtr =
4346 Address(CGF.EmitLoadOfScalar(
4347 CGF.EmitLValueForField(
4348 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4349 KmpTaskTShareds)),
4350 Loc),
4351 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004352 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004353 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004354 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00004355 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004356 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004357 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4358 SharedsTy, SharedsPtrTy, Data, Privates,
4359 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004360 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4361 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4362 Result.TaskDupFn = emitTaskDupFunction(
4363 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4364 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4365 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004366 }
4367 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00004368 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4369 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00004370 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00004371 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
4372 auto *KmpCmplrdataUD = (*FI)->getType()->getAsUnionType()->getDecl();
4373 if (NeedsCleanup) {
4374 llvm::Value *DestructorFn = emitDestructorsFunction(
4375 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4376 KmpTaskTWithPrivatesQTy);
4377 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4378 LValue DestructorsLV = CGF.EmitLValueForField(
4379 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4380 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4381 DestructorFn, KmpRoutineEntryPtrTy),
4382 DestructorsLV);
4383 }
4384 // Set priority.
4385 if (Data.Priority.getInt()) {
4386 LValue Data2LV = CGF.EmitLValueForField(
4387 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
4388 LValue PriorityLV = CGF.EmitLValueForField(
4389 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
4390 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
4391 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004392 Result.NewTask = NewTask;
4393 Result.TaskEntry = TaskEntry;
4394 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
4395 Result.TDBase = TDBase;
4396 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
4397 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00004398}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004399
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004400void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
4401 const OMPExecutableDirective &D,
4402 llvm::Value *TaskFunction,
4403 QualType SharedsTy, Address Shareds,
4404 const Expr *IfCond,
4405 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004406 if (!CGF.HaveInsertPoint())
4407 return;
4408
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004409 TaskResultTy Result =
4410 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4411 llvm::Value *NewTask = Result.NewTask;
4412 llvm::Value *TaskEntry = Result.TaskEntry;
4413 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
4414 LValue TDBase = Result.TDBase;
4415 RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
Alexey Bataev7292c292016-04-25 12:22:29 +00004416 auto &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004417 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00004418 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004419 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00004420 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004421 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00004422 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004423 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
4424 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004425 QualType FlagsTy =
4426 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004427 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
4428 if (KmpDependInfoTy.isNull()) {
4429 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
4430 KmpDependInfoRD->startDefinition();
4431 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
4432 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
4433 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
4434 KmpDependInfoRD->completeDefinition();
4435 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004436 } else
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004437 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
John McCall7f416cc2015-09-08 08:05:57 +00004438 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004439 // Define type kmp_depend_info[<Dependences.size()>];
4440 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00004441 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004442 ArrayType::Normal, /*IndexTypeQuals=*/0);
4443 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00004444 DependenciesArray =
4445 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
John McCall7f416cc2015-09-08 08:05:57 +00004446 for (unsigned i = 0; i < NumDependencies; ++i) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004447 const Expr *E = Data.Dependences[i].second;
John McCall7f416cc2015-09-08 08:05:57 +00004448 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004449 llvm::Value *Size;
4450 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004451 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
4452 LValue UpAddrLVal =
4453 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
4454 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00004455 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004456 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00004457 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004458 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
4459 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004460 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00004461 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00004462 auto Base = CGF.MakeAddrLValue(
4463 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004464 KmpDependInfoTy);
4465 // deps[i].base_addr = &<Dependences[i].second>;
4466 auto BaseAddrLVal = CGF.EmitLValueForField(
4467 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00004468 CGF.EmitStoreOfScalar(
4469 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
4470 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004471 // deps[i].len = sizeof(<Dependences[i].second>);
4472 auto LenLVal = CGF.EmitLValueForField(
4473 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
4474 CGF.EmitStoreOfScalar(Size, LenLVal);
4475 // deps[i].flags = <Dependences[i].first>;
4476 RTLDependenceKindTy DepKind;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004477 switch (Data.Dependences[i].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004478 case OMPC_DEPEND_in:
4479 DepKind = DepIn;
4480 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00004481 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004482 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004483 case OMPC_DEPEND_inout:
4484 DepKind = DepInOut;
4485 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00004486 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004487 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004488 case OMPC_DEPEND_unknown:
4489 llvm_unreachable("Unknown task dependence type");
4490 }
4491 auto FlagsLVal = CGF.EmitLValueForField(
4492 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
4493 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
4494 FlagsLVal);
4495 }
John McCall7f416cc2015-09-08 08:05:57 +00004496 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4497 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004498 CGF.VoidPtrTy);
4499 }
4500
Alexey Bataev62b63b12015-03-10 07:28:44 +00004501 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4502 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004503 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
4504 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
4505 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
4506 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00004507 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004508 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00004509 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
4510 llvm::Value *DepTaskArgs[7];
4511 if (NumDependencies) {
4512 DepTaskArgs[0] = UpLoc;
4513 DepTaskArgs[1] = ThreadID;
4514 DepTaskArgs[2] = NewTask;
4515 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
4516 DepTaskArgs[4] = DependenciesArray.getPointer();
4517 DepTaskArgs[5] = CGF.Builder.getInt32(0);
4518 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4519 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00004520 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
4521 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004522 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004523 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004524 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4525 auto PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
4526 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
4527 }
John McCall7f416cc2015-09-08 08:05:57 +00004528 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004529 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00004530 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00004531 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004532 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00004533 TaskArgs);
4534 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00004535 // Check if parent region is untied and build return for untied task;
4536 if (auto *Region =
4537 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4538 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00004539 };
John McCall7f416cc2015-09-08 08:05:57 +00004540
4541 llvm::Value *DepWaitTaskArgs[6];
4542 if (NumDependencies) {
4543 DepWaitTaskArgs[0] = UpLoc;
4544 DepWaitTaskArgs[1] = ThreadID;
4545 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
4546 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
4547 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
4548 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4549 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004550 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00004551 NumDependencies, &DepWaitTaskArgs,
4552 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004553 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004554 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
4555 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
4556 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
4557 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
4558 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00004559 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004560 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004561 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004562 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00004563 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
4564 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004565 Action.Enter(CGF);
4566 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00004567 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00004568 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004569 };
4570
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004571 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
4572 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004573 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
4574 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004575 RegionCodeGenTy RCG(CodeGen);
4576 CommonActionTy Action(
4577 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
4578 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
4579 RCG.setAction(Action);
4580 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004581 };
John McCall7f416cc2015-09-08 08:05:57 +00004582
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004583 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00004584 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004585 else {
4586 RegionCodeGenTy ThenRCG(ThenCodeGen);
4587 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00004588 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004589}
4590
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004591void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
4592 const OMPLoopDirective &D,
4593 llvm::Value *TaskFunction,
4594 QualType SharedsTy, Address Shareds,
4595 const Expr *IfCond,
4596 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004597 if (!CGF.HaveInsertPoint())
4598 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004599 TaskResultTy Result =
4600 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004601 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4602 // libcall.
4603 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
4604 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
4605 // sched, kmp_uint64 grainsize, void *task_dup);
4606 llvm::Value *ThreadID = getThreadID(CGF, Loc);
4607 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
4608 llvm::Value *IfVal;
4609 if (IfCond) {
4610 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
4611 /*isSigned=*/true);
4612 } else
4613 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
4614
4615 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004616 Result.TDBase,
4617 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004618 auto *LBVar =
4619 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
4620 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
4621 /*IsInitializer=*/true);
4622 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004623 Result.TDBase,
4624 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004625 auto *UBVar =
4626 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
4627 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
4628 /*IsInitializer=*/true);
4629 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004630 Result.TDBase,
4631 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataev7292c292016-04-25 12:22:29 +00004632 auto *StVar =
4633 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
4634 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
4635 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004636 // Store reductions address.
4637 LValue RedLVal = CGF.EmitLValueForField(
4638 Result.TDBase,
4639 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
4640 if (Data.Reductions)
4641 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
4642 else {
4643 CGF.EmitNullInitialization(RedLVal.getAddress(),
4644 CGF.getContext().VoidPtrTy);
4645 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004646 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00004647 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00004648 UpLoc,
4649 ThreadID,
4650 Result.NewTask,
4651 IfVal,
4652 LBLVal.getPointer(),
4653 UBLVal.getPointer(),
4654 CGF.EmitLoadOfScalar(StLVal, SourceLocation()),
4655 llvm::ConstantInt::getNullValue(
4656 CGF.IntTy), // Always 0 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004657 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004658 CGF.IntTy, Data.Schedule.getPointer()
4659 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004660 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004661 Data.Schedule.getPointer()
4662 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004663 /*isSigned=*/false)
4664 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00004665 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4666 Result.TaskDupFn, CGF.VoidPtrTy)
4667 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00004668 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
4669}
4670
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004671/// \brief Emit reduction operation for each element of array (required for
4672/// array sections) LHS op = RHS.
4673/// \param Type Type of array.
4674/// \param LHSVar Variable on the left side of the reduction operation
4675/// (references element of array in original variable).
4676/// \param RHSVar Variable on the right side of the reduction operation
4677/// (references element of array in original variable).
4678/// \param RedOpGen Generator of reduction operation with use of LHSVar and
4679/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00004680static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004681 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
4682 const VarDecl *RHSVar,
4683 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
4684 const Expr *, const Expr *)> &RedOpGen,
4685 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
4686 const Expr *UpExpr = nullptr) {
4687 // Perform element-by-element initialization.
4688 QualType ElementTy;
4689 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
4690 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
4691
4692 // Drill down to the base element type on both arrays.
4693 auto ArrayTy = Type->getAsArrayTypeUnsafe();
4694 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
4695
4696 auto RHSBegin = RHSAddr.getPointer();
4697 auto LHSBegin = LHSAddr.getPointer();
4698 // Cast from pointer to array type to pointer to single element.
4699 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
4700 // The basic structure here is a while-do loop.
4701 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
4702 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
4703 auto IsEmpty =
4704 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
4705 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
4706
4707 // Enter the loop body, making that address the current address.
4708 auto EntryBB = CGF.Builder.GetInsertBlock();
4709 CGF.EmitBlock(BodyBB);
4710
4711 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
4712
4713 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
4714 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
4715 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
4716 Address RHSElementCurrent =
4717 Address(RHSElementPHI,
4718 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4719
4720 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
4721 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
4722 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
4723 Address LHSElementCurrent =
4724 Address(LHSElementPHI,
4725 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4726
4727 // Emit copy.
4728 CodeGenFunction::OMPPrivateScope Scope(CGF);
4729 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
4730 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
4731 Scope.Privatize();
4732 RedOpGen(CGF, XExpr, EExpr, UpExpr);
4733 Scope.ForceCleanup();
4734
4735 // Shift the address forward by one element.
4736 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
4737 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
4738 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
4739 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
4740 // Check whether we've reached the end.
4741 auto Done =
4742 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
4743 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
4744 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
4745 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
4746
4747 // Done.
4748 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
4749}
4750
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004751/// Emit reduction combiner. If the combiner is a simple expression emit it as
4752/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
4753/// UDR combiner function.
4754static void emitReductionCombiner(CodeGenFunction &CGF,
4755 const Expr *ReductionOp) {
4756 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
4757 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
4758 if (auto *DRE =
4759 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
4760 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
4761 std::pair<llvm::Function *, llvm::Function *> Reduction =
4762 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
4763 RValue Func = RValue::get(Reduction.first);
4764 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
4765 CGF.EmitIgnoredExpr(ReductionOp);
4766 return;
4767 }
4768 CGF.EmitIgnoredExpr(ReductionOp);
4769}
4770
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004771llvm::Value *CGOpenMPRuntime::emitReductionFunction(
4772 CodeGenModule &CGM, llvm::Type *ArgsType, ArrayRef<const Expr *> Privates,
4773 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4774 ArrayRef<const Expr *> ReductionOps) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004775 auto &C = CGM.getContext();
4776
4777 // void reduction_func(void *LHSArg, void *RHSArg);
4778 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004779 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
4780 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004781 Args.push_back(&LHSArg);
4782 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00004783 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004784 auto *Fn = llvm::Function::Create(
4785 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
4786 ".omp.reduction.reduction_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004787 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004788 CodeGenFunction CGF(CGM);
4789 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
4790
4791 // Dst = (void*[n])(LHSArg);
4792 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00004793 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4794 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
4795 ArgsType), CGF.getPointerAlign());
4796 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4797 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
4798 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004799
4800 // ...
4801 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
4802 // ...
4803 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004804 auto IPriv = Privates.begin();
4805 unsigned Idx = 0;
4806 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004807 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
4808 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004809 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004810 });
4811 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
4812 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004813 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004814 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004815 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004816 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004817 // Get array size and emit VLA type.
4818 ++Idx;
4819 Address Elem =
4820 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
4821 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004822 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
4823 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004824 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00004825 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004826 CGF.EmitVariablyModifiedType(PrivTy);
4827 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004828 }
4829 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004830 IPriv = Privates.begin();
4831 auto ILHS = LHSExprs.begin();
4832 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004833 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004834 if ((*IPriv)->getType()->isArrayType()) {
4835 // Emit reduction for array section.
4836 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4837 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004838 EmitOMPAggregateReduction(
4839 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4840 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4841 emitReductionCombiner(CGF, E);
4842 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004843 } else
4844 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004845 emitReductionCombiner(CGF, E);
Richard Trieucc3949d2016-02-18 22:34:54 +00004846 ++IPriv;
4847 ++ILHS;
4848 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004849 }
4850 Scope.ForceCleanup();
4851 CGF.FinishFunction();
4852 return Fn;
4853}
4854
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004855void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
4856 const Expr *ReductionOp,
4857 const Expr *PrivateRef,
4858 const DeclRefExpr *LHS,
4859 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004860 if (PrivateRef->getType()->isArrayType()) {
4861 // Emit reduction for array section.
4862 auto *LHSVar = cast<VarDecl>(LHS->getDecl());
4863 auto *RHSVar = cast<VarDecl>(RHS->getDecl());
4864 EmitOMPAggregateReduction(
4865 CGF, PrivateRef->getType(), LHSVar, RHSVar,
4866 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4867 emitReductionCombiner(CGF, ReductionOp);
4868 });
4869 } else
4870 // Emit reduction for array subscript or single variable.
4871 emitReductionCombiner(CGF, ReductionOp);
4872}
4873
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004874void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004875 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004876 ArrayRef<const Expr *> LHSExprs,
4877 ArrayRef<const Expr *> RHSExprs,
4878 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004879 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004880 if (!CGF.HaveInsertPoint())
4881 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004882
4883 bool WithNowait = Options.WithNowait;
4884 bool SimpleReduction = Options.SimpleReduction;
4885
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004886 // Next code should be emitted for reduction:
4887 //
4888 // static kmp_critical_name lock = { 0 };
4889 //
4890 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
4891 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
4892 // ...
4893 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
4894 // *(Type<n>-1*)rhs[<n>-1]);
4895 // }
4896 //
4897 // ...
4898 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
4899 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4900 // RedList, reduce_func, &<lock>)) {
4901 // case 1:
4902 // ...
4903 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4904 // ...
4905 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4906 // break;
4907 // case 2:
4908 // ...
4909 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4910 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00004911 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004912 // break;
4913 // default:;
4914 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004915 //
4916 // if SimpleReduction is true, only the next code is generated:
4917 // ...
4918 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4919 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004920
4921 auto &C = CGM.getContext();
4922
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004923 if (SimpleReduction) {
4924 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004925 auto IPriv = Privates.begin();
4926 auto ILHS = LHSExprs.begin();
4927 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004928 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004929 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4930 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00004931 ++IPriv;
4932 ++ILHS;
4933 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004934 }
4935 return;
4936 }
4937
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004938 // 1. Build a list of reduction variables.
4939 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004940 auto Size = RHSExprs.size();
4941 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00004942 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004943 // Reserve place for array size.
4944 ++Size;
4945 }
4946 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004947 QualType ReductionArrayTy =
4948 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4949 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00004950 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004951 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004952 auto IPriv = Privates.begin();
4953 unsigned Idx = 0;
4954 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004955 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004956 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00004957 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004958 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004959 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4960 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004961 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004962 // Store array size.
4963 ++Idx;
4964 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
4965 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00004966 llvm::Value *Size = CGF.Builder.CreateIntCast(
4967 CGF.getVLASize(
4968 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4969 .first,
4970 CGF.SizeTy, /*isSigned=*/false);
4971 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4972 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004973 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004974 }
4975
4976 // 2. Emit reduce_func().
4977 auto *ReductionFn = emitReductionFunction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004978 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
4979 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004980
4981 // 3. Create static kmp_critical_name lock = { 0 };
4982 auto *Lock = getCriticalRegionLock(".reduction");
4983
4984 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4985 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00004986 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004987 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004988 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
Samuel Antao4c8035b2016-12-12 18:00:20 +00004989 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4990 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004991 llvm::Value *Args[] = {
4992 IdentTLoc, // ident_t *<loc>
4993 ThreadId, // i32 <gtid>
4994 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
4995 ReductionArrayTySize, // size_type sizeof(RedList)
4996 RL, // void *RedList
4997 ReductionFn, // void (*) (void *, void *) <reduce_func>
4998 Lock // kmp_critical_name *&<lock>
4999 };
5000 auto Res = CGF.EmitRuntimeCall(
5001 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
5002 : OMPRTL__kmpc_reduce),
5003 Args);
5004
5005 // 5. Build switch(res)
5006 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
5007 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
5008
5009 // 6. Build case 1:
5010 // ...
5011 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
5012 // ...
5013 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5014 // break;
5015 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
5016 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5017 CGF.EmitBlock(Case1BB);
5018
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005019 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5020 llvm::Value *EndArgs[] = {
5021 IdentTLoc, // ident_t *<loc>
5022 ThreadId, // i32 <gtid>
5023 Lock // kmp_critical_name *&<lock>
5024 };
5025 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5026 CodeGenFunction &CGF, PrePostActionTy &Action) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005027 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005028 auto IPriv = Privates.begin();
5029 auto ILHS = LHSExprs.begin();
5030 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005031 for (auto *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005032 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5033 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005034 ++IPriv;
5035 ++ILHS;
5036 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005037 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005038 };
5039 RegionCodeGenTy RCG(CodeGen);
5040 CommonActionTy Action(
5041 nullptr, llvm::None,
5042 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5043 : OMPRTL__kmpc_end_reduce),
5044 EndArgs);
5045 RCG.setAction(Action);
5046 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005047
5048 CGF.EmitBranch(DefaultBB);
5049
5050 // 7. Build case 2:
5051 // ...
5052 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5053 // ...
5054 // break;
5055 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
5056 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5057 CGF.EmitBlock(Case2BB);
5058
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005059 auto &&AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5060 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005061 auto ILHS = LHSExprs.begin();
5062 auto IRHS = RHSExprs.begin();
5063 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005064 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005065 const Expr *XExpr = nullptr;
5066 const Expr *EExpr = nullptr;
5067 const Expr *UpExpr = nullptr;
5068 BinaryOperatorKind BO = BO_Comma;
5069 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
5070 if (BO->getOpcode() == BO_Assign) {
5071 XExpr = BO->getLHS();
5072 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005073 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005074 }
5075 // Try to emit update expression as a simple atomic.
5076 auto *RHSExpr = UpExpr;
5077 if (RHSExpr) {
5078 // Analyze RHS part of the whole expression.
5079 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
5080 RHSExpr->IgnoreParenImpCasts())) {
5081 // If this is a conditional operator, analyze its condition for
5082 // min/max reduction operator.
5083 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005084 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005085 if (auto *BORHS =
5086 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5087 EExpr = BORHS->getRHS();
5088 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005089 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005090 }
5091 if (XExpr) {
5092 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005093 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005094 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5095 const Expr *EExpr, const Expr *UpExpr) {
5096 LValue X = CGF.EmitLValue(XExpr);
5097 RValue E;
5098 if (EExpr)
5099 E = CGF.EmitAnyExpr(EExpr);
5100 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005101 X, E, BO, /*IsXLHSInRHSPart=*/true,
5102 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005103 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005104 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5105 PrivateScope.addPrivate(
5106 VD, [&CGF, VD, XRValue, Loc]() -> Address {
5107 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5108 CGF.emitOMPSimpleStore(
5109 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5110 VD->getType().getNonReferenceType(), Loc);
5111 return LHSTemp;
5112 });
5113 (void)PrivateScope.Privatize();
5114 return CGF.EmitAnyExpr(UpExpr);
5115 });
5116 };
5117 if ((*IPriv)->getType()->isArrayType()) {
5118 // Emit atomic reduction for array section.
5119 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5120 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5121 AtomicRedGen, XExpr, EExpr, UpExpr);
5122 } else
5123 // Emit atomic reduction for array subscript or single variable.
5124 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
5125 } else {
5126 // Emit as a critical region.
5127 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
5128 const Expr *, const Expr *) {
5129 auto &RT = CGF.CGM.getOpenMPRuntime();
5130 RT.emitCriticalRegion(
5131 CGF, ".atomic_reduction",
5132 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5133 Action.Enter(CGF);
5134 emitReductionCombiner(CGF, E);
5135 },
5136 Loc);
5137 };
5138 if ((*IPriv)->getType()->isArrayType()) {
5139 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5140 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5141 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5142 CritRedGen);
5143 } else
5144 CritRedGen(CGF, nullptr, nullptr, nullptr);
5145 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005146 ++ILHS;
5147 ++IRHS;
5148 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005149 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005150 };
5151 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5152 if (!WithNowait) {
5153 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5154 llvm::Value *EndArgs[] = {
5155 IdentTLoc, // ident_t *<loc>
5156 ThreadId, // i32 <gtid>
5157 Lock // kmp_critical_name *&<lock>
5158 };
5159 CommonActionTy Action(nullptr, llvm::None,
5160 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5161 EndArgs);
5162 AtomicRCG.setAction(Action);
5163 AtomicRCG(CGF);
5164 } else
5165 AtomicRCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005166
5167 CGF.EmitBranch(DefaultBB);
5168 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5169}
5170
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005171/// Generates unique name for artificial threadprivate variables.
5172/// Format is: <Prefix> "." <Loc_raw_encoding> "_" <N>
5173static std::string generateUniqueName(StringRef Prefix, SourceLocation Loc,
5174 unsigned N) {
5175 SmallString<256> Buffer;
5176 llvm::raw_svector_ostream Out(Buffer);
5177 Out << Prefix << "." << Loc.getRawEncoding() << "_" << N;
5178 return Out.str();
5179}
5180
5181/// Emits reduction initializer function:
5182/// \code
5183/// void @.red_init(void* %arg) {
5184/// %0 = bitcast void* %arg to <type>*
5185/// store <type> <init>, <type>* %0
5186/// ret void
5187/// }
5188/// \endcode
5189static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5190 SourceLocation Loc,
5191 ReductionCodeGen &RCG, unsigned N) {
5192 auto &C = CGM.getContext();
5193 FunctionArgList Args;
5194 ImplicitParamDecl Param(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5195 Args.emplace_back(&Param);
5196 auto &FnInfo =
5197 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5198 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5199 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5200 ".red_init.", &CGM.getModule());
5201 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5202 CodeGenFunction CGF(CGM);
5203 CGF.disableDebugInfo();
5204 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5205 Address PrivateAddr = CGF.EmitLoadOfPointer(
5206 CGF.GetAddrOfLocalVar(&Param),
5207 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5208 llvm::Value *Size = nullptr;
5209 // If the size of the reduction item is non-constant, load it from global
5210 // threadprivate variable.
5211 if (RCG.getSizes(N).second) {
5212 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5213 CGF, CGM.getContext().getSizeType(),
5214 generateUniqueName("reduction_size", Loc, N));
5215 Size =
5216 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5217 CGM.getContext().getSizeType(), SourceLocation());
5218 }
5219 RCG.emitAggregateType(CGF, N, Size);
5220 LValue SharedLVal;
5221 // If initializer uses initializer from declare reduction construct, emit a
5222 // pointer to the address of the original reduction item (reuired by reduction
5223 // initializer)
5224 if (RCG.usesReductionInitializer(N)) {
5225 Address SharedAddr =
5226 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5227 CGF, CGM.getContext().VoidPtrTy,
5228 generateUniqueName("reduction", Loc, N));
5229 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5230 } else {
5231 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5232 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5233 CGM.getContext().VoidPtrTy);
5234 }
5235 // Emit the initializer:
5236 // %0 = bitcast void* %arg to <type>*
5237 // store <type> <init>, <type>* %0
5238 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5239 [](CodeGenFunction &) { return false; });
5240 CGF.FinishFunction();
5241 return Fn;
5242}
5243
5244/// Emits reduction combiner function:
5245/// \code
5246/// void @.red_comb(void* %arg0, void* %arg1) {
5247/// %lhs = bitcast void* %arg0 to <type>*
5248/// %rhs = bitcast void* %arg1 to <type>*
5249/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5250/// store <type> %2, <type>* %lhs
5251/// ret void
5252/// }
5253/// \endcode
5254static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5255 SourceLocation Loc,
5256 ReductionCodeGen &RCG, unsigned N,
5257 const Expr *ReductionOp,
5258 const Expr *LHS, const Expr *RHS,
5259 const Expr *PrivateRef) {
5260 auto &C = CGM.getContext();
5261 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5262 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
5263 FunctionArgList Args;
5264 ImplicitParamDecl ParamInOut(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5265 ImplicitParamDecl ParamIn(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5266 Args.emplace_back(&ParamInOut);
5267 Args.emplace_back(&ParamIn);
5268 auto &FnInfo =
5269 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5270 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5271 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5272 ".red_comb.", &CGM.getModule());
5273 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5274 CodeGenFunction CGF(CGM);
5275 CGF.disableDebugInfo();
5276 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5277 llvm::Value *Size = nullptr;
5278 // If the size of the reduction item is non-constant, load it from global
5279 // threadprivate variable.
5280 if (RCG.getSizes(N).second) {
5281 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5282 CGF, CGM.getContext().getSizeType(),
5283 generateUniqueName("reduction_size", Loc, N));
5284 Size =
5285 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5286 CGM.getContext().getSizeType(), SourceLocation());
5287 }
5288 RCG.emitAggregateType(CGF, N, Size);
5289 // Remap lhs and rhs variables to the addresses of the function arguments.
5290 // %lhs = bitcast void* %arg0 to <type>*
5291 // %rhs = bitcast void* %arg1 to <type>*
5292 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5293 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() -> Address {
5294 // Pull out the pointer to the variable.
5295 Address PtrAddr = CGF.EmitLoadOfPointer(
5296 CGF.GetAddrOfLocalVar(&ParamInOut),
5297 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5298 return CGF.Builder.CreateElementBitCast(
5299 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
5300 });
5301 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() -> Address {
5302 // Pull out the pointer to the variable.
5303 Address PtrAddr = CGF.EmitLoadOfPointer(
5304 CGF.GetAddrOfLocalVar(&ParamIn),
5305 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5306 return CGF.Builder.CreateElementBitCast(
5307 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
5308 });
5309 PrivateScope.Privatize();
5310 // Emit the combiner body:
5311 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
5312 // store <type> %2, <type>* %lhs
5313 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
5314 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
5315 cast<DeclRefExpr>(RHS));
5316 CGF.FinishFunction();
5317 return Fn;
5318}
5319
5320/// Emits reduction finalizer function:
5321/// \code
5322/// void @.red_fini(void* %arg) {
5323/// %0 = bitcast void* %arg to <type>*
5324/// <destroy>(<type>* %0)
5325/// ret void
5326/// }
5327/// \endcode
5328static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
5329 SourceLocation Loc,
5330 ReductionCodeGen &RCG, unsigned N) {
5331 if (!RCG.needCleanups(N))
5332 return nullptr;
5333 auto &C = CGM.getContext();
5334 FunctionArgList Args;
5335 ImplicitParamDecl Param(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5336 Args.emplace_back(&Param);
5337 auto &FnInfo =
5338 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5339 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5340 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5341 ".red_fini.", &CGM.getModule());
5342 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5343 CodeGenFunction CGF(CGM);
5344 CGF.disableDebugInfo();
5345 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5346 Address PrivateAddr = CGF.EmitLoadOfPointer(
5347 CGF.GetAddrOfLocalVar(&Param),
5348 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5349 llvm::Value *Size = nullptr;
5350 // If the size of the reduction item is non-constant, load it from global
5351 // threadprivate variable.
5352 if (RCG.getSizes(N).second) {
5353 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5354 CGF, CGM.getContext().getSizeType(),
5355 generateUniqueName("reduction_size", Loc, N));
5356 Size =
5357 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5358 CGM.getContext().getSizeType(), SourceLocation());
5359 }
5360 RCG.emitAggregateType(CGF, N, Size);
5361 // Emit the finalizer body:
5362 // <destroy>(<type>* %0)
5363 RCG.emitCleanups(CGF, N, PrivateAddr);
5364 CGF.FinishFunction();
5365 return Fn;
5366}
5367
5368llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
5369 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
5370 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
5371 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
5372 return nullptr;
5373
5374 // Build typedef struct:
5375 // kmp_task_red_input {
5376 // void *reduce_shar; // shared reduction item
5377 // size_t reduce_size; // size of data item
5378 // void *reduce_init; // data initialization routine
5379 // void *reduce_fini; // data finalization routine
5380 // void *reduce_comb; // data combiner routine
5381 // kmp_task_red_flags_t flags; // flags for additional info from compiler
5382 // } kmp_task_red_input_t;
5383 ASTContext &C = CGM.getContext();
5384 auto *RD = C.buildImplicitRecord("kmp_task_red_input_t");
5385 RD->startDefinition();
5386 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5387 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
5388 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5389 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5390 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5391 const FieldDecl *FlagsFD = addFieldToRecordDecl(
5392 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
5393 RD->completeDefinition();
5394 QualType RDType = C.getRecordType(RD);
5395 unsigned Size = Data.ReductionVars.size();
5396 llvm::APInt ArraySize(/*numBits=*/64, Size);
5397 QualType ArrayRDType = C.getConstantArrayType(
5398 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5399 // kmp_task_red_input_t .rd_input.[Size];
5400 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
5401 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
5402 Data.ReductionOps);
5403 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
5404 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
5405 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
5406 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
5407 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
5408 TaskRedInput.getPointer(), Idxs,
5409 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
5410 ".rd_input.gep.");
5411 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
5412 // ElemLVal.reduce_shar = &Shareds[Cnt];
5413 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
5414 RCG.emitSharedLValue(CGF, Cnt);
5415 llvm::Value *CastedShared =
5416 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
5417 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
5418 RCG.emitAggregateType(CGF, Cnt);
5419 llvm::Value *SizeValInChars;
5420 llvm::Value *SizeVal;
5421 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
5422 // We use delayed creation/initialization for VLAs, array sections and
5423 // custom reduction initializations. It is required because runtime does not
5424 // provide the way to pass the sizes of VLAs/array sections to
5425 // initializer/combiner/finalizer functions and does not pass the pointer to
5426 // original reduction item to the initializer. Instead threadprivate global
5427 // variables are used to store these values and use them in the functions.
5428 bool DelayedCreation = !!SizeVal;
5429 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
5430 /*isSigned=*/false);
5431 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
5432 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
5433 // ElemLVal.reduce_init = init;
5434 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
5435 llvm::Value *InitAddr =
5436 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
5437 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
5438 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
5439 // ElemLVal.reduce_fini = fini;
5440 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
5441 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
5442 llvm::Value *FiniAddr = Fini
5443 ? CGF.EmitCastToVoidPtr(Fini)
5444 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
5445 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
5446 // ElemLVal.reduce_comb = comb;
5447 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
5448 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
5449 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
5450 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
5451 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
5452 // ElemLVal.flags = 0;
5453 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
5454 if (DelayedCreation) {
5455 CGF.EmitStoreOfScalar(
5456 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
5457 FlagsLVal);
5458 } else
5459 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
5460 }
5461 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
5462 // *data);
5463 llvm::Value *Args[] = {
5464 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5465 /*isSigned=*/true),
5466 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
5467 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
5468 CGM.VoidPtrTy)};
5469 return CGF.EmitRuntimeCall(
5470 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
5471}
5472
5473void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
5474 SourceLocation Loc,
5475 ReductionCodeGen &RCG,
5476 unsigned N) {
5477 auto Sizes = RCG.getSizes(N);
5478 // Emit threadprivate global variable if the type is non-constant
5479 // (Sizes.second = nullptr).
5480 if (Sizes.second) {
5481 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
5482 /*isSigned=*/false);
5483 Address SizeAddr = getAddrOfArtificialThreadPrivate(
5484 CGF, CGM.getContext().getSizeType(),
5485 generateUniqueName("reduction_size", Loc, N));
5486 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
5487 }
5488 // Store address of the original reduction item if custom initializer is used.
5489 if (RCG.usesReductionInitializer(N)) {
5490 Address SharedAddr = getAddrOfArtificialThreadPrivate(
5491 CGF, CGM.getContext().VoidPtrTy,
5492 generateUniqueName("reduction", Loc, N));
5493 CGF.Builder.CreateStore(
5494 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5495 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
5496 SharedAddr, /*IsVolatile=*/false);
5497 }
5498}
5499
5500Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
5501 SourceLocation Loc,
5502 llvm::Value *ReductionsPtr,
5503 LValue SharedLVal) {
5504 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
5505 // *d);
5506 llvm::Value *Args[] = {
5507 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5508 /*isSigned=*/true),
5509 ReductionsPtr,
5510 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
5511 CGM.VoidPtrTy)};
5512 return Address(
5513 CGF.EmitRuntimeCall(
5514 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
5515 SharedLVal.getAlignment());
5516}
5517
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005518void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
5519 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005520 if (!CGF.HaveInsertPoint())
5521 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005522 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
5523 // global_tid);
5524 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
5525 // Ignore return result until untied tasks are supported.
5526 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005527 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5528 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005529}
5530
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005531void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005532 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005533 const RegionCodeGenTy &CodeGen,
5534 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005535 if (!CGF.HaveInsertPoint())
5536 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005537 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005538 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00005539}
5540
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005541namespace {
5542enum RTCancelKind {
5543 CancelNoreq = 0,
5544 CancelParallel = 1,
5545 CancelLoop = 2,
5546 CancelSections = 3,
5547 CancelTaskgroup = 4
5548};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00005549} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005550
5551static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
5552 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00005553 if (CancelRegion == OMPD_parallel)
5554 CancelKind = CancelParallel;
5555 else if (CancelRegion == OMPD_for)
5556 CancelKind = CancelLoop;
5557 else if (CancelRegion == OMPD_sections)
5558 CancelKind = CancelSections;
5559 else {
5560 assert(CancelRegion == OMPD_taskgroup);
5561 CancelKind = CancelTaskgroup;
5562 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005563 return CancelKind;
5564}
5565
5566void CGOpenMPRuntime::emitCancellationPointCall(
5567 CodeGenFunction &CGF, SourceLocation Loc,
5568 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005569 if (!CGF.HaveInsertPoint())
5570 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005571 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
5572 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005573 if (auto *OMPRegionInfo =
5574 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00005575 // For 'cancellation point taskgroup', the task region info may not have a
5576 // cancel. This may instead happen in another adjacent task.
5577 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005578 llvm::Value *Args[] = {
5579 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
5580 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005581 // Ignore return result until untied tasks are supported.
5582 auto *Result = CGF.EmitRuntimeCall(
5583 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
5584 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005585 // exit from construct;
5586 // }
5587 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5588 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5589 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5590 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5591 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005592 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005593 auto CancelDest =
5594 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005595 CGF.EmitBranchThroughCleanup(CancelDest);
5596 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5597 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005598 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005599}
5600
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005601void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00005602 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005603 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005604 if (!CGF.HaveInsertPoint())
5605 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005606 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
5607 // kmp_int32 cncl_kind);
5608 if (auto *OMPRegionInfo =
5609 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005610 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
5611 PrePostActionTy &) {
5612 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00005613 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005614 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00005615 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
5616 // Ignore return result until untied tasks are supported.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005617 auto *Result = CGF.EmitRuntimeCall(
5618 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00005619 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00005620 // exit from construct;
5621 // }
5622 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5623 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5624 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5625 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5626 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00005627 // exit from construct;
5628 auto CancelDest =
5629 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
5630 CGF.EmitBranchThroughCleanup(CancelDest);
5631 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5632 };
5633 if (IfCond)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005634 emitOMPIfClause(CGF, IfCond, ThenGen,
5635 [](CodeGenFunction &, PrePostActionTy &) {});
5636 else {
5637 RegionCodeGenTy ThenRCG(ThenGen);
5638 ThenRCG(CGF);
5639 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005640 }
5641}
Samuel Antaobed3c462015-10-02 16:14:20 +00005642
Samuel Antaoee8fb302016-01-06 13:42:12 +00005643/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00005644/// consists of the file and device IDs as well as line number associated with
5645/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005646static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
5647 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005648 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005649
5650 auto &SM = C.getSourceManager();
5651
5652 // The loc should be always valid and have a file ID (the user cannot use
5653 // #pragma directives in macros)
5654
5655 assert(Loc.isValid() && "Source location is expected to be always valid.");
5656 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
5657
5658 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
5659 assert(PLoc.isValid() && "Source location is expected to be always valid.");
5660
5661 llvm::sys::fs::UniqueID ID;
5662 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
5663 llvm_unreachable("Source file with target region no longer exists!");
5664
5665 DeviceID = ID.getDevice();
5666 FileID = ID.getFile();
5667 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00005668}
5669
5670void CGOpenMPRuntime::emitTargetOutlinedFunction(
5671 const OMPExecutableDirective &D, StringRef ParentName,
5672 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005673 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005674 assert(!ParentName.empty() && "Invalid target region parent name!");
5675
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005676 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
5677 IsOffloadEntry, CodeGen);
5678}
5679
5680void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
5681 const OMPExecutableDirective &D, StringRef ParentName,
5682 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
5683 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00005684 // Create a unique name for the entry function using the source location
5685 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00005686 //
Samuel Antao2de62b02016-02-13 23:35:10 +00005687 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00005688 //
5689 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00005690 // mangled name of the function that encloses the target region and BB is the
5691 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005692
5693 unsigned DeviceID;
5694 unsigned FileID;
5695 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005696 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005697 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005698 SmallString<64> EntryFnName;
5699 {
5700 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00005701 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
5702 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005703 }
5704
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005705 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5706
Samuel Antaobed3c462015-10-02 16:14:20 +00005707 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005708 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00005709 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005710
Samuel Antao6d004262016-06-16 18:39:34 +00005711 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005712
5713 // If this target outline function is not an offload entry, we don't need to
5714 // register it.
5715 if (!IsOffloadEntry)
5716 return;
5717
5718 // The target region ID is used by the runtime library to identify the current
5719 // target region, so it only has to be unique and not necessarily point to
5720 // anything. It could be the pointer to the outlined function that implements
5721 // the target region, but we aren't using that so that the compiler doesn't
5722 // need to keep that, and could therefore inline the host function if proven
5723 // worthwhile during optimization. In the other hand, if emitting code for the
5724 // device, the ID has to be the function address so that it can retrieved from
5725 // the offloading entry and launched by the runtime library. We also mark the
5726 // outlined function to have external linkage in case we are emitting code for
5727 // the device, because these functions will be entry points to the device.
5728
5729 if (CGM.getLangOpts().OpenMPIsDevice) {
5730 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
5731 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
5732 } else
5733 OutlinedFnID = new llvm::GlobalVariable(
5734 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
5735 llvm::GlobalValue::PrivateLinkage,
5736 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
5737
5738 // Register the information for the entry associated with this target region.
5739 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00005740 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
5741 /*Flags=*/0);
Samuel Antaobed3c462015-10-02 16:14:20 +00005742}
5743
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005744/// discard all CompoundStmts intervening between two constructs
5745static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
5746 while (auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
5747 Body = CS->body_front();
5748
5749 return Body;
5750}
5751
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005752/// Emit the number of teams for a target directive. Inspect the num_teams
5753/// clause associated with a teams construct combined or closely nested
5754/// with the target directive.
5755///
5756/// Emit a team of size one for directives such as 'target parallel' that
5757/// have no associated teams construct.
5758///
5759/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00005760static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005761emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
5762 CodeGenFunction &CGF,
5763 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005764
5765 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
5766 "teams directive expected to be "
5767 "emitted only for the host!");
5768
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005769 auto &Bld = CGF.Builder;
5770
5771 // If the target directive is combined with a teams directive:
5772 // Return the value in the num_teams clause, if any.
5773 // Otherwise, return 0 to denote the runtime default.
5774 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
5775 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
5776 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
5777 auto NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
5778 /*IgnoreResultAssign*/ true);
5779 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5780 /*IsSigned=*/true);
5781 }
5782
5783 // The default value is 0.
5784 return Bld.getInt32(0);
5785 }
5786
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005787 // If the target directive is combined with a parallel directive but not a
5788 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005789 if (isOpenMPParallelDirective(D.getDirectiveKind()))
5790 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005791
5792 // If the current target region has a teams region enclosed, we need to get
5793 // the number of teams to pass to the runtime function call. This is done
5794 // by generating the expression in a inlined region. This is required because
5795 // the expression is captured in the enclosing target environment when the
5796 // teams directive is not combined with target.
5797
5798 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5799
5800 // FIXME: Accommodate other combined directives with teams when they become
5801 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005802 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
5803 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005804 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
5805 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5806 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5807 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005808 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5809 /*IsSigned=*/true);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005810 }
5811
5812 // If we have an enclosed teams directive but no num_teams clause we use
5813 // the default value 0.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005814 return Bld.getInt32(0);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005815 }
5816
5817 // No teams associated with the directive.
5818 return nullptr;
5819}
5820
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005821/// Emit the number of threads for a target directive. Inspect the
5822/// thread_limit clause associated with a teams construct combined or closely
5823/// nested with the target directive.
5824///
5825/// Emit the num_threads clause for directives such as 'target parallel' that
5826/// have no associated teams construct.
5827///
5828/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00005829static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005830emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
5831 CodeGenFunction &CGF,
5832 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005833
5834 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
5835 "teams directive expected to be "
5836 "emitted only for the host!");
5837
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005838 auto &Bld = CGF.Builder;
5839
5840 //
5841 // If the target directive is combined with a teams directive:
5842 // Return the value in the thread_limit clause, if any.
5843 //
5844 // If the target directive is combined with a parallel directive:
5845 // Return the value in the num_threads clause, if any.
5846 //
5847 // If both clauses are set, select the minimum of the two.
5848 //
5849 // If neither teams or parallel combined directives set the number of threads
5850 // in a team, return 0 to denote the runtime default.
5851 //
5852 // If this is not a teams directive return nullptr.
5853
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005854 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
5855 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005856 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
5857 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005858 llvm::Value *ThreadLimitVal = nullptr;
5859
5860 if (const auto *ThreadLimitClause =
5861 D.getSingleClause<OMPThreadLimitClause>()) {
5862 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
5863 auto ThreadLimit = CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
5864 /*IgnoreResultAssign*/ true);
5865 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5866 /*IsSigned=*/true);
5867 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005868
5869 if (const auto *NumThreadsClause =
5870 D.getSingleClause<OMPNumThreadsClause>()) {
5871 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
5872 llvm::Value *NumThreads =
5873 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
5874 /*IgnoreResultAssign*/ true);
5875 NumThreadsVal =
5876 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
5877 }
5878
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005879 // Select the lesser of thread_limit and num_threads.
5880 if (NumThreadsVal)
5881 ThreadLimitVal = ThreadLimitVal
5882 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
5883 ThreadLimitVal),
5884 NumThreadsVal, ThreadLimitVal)
5885 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00005886
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005887 // Set default value passed to the runtime if either teams or a target
5888 // parallel type directive is found but no clause is specified.
5889 if (!ThreadLimitVal)
5890 ThreadLimitVal = DefaultThreadLimitVal;
5891
5892 return ThreadLimitVal;
5893 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00005894
Samuel Antaob68e2db2016-03-03 16:20:23 +00005895 // If the current target region has a teams region enclosed, we need to get
5896 // the thread limit to pass to the runtime function call. This is done
5897 // by generating the expression in a inlined region. This is required because
5898 // the expression is captured in the enclosing target environment when the
5899 // teams directive is not combined with target.
5900
5901 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5902
5903 // FIXME: Accommodate other combined directives with teams when they become
5904 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005905 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
5906 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005907 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
5908 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5909 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5910 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
5911 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5912 /*IsSigned=*/true);
5913 }
5914
5915 // If we have an enclosed teams directive but no thread_limit clause we use
5916 // the default value 0.
5917 return CGF.Builder.getInt32(0);
5918 }
5919
5920 // No teams associated with the directive.
5921 return nullptr;
5922}
5923
Samuel Antao86ace552016-04-27 22:40:57 +00005924namespace {
5925// \brief Utility to handle information from clauses associated with a given
5926// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
5927// It provides a convenient interface to obtain the information and generate
5928// code for that information.
5929class MappableExprsHandler {
5930public:
5931 /// \brief Values for bit flags used to specify the mapping type for
5932 /// offloading.
5933 enum OpenMPOffloadMappingFlags {
Samuel Antao86ace552016-04-27 22:40:57 +00005934 /// \brief Allocate memory on the device and move data from host to device.
5935 OMP_MAP_TO = 0x01,
5936 /// \brief Allocate memory on the device and move data from device to host.
5937 OMP_MAP_FROM = 0x02,
5938 /// \brief Always perform the requested mapping action on the element, even
5939 /// if it was already mapped before.
5940 OMP_MAP_ALWAYS = 0x04,
Samuel Antao86ace552016-04-27 22:40:57 +00005941 /// \brief Delete the element from the device environment, ignoring the
5942 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00005943 OMP_MAP_DELETE = 0x08,
5944 /// \brief The element being mapped is a pointer, therefore the pointee
5945 /// should be mapped as well.
5946 OMP_MAP_IS_PTR = 0x10,
5947 /// \brief This flags signals that an argument is the first one relating to
5948 /// a map/private clause expression. For some cases a single
5949 /// map/privatization results in multiple arguments passed to the runtime
5950 /// library.
5951 OMP_MAP_FIRST_REF = 0x20,
Samuel Antaocc10b852016-07-28 14:23:26 +00005952 /// \brief Signal that the runtime library has to return the device pointer
5953 /// in the current position for the data being mapped.
5954 OMP_MAP_RETURN_PTR = 0x40,
Samuel Antaod486f842016-05-26 16:53:38 +00005955 /// \brief This flag signals that the reference being passed is a pointer to
5956 /// private data.
5957 OMP_MAP_PRIVATE_PTR = 0x80,
Samuel Antao86ace552016-04-27 22:40:57 +00005958 /// \brief Pass the element to the device by value.
Samuel Antao6782e942016-05-26 16:48:10 +00005959 OMP_MAP_PRIVATE_VAL = 0x100,
Samuel Antao86ace552016-04-27 22:40:57 +00005960 };
5961
Samuel Antaocc10b852016-07-28 14:23:26 +00005962 /// Class that associates information with a base pointer to be passed to the
5963 /// runtime library.
5964 class BasePointerInfo {
5965 /// The base pointer.
5966 llvm::Value *Ptr = nullptr;
5967 /// The base declaration that refers to this device pointer, or null if
5968 /// there is none.
5969 const ValueDecl *DevPtrDecl = nullptr;
5970
5971 public:
5972 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
5973 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
5974 llvm::Value *operator*() const { return Ptr; }
5975 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
5976 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
5977 };
5978
5979 typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00005980 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
5981 typedef SmallVector<unsigned, 16> MapFlagsArrayTy;
5982
5983private:
5984 /// \brief Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00005985 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00005986
5987 /// \brief Function the directive is being generated for.
5988 CodeGenFunction &CGF;
5989
Samuel Antaod486f842016-05-26 16:53:38 +00005990 /// \brief Set of all first private variables in the current directive.
5991 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
5992
Samuel Antao6890b092016-07-28 14:25:09 +00005993 /// Map between device pointer declarations and their expression components.
5994 /// The key value for declarations in 'this' is null.
5995 llvm::DenseMap<
5996 const ValueDecl *,
5997 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
5998 DevPointersMap;
5999
Samuel Antao86ace552016-04-27 22:40:57 +00006000 llvm::Value *getExprTypeSize(const Expr *E) const {
6001 auto ExprTy = E->getType().getCanonicalType();
6002
6003 // Reference types are ignored for mapping purposes.
6004 if (auto *RefTy = ExprTy->getAs<ReferenceType>())
6005 ExprTy = RefTy->getPointeeType().getCanonicalType();
6006
6007 // Given that an array section is considered a built-in type, we need to
6008 // do the calculation based on the length of the section instead of relying
6009 // on CGF.getTypeSize(E->getType()).
6010 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
6011 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
6012 OAE->getBase()->IgnoreParenImpCasts())
6013 .getCanonicalType();
6014
6015 // If there is no length associated with the expression, that means we
6016 // are using the whole length of the base.
6017 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6018 return CGF.getTypeSize(BaseTy);
6019
6020 llvm::Value *ElemSize;
6021 if (auto *PTy = BaseTy->getAs<PointerType>())
6022 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
6023 else {
6024 auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
6025 assert(ATy && "Expecting array type if not a pointer type.");
6026 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6027 }
6028
6029 // If we don't have a length at this point, that is because we have an
6030 // array section with a single element.
6031 if (!OAE->getLength())
6032 return ElemSize;
6033
6034 auto *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
6035 LengthVal =
6036 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6037 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6038 }
6039 return CGF.getTypeSize(ExprTy);
6040 }
6041
6042 /// \brief Return the corresponding bits for a given map clause modifier. Add
6043 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006044 /// map as the first one of a series of maps that relate to the same map
6045 /// expression.
Samuel Antao86ace552016-04-27 22:40:57 +00006046 unsigned getMapTypeBits(OpenMPMapClauseKind MapType,
6047 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
Samuel Antao6782e942016-05-26 16:48:10 +00006048 bool AddIsFirstFlag) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006049 unsigned Bits = 0u;
6050 switch (MapType) {
6051 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006052 case OMPC_MAP_release:
6053 // alloc and release is the default behavior in the runtime library, i.e.
6054 // if we don't pass any bits alloc/release that is what the runtime is
6055 // going to do. Therefore, we don't need to signal anything for these two
6056 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006057 break;
6058 case OMPC_MAP_to:
6059 Bits = OMP_MAP_TO;
6060 break;
6061 case OMPC_MAP_from:
6062 Bits = OMP_MAP_FROM;
6063 break;
6064 case OMPC_MAP_tofrom:
6065 Bits = OMP_MAP_TO | OMP_MAP_FROM;
6066 break;
6067 case OMPC_MAP_delete:
6068 Bits = OMP_MAP_DELETE;
6069 break;
Samuel Antao86ace552016-04-27 22:40:57 +00006070 default:
6071 llvm_unreachable("Unexpected map type!");
6072 break;
6073 }
6074 if (AddPtrFlag)
Samuel Antao6782e942016-05-26 16:48:10 +00006075 Bits |= OMP_MAP_IS_PTR;
6076 if (AddIsFirstFlag)
6077 Bits |= OMP_MAP_FIRST_REF;
Samuel Antao86ace552016-04-27 22:40:57 +00006078 if (MapTypeModifier == OMPC_MAP_always)
6079 Bits |= OMP_MAP_ALWAYS;
6080 return Bits;
6081 }
6082
6083 /// \brief Return true if the provided expression is a final array section. A
6084 /// final array section, is one whose length can't be proved to be one.
6085 bool isFinalArraySectionExpression(const Expr *E) const {
6086 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
6087
6088 // It is not an array section and therefore not a unity-size one.
6089 if (!OASE)
6090 return false;
6091
6092 // An array section with no colon always refer to a single element.
6093 if (OASE->getColonLoc().isInvalid())
6094 return false;
6095
6096 auto *Length = OASE->getLength();
6097
6098 // If we don't have a length we have to check if the array has size 1
6099 // for this dimension. Also, we should always expect a length if the
6100 // base type is pointer.
6101 if (!Length) {
6102 auto BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6103 OASE->getBase()->IgnoreParenImpCasts())
6104 .getCanonicalType();
6105 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
6106 return ATy->getSize().getSExtValue() != 1;
6107 // If we don't have a constant dimension length, we have to consider
6108 // the current section as having any size, so it is not necessarily
6109 // unitary. If it happen to be unity size, that's user fault.
6110 return true;
6111 }
6112
6113 // Check if the length evaluates to 1.
6114 llvm::APSInt ConstLength;
6115 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
6116 return true; // Can have more that size 1.
6117
6118 return ConstLength.getSExtValue() != 1;
6119 }
6120
6121 /// \brief Generate the base pointers, section pointers, sizes and map type
6122 /// bits for the provided map type, map modifier, and expression components.
6123 /// \a IsFirstComponent should be set to true if the provided set of
6124 /// components is the first associated with a capture.
6125 void generateInfoForComponentList(
6126 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6127 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006128 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006129 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
6130 bool IsFirstComponentList) const {
6131
6132 // The following summarizes what has to be generated for each map and the
6133 // types bellow. The generated information is expressed in this order:
6134 // base pointer, section pointer, size, flags
6135 // (to add to the ones that come from the map type and modifier).
6136 //
6137 // double d;
6138 // int i[100];
6139 // float *p;
6140 //
6141 // struct S1 {
6142 // int i;
6143 // float f[50];
6144 // }
6145 // struct S2 {
6146 // int i;
6147 // float f[50];
6148 // S1 s;
6149 // double *p;
6150 // struct S2 *ps;
6151 // }
6152 // S2 s;
6153 // S2 *ps;
6154 //
6155 // map(d)
6156 // &d, &d, sizeof(double), noflags
6157 //
6158 // map(i)
6159 // &i, &i, 100*sizeof(int), noflags
6160 //
6161 // map(i[1:23])
6162 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
6163 //
6164 // map(p)
6165 // &p, &p, sizeof(float*), noflags
6166 //
6167 // map(p[1:24])
6168 // p, &p[1], 24*sizeof(float), noflags
6169 //
6170 // map(s)
6171 // &s, &s, sizeof(S2), noflags
6172 //
6173 // map(s.i)
6174 // &s, &(s.i), sizeof(int), noflags
6175 //
6176 // map(s.s.f)
6177 // &s, &(s.i.f), 50*sizeof(int), noflags
6178 //
6179 // map(s.p)
6180 // &s, &(s.p), sizeof(double*), noflags
6181 //
6182 // map(s.p[:22], s.a s.b)
6183 // &s, &(s.p), sizeof(double*), noflags
6184 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag + extra_flag
6185 //
6186 // map(s.ps)
6187 // &s, &(s.ps), sizeof(S2*), noflags
6188 //
6189 // map(s.ps->s.i)
6190 // &s, &(s.ps), sizeof(S2*), noflags
6191 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag + extra_flag
6192 //
6193 // map(s.ps->ps)
6194 // &s, &(s.ps), sizeof(S2*), noflags
6195 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
6196 //
6197 // map(s.ps->ps->ps)
6198 // &s, &(s.ps), sizeof(S2*), noflags
6199 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
6200 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6201 //
6202 // map(s.ps->ps->s.f[:22])
6203 // &s, &(s.ps), sizeof(S2*), noflags
6204 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
6205 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag + extra_flag
6206 //
6207 // map(ps)
6208 // &ps, &ps, sizeof(S2*), noflags
6209 //
6210 // map(ps->i)
6211 // ps, &(ps->i), sizeof(int), noflags
6212 //
6213 // map(ps->s.f)
6214 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
6215 //
6216 // map(ps->p)
6217 // ps, &(ps->p), sizeof(double*), noflags
6218 //
6219 // map(ps->p[:22])
6220 // ps, &(ps->p), sizeof(double*), noflags
6221 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag + extra_flag
6222 //
6223 // map(ps->ps)
6224 // ps, &(ps->ps), sizeof(S2*), noflags
6225 //
6226 // map(ps->ps->s.i)
6227 // ps, &(ps->ps), sizeof(S2*), noflags
6228 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag + extra_flag
6229 //
6230 // map(ps->ps->ps)
6231 // ps, &(ps->ps), sizeof(S2*), noflags
6232 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6233 //
6234 // map(ps->ps->ps->ps)
6235 // ps, &(ps->ps), sizeof(S2*), noflags
6236 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6237 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6238 //
6239 // map(ps->ps->ps->s.f[:22])
6240 // ps, &(ps->ps), sizeof(S2*), noflags
6241 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6242 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag +
6243 // extra_flag
6244
6245 // Track if the map information being generated is the first for a capture.
6246 bool IsCaptureFirstInfo = IsFirstComponentList;
6247
6248 // Scan the components from the base to the complete expression.
6249 auto CI = Components.rbegin();
6250 auto CE = Components.rend();
6251 auto I = CI;
6252
6253 // Track if the map information being generated is the first for a list of
6254 // components.
6255 bool IsExpressionFirstInfo = true;
6256 llvm::Value *BP = nullptr;
6257
6258 if (auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
6259 // The base is the 'this' pointer. The content of the pointer is going
6260 // to be the base of the field being mapped.
6261 BP = CGF.EmitScalarExpr(ME->getBase());
6262 } else {
6263 // The base is the reference to the variable.
6264 // BP = &Var.
6265 BP = CGF.EmitLValue(cast<DeclRefExpr>(I->getAssociatedExpression()))
6266 .getPointer();
6267
6268 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00006269 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00006270 // reference. References are ignored for mapping purposes.
6271 QualType Ty =
6272 I->getAssociatedDeclaration()->getType().getNonReferenceType();
6273 if (Ty->isAnyPointerType() && std::next(I) != CE) {
6274 auto PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
Samuel Antao86ace552016-04-27 22:40:57 +00006275 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
Samuel Antao403ffd42016-07-27 22:49:49 +00006276 Ty->castAs<PointerType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006277 .getPointer();
6278
6279 // We do not need to generate individual map information for the
6280 // pointer, it can be associated with the combined storage.
6281 ++I;
6282 }
6283 }
6284
6285 for (; I != CE; ++I) {
6286 auto Next = std::next(I);
6287
6288 // We need to generate the addresses and sizes if this is the last
6289 // component, if the component is a pointer or if it is an array section
6290 // whose length can't be proved to be one. If this is a pointer, it
6291 // becomes the base address for the following components.
6292
6293 // A final array section, is one whose length can't be proved to be one.
6294 bool IsFinalArraySection =
6295 isFinalArraySectionExpression(I->getAssociatedExpression());
6296
6297 // Get information on whether the element is a pointer. Have to do a
6298 // special treatment for array sections given that they are built-in
6299 // types.
6300 const auto *OASE =
6301 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
6302 bool IsPointer =
6303 (OASE &&
6304 OMPArraySectionExpr::getBaseOriginalType(OASE)
6305 .getCanonicalType()
6306 ->isAnyPointerType()) ||
6307 I->getAssociatedExpression()->getType()->isAnyPointerType();
6308
6309 if (Next == CE || IsPointer || IsFinalArraySection) {
6310
6311 // If this is not the last component, we expect the pointer to be
6312 // associated with an array expression or member expression.
6313 assert((Next == CE ||
6314 isa<MemberExpr>(Next->getAssociatedExpression()) ||
6315 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
6316 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
6317 "Unexpected expression");
6318
Samuel Antao86ace552016-04-27 22:40:57 +00006319 auto *LB = CGF.EmitLValue(I->getAssociatedExpression()).getPointer();
6320 auto *Size = getExprTypeSize(I->getAssociatedExpression());
6321
Samuel Antao03a3cec2016-07-27 22:52:16 +00006322 // If we have a member expression and the current component is a
6323 // reference, we have to map the reference too. Whenever we have a
6324 // reference, the section that reference refers to is going to be a
6325 // load instruction from the storage assigned to the reference.
6326 if (isa<MemberExpr>(I->getAssociatedExpression()) &&
6327 I->getAssociatedDeclaration()->getType()->isReferenceType()) {
6328 auto *LI = cast<llvm::LoadInst>(LB);
6329 auto *RefAddr = LI->getPointerOperand();
6330
6331 BasePointers.push_back(BP);
6332 Pointers.push_back(RefAddr);
6333 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
6334 Types.push_back(getMapTypeBits(
6335 /*MapType*/ OMPC_MAP_alloc, /*MapTypeModifier=*/OMPC_MAP_unknown,
6336 !IsExpressionFirstInfo, IsCaptureFirstInfo));
6337 IsExpressionFirstInfo = false;
6338 IsCaptureFirstInfo = false;
6339 // The reference will be the next base address.
6340 BP = RefAddr;
6341 }
6342
6343 BasePointers.push_back(BP);
Samuel Antao86ace552016-04-27 22:40:57 +00006344 Pointers.push_back(LB);
6345 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00006346
Samuel Antao6782e942016-05-26 16:48:10 +00006347 // We need to add a pointer flag for each map that comes from the
6348 // same expression except for the first one. We also need to signal
6349 // this map is the first one that relates with the current capture
6350 // (there is a set of entries for each capture).
Samuel Antao86ace552016-04-27 22:40:57 +00006351 Types.push_back(getMapTypeBits(MapType, MapTypeModifier,
6352 !IsExpressionFirstInfo,
Samuel Antao6782e942016-05-26 16:48:10 +00006353 IsCaptureFirstInfo));
Samuel Antao86ace552016-04-27 22:40:57 +00006354
6355 // If we have a final array section, we are done with this expression.
6356 if (IsFinalArraySection)
6357 break;
6358
6359 // The pointer becomes the base for the next element.
6360 if (Next != CE)
6361 BP = LB;
6362
6363 IsExpressionFirstInfo = false;
6364 IsCaptureFirstInfo = false;
6365 continue;
6366 }
6367 }
6368 }
6369
Samuel Antaod486f842016-05-26 16:53:38 +00006370 /// \brief Return the adjusted map modifiers if the declaration a capture
6371 /// refers to appears in a first-private clause. This is expected to be used
6372 /// only with directives that start with 'target'.
6373 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
6374 unsigned CurrentModifiers) {
6375 assert(Cap.capturesVariable() && "Expected capture by reference only!");
6376
6377 // A first private variable captured by reference will use only the
6378 // 'private ptr' and 'map to' flag. Return the right flags if the captured
6379 // declaration is known as first-private in this handler.
6380 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
6381 return MappableExprsHandler::OMP_MAP_PRIVATE_PTR |
6382 MappableExprsHandler::OMP_MAP_TO;
6383
6384 // We didn't modify anything.
6385 return CurrentModifiers;
6386 }
6387
Samuel Antao86ace552016-04-27 22:40:57 +00006388public:
6389 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
Samuel Antao44bcdb32016-07-28 15:31:29 +00006390 : CurDir(Dir), CGF(CGF) {
Samuel Antaod486f842016-05-26 16:53:38 +00006391 // Extract firstprivate clause information.
6392 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
6393 for (const auto *D : C->varlists())
6394 FirstPrivateDecls.insert(
6395 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
Samuel Antao6890b092016-07-28 14:25:09 +00006396 // Extract device pointer clause information.
6397 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
6398 for (auto L : C->component_lists())
6399 DevPointersMap[L.first].push_back(L.second);
Samuel Antaod486f842016-05-26 16:53:38 +00006400 }
Samuel Antao86ace552016-04-27 22:40:57 +00006401
6402 /// \brief Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00006403 /// types for the extracted mappable expressions. Also, for each item that
6404 /// relates with a device pointer, a pair of the relevant declaration and
6405 /// index where it occurs is appended to the device pointers info array.
6406 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006407 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
6408 MapFlagsArrayTy &Types) const {
6409 BasePointers.clear();
6410 Pointers.clear();
6411 Sizes.clear();
6412 Types.clear();
6413
6414 struct MapInfo {
Samuel Antaocc10b852016-07-28 14:23:26 +00006415 /// Kind that defines how a device pointer has to be returned.
6416 enum ReturnPointerKind {
6417 // Don't have to return any pointer.
6418 RPK_None,
6419 // Pointer is the base of the declaration.
6420 RPK_Base,
6421 // Pointer is a member of the base declaration - 'this'
6422 RPK_Member,
6423 // Pointer is a reference and a member of the base declaration - 'this'
6424 RPK_MemberReference,
6425 };
Samuel Antao86ace552016-04-27 22:40:57 +00006426 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
Hans Wennborgbc1b58d2016-07-30 00:41:37 +00006427 OpenMPMapClauseKind MapType;
6428 OpenMPMapClauseKind MapTypeModifier;
6429 ReturnPointerKind ReturnDevicePointer;
6430
6431 MapInfo()
6432 : MapType(OMPC_MAP_unknown), MapTypeModifier(OMPC_MAP_unknown),
6433 ReturnDevicePointer(RPK_None) {}
Samuel Antaocc10b852016-07-28 14:23:26 +00006434 MapInfo(
6435 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
6436 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6437 ReturnPointerKind ReturnDevicePointer)
6438 : Components(Components), MapType(MapType),
6439 MapTypeModifier(MapTypeModifier),
6440 ReturnDevicePointer(ReturnDevicePointer) {}
Samuel Antao86ace552016-04-27 22:40:57 +00006441 };
6442
6443 // We have to process the component lists that relate with the same
6444 // declaration in a single chunk so that we can generate the map flags
6445 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00006446 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00006447
6448 // Helper function to fill the information map for the different supported
6449 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00006450 auto &&InfoGen = [&Info](
6451 const ValueDecl *D,
6452 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
6453 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006454 MapInfo::ReturnPointerKind ReturnDevicePointer) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006455 const ValueDecl *VD =
6456 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
6457 Info[VD].push_back({L, MapType, MapModifier, ReturnDevicePointer});
6458 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00006459
Paul Robinson78fb1322016-08-01 22:12:46 +00006460 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006461 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00006462 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006463 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
6464 MapInfo::RPK_None);
Paul Robinson15c84002016-07-29 20:46:16 +00006465 for (auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00006466 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006467 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
6468 MapInfo::RPK_None);
Paul Robinson15c84002016-07-29 20:46:16 +00006469 for (auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00006470 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006471 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
6472 MapInfo::RPK_None);
Samuel Antao86ace552016-04-27 22:40:57 +00006473
Samuel Antaocc10b852016-07-28 14:23:26 +00006474 // Look at the use_device_ptr clause information and mark the existing map
6475 // entries as such. If there is no map information for an entry in the
6476 // use_device_ptr list, we create one with map type 'alloc' and zero size
6477 // section. It is the user fault if that was not mapped before.
Paul Robinson78fb1322016-08-01 22:12:46 +00006478 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006479 for (auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
Samuel Antaocc10b852016-07-28 14:23:26 +00006480 for (auto L : C->component_lists()) {
6481 assert(!L.second.empty() && "Not expecting empty list of components!");
6482 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
6483 VD = cast<ValueDecl>(VD->getCanonicalDecl());
6484 auto *IE = L.second.back().getAssociatedExpression();
6485 // If the first component is a member expression, we have to look into
6486 // 'this', which maps to null in the map of map information. Otherwise
6487 // look directly for the information.
6488 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
6489
6490 // We potentially have map information for this declaration already.
6491 // Look for the first set of components that refer to it.
6492 if (It != Info.end()) {
6493 auto CI = std::find_if(
6494 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
6495 return MI.Components.back().getAssociatedDeclaration() == VD;
6496 });
6497 // If we found a map entry, signal that the pointer has to be returned
6498 // and move on to the next declaration.
6499 if (CI != It->second.end()) {
6500 CI->ReturnDevicePointer = isa<MemberExpr>(IE)
6501 ? (VD->getType()->isReferenceType()
6502 ? MapInfo::RPK_MemberReference
6503 : MapInfo::RPK_Member)
6504 : MapInfo::RPK_Base;
6505 continue;
6506 }
6507 }
6508
6509 // We didn't find any match in our map information - generate a zero
6510 // size array section.
Paul Robinson78fb1322016-08-01 22:12:46 +00006511 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Samuel Antaocc10b852016-07-28 14:23:26 +00006512 llvm::Value *Ptr =
Paul Robinson15c84002016-07-29 20:46:16 +00006513 this->CGF
6514 .EmitLoadOfLValue(this->CGF.EmitLValue(IE), SourceLocation())
Samuel Antaocc10b852016-07-28 14:23:26 +00006515 .getScalarVal();
6516 BasePointers.push_back({Ptr, VD});
6517 Pointers.push_back(Ptr);
Paul Robinson15c84002016-07-29 20:46:16 +00006518 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
Samuel Antaocc10b852016-07-28 14:23:26 +00006519 Types.push_back(OMP_MAP_RETURN_PTR | OMP_MAP_FIRST_REF);
6520 }
6521
Samuel Antao86ace552016-04-27 22:40:57 +00006522 for (auto &M : Info) {
6523 // We need to know when we generate information for the first component
6524 // associated with a capture, because the mapping flags depend on it.
6525 bool IsFirstComponentList = true;
6526 for (MapInfo &L : M.second) {
6527 assert(!L.Components.empty() &&
6528 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00006529
6530 // Remember the current base pointer index.
6531 unsigned CurrentBasePointersIdx = BasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00006532 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Paul Robinson15c84002016-07-29 20:46:16 +00006533 this->generateInfoForComponentList(L.MapType, L.MapTypeModifier,
6534 L.Components, BasePointers, Pointers,
6535 Sizes, Types, IsFirstComponentList);
Samuel Antaocc10b852016-07-28 14:23:26 +00006536
6537 // If this entry relates with a device pointer, set the relevant
6538 // declaration and add the 'return pointer' flag.
6539 if (IsFirstComponentList &&
6540 L.ReturnDevicePointer != MapInfo::RPK_None) {
6541 // If the pointer is not the base of the map, we need to skip the
6542 // base. If it is a reference in a member field, we also need to skip
6543 // the map of the reference.
6544 if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
6545 ++CurrentBasePointersIdx;
6546 if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
6547 ++CurrentBasePointersIdx;
6548 }
6549 assert(BasePointers.size() > CurrentBasePointersIdx &&
6550 "Unexpected number of mapped base pointers.");
6551
6552 auto *RelevantVD = L.Components.back().getAssociatedDeclaration();
6553 assert(RelevantVD &&
6554 "No relevant declaration related with device pointer??");
6555
6556 BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
6557 Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PTR;
6558 }
Samuel Antao86ace552016-04-27 22:40:57 +00006559 IsFirstComponentList = false;
6560 }
6561 }
6562 }
6563
6564 /// \brief Generate the base pointers, section pointers, sizes and map types
6565 /// associated to a given capture.
6566 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00006567 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006568 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006569 MapValuesArrayTy &Pointers,
6570 MapValuesArrayTy &Sizes,
6571 MapFlagsArrayTy &Types) const {
6572 assert(!Cap->capturesVariableArrayType() &&
6573 "Not expecting to generate map info for a variable array type!");
6574
6575 BasePointers.clear();
6576 Pointers.clear();
6577 Sizes.clear();
6578 Types.clear();
6579
Samuel Antao6890b092016-07-28 14:25:09 +00006580 // We need to know when we generating information for the first component
6581 // associated with a capture, because the mapping flags depend on it.
6582 bool IsFirstComponentList = true;
6583
Samuel Antao86ace552016-04-27 22:40:57 +00006584 const ValueDecl *VD =
6585 Cap->capturesThis()
6586 ? nullptr
6587 : cast<ValueDecl>(Cap->getCapturedVar()->getCanonicalDecl());
6588
Samuel Antao6890b092016-07-28 14:25:09 +00006589 // If this declaration appears in a is_device_ptr clause we just have to
6590 // pass the pointer by value. If it is a reference to a declaration, we just
6591 // pass its value, otherwise, if it is a member expression, we need to map
6592 // 'to' the field.
6593 if (!VD) {
6594 auto It = DevPointersMap.find(VD);
6595 if (It != DevPointersMap.end()) {
6596 for (auto L : It->second) {
6597 generateInfoForComponentList(
6598 /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
6599 BasePointers, Pointers, Sizes, Types, IsFirstComponentList);
6600 IsFirstComponentList = false;
6601 }
6602 return;
6603 }
6604 } else if (DevPointersMap.count(VD)) {
6605 BasePointers.push_back({Arg, VD});
6606 Pointers.push_back(Arg);
6607 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
6608 Types.push_back(OMP_MAP_PRIVATE_VAL | OMP_MAP_FIRST_REF);
6609 return;
6610 }
6611
Paul Robinson78fb1322016-08-01 22:12:46 +00006612 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006613 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao86ace552016-04-27 22:40:57 +00006614 for (auto L : C->decl_component_lists(VD)) {
6615 assert(L.first == VD &&
6616 "We got information for the wrong declaration??");
6617 assert(!L.second.empty() &&
6618 "Not expecting declaration with no component lists.");
6619 generateInfoForComponentList(C->getMapType(), C->getMapTypeModifier(),
6620 L.second, BasePointers, Pointers, Sizes,
6621 Types, IsFirstComponentList);
6622 IsFirstComponentList = false;
6623 }
6624
6625 return;
6626 }
Samuel Antaod486f842016-05-26 16:53:38 +00006627
6628 /// \brief Generate the default map information for a given capture \a CI,
6629 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00006630 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
6631 const FieldDecl &RI, llvm::Value *CV,
6632 MapBaseValuesArrayTy &CurBasePointers,
6633 MapValuesArrayTy &CurPointers,
6634 MapValuesArrayTy &CurSizes,
6635 MapFlagsArrayTy &CurMapTypes) {
Samuel Antaod486f842016-05-26 16:53:38 +00006636
6637 // Do the default mapping.
6638 if (CI.capturesThis()) {
6639 CurBasePointers.push_back(CV);
6640 CurPointers.push_back(CV);
6641 const PointerType *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
6642 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
6643 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00006644 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00006645 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00006646 CurBasePointers.push_back(CV);
6647 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00006648 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00006649 // We have to signal to the runtime captures passed by value that are
6650 // not pointers.
Samuel Antaocc10b852016-07-28 14:23:26 +00006651 CurMapTypes.push_back(OMP_MAP_PRIVATE_VAL);
Samuel Antaod486f842016-05-26 16:53:38 +00006652 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
6653 } else {
6654 // Pointers are implicitly mapped with a zero size and no flags
6655 // (other than first map that is added for all implicit maps).
6656 CurMapTypes.push_back(0u);
Samuel Antaod486f842016-05-26 16:53:38 +00006657 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
6658 }
6659 } else {
6660 assert(CI.capturesVariable() && "Expected captured reference.");
6661 CurBasePointers.push_back(CV);
6662 CurPointers.push_back(CV);
6663
6664 const ReferenceType *PtrTy =
6665 cast<ReferenceType>(RI.getType().getTypePtr());
6666 QualType ElementType = PtrTy->getPointeeType();
6667 CurSizes.push_back(CGF.getTypeSize(ElementType));
6668 // The default map type for a scalar/complex type is 'to' because by
6669 // default the value doesn't have to be retrieved. For an aggregate
6670 // type, the default is 'tofrom'.
6671 CurMapTypes.push_back(ElementType->isAggregateType()
Samuel Antaocc10b852016-07-28 14:23:26 +00006672 ? (OMP_MAP_TO | OMP_MAP_FROM)
6673 : OMP_MAP_TO);
Samuel Antaod486f842016-05-26 16:53:38 +00006674
6675 // If we have a capture by reference we may need to add the private
6676 // pointer flag if the base declaration shows in some first-private
6677 // clause.
6678 CurMapTypes.back() =
6679 adjustMapModifiersForPrivateClauses(CI, CurMapTypes.back());
6680 }
6681 // Every default map produces a single argument, so, it is always the
6682 // first one.
Samuel Antaocc10b852016-07-28 14:23:26 +00006683 CurMapTypes.back() |= OMP_MAP_FIRST_REF;
Samuel Antaod486f842016-05-26 16:53:38 +00006684 }
Samuel Antao86ace552016-04-27 22:40:57 +00006685};
Samuel Antaodf158d52016-04-27 22:58:19 +00006686
6687enum OpenMPOffloadingReservedDeviceIDs {
6688 /// \brief Device ID if the device was not defined, runtime should get it
6689 /// from environment variables in the spec.
6690 OMP_DEVICEID_UNDEF = -1,
6691};
6692} // anonymous namespace
6693
6694/// \brief Emit the arrays used to pass the captures and map information to the
6695/// offloading runtime library. If there is no map or capture information,
6696/// return nullptr by reference.
6697static void
Samuel Antaocc10b852016-07-28 14:23:26 +00006698emitOffloadingArrays(CodeGenFunction &CGF,
6699 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00006700 MappableExprsHandler::MapValuesArrayTy &Pointers,
6701 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00006702 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
6703 CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006704 auto &CGM = CGF.CGM;
6705 auto &Ctx = CGF.getContext();
6706
Samuel Antaocc10b852016-07-28 14:23:26 +00006707 // Reset the array information.
6708 Info.clearArrayInfo();
6709 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00006710
Samuel Antaocc10b852016-07-28 14:23:26 +00006711 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006712 // Detect if we have any capture size requiring runtime evaluation of the
6713 // size so that a constant array could be eventually used.
6714 bool hasRuntimeEvaluationCaptureSize = false;
6715 for (auto *S : Sizes)
6716 if (!isa<llvm::Constant>(S)) {
6717 hasRuntimeEvaluationCaptureSize = true;
6718 break;
6719 }
6720
Samuel Antaocc10b852016-07-28 14:23:26 +00006721 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00006722 QualType PointerArrayType =
6723 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
6724 /*IndexTypeQuals=*/0);
6725
Samuel Antaocc10b852016-07-28 14:23:26 +00006726 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006727 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00006728 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006729 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
6730
6731 // If we don't have any VLA types or other types that require runtime
6732 // evaluation, we can use a constant array for the map sizes, otherwise we
6733 // need to fill up the arrays as we do for the pointers.
6734 if (hasRuntimeEvaluationCaptureSize) {
6735 QualType SizeArrayType = Ctx.getConstantArrayType(
6736 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
6737 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00006738 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006739 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
6740 } else {
6741 // We expect all the sizes to be constant, so we collect them to create
6742 // a constant array.
6743 SmallVector<llvm::Constant *, 16> ConstSizes;
6744 for (auto S : Sizes)
6745 ConstSizes.push_back(cast<llvm::Constant>(S));
6746
6747 auto *SizesArrayInit = llvm::ConstantArray::get(
6748 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
6749 auto *SizesArrayGbl = new llvm::GlobalVariable(
6750 CGM.getModule(), SizesArrayInit->getType(),
6751 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
6752 SizesArrayInit, ".offload_sizes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00006753 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00006754 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00006755 }
6756
6757 // The map types are always constant so we don't need to generate code to
6758 // fill arrays. Instead, we create an array constant.
6759 llvm::Constant *MapTypesArrayInit =
6760 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
6761 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
6762 CGM.getModule(), MapTypesArrayInit->getType(),
6763 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
6764 MapTypesArrayInit, ".offload_maptypes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00006765 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00006766 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00006767
Samuel Antaocc10b852016-07-28 14:23:26 +00006768 for (unsigned i = 0; i < Info.NumberOfPtrs; ++i) {
6769 llvm::Value *BPVal = *BasePointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00006770 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006771 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6772 Info.BasePointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00006773 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6774 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00006775 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
6776 CGF.Builder.CreateStore(BPVal, BPAddr);
6777
Samuel Antaocc10b852016-07-28 14:23:26 +00006778 if (Info.requiresDevicePointerInfo())
6779 if (auto *DevVD = BasePointers[i].getDevicePtrDecl())
6780 Info.CaptureDeviceAddrMap.insert(std::make_pair(DevVD, BPAddr));
6781
Samuel Antaodf158d52016-04-27 22:58:19 +00006782 llvm::Value *PVal = Pointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00006783 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006784 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6785 Info.PointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00006786 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6787 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00006788 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
6789 CGF.Builder.CreateStore(PVal, PAddr);
6790
6791 if (hasRuntimeEvaluationCaptureSize) {
6792 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006793 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
6794 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006795 /*Idx0=*/0,
6796 /*Idx1=*/i);
6797 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
6798 CGF.Builder.CreateStore(
6799 CGF.Builder.CreateIntCast(Sizes[i], CGM.SizeTy, /*isSigned=*/true),
6800 SAddr);
6801 }
6802 }
6803 }
6804}
6805/// \brief Emit the arguments to be passed to the runtime library based on the
6806/// arrays of pointers, sizes and map types.
6807static void emitOffloadingArraysArgument(
6808 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
6809 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006810 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006811 auto &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00006812 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006813 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006814 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6815 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006816 /*Idx0=*/0, /*Idx1=*/0);
6817 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006818 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6819 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006820 /*Idx0=*/0,
6821 /*Idx1=*/0);
6822 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006823 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006824 /*Idx0=*/0, /*Idx1=*/0);
6825 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006826 llvm::ArrayType::get(CGM.Int32Ty, Info.NumberOfPtrs),
6827 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006828 /*Idx0=*/0,
6829 /*Idx1=*/0);
6830 } else {
6831 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
6832 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
6833 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
6834 MapTypesArrayArg =
6835 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo());
6836 }
Samuel Antao86ace552016-04-27 22:40:57 +00006837}
6838
Samuel Antaobed3c462015-10-02 16:14:20 +00006839void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
6840 const OMPExecutableDirective &D,
6841 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00006842 llvm::Value *OutlinedFnID,
Samuel Antaobed3c462015-10-02 16:14:20 +00006843 const Expr *IfCond, const Expr *Device,
6844 ArrayRef<llvm::Value *> CapturedVars) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006845 if (!CGF.HaveInsertPoint())
6846 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00006847
Samuel Antaoee8fb302016-01-06 13:42:12 +00006848 assert(OutlinedFn && "Invalid outlined function!");
6849
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006850 auto &Ctx = CGF.getContext();
6851
Samuel Antao86ace552016-04-27 22:40:57 +00006852 // Fill up the arrays with all the captured variables.
6853 MappableExprsHandler::MapValuesArrayTy KernelArgs;
Samuel Antaocc10b852016-07-28 14:23:26 +00006854 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00006855 MappableExprsHandler::MapValuesArrayTy Pointers;
6856 MappableExprsHandler::MapValuesArrayTy Sizes;
6857 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobed3c462015-10-02 16:14:20 +00006858
Samuel Antaocc10b852016-07-28 14:23:26 +00006859 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00006860 MappableExprsHandler::MapValuesArrayTy CurPointers;
6861 MappableExprsHandler::MapValuesArrayTy CurSizes;
6862 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
6863
Samuel Antaod486f842016-05-26 16:53:38 +00006864 // Get mappable expression information.
6865 MappableExprsHandler MEHandler(D, CGF);
Samuel Antaobed3c462015-10-02 16:14:20 +00006866
6867 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
6868 auto RI = CS.getCapturedRecordDecl()->field_begin();
Samuel Antaobed3c462015-10-02 16:14:20 +00006869 auto CV = CapturedVars.begin();
6870 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
6871 CE = CS.capture_end();
6872 CI != CE; ++CI, ++RI, ++CV) {
6873 StringRef Name;
6874 QualType Ty;
Samuel Antaobed3c462015-10-02 16:14:20 +00006875
Samuel Antao86ace552016-04-27 22:40:57 +00006876 CurBasePointers.clear();
6877 CurPointers.clear();
6878 CurSizes.clear();
6879 CurMapTypes.clear();
6880
6881 // VLA sizes are passed to the outlined region by copy and do not have map
6882 // information associated.
Samuel Antaobed3c462015-10-02 16:14:20 +00006883 if (CI->capturesVariableArrayType()) {
Samuel Antao86ace552016-04-27 22:40:57 +00006884 CurBasePointers.push_back(*CV);
6885 CurPointers.push_back(*CV);
6886 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006887 // Copy to the device as an argument. No need to retrieve it.
Samuel Antao6782e942016-05-26 16:48:10 +00006888 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_PRIVATE_VAL |
6889 MappableExprsHandler::OMP_MAP_FIRST_REF);
Samuel Antaobed3c462015-10-02 16:14:20 +00006890 } else {
Samuel Antao86ace552016-04-27 22:40:57 +00006891 // If we have any information in the map clause, we use it, otherwise we
6892 // just do a default mapping.
Samuel Antao6890b092016-07-28 14:25:09 +00006893 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006894 CurSizes, CurMapTypes);
Samuel Antaod486f842016-05-26 16:53:38 +00006895 if (CurBasePointers.empty())
6896 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
6897 CurPointers, CurSizes, CurMapTypes);
Samuel Antaobed3c462015-10-02 16:14:20 +00006898 }
Samuel Antao86ace552016-04-27 22:40:57 +00006899 // We expect to have at least an element of information for this capture.
6900 assert(!CurBasePointers.empty() && "Non-existing map pointer for capture!");
6901 assert(CurBasePointers.size() == CurPointers.size() &&
6902 CurBasePointers.size() == CurSizes.size() &&
6903 CurBasePointers.size() == CurMapTypes.size() &&
6904 "Inconsistent map information sizes!");
Samuel Antaobed3c462015-10-02 16:14:20 +00006905
Samuel Antao86ace552016-04-27 22:40:57 +00006906 // The kernel args are always the first elements of the base pointers
6907 // associated with a capture.
Samuel Antaocc10b852016-07-28 14:23:26 +00006908 KernelArgs.push_back(*CurBasePointers.front());
Samuel Antao86ace552016-04-27 22:40:57 +00006909 // We need to append the results of this capture to what we already have.
6910 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
6911 Pointers.append(CurPointers.begin(), CurPointers.end());
6912 Sizes.append(CurSizes.begin(), CurSizes.end());
6913 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
Samuel Antaobed3c462015-10-02 16:14:20 +00006914 }
6915
6916 // Keep track on whether the host function has to be executed.
6917 auto OffloadErrorQType =
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006918 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006919 auto OffloadError = CGF.MakeAddrLValue(
6920 CGF.CreateMemTemp(OffloadErrorQType, ".run_host_version"),
6921 OffloadErrorQType);
6922 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty),
6923 OffloadError);
6924
6925 // Fill up the pointer arrays and transfer execution to the device.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00006926 auto &&ThenGen = [&BasePointers, &Pointers, &Sizes, &MapTypes, Device,
6927 OutlinedFnID, OffloadError,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006928 &D](CodeGenFunction &CGF, PrePostActionTy &) {
6929 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antaodf158d52016-04-27 22:58:19 +00006930 // Emit the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00006931 TargetDataInfo Info;
6932 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
6933 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
6934 Info.PointersArray, Info.SizesArray,
6935 Info.MapTypesArray, Info);
Samuel Antaobed3c462015-10-02 16:14:20 +00006936
6937 // On top of the arrays that were filled up, the target offloading call
6938 // takes as arguments the device id as well as the host pointer. The host
6939 // pointer is used by the runtime library to identify the current target
6940 // region, so it only has to be unique and not necessarily point to
6941 // anything. It could be the pointer to the outlined function that
6942 // implements the target region, but we aren't using that so that the
6943 // compiler doesn't need to keep that, and could therefore inline the host
6944 // function if proven worthwhile during optimization.
6945
Samuel Antaoee8fb302016-01-06 13:42:12 +00006946 // From this point on, we need to have an ID of the target region defined.
6947 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00006948
6949 // Emit device ID if any.
6950 llvm::Value *DeviceID;
6951 if (Device)
6952 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006953 CGF.Int32Ty, /*isSigned=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006954 else
6955 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6956
Samuel Antaodf158d52016-04-27 22:58:19 +00006957 // Emit the number of elements in the offloading arrays.
6958 llvm::Value *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6959
Samuel Antaob68e2db2016-03-03 16:20:23 +00006960 // Return value of the runtime offloading call.
6961 llvm::Value *Return;
6962
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006963 auto *NumTeams = emitNumTeamsForTargetDirective(RT, CGF, D);
6964 auto *NumThreads = emitNumThreadsForTargetDirective(RT, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006965
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006966 // The target region is an outlined function launched by the runtime
6967 // via calls __tgt_target() or __tgt_target_teams().
6968 //
6969 // __tgt_target() launches a target region with one team and one thread,
6970 // executing a serial region. This master thread may in turn launch
6971 // more threads within its team upon encountering a parallel region,
6972 // however, no additional teams can be launched on the device.
6973 //
6974 // __tgt_target_teams() launches a target region with one or more teams,
6975 // each with one or more threads. This call is required for target
6976 // constructs such as:
6977 // 'target teams'
6978 // 'target' / 'teams'
6979 // 'target teams distribute parallel for'
6980 // 'target parallel'
6981 // and so on.
6982 //
6983 // Note that on the host and CPU targets, the runtime implementation of
6984 // these calls simply call the outlined function without forking threads.
6985 // The outlined functions themselves have runtime calls to
6986 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
6987 // the compiler in emitTeamsCall() and emitParallelCall().
6988 //
6989 // In contrast, on the NVPTX target, the implementation of
6990 // __tgt_target_teams() launches a GPU kernel with the requested number
6991 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006992 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006993 // If we have NumTeams defined this means that we have an enclosed teams
6994 // region. Therefore we also expect to have NumThreads defined. These two
6995 // values should be defined in the presence of a teams directive,
6996 // regardless of having any clauses associated. If the user is using teams
6997 // but no clauses, these two values will be the default that should be
6998 // passed to the runtime library - a 32-bit integer with the value zero.
6999 assert(NumThreads && "Thread limit expression should be available along "
7000 "with number of teams.");
Samuel Antaob68e2db2016-03-03 16:20:23 +00007001 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007002 DeviceID, OutlinedFnID,
7003 PointerNum, Info.BasePointersArray,
7004 Info.PointersArray, Info.SizesArray,
7005 Info.MapTypesArray, NumTeams,
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007006 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00007007 Return = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007008 RT.createRuntimeFunction(OMPRTL__tgt_target_teams), OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00007009 } else {
7010 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007011 DeviceID, OutlinedFnID,
7012 PointerNum, Info.BasePointersArray,
7013 Info.PointersArray, Info.SizesArray,
7014 Info.MapTypesArray};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007015 Return = CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target),
Samuel Antaob68e2db2016-03-03 16:20:23 +00007016 OffloadingArgs);
7017 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007018
7019 CGF.EmitStoreOfScalar(Return, OffloadError);
7020 };
7021
Samuel Antaoee8fb302016-01-06 13:42:12 +00007022 // Notify that the host version must be executed.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007023 auto &&ElseGen = [OffloadError](CodeGenFunction &CGF, PrePostActionTy &) {
7024 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/-1u),
Samuel Antaoee8fb302016-01-06 13:42:12 +00007025 OffloadError);
7026 };
7027
7028 // If we have a target function ID it means that we need to support
7029 // offloading, otherwise, just execute on the host. We need to execute on host
7030 // regardless of the conditional in the if clause if, e.g., the user do not
7031 // specify target triples.
7032 if (OutlinedFnID) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007033 if (IfCond)
Samuel Antaoee8fb302016-01-06 13:42:12 +00007034 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007035 else {
7036 RegionCodeGenTy ThenRCG(ThenGen);
7037 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007038 }
7039 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007040 RegionCodeGenTy ElseRCG(ElseGen);
7041 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007042 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007043
7044 // Check the error code and execute the host version if required.
7045 auto OffloadFailedBlock = CGF.createBasicBlock("omp_offload.failed");
7046 auto OffloadContBlock = CGF.createBasicBlock("omp_offload.cont");
7047 auto OffloadErrorVal = CGF.EmitLoadOfScalar(OffloadError, SourceLocation());
7048 auto Failed = CGF.Builder.CreateIsNotNull(OffloadErrorVal);
7049 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
7050
7051 CGF.EmitBlock(OffloadFailedBlock);
Alexey Bataev3c595a62017-08-14 15:01:03 +00007052 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, KernelArgs);
Samuel Antaobed3c462015-10-02 16:14:20 +00007053 CGF.EmitBranch(OffloadContBlock);
7054
7055 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00007056}
Samuel Antaoee8fb302016-01-06 13:42:12 +00007057
7058void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
7059 StringRef ParentName) {
7060 if (!S)
7061 return;
7062
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007063 // Codegen OMP target directives that offload compute to the device.
7064 bool requiresDeviceCodegen =
7065 isa<OMPExecutableDirective>(S) &&
7066 isOpenMPTargetExecutionDirective(
7067 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00007068
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007069 if (requiresDeviceCodegen) {
7070 auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007071 unsigned DeviceID;
7072 unsigned FileID;
7073 unsigned Line;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007074 getTargetEntryUniqueInfo(CGM.getContext(), E.getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00007075 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007076
7077 // Is this a target region that should not be emitted as an entry point? If
7078 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00007079 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
7080 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007081 return;
7082
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007083 switch (S->getStmtClass()) {
7084 case Stmt::OMPTargetDirectiveClass:
7085 CodeGenFunction::EmitOMPTargetDeviceFunction(
7086 CGM, ParentName, cast<OMPTargetDirective>(*S));
7087 break;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00007088 case Stmt::OMPTargetParallelDirectiveClass:
7089 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
7090 CGM, ParentName, cast<OMPTargetParallelDirective>(*S));
7091 break;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00007092 case Stmt::OMPTargetTeamsDirectiveClass:
7093 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
7094 CGM, ParentName, cast<OMPTargetTeamsDirective>(*S));
7095 break;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007096 default:
7097 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
7098 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00007099 return;
7100 }
7101
7102 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
Samuel Antaoe49645c2016-05-08 06:43:56 +00007103 if (!E->hasAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00007104 return;
7105
7106 scanForTargetRegionsFunctions(
7107 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
7108 ParentName);
7109 return;
7110 }
7111
7112 // If this is a lambda function, look into its body.
7113 if (auto *L = dyn_cast<LambdaExpr>(S))
7114 S = L->getBody();
7115
7116 // Keep looking for target regions recursively.
7117 for (auto *II : S->children())
7118 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007119}
7120
7121bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
7122 auto &FD = *cast<FunctionDecl>(GD.getDecl());
7123
7124 // If emitting code for the host, we do not process FD here. Instead we do
7125 // the normal code generation.
7126 if (!CGM.getLangOpts().OpenMPIsDevice)
7127 return false;
7128
7129 // Try to detect target regions in the function.
7130 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
7131
Samuel Antao4b75b872016-12-12 19:26:31 +00007132 // We should not emit any function other that the ones created during the
Samuel Antaoee8fb302016-01-06 13:42:12 +00007133 // scanning. Therefore, we signal that this function is completely dealt
7134 // with.
7135 return true;
7136}
7137
7138bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
7139 if (!CGM.getLangOpts().OpenMPIsDevice)
7140 return false;
7141
7142 // Check if there are Ctors/Dtors in this declaration and look for target
7143 // regions in it. We use the complete variant to produce the kernel name
7144 // mangling.
7145 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
7146 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
7147 for (auto *Ctor : RD->ctors()) {
7148 StringRef ParentName =
7149 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
7150 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
7151 }
7152 auto *Dtor = RD->getDestructor();
7153 if (Dtor) {
7154 StringRef ParentName =
7155 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
7156 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
7157 }
7158 }
7159
Gheorghe-Teodor Bercea47633db2017-06-13 15:35:27 +00007160 // If we are in target mode, we do not emit any global (declare target is not
Samuel Antaoee8fb302016-01-06 13:42:12 +00007161 // implemented yet). Therefore we signal that GD was processed in this case.
7162 return true;
7163}
7164
7165bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
7166 auto *VD = GD.getDecl();
7167 if (isa<FunctionDecl>(VD))
7168 return emitTargetFunctions(GD);
7169
7170 return emitTargetGlobalVariable(GD);
7171}
7172
7173llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
7174 // If we have offloading in the current module, we need to emit the entries
7175 // now and register the offloading descriptor.
7176 createOffloadEntriesAndInfoMetadata();
7177
7178 // Create and register the offloading binary descriptors. This is the main
7179 // entity that captures all the information about offloading in the current
7180 // compilation unit.
7181 return createOffloadingBinaryDescriptorRegistration();
7182}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007183
7184void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
7185 const OMPExecutableDirective &D,
7186 SourceLocation Loc,
7187 llvm::Value *OutlinedFn,
7188 ArrayRef<llvm::Value *> CapturedVars) {
7189 if (!CGF.HaveInsertPoint())
7190 return;
7191
7192 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7193 CodeGenFunction::RunCleanupsScope Scope(CGF);
7194
7195 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
7196 llvm::Value *Args[] = {
7197 RTLoc,
7198 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
7199 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
7200 llvm::SmallVector<llvm::Value *, 16> RealArgs;
7201 RealArgs.append(std::begin(Args), std::end(Args));
7202 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
7203
7204 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
7205 CGF.EmitRuntimeCall(RTLFn, RealArgs);
7206}
7207
7208void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00007209 const Expr *NumTeams,
7210 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007211 SourceLocation Loc) {
7212 if (!CGF.HaveInsertPoint())
7213 return;
7214
7215 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7216
Carlo Bertollic6872252016-04-04 15:55:02 +00007217 llvm::Value *NumTeamsVal =
7218 (NumTeams)
7219 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
7220 CGF.CGM.Int32Ty, /* isSigned = */ true)
7221 : CGF.Builder.getInt32(0);
7222
7223 llvm::Value *ThreadLimitVal =
7224 (ThreadLimit)
7225 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
7226 CGF.CGM.Int32Ty, /* isSigned = */ true)
7227 : CGF.Builder.getInt32(0);
7228
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007229 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00007230 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
7231 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007232 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
7233 PushNumTeamsArgs);
7234}
Samuel Antaodf158d52016-04-27 22:58:19 +00007235
Samuel Antaocc10b852016-07-28 14:23:26 +00007236void CGOpenMPRuntime::emitTargetDataCalls(
7237 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7238 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007239 if (!CGF.HaveInsertPoint())
7240 return;
7241
Samuel Antaocc10b852016-07-28 14:23:26 +00007242 // Action used to replace the default codegen action and turn privatization
7243 // off.
7244 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00007245
7246 // Generate the code for the opening of the data environment. Capture all the
7247 // arguments of the runtime call by reference because they are used in the
7248 // closing of the region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007249 auto &&BeginThenGen = [&D, Device, &Info, &CodeGen](CodeGenFunction &CGF,
7250 PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007251 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00007252 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00007253 MappableExprsHandler::MapValuesArrayTy Pointers;
7254 MappableExprsHandler::MapValuesArrayTy Sizes;
7255 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7256
7257 // Get map clause information.
7258 MappableExprsHandler MCHandler(D, CGF);
7259 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00007260
7261 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00007262 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007263
7264 llvm::Value *BasePointersArrayArg = nullptr;
7265 llvm::Value *PointersArrayArg = nullptr;
7266 llvm::Value *SizesArrayArg = nullptr;
7267 llvm::Value *MapTypesArrayArg = nullptr;
7268 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007269 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007270
7271 // Emit device ID if any.
7272 llvm::Value *DeviceID = nullptr;
7273 if (Device)
7274 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7275 CGF.Int32Ty, /*isSigned=*/true);
7276 else
7277 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
7278
7279 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007280 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007281
7282 llvm::Value *OffloadingArgs[] = {
7283 DeviceID, PointerNum, BasePointersArrayArg,
7284 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
7285 auto &RT = CGF.CGM.getOpenMPRuntime();
7286 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_begin),
7287 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00007288
7289 // If device pointer privatization is required, emit the body of the region
7290 // here. It will have to be duplicated: with and without privatization.
7291 if (!Info.CaptureDeviceAddrMap.empty())
7292 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007293 };
7294
7295 // Generate code for the closing of the data region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007296 auto &&EndThenGen = [Device, &Info](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007297 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00007298
7299 llvm::Value *BasePointersArrayArg = nullptr;
7300 llvm::Value *PointersArrayArg = nullptr;
7301 llvm::Value *SizesArrayArg = nullptr;
7302 llvm::Value *MapTypesArrayArg = nullptr;
7303 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007304 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007305
7306 // Emit device ID if any.
7307 llvm::Value *DeviceID = nullptr;
7308 if (Device)
7309 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7310 CGF.Int32Ty, /*isSigned=*/true);
7311 else
7312 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
7313
7314 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007315 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007316
7317 llvm::Value *OffloadingArgs[] = {
7318 DeviceID, PointerNum, BasePointersArrayArg,
7319 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
7320 auto &RT = CGF.CGM.getOpenMPRuntime();
7321 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_end),
7322 OffloadingArgs);
7323 };
7324
Samuel Antaocc10b852016-07-28 14:23:26 +00007325 // If we need device pointer privatization, we need to emit the body of the
7326 // region with no privatization in the 'else' branch of the conditional.
7327 // Otherwise, we don't have to do anything.
7328 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
7329 PrePostActionTy &) {
7330 if (!Info.CaptureDeviceAddrMap.empty()) {
7331 CodeGen.setAction(NoPrivAction);
7332 CodeGen(CGF);
7333 }
7334 };
7335
7336 // We don't have to do anything to close the region if the if clause evaluates
7337 // to false.
7338 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00007339
7340 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007341 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007342 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007343 RegionCodeGenTy RCG(BeginThenGen);
7344 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007345 }
7346
Samuel Antaocc10b852016-07-28 14:23:26 +00007347 // If we don't require privatization of device pointers, we emit the body in
7348 // between the runtime calls. This avoids duplicating the body code.
7349 if (Info.CaptureDeviceAddrMap.empty()) {
7350 CodeGen.setAction(NoPrivAction);
7351 CodeGen(CGF);
7352 }
Samuel Antaodf158d52016-04-27 22:58:19 +00007353
7354 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007355 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007356 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007357 RegionCodeGenTy RCG(EndThenGen);
7358 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007359 }
7360}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007361
Samuel Antao8d2d7302016-05-26 18:30:22 +00007362void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00007363 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7364 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007365 if (!CGF.HaveInsertPoint())
7366 return;
7367
Samuel Antao8dd66282016-04-27 23:14:30 +00007368 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00007369 isa<OMPTargetExitDataDirective>(D) ||
7370 isa<OMPTargetUpdateDirective>(D)) &&
7371 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00007372
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007373 // Generate the code for the opening of the data environment.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007374 auto &&ThenGen = [&D, Device](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007375 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00007376 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007377 MappableExprsHandler::MapValuesArrayTy Pointers;
7378 MappableExprsHandler::MapValuesArrayTy Sizes;
7379 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7380
7381 // Get map clause information.
Samuel Antao8d2d7302016-05-26 18:30:22 +00007382 MappableExprsHandler MEHandler(D, CGF);
7383 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007384
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007385 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00007386 TargetDataInfo Info;
7387 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
7388 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
7389 Info.PointersArray, Info.SizesArray,
7390 Info.MapTypesArray, Info);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007391
7392 // Emit device ID if any.
7393 llvm::Value *DeviceID = nullptr;
7394 if (Device)
7395 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7396 CGF.Int32Ty, /*isSigned=*/true);
7397 else
7398 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
7399
7400 // Emit the number of elements in the offloading arrays.
7401 auto *PointerNum = CGF.Builder.getInt32(BasePointers.size());
7402
7403 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007404 DeviceID, PointerNum, Info.BasePointersArray,
7405 Info.PointersArray, Info.SizesArray, Info.MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00007406
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007407 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antao8d2d7302016-05-26 18:30:22 +00007408 // Select the right runtime function call for each expected standalone
7409 // directive.
7410 OpenMPRTLFunction RTLFn;
7411 switch (D.getDirectiveKind()) {
7412 default:
7413 llvm_unreachable("Unexpected standalone target data directive.");
7414 break;
7415 case OMPD_target_enter_data:
7416 RTLFn = OMPRTL__tgt_target_data_begin;
7417 break;
7418 case OMPD_target_exit_data:
7419 RTLFn = OMPRTL__tgt_target_data_end;
7420 break;
7421 case OMPD_target_update:
7422 RTLFn = OMPRTL__tgt_target_data_update;
7423 break;
7424 }
7425 CGF.EmitRuntimeCall(RT.createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007426 };
7427
7428 // In the event we get an if clause, we don't have to take any action on the
7429 // else side.
7430 auto &&ElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
7431
7432 if (IfCond) {
7433 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
7434 } else {
7435 RegionCodeGenTy ThenGenRCG(ThenGen);
7436 ThenGenRCG(CGF);
7437 }
7438}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007439
7440namespace {
7441 /// Kind of parameter in a function with 'declare simd' directive.
7442 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
7443 /// Attribute set of the parameter.
7444 struct ParamAttrTy {
7445 ParamKindTy Kind = Vector;
7446 llvm::APSInt StrideOrArg;
7447 llvm::APSInt Alignment;
7448 };
7449} // namespace
7450
7451static unsigned evaluateCDTSize(const FunctionDecl *FD,
7452 ArrayRef<ParamAttrTy> ParamAttrs) {
7453 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
7454 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
7455 // of that clause. The VLEN value must be power of 2.
7456 // In other case the notion of the function`s "characteristic data type" (CDT)
7457 // is used to compute the vector length.
7458 // CDT is defined in the following order:
7459 // a) For non-void function, the CDT is the return type.
7460 // b) If the function has any non-uniform, non-linear parameters, then the
7461 // CDT is the type of the first such parameter.
7462 // c) If the CDT determined by a) or b) above is struct, union, or class
7463 // type which is pass-by-value (except for the type that maps to the
7464 // built-in complex data type), the characteristic data type is int.
7465 // d) If none of the above three cases is applicable, the CDT is int.
7466 // The VLEN is then determined based on the CDT and the size of vector
7467 // register of that ISA for which current vector version is generated. The
7468 // VLEN is computed using the formula below:
7469 // VLEN = sizeof(vector_register) / sizeof(CDT),
7470 // where vector register size specified in section 3.2.1 Registers and the
7471 // Stack Frame of original AMD64 ABI document.
7472 QualType RetType = FD->getReturnType();
7473 if (RetType.isNull())
7474 return 0;
7475 ASTContext &C = FD->getASTContext();
7476 QualType CDT;
7477 if (!RetType.isNull() && !RetType->isVoidType())
7478 CDT = RetType;
7479 else {
7480 unsigned Offset = 0;
7481 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
7482 if (ParamAttrs[Offset].Kind == Vector)
7483 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
7484 ++Offset;
7485 }
7486 if (CDT.isNull()) {
7487 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
7488 if (ParamAttrs[I + Offset].Kind == Vector) {
7489 CDT = FD->getParamDecl(I)->getType();
7490 break;
7491 }
7492 }
7493 }
7494 }
7495 if (CDT.isNull())
7496 CDT = C.IntTy;
7497 CDT = CDT->getCanonicalTypeUnqualified();
7498 if (CDT->isRecordType() || CDT->isUnionType())
7499 CDT = C.IntTy;
7500 return C.getTypeSize(CDT);
7501}
7502
7503static void
7504emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00007505 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007506 ArrayRef<ParamAttrTy> ParamAttrs,
7507 OMPDeclareSimdDeclAttr::BranchStateTy State) {
7508 struct ISADataTy {
7509 char ISA;
7510 unsigned VecRegSize;
7511 };
7512 ISADataTy ISAData[] = {
7513 {
7514 'b', 128
7515 }, // SSE
7516 {
7517 'c', 256
7518 }, // AVX
7519 {
7520 'd', 256
7521 }, // AVX2
7522 {
7523 'e', 512
7524 }, // AVX512
7525 };
7526 llvm::SmallVector<char, 2> Masked;
7527 switch (State) {
7528 case OMPDeclareSimdDeclAttr::BS_Undefined:
7529 Masked.push_back('N');
7530 Masked.push_back('M');
7531 break;
7532 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
7533 Masked.push_back('N');
7534 break;
7535 case OMPDeclareSimdDeclAttr::BS_Inbranch:
7536 Masked.push_back('M');
7537 break;
7538 }
7539 for (auto Mask : Masked) {
7540 for (auto &Data : ISAData) {
7541 SmallString<256> Buffer;
7542 llvm::raw_svector_ostream Out(Buffer);
7543 Out << "_ZGV" << Data.ISA << Mask;
7544 if (!VLENVal) {
7545 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
7546 evaluateCDTSize(FD, ParamAttrs));
7547 } else
7548 Out << VLENVal;
7549 for (auto &ParamAttr : ParamAttrs) {
7550 switch (ParamAttr.Kind){
7551 case LinearWithVarStride:
7552 Out << 's' << ParamAttr.StrideOrArg;
7553 break;
7554 case Linear:
7555 Out << 'l';
7556 if (!!ParamAttr.StrideOrArg)
7557 Out << ParamAttr.StrideOrArg;
7558 break;
7559 case Uniform:
7560 Out << 'u';
7561 break;
7562 case Vector:
7563 Out << 'v';
7564 break;
7565 }
7566 if (!!ParamAttr.Alignment)
7567 Out << 'a' << ParamAttr.Alignment;
7568 }
7569 Out << '_' << Fn->getName();
7570 Fn->addFnAttr(Out.str());
7571 }
7572 }
7573}
7574
7575void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
7576 llvm::Function *Fn) {
7577 ASTContext &C = CGM.getContext();
7578 FD = FD->getCanonicalDecl();
7579 // Map params to their positions in function decl.
7580 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
7581 if (isa<CXXMethodDecl>(FD))
7582 ParamPositions.insert({FD, 0});
7583 unsigned ParamPos = ParamPositions.size();
David Majnemer59f77922016-06-24 04:05:48 +00007584 for (auto *P : FD->parameters()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007585 ParamPositions.insert({P->getCanonicalDecl(), ParamPos});
7586 ++ParamPos;
7587 }
7588 for (auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
7589 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
7590 // Mark uniform parameters.
7591 for (auto *E : Attr->uniforms()) {
7592 E = E->IgnoreParenImpCasts();
7593 unsigned Pos;
7594 if (isa<CXXThisExpr>(E))
7595 Pos = ParamPositions[FD];
7596 else {
7597 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7598 ->getCanonicalDecl();
7599 Pos = ParamPositions[PVD];
7600 }
7601 ParamAttrs[Pos].Kind = Uniform;
7602 }
7603 // Get alignment info.
7604 auto NI = Attr->alignments_begin();
7605 for (auto *E : Attr->aligneds()) {
7606 E = E->IgnoreParenImpCasts();
7607 unsigned Pos;
7608 QualType ParmTy;
7609 if (isa<CXXThisExpr>(E)) {
7610 Pos = ParamPositions[FD];
7611 ParmTy = E->getType();
7612 } else {
7613 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7614 ->getCanonicalDecl();
7615 Pos = ParamPositions[PVD];
7616 ParmTy = PVD->getType();
7617 }
7618 ParamAttrs[Pos].Alignment =
7619 (*NI) ? (*NI)->EvaluateKnownConstInt(C)
7620 : llvm::APSInt::getUnsigned(
7621 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
7622 .getQuantity());
7623 ++NI;
7624 }
7625 // Mark linear parameters.
7626 auto SI = Attr->steps_begin();
7627 auto MI = Attr->modifiers_begin();
7628 for (auto *E : Attr->linears()) {
7629 E = E->IgnoreParenImpCasts();
7630 unsigned Pos;
7631 if (isa<CXXThisExpr>(E))
7632 Pos = ParamPositions[FD];
7633 else {
7634 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7635 ->getCanonicalDecl();
7636 Pos = ParamPositions[PVD];
7637 }
7638 auto &ParamAttr = ParamAttrs[Pos];
7639 ParamAttr.Kind = Linear;
7640 if (*SI) {
7641 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
7642 Expr::SE_AllowSideEffects)) {
7643 if (auto *DRE = cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
7644 if (auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
7645 ParamAttr.Kind = LinearWithVarStride;
7646 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
7647 ParamPositions[StridePVD->getCanonicalDecl()]);
7648 }
7649 }
7650 }
7651 }
7652 ++SI;
7653 ++MI;
7654 }
7655 llvm::APSInt VLENVal;
7656 if (const Expr *VLEN = Attr->getSimdlen())
7657 VLENVal = VLEN->EvaluateKnownConstInt(C);
7658 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
7659 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
7660 CGM.getTriple().getArch() == llvm::Triple::x86_64)
7661 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
7662 }
7663}
Alexey Bataev8b427062016-05-25 12:36:08 +00007664
7665namespace {
7666/// Cleanup action for doacross support.
7667class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
7668public:
7669 static const int DoacrossFinArgs = 2;
7670
7671private:
7672 llvm::Value *RTLFn;
7673 llvm::Value *Args[DoacrossFinArgs];
7674
7675public:
7676 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
7677 : RTLFn(RTLFn) {
7678 assert(CallArgs.size() == DoacrossFinArgs);
7679 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
7680 }
7681 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
7682 if (!CGF.HaveInsertPoint())
7683 return;
7684 CGF.EmitRuntimeCall(RTLFn, Args);
7685 }
7686};
7687} // namespace
7688
7689void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
7690 const OMPLoopDirective &D) {
7691 if (!CGF.HaveInsertPoint())
7692 return;
7693
7694 ASTContext &C = CGM.getContext();
7695 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
7696 RecordDecl *RD;
7697 if (KmpDimTy.isNull()) {
7698 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
7699 // kmp_int64 lo; // lower
7700 // kmp_int64 up; // upper
7701 // kmp_int64 st; // stride
7702 // };
7703 RD = C.buildImplicitRecord("kmp_dim");
7704 RD->startDefinition();
7705 addFieldToRecordDecl(C, RD, Int64Ty);
7706 addFieldToRecordDecl(C, RD, Int64Ty);
7707 addFieldToRecordDecl(C, RD, Int64Ty);
7708 RD->completeDefinition();
7709 KmpDimTy = C.getRecordType(RD);
7710 } else
7711 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
7712
7713 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
7714 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
7715 enum { LowerFD = 0, UpperFD, StrideFD };
7716 // Fill dims with data.
7717 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
7718 // dims.upper = num_iterations;
7719 LValue UpperLVal =
7720 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
7721 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
7722 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
7723 Int64Ty, D.getNumIterations()->getExprLoc());
7724 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
7725 // dims.stride = 1;
7726 LValue StrideLVal =
7727 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
7728 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
7729 StrideLVal);
7730
7731 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
7732 // kmp_int32 num_dims, struct kmp_dim * dims);
7733 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
7734 getThreadID(CGF, D.getLocStart()),
7735 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
7736 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7737 DimsAddr.getPointer(), CGM.VoidPtrTy)};
7738
7739 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
7740 CGF.EmitRuntimeCall(RTLFn, Args);
7741 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
7742 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
7743 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
7744 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
7745 llvm::makeArrayRef(FiniArgs));
7746}
7747
7748void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
7749 const OMPDependClause *C) {
7750 QualType Int64Ty =
7751 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
7752 const Expr *CounterVal = C->getCounterValue();
7753 assert(CounterVal);
7754 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
7755 CounterVal->getType(), Int64Ty,
7756 CounterVal->getExprLoc());
7757 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
7758 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
7759 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
7760 getThreadID(CGF, C->getLocStart()),
7761 CntAddr.getPointer()};
7762 llvm::Value *RTLFn;
7763 if (C->getDependencyKind() == OMPC_DEPEND_source)
7764 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
7765 else {
7766 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
7767 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
7768 }
7769 CGF.EmitRuntimeCall(RTLFn, Args);
7770}
7771
Alexey Bataev3c595a62017-08-14 15:01:03 +00007772void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, llvm::Value *Callee,
7773 ArrayRef<llvm::Value *> Args,
7774 SourceLocation Loc) const {
7775 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
7776
7777 if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007778 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00007779 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007780 return;
7781 }
7782 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00007783 CGF.EmitRuntimeCall(Callee, Args);
7784}
7785
7786void CGOpenMPRuntime::emitOutlinedFunctionCall(
7787 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
7788 ArrayRef<llvm::Value *> Args) const {
7789 assert(Loc.isValid() && "Outlined function call location must be valid.");
7790 emitCall(CGF, OutlinedFn, Args, Loc);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007791}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00007792
7793Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
7794 const VarDecl *NativeParam,
7795 const VarDecl *TargetParam) const {
7796 return CGF.GetAddrOfLocalVar(NativeParam);
7797}