blob: 3df95a4e9b2a9234e5aa322539a337d9ed32dbb5 [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"
Teresa Johnsonffc4e242016-11-11 05:35:12 +000022#include "llvm/Bitcode/BitcodeReader.h"
Alexey Bataevd74d0602014-10-13 06:02:40 +000023#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000024#include "llvm/IR/DerivedTypes.h"
25#include "llvm/IR/GlobalValue.h"
26#include "llvm/IR/Value.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000027#include "llvm/Support/Format.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000028#include "llvm/Support/raw_ostream.h"
Alexey Bataev23b69422014-06-18 07:08:49 +000029#include <cassert>
Alexey Bataev9959db52014-05-06 10:08:46 +000030
31using namespace clang;
32using namespace CodeGen;
33
Benjamin Kramerc52193f2014-10-10 13:57:57 +000034namespace {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000035/// \brief Base class for handling code generation inside OpenMP regions.
Alexey Bataev18095712014-10-10 12:19:54 +000036class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
37public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000038 /// \brief Kinds of OpenMP regions used in codegen.
39 enum CGOpenMPRegionKind {
40 /// \brief Region with outlined function for standalone 'parallel'
41 /// directive.
42 ParallelOutlinedRegion,
43 /// \brief Region with outlined function for standalone 'task' directive.
44 TaskOutlinedRegion,
45 /// \brief Region for constructs that do not require function outlining,
46 /// like 'for', 'sections', 'atomic' etc. directives.
47 InlinedRegion,
Samuel Antaobed3c462015-10-02 16:14:20 +000048 /// \brief Region with outlined function for standalone 'target' directive.
49 TargetRegion,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000050 };
Alexey Bataev18095712014-10-10 12:19:54 +000051
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000052 CGOpenMPRegionInfo(const CapturedStmt &CS,
53 const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000054 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
55 bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000056 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
Alexey Bataev25e5b442015-09-15 12:52:43 +000057 CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000058
59 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000060 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
61 bool HasCancel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +000062 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
Alexey Bataev25e5b442015-09-15 12:52:43 +000063 Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000064
65 /// \brief Get a variable or parameter for storing global thread id
Alexey Bataev18095712014-10-10 12:19:54 +000066 /// inside OpenMP construct.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000067 virtual const VarDecl *getThreadIDVariable() const = 0;
Alexey Bataev18095712014-10-10 12:19:54 +000068
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000069 /// \brief Emit the captured statement body.
Hans Wennborg7eb54642015-09-10 17:07:54 +000070 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000071
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000072 /// \brief Get an LValue for the current ThreadID variable.
Alexey Bataev62b63b12015-03-10 07:28:44 +000073 /// \return LValue for thread id variable. This LValue always has type int32*.
74 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
Alexey Bataev18095712014-10-10 12:19:54 +000075
Alexey Bataev48591dd2016-04-20 04:01:36 +000076 virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {}
77
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000078 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000079
Alexey Bataev81c7ea02015-07-03 09:56:58 +000080 OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
81
Alexey Bataev25e5b442015-09-15 12:52:43 +000082 bool hasCancel() const { return HasCancel; }
83
Alexey Bataev18095712014-10-10 12:19:54 +000084 static bool classof(const CGCapturedStmtInfo *Info) {
85 return Info->getKind() == CR_OpenMP;
86 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000087
Alexey Bataev48591dd2016-04-20 04:01:36 +000088 ~CGOpenMPRegionInfo() override = default;
89
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000090protected:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000091 CGOpenMPRegionKind RegionKind;
Hans Wennborg45c74392016-01-12 20:54:36 +000092 RegionCodeGenTy CodeGen;
Alexey Bataev81c7ea02015-07-03 09:56:58 +000093 OpenMPDirectiveKind Kind;
Alexey Bataev25e5b442015-09-15 12:52:43 +000094 bool HasCancel;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000095};
Alexey Bataev18095712014-10-10 12:19:54 +000096
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000097/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +000098class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000099public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000100 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000101 const RegionCodeGenTy &CodeGen,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000102 OpenMPDirectiveKind Kind, bool HasCancel,
103 StringRef HelperName)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000104 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
105 HasCancel),
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000106 ThreadIDVar(ThreadIDVar), HelperName(HelperName) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000107 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
108 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000109
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000110 /// \brief Get a variable or parameter for storing global thread id
111 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000112 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000113
Alexey Bataev18095712014-10-10 12:19:54 +0000114 /// \brief Get the name of the capture helper.
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000115 StringRef getHelperName() const override { return HelperName; }
Alexey Bataev18095712014-10-10 12:19:54 +0000116
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000117 static bool classof(const CGCapturedStmtInfo *Info) {
118 return CGOpenMPRegionInfo::classof(Info) &&
119 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
120 ParallelOutlinedRegion;
121 }
122
Alexey Bataev18095712014-10-10 12:19:54 +0000123private:
124 /// \brief A variable or parameter storing global thread id for OpenMP
125 /// constructs.
126 const VarDecl *ThreadIDVar;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000127 StringRef HelperName;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000128};
129
Alexey Bataev62b63b12015-03-10 07:28:44 +0000130/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000131class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000132public:
Alexey Bataev48591dd2016-04-20 04:01:36 +0000133 class UntiedTaskActionTy final : public PrePostActionTy {
134 bool Untied;
135 const VarDecl *PartIDVar;
136 const RegionCodeGenTy UntiedCodeGen;
137 llvm::SwitchInst *UntiedSwitch = nullptr;
138
139 public:
140 UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
141 const RegionCodeGenTy &UntiedCodeGen)
142 : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
143 void Enter(CodeGenFunction &CGF) override {
144 if (Untied) {
145 // Emit task switching point.
146 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
147 CGF.GetAddrOfLocalVar(PartIDVar),
148 PartIDVar->getType()->castAs<PointerType>());
149 auto *Res = CGF.EmitLoadOfScalar(PartIdLVal, SourceLocation());
150 auto *DoneBB = CGF.createBasicBlock(".untied.done.");
151 UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
152 CGF.EmitBlock(DoneBB);
153 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
154 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
155 UntiedSwitch->addCase(CGF.Builder.getInt32(0),
156 CGF.Builder.GetInsertBlock());
157 emitUntiedSwitch(CGF);
158 }
159 }
160 void emitUntiedSwitch(CodeGenFunction &CGF) const {
161 if (Untied) {
162 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
163 CGF.GetAddrOfLocalVar(PartIDVar),
164 PartIDVar->getType()->castAs<PointerType>());
165 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
166 PartIdLVal);
167 UntiedCodeGen(CGF);
168 CodeGenFunction::JumpDest CurPoint =
169 CGF.getJumpDestInCurrentScope(".untied.next.");
170 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
171 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
172 UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
173 CGF.Builder.GetInsertBlock());
174 CGF.EmitBranchThroughCleanup(CurPoint);
175 CGF.EmitBlock(CurPoint.getBlock());
176 }
177 }
178 unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
179 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000180 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000181 const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000182 const RegionCodeGenTy &CodeGen,
Alexey Bataev48591dd2016-04-20 04:01:36 +0000183 OpenMPDirectiveKind Kind, bool HasCancel,
184 const UntiedTaskActionTy &Action)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000185 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
Alexey Bataev48591dd2016-04-20 04:01:36 +0000186 ThreadIDVar(ThreadIDVar), Action(Action) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000187 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
188 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000189
Alexey Bataev62b63b12015-03-10 07:28:44 +0000190 /// \brief Get a variable or parameter for storing global thread id
191 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000192 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000193
194 /// \brief Get an LValue for the current ThreadID variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000195 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000196
Alexey Bataev62b63b12015-03-10 07:28:44 +0000197 /// \brief Get the name of the capture helper.
198 StringRef getHelperName() const override { return ".omp_outlined."; }
199
Alexey Bataev48591dd2016-04-20 04:01:36 +0000200 void emitUntiedSwitch(CodeGenFunction &CGF) override {
201 Action.emitUntiedSwitch(CGF);
202 }
203
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000204 static bool classof(const CGCapturedStmtInfo *Info) {
205 return CGOpenMPRegionInfo::classof(Info) &&
206 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
207 TaskOutlinedRegion;
208 }
209
Alexey Bataev62b63b12015-03-10 07:28:44 +0000210private:
211 /// \brief A variable or parameter storing global thread id for OpenMP
212 /// constructs.
213 const VarDecl *ThreadIDVar;
Alexey Bataev48591dd2016-04-20 04:01:36 +0000214 /// Action for emitting code for untied tasks.
215 const UntiedTaskActionTy &Action;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000216};
217
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000218/// \brief API for inlined captured statement code generation in OpenMP
219/// constructs.
220class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
221public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000222 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000223 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000224 OpenMPDirectiveKind Kind, bool HasCancel)
225 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
226 OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000227 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000228
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000229 // \brief Retrieve the value of the context parameter.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000230 llvm::Value *getContextValue() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000231 if (OuterRegionInfo)
232 return OuterRegionInfo->getContextValue();
233 llvm_unreachable("No context value for inlined OpenMP region");
234 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000235
Hans Wennborg7eb54642015-09-10 17:07:54 +0000236 void setContextValue(llvm::Value *V) override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000237 if (OuterRegionInfo) {
238 OuterRegionInfo->setContextValue(V);
239 return;
240 }
241 llvm_unreachable("No context value for inlined OpenMP region");
242 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000243
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000244 /// \brief Lookup the captured field decl for a variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000245 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000246 if (OuterRegionInfo)
247 return OuterRegionInfo->lookup(VD);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000248 // If there is no outer outlined region,no need to lookup in a list of
249 // captured variables, we can use the original one.
250 return nullptr;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000251 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000252
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000253 FieldDecl *getThisFieldDecl() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000254 if (OuterRegionInfo)
255 return OuterRegionInfo->getThisFieldDecl();
256 return nullptr;
257 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000258
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000259 /// \brief Get a variable or parameter for storing global thread id
260 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000261 const VarDecl *getThreadIDVariable() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000262 if (OuterRegionInfo)
263 return OuterRegionInfo->getThreadIDVariable();
264 return nullptr;
265 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000266
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000267 /// \brief Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000268 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000269 if (auto *OuterRegionInfo = getOldCSI())
270 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000271 llvm_unreachable("No helper name for inlined OpenMP construct");
272 }
273
Alexey Bataev48591dd2016-04-20 04:01:36 +0000274 void emitUntiedSwitch(CodeGenFunction &CGF) override {
275 if (OuterRegionInfo)
276 OuterRegionInfo->emitUntiedSwitch(CGF);
277 }
278
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000279 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
280
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000281 static bool classof(const CGCapturedStmtInfo *Info) {
282 return CGOpenMPRegionInfo::classof(Info) &&
283 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
284 }
285
Alexey Bataev48591dd2016-04-20 04:01:36 +0000286 ~CGOpenMPInlinedRegionInfo() override = default;
287
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000288private:
289 /// \brief CodeGen info about outer OpenMP region.
290 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
291 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000292};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000293
Samuel Antaobed3c462015-10-02 16:14:20 +0000294/// \brief API for captured statement code generation in OpenMP target
295/// constructs. For this captures, implicit parameters are used instead of the
Samuel Antaoee8fb302016-01-06 13:42:12 +0000296/// captured fields. The name of the target region has to be unique in a given
297/// application so it is provided by the client, because only the client has
298/// the information to generate that.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000299class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
Samuel Antaobed3c462015-10-02 16:14:20 +0000300public:
301 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000302 const RegionCodeGenTy &CodeGen, StringRef HelperName)
Samuel Antaobed3c462015-10-02 16:14:20 +0000303 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000304 /*HasCancel=*/false),
305 HelperName(HelperName) {}
Samuel Antaobed3c462015-10-02 16:14:20 +0000306
307 /// \brief This is unused for target regions because each starts executing
308 /// with a single thread.
309 const VarDecl *getThreadIDVariable() const override { return nullptr; }
310
311 /// \brief Get the name of the capture helper.
Samuel Antaoee8fb302016-01-06 13:42:12 +0000312 StringRef getHelperName() const override { return HelperName; }
Samuel Antaobed3c462015-10-02 16:14:20 +0000313
314 static bool classof(const CGCapturedStmtInfo *Info) {
315 return CGOpenMPRegionInfo::classof(Info) &&
316 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
317 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000318
319private:
320 StringRef HelperName;
Samuel Antaobed3c462015-10-02 16:14:20 +0000321};
322
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000323static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000324 llvm_unreachable("No codegen for expressions");
325}
326/// \brief API for generation of expressions captured in a innermost OpenMP
327/// region.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000328class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000329public:
330 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
331 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
332 OMPD_unknown,
333 /*HasCancel=*/false),
334 PrivScope(CGF) {
335 // Make sure the globals captured in the provided statement are local by
336 // using the privatization logic. We assume the same variable is not
337 // captured more than once.
338 for (auto &C : CS.captures()) {
339 if (!C.capturesVariable() && !C.capturesVariableByCopy())
340 continue;
341
342 const VarDecl *VD = C.getCapturedVar();
343 if (VD->isLocalVarDeclOrParm())
344 continue;
345
346 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
347 /*RefersToEnclosingVariableOrCapture=*/false,
348 VD->getType().getNonReferenceType(), VK_LValue,
349 SourceLocation());
350 PrivScope.addPrivate(VD, [&CGF, &DRE]() -> Address {
351 return CGF.EmitLValue(&DRE).getAddress();
352 });
353 }
354 (void)PrivScope.Privatize();
355 }
356
357 /// \brief Lookup the captured field decl for a variable.
358 const FieldDecl *lookup(const VarDecl *VD) const override {
359 if (auto *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
360 return FD;
361 return nullptr;
362 }
363
364 /// \brief Emit the captured statement body.
365 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
366 llvm_unreachable("No body for expressions");
367 }
368
369 /// \brief Get a variable or parameter for storing global thread id
370 /// inside OpenMP construct.
371 const VarDecl *getThreadIDVariable() const override {
372 llvm_unreachable("No thread id for expressions");
373 }
374
375 /// \brief Get the name of the capture helper.
376 StringRef getHelperName() const override {
377 llvm_unreachable("No helper name for expressions");
378 }
379
380 static bool classof(const CGCapturedStmtInfo *Info) { return false; }
381
382private:
383 /// Private scope to capture global variables.
384 CodeGenFunction::OMPPrivateScope PrivScope;
385};
386
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000387/// \brief RAII for emitting code of OpenMP constructs.
388class InlinedOpenMPRegionRAII {
389 CodeGenFunction &CGF;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000390 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
391 FieldDecl *LambdaThisCaptureField = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000392
393public:
394 /// \brief Constructs region for combined constructs.
395 /// \param CodeGen Code generation sequence for combined directives. Includes
396 /// a list of functions used for code generation of implicitly inlined
397 /// regions.
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000398 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000399 OpenMPDirectiveKind Kind, bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000400 : CGF(CGF) {
401 // Start emission for the construct.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000402 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
403 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000404 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
405 LambdaThisCaptureField = CGF.LambdaThisCaptureField;
406 CGF.LambdaThisCaptureField = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000407 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000408
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000409 ~InlinedOpenMPRegionRAII() {
410 // Restore original CapturedStmtInfo only if we're done with code emission.
411 auto *OldCSI =
412 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
413 delete CGF.CapturedStmtInfo;
414 CGF.CapturedStmtInfo = OldCSI;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000415 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
416 CGF.LambdaThisCaptureField = LambdaThisCaptureField;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000417 }
418};
419
Alexey Bataev50b3c952016-02-19 10:38:26 +0000420/// \brief Values for bit flags used in the ident_t to describe the fields.
421/// All enumeric elements are named and described in accordance with the code
422/// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
423enum OpenMPLocationFlags {
424 /// \brief Use trampoline for internal microtask.
425 OMP_IDENT_IMD = 0x01,
426 /// \brief Use c-style ident structure.
427 OMP_IDENT_KMPC = 0x02,
428 /// \brief Atomic reduction option for kmpc_reduce.
429 OMP_ATOMIC_REDUCE = 0x10,
430 /// \brief Explicit 'barrier' directive.
431 OMP_IDENT_BARRIER_EXPL = 0x20,
432 /// \brief Implicit barrier in code.
433 OMP_IDENT_BARRIER_IMPL = 0x40,
434 /// \brief Implicit barrier in 'for' directive.
435 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
436 /// \brief Implicit barrier in 'sections' directive.
437 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
438 /// \brief Implicit barrier in 'single' directive.
439 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140
440};
441
442/// \brief Describes ident structure that describes a source location.
443/// All descriptions are taken from
444/// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
445/// Original structure:
446/// typedef struct ident {
447/// kmp_int32 reserved_1; /**< might be used in Fortran;
448/// see above */
449/// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
450/// KMP_IDENT_KMPC identifies this union
451/// member */
452/// kmp_int32 reserved_2; /**< not really used in Fortran any more;
453/// see above */
454///#if USE_ITT_BUILD
455/// /* but currently used for storing
456/// region-specific ITT */
457/// /* contextual information. */
458///#endif /* USE_ITT_BUILD */
459/// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
460/// C++ */
461/// char const *psource; /**< String describing the source location.
462/// The string is composed of semi-colon separated
463// fields which describe the source file,
464/// the function and a pair of line numbers that
465/// delimit the construct.
466/// */
467/// } ident_t;
468enum IdentFieldIndex {
469 /// \brief might be used in Fortran
470 IdentField_Reserved_1,
471 /// \brief OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
472 IdentField_Flags,
473 /// \brief Not really used in Fortran any more
474 IdentField_Reserved_2,
475 /// \brief Source[4] in Fortran, do not use for C++
476 IdentField_Reserved_3,
477 /// \brief String describing the source location. The string is composed of
478 /// semi-colon separated fields which describe the source file, the function
479 /// and a pair of line numbers that delimit the construct.
480 IdentField_PSource
481};
482
483/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
484/// the enum sched_type in kmp.h).
485enum OpenMPSchedType {
486 /// \brief Lower bound for default (unordered) versions.
487 OMP_sch_lower = 32,
488 OMP_sch_static_chunked = 33,
489 OMP_sch_static = 34,
490 OMP_sch_dynamic_chunked = 35,
491 OMP_sch_guided_chunked = 36,
492 OMP_sch_runtime = 37,
493 OMP_sch_auto = 38,
Alexey Bataev6cff6242016-05-30 13:05:14 +0000494 /// static with chunk adjustment (e.g., simd)
Samuel Antao4c8035b2016-12-12 18:00:20 +0000495 OMP_sch_static_balanced_chunked = 45,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000496 /// \brief Lower bound for 'ordered' versions.
497 OMP_ord_lower = 64,
498 OMP_ord_static_chunked = 65,
499 OMP_ord_static = 66,
500 OMP_ord_dynamic_chunked = 67,
501 OMP_ord_guided_chunked = 68,
502 OMP_ord_runtime = 69,
503 OMP_ord_auto = 70,
504 OMP_sch_default = OMP_sch_static,
Carlo Bertollifc35ad22016-03-07 16:04:49 +0000505 /// \brief dist_schedule types
506 OMP_dist_sch_static_chunked = 91,
507 OMP_dist_sch_static = 92,
Alexey Bataev9ebd7422016-05-10 09:57:36 +0000508 /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
509 /// Set if the monotonic schedule modifier was present.
510 OMP_sch_modifier_monotonic = (1 << 29),
511 /// Set if the nonmonotonic schedule modifier was present.
512 OMP_sch_modifier_nonmonotonic = (1 << 30),
Alexey Bataev50b3c952016-02-19 10:38:26 +0000513};
514
515enum OpenMPRTLFunction {
516 /// \brief Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
517 /// kmpc_micro microtask, ...);
518 OMPRTL__kmpc_fork_call,
519 /// \brief Call to void *__kmpc_threadprivate_cached(ident_t *loc,
520 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
521 OMPRTL__kmpc_threadprivate_cached,
522 /// \brief Call to void __kmpc_threadprivate_register( ident_t *,
523 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
524 OMPRTL__kmpc_threadprivate_register,
525 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
526 OMPRTL__kmpc_global_thread_num,
527 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
528 // kmp_critical_name *crit);
529 OMPRTL__kmpc_critical,
530 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
531 // global_tid, kmp_critical_name *crit, uintptr_t hint);
532 OMPRTL__kmpc_critical_with_hint,
533 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
534 // kmp_critical_name *crit);
535 OMPRTL__kmpc_end_critical,
536 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
537 // global_tid);
538 OMPRTL__kmpc_cancel_barrier,
539 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
540 OMPRTL__kmpc_barrier,
541 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
542 OMPRTL__kmpc_for_static_fini,
543 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
544 // global_tid);
545 OMPRTL__kmpc_serialized_parallel,
546 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
547 // global_tid);
548 OMPRTL__kmpc_end_serialized_parallel,
549 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
550 // kmp_int32 num_threads);
551 OMPRTL__kmpc_push_num_threads,
552 // Call to void __kmpc_flush(ident_t *loc);
553 OMPRTL__kmpc_flush,
554 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
555 OMPRTL__kmpc_master,
556 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
557 OMPRTL__kmpc_end_master,
558 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
559 // int end_part);
560 OMPRTL__kmpc_omp_taskyield,
561 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
562 OMPRTL__kmpc_single,
563 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
564 OMPRTL__kmpc_end_single,
565 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
566 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
567 // kmp_routine_entry_t *task_entry);
568 OMPRTL__kmpc_omp_task_alloc,
569 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
570 // new_task);
571 OMPRTL__kmpc_omp_task,
572 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
573 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
574 // kmp_int32 didit);
575 OMPRTL__kmpc_copyprivate,
576 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
577 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
578 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
579 OMPRTL__kmpc_reduce,
580 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
581 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
582 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
583 // *lck);
584 OMPRTL__kmpc_reduce_nowait,
585 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
586 // kmp_critical_name *lck);
587 OMPRTL__kmpc_end_reduce,
588 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
589 // kmp_critical_name *lck);
590 OMPRTL__kmpc_end_reduce_nowait,
591 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
592 // kmp_task_t * new_task);
593 OMPRTL__kmpc_omp_task_begin_if0,
594 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
595 // kmp_task_t * new_task);
596 OMPRTL__kmpc_omp_task_complete_if0,
597 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
598 OMPRTL__kmpc_ordered,
599 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
600 OMPRTL__kmpc_end_ordered,
601 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
602 // global_tid);
603 OMPRTL__kmpc_omp_taskwait,
604 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
605 OMPRTL__kmpc_taskgroup,
606 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
607 OMPRTL__kmpc_end_taskgroup,
608 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
609 // int proc_bind);
610 OMPRTL__kmpc_push_proc_bind,
611 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
612 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
613 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
614 OMPRTL__kmpc_omp_task_with_deps,
615 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
616 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
617 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
618 OMPRTL__kmpc_omp_wait_deps,
619 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
620 // global_tid, kmp_int32 cncl_kind);
621 OMPRTL__kmpc_cancellationpoint,
622 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
623 // kmp_int32 cncl_kind);
624 OMPRTL__kmpc_cancel,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000625 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
626 // kmp_int32 num_teams, kmp_int32 thread_limit);
627 OMPRTL__kmpc_push_num_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000628 // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
629 // microtask, ...);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000630 OMPRTL__kmpc_fork_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000631 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
632 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
633 // sched, kmp_uint64 grainsize, void *task_dup);
634 OMPRTL__kmpc_taskloop,
Alexey Bataev8b427062016-05-25 12:36:08 +0000635 // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
636 // num_dims, struct kmp_dim *dims);
637 OMPRTL__kmpc_doacross_init,
638 // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
639 OMPRTL__kmpc_doacross_fini,
640 // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
641 // *vec);
642 OMPRTL__kmpc_doacross_post,
643 // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
644 // *vec);
645 OMPRTL__kmpc_doacross_wait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000646
647 //
648 // Offloading related calls
649 //
650 // Call to int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
651 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
652 // *arg_types);
653 OMPRTL__tgt_target,
Samuel Antaob68e2db2016-03-03 16:20:23 +0000654 // Call to int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
655 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
656 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
657 OMPRTL__tgt_target_teams,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000658 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
659 OMPRTL__tgt_register_lib,
660 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
661 OMPRTL__tgt_unregister_lib,
Samuel Antaodf158d52016-04-27 22:58:19 +0000662 // Call to void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
663 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
664 OMPRTL__tgt_target_data_begin,
665 // Call to void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
666 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
667 OMPRTL__tgt_target_data_end,
Samuel Antao8d2d7302016-05-26 18:30:22 +0000668 // Call to void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
669 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
670 OMPRTL__tgt_target_data_update,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000671};
672
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000673/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
674/// region.
675class CleanupTy final : public EHScopeStack::Cleanup {
676 PrePostActionTy *Action;
677
678public:
679 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
680 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
681 if (!CGF.HaveInsertPoint())
682 return;
683 Action->Exit(CGF);
684 }
685};
686
Hans Wennborg7eb54642015-09-10 17:07:54 +0000687} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000688
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000689void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
690 CodeGenFunction::RunCleanupsScope Scope(CGF);
691 if (PrePostAction) {
692 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
693 Callback(CodeGen, CGF, *PrePostAction);
694 } else {
695 PrePostActionTy Action;
696 Callback(CodeGen, CGF, Action);
697 }
698}
699
Alexey Bataev18095712014-10-10 12:19:54 +0000700LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +0000701 return CGF.EmitLoadOfPointerLValue(
702 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
703 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +0000704}
705
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000706void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000707 if (!CGF.HaveInsertPoint())
708 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000709 // 1.2.2 OpenMP Language Terminology
710 // Structured block - An executable statement with a single entry at the
711 // top and a single exit at the bottom.
712 // The point of exit cannot be a branch out of the structured block.
713 // longjmp() and throw() must not violate the entry/exit criteria.
714 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000715 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000716 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000717}
718
Alexey Bataev62b63b12015-03-10 07:28:44 +0000719LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
720 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000721 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
722 getThreadIDVariable()->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000723 LValueBaseInfo(AlignmentSource::Decl, false));
Alexey Bataev62b63b12015-03-10 07:28:44 +0000724}
725
Alexey Bataev9959db52014-05-06 10:08:46 +0000726CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000727 : CGM(CGM), OffloadEntriesInfoManager(CGM) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000728 IdentTy = llvm::StructType::create(
729 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
730 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Serge Guelton1d993272017-05-09 19:31:30 +0000731 CGM.Int8PtrTy /* psource */);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000732 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +0000733
734 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +0000735}
736
Alexey Bataev91797552015-03-18 04:13:55 +0000737void CGOpenMPRuntime::clear() {
738 InternalVars.clear();
739}
740
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000741static llvm::Function *
742emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
743 const Expr *CombinerInitializer, const VarDecl *In,
744 const VarDecl *Out, bool IsCombiner) {
745 // void .omp_combiner.(Ty *in, Ty *out);
746 auto &C = CGM.getContext();
747 QualType PtrTy = C.getPointerType(Ty).withRestrict();
748 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000749 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +0000750 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000751 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +0000752 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000753 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000754 Args.push_back(&OmpInParm);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000755 auto &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +0000756 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000757 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
758 auto *Fn = llvm::Function::Create(
759 FnTy, llvm::GlobalValue::InternalLinkage,
760 IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
761 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +0000762 Fn->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +0000763 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000764 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000765 CodeGenFunction CGF(CGM);
766 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
767 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
768 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
769 CodeGenFunction::OMPPrivateScope Scope(CGF);
770 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
771 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
772 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
773 .getAddress();
774 });
775 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
776 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
777 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
778 .getAddress();
779 });
780 (void)Scope.Privatize();
781 CGF.EmitIgnoredExpr(CombinerInitializer);
782 Scope.ForceCleanup();
783 CGF.FinishFunction();
784 return Fn;
785}
786
787void CGOpenMPRuntime::emitUserDefinedReduction(
788 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
789 if (UDRMap.count(D) > 0)
790 return;
791 auto &C = CGM.getContext();
792 if (!In || !Out) {
793 In = &C.Idents.get("omp_in");
794 Out = &C.Idents.get("omp_out");
795 }
796 llvm::Function *Combiner = emitCombinerOrInitializer(
797 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
798 cast<VarDecl>(D->lookup(Out).front()),
799 /*IsCombiner=*/true);
800 llvm::Function *Initializer = nullptr;
801 if (auto *Init = D->getInitializer()) {
802 if (!Priv || !Orig) {
803 Priv = &C.Idents.get("omp_priv");
804 Orig = &C.Idents.get("omp_orig");
805 }
806 Initializer = emitCombinerOrInitializer(
807 CGM, D->getType(), Init, cast<VarDecl>(D->lookup(Orig).front()),
808 cast<VarDecl>(D->lookup(Priv).front()),
809 /*IsCombiner=*/false);
810 }
811 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
812 if (CGF) {
813 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
814 Decls.second.push_back(D);
815 }
816}
817
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000818std::pair<llvm::Function *, llvm::Function *>
819CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
820 auto I = UDRMap.find(D);
821 if (I != UDRMap.end())
822 return I->second;
823 emitUserDefinedReduction(/*CGF=*/nullptr, D);
824 return UDRMap.lookup(D);
825}
826
John McCall7f416cc2015-09-08 08:05:57 +0000827// Layout information for ident_t.
828static CharUnits getIdentAlign(CodeGenModule &CGM) {
829 return CGM.getPointerAlign();
830}
831static CharUnits getIdentSize(CodeGenModule &CGM) {
832 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
833 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
834}
Alexey Bataev50b3c952016-02-19 10:38:26 +0000835static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
John McCall7f416cc2015-09-08 08:05:57 +0000836 // All the fields except the last are i32, so this works beautifully.
837 return unsigned(Field) * CharUnits::fromQuantity(4);
838}
839static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000840 IdentFieldIndex Field,
John McCall7f416cc2015-09-08 08:05:57 +0000841 const llvm::Twine &Name = "") {
842 auto Offset = getOffsetOfIdentField(Field);
843 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
844}
845
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +0000846static llvm::Value *emitParallelOrTeamsOutlinedFunction(
847 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
848 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
849 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000850 assert(ThreadIDVar->getType()->isPointerType() &&
851 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +0000852 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +0000853 bool HasCancel = false;
854 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
855 HasCancel = OPD->hasCancel();
856 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
857 HasCancel = OPSD->hasCancel();
858 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
859 HasCancel = OPFD->hasCancel();
860 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +0000861 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +0000862 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000863 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +0000864}
865
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +0000866llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
867 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
868 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
869 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
870 return emitParallelOrTeamsOutlinedFunction(
871 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
872}
873
874llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
875 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
876 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
877 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
878 return emitParallelOrTeamsOutlinedFunction(
879 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
880}
881
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000882llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
883 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +0000884 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
885 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
886 bool Tied, unsigned &NumberOfParts) {
887 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
888 PrePostActionTy &) {
889 auto *ThreadID = getThreadID(CGF, D.getLocStart());
890 auto *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
891 llvm::Value *TaskArgs[] = {
892 UpLoc, ThreadID,
893 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
894 TaskTVar->getType()->castAs<PointerType>())
895 .getPointer()};
896 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
897 };
898 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
899 UntiedCodeGen);
900 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000901 assert(!ThreadIDVar->getType()->isPointerType() &&
902 "thread id variable must be of type kmp_int32 for tasks");
903 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
Alexey Bataev7292c292016-04-25 12:22:29 +0000904 auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000905 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +0000906 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
907 InnermostKind,
908 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +0000909 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev48591dd2016-04-20 04:01:36 +0000910 auto *Res = CGF.GenerateCapturedStmtFunction(*CS);
911 if (!Tied)
912 NumberOfParts = Action.getNumberOfParts();
913 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000914}
915
Alexey Bataev50b3c952016-02-19 10:38:26 +0000916Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +0000917 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +0000918 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000919 if (!Entry) {
920 if (!DefaultOpenMPPSource) {
921 // Initialize default location for psource field of ident_t structure of
922 // all ident_t objects. Format is ";file;function;line;column;;".
923 // Taken from
924 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
925 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +0000926 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000927 DefaultOpenMPPSource =
928 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
929 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000930
John McCall23c9dc62016-11-28 22:18:27 +0000931 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +0000932 auto fields = builder.beginStruct(IdentTy);
933 fields.addInt(CGM.Int32Ty, 0);
934 fields.addInt(CGM.Int32Ty, Flags);
935 fields.addInt(CGM.Int32Ty, 0);
936 fields.addInt(CGM.Int32Ty, 0);
937 fields.add(DefaultOpenMPPSource);
938 auto DefaultOpenMPLocation =
939 fields.finishAndCreateGlobal("", Align, /*isConstant*/ true,
940 llvm::GlobalValue::PrivateLinkage);
941 DefaultOpenMPLocation->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
942
John McCall7f416cc2015-09-08 08:05:57 +0000943 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +0000944 }
John McCall7f416cc2015-09-08 08:05:57 +0000945 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +0000946}
947
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000948llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
949 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000950 unsigned Flags) {
951 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +0000952 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +0000953 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +0000954 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +0000955 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000956
957 assert(CGF.CurFn && "No function in current CodeGenFunction.");
958
John McCall7f416cc2015-09-08 08:05:57 +0000959 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000960 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
961 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +0000962 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
963
Alexander Musmanc6388682014-12-15 07:07:06 +0000964 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
965 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +0000966 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000967 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +0000968 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
969 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +0000970 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +0000971 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000972 LocValue = AI;
973
974 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
975 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000976 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +0000977 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +0000978 }
979
980 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +0000981 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +0000982
Alexey Bataevf002aca2014-05-30 05:48:40 +0000983 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
984 if (OMPDebugLoc == nullptr) {
985 SmallString<128> Buffer2;
986 llvm::raw_svector_ostream OS2(Buffer2);
987 // Build debug location
988 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
989 OS2 << ";" << PLoc.getFilename() << ";";
990 if (const FunctionDecl *FD =
991 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
992 OS2 << FD->getQualifiedNameAsString();
993 }
994 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
995 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
996 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +0000997 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000998 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +0000999 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
1000
John McCall7f416cc2015-09-08 08:05:57 +00001001 // Our callers always pass this to a runtime function, so for
1002 // convenience, go ahead and return a naked pointer.
1003 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001004}
1005
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001006llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1007 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001008 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1009
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001010 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001011 // Check whether we've already cached a load of the thread id in this
1012 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001013 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001014 if (I != OpenMPLocThreadIDMap.end()) {
1015 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001016 if (ThreadID != nullptr)
1017 return ThreadID;
1018 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001019 if (auto *OMPRegionInfo =
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001020 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001021 if (OMPRegionInfo->getThreadIDVariable()) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001022 // Check if this an outlined function with thread id passed as argument.
1023 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001024 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
1025 // If value loaded in entry block, cache it and use it everywhere in
1026 // function.
1027 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1028 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1029 Elem.second.ThreadID = ThreadID;
1030 }
1031 return ThreadID;
Alexey Bataevd6c57552014-07-25 07:55:17 +00001032 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001033 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001034
1035 // This is not an outlined function region - need to call __kmpc_int32
1036 // kmpc_global_thread_num(ident_t *loc).
1037 // Generate thread id value and cache this value for use across the
1038 // function.
1039 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1040 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
1041 ThreadID =
1042 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1043 emitUpdateLocation(CGF, Loc));
1044 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1045 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001046 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +00001047}
1048
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001049void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001050 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001051 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1052 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001053 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1054 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
1055 UDRMap.erase(D);
1056 }
1057 FunctionUDRMap.erase(CGF.CurFn);
1058 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001059}
1060
1061llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001062 if (!IdentTy) {
1063 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001064 return llvm::PointerType::getUnqual(IdentTy);
1065}
1066
1067llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001068 if (!Kmpc_MicroTy) {
1069 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1070 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1071 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1072 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1073 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001074 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1075}
1076
1077llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001078CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001079 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001080 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001081 case OMPRTL__kmpc_fork_call: {
1082 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1083 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001084 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1085 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001086 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001087 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001088 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1089 break;
1090 }
1091 case OMPRTL__kmpc_global_thread_num: {
1092 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001093 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001094 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001095 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001096 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1097 break;
1098 }
Alexey Bataev97720002014-11-11 04:05:39 +00001099 case OMPRTL__kmpc_threadprivate_cached: {
1100 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1101 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1102 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1103 CGM.VoidPtrTy, CGM.SizeTy,
1104 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1105 llvm::FunctionType *FnTy =
1106 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1107 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1108 break;
1109 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001110 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001111 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1112 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001113 llvm::Type *TypeParams[] = {
1114 getIdentTyPointerTy(), CGM.Int32Ty,
1115 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1116 llvm::FunctionType *FnTy =
1117 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1118 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1119 break;
1120 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001121 case OMPRTL__kmpc_critical_with_hint: {
1122 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1123 // kmp_critical_name *crit, uintptr_t hint);
1124 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1125 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1126 CGM.IntPtrTy};
1127 llvm::FunctionType *FnTy =
1128 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1129 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1130 break;
1131 }
Alexey Bataev97720002014-11-11 04:05:39 +00001132 case OMPRTL__kmpc_threadprivate_register: {
1133 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1134 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1135 // typedef void *(*kmpc_ctor)(void *);
1136 auto KmpcCtorTy =
1137 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1138 /*isVarArg*/ false)->getPointerTo();
1139 // typedef void *(*kmpc_cctor)(void *, void *);
1140 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1141 auto KmpcCopyCtorTy =
1142 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1143 /*isVarArg*/ false)->getPointerTo();
1144 // typedef void (*kmpc_dtor)(void *);
1145 auto KmpcDtorTy =
1146 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1147 ->getPointerTo();
1148 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1149 KmpcCopyCtorTy, KmpcDtorTy};
1150 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1151 /*isVarArg*/ false);
1152 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1153 break;
1154 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001155 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001156 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1157 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001158 llvm::Type *TypeParams[] = {
1159 getIdentTyPointerTy(), CGM.Int32Ty,
1160 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1161 llvm::FunctionType *FnTy =
1162 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1163 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1164 break;
1165 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001166 case OMPRTL__kmpc_cancel_barrier: {
1167 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1168 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001169 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1170 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001171 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1172 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001173 break;
1174 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001175 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001176 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001177 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1178 llvm::FunctionType *FnTy =
1179 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1180 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1181 break;
1182 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001183 case OMPRTL__kmpc_for_static_fini: {
1184 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1185 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1186 llvm::FunctionType *FnTy =
1187 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1188 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1189 break;
1190 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001191 case OMPRTL__kmpc_push_num_threads: {
1192 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1193 // kmp_int32 num_threads)
1194 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1195 CGM.Int32Ty};
1196 llvm::FunctionType *FnTy =
1197 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1198 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1199 break;
1200 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001201 case OMPRTL__kmpc_serialized_parallel: {
1202 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1203 // global_tid);
1204 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1205 llvm::FunctionType *FnTy =
1206 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1207 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1208 break;
1209 }
1210 case OMPRTL__kmpc_end_serialized_parallel: {
1211 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1212 // global_tid);
1213 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1214 llvm::FunctionType *FnTy =
1215 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1216 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1217 break;
1218 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001219 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001220 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001221 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1222 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001223 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001224 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1225 break;
1226 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001227 case OMPRTL__kmpc_master: {
1228 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1229 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1230 llvm::FunctionType *FnTy =
1231 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1232 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1233 break;
1234 }
1235 case OMPRTL__kmpc_end_master: {
1236 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1237 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1238 llvm::FunctionType *FnTy =
1239 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1240 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1241 break;
1242 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001243 case OMPRTL__kmpc_omp_taskyield: {
1244 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1245 // int end_part);
1246 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1247 llvm::FunctionType *FnTy =
1248 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1249 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1250 break;
1251 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001252 case OMPRTL__kmpc_single: {
1253 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1254 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1255 llvm::FunctionType *FnTy =
1256 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1257 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1258 break;
1259 }
1260 case OMPRTL__kmpc_end_single: {
1261 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1262 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1263 llvm::FunctionType *FnTy =
1264 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1265 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1266 break;
1267 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001268 case OMPRTL__kmpc_omp_task_alloc: {
1269 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1270 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1271 // kmp_routine_entry_t *task_entry);
1272 assert(KmpRoutineEntryPtrTy != nullptr &&
1273 "Type kmp_routine_entry_t must be created.");
1274 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1275 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1276 // Return void * and then cast to particular kmp_task_t type.
1277 llvm::FunctionType *FnTy =
1278 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1279 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1280 break;
1281 }
1282 case OMPRTL__kmpc_omp_task: {
1283 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1284 // *new_task);
1285 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1286 CGM.VoidPtrTy};
1287 llvm::FunctionType *FnTy =
1288 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1289 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1290 break;
1291 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001292 case OMPRTL__kmpc_copyprivate: {
1293 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001294 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001295 // kmp_int32 didit);
1296 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1297 auto *CpyFnTy =
1298 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001299 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001300 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1301 CGM.Int32Ty};
1302 llvm::FunctionType *FnTy =
1303 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1304 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1305 break;
1306 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001307 case OMPRTL__kmpc_reduce: {
1308 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1309 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1310 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1311 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1312 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1313 /*isVarArg=*/false);
1314 llvm::Type *TypeParams[] = {
1315 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1316 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1317 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1318 llvm::FunctionType *FnTy =
1319 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1320 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1321 break;
1322 }
1323 case OMPRTL__kmpc_reduce_nowait: {
1324 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1325 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1326 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1327 // *lck);
1328 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1329 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1330 /*isVarArg=*/false);
1331 llvm::Type *TypeParams[] = {
1332 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1333 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1334 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1335 llvm::FunctionType *FnTy =
1336 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1337 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1338 break;
1339 }
1340 case OMPRTL__kmpc_end_reduce: {
1341 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1342 // kmp_critical_name *lck);
1343 llvm::Type *TypeParams[] = {
1344 getIdentTyPointerTy(), CGM.Int32Ty,
1345 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1346 llvm::FunctionType *FnTy =
1347 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1348 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1349 break;
1350 }
1351 case OMPRTL__kmpc_end_reduce_nowait: {
1352 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1353 // kmp_critical_name *lck);
1354 llvm::Type *TypeParams[] = {
1355 getIdentTyPointerTy(), CGM.Int32Ty,
1356 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1357 llvm::FunctionType *FnTy =
1358 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1359 RTLFn =
1360 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1361 break;
1362 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001363 case OMPRTL__kmpc_omp_task_begin_if0: {
1364 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1365 // *new_task);
1366 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1367 CGM.VoidPtrTy};
1368 llvm::FunctionType *FnTy =
1369 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1370 RTLFn =
1371 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1372 break;
1373 }
1374 case OMPRTL__kmpc_omp_task_complete_if0: {
1375 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1376 // *new_task);
1377 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1378 CGM.VoidPtrTy};
1379 llvm::FunctionType *FnTy =
1380 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1381 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1382 /*Name=*/"__kmpc_omp_task_complete_if0");
1383 break;
1384 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001385 case OMPRTL__kmpc_ordered: {
1386 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1387 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1388 llvm::FunctionType *FnTy =
1389 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1390 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1391 break;
1392 }
1393 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001394 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001395 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1396 llvm::FunctionType *FnTy =
1397 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1398 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1399 break;
1400 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001401 case OMPRTL__kmpc_omp_taskwait: {
1402 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1403 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1404 llvm::FunctionType *FnTy =
1405 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1406 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1407 break;
1408 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001409 case OMPRTL__kmpc_taskgroup: {
1410 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1411 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1412 llvm::FunctionType *FnTy =
1413 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1414 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1415 break;
1416 }
1417 case OMPRTL__kmpc_end_taskgroup: {
1418 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1419 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1420 llvm::FunctionType *FnTy =
1421 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1422 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1423 break;
1424 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001425 case OMPRTL__kmpc_push_proc_bind: {
1426 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1427 // int proc_bind)
1428 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1429 llvm::FunctionType *FnTy =
1430 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1431 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1432 break;
1433 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001434 case OMPRTL__kmpc_omp_task_with_deps: {
1435 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1436 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1437 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1438 llvm::Type *TypeParams[] = {
1439 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1440 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1441 llvm::FunctionType *FnTy =
1442 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1443 RTLFn =
1444 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1445 break;
1446 }
1447 case OMPRTL__kmpc_omp_wait_deps: {
1448 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1449 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1450 // kmp_depend_info_t *noalias_dep_list);
1451 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1452 CGM.Int32Ty, CGM.VoidPtrTy,
1453 CGM.Int32Ty, CGM.VoidPtrTy};
1454 llvm::FunctionType *FnTy =
1455 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1456 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1457 break;
1458 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001459 case OMPRTL__kmpc_cancellationpoint: {
1460 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1461 // global_tid, kmp_int32 cncl_kind)
1462 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1463 llvm::FunctionType *FnTy =
1464 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1465 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1466 break;
1467 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001468 case OMPRTL__kmpc_cancel: {
1469 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1470 // kmp_int32 cncl_kind)
1471 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1472 llvm::FunctionType *FnTy =
1473 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1474 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1475 break;
1476 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001477 case OMPRTL__kmpc_push_num_teams: {
1478 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1479 // kmp_int32 num_teams, kmp_int32 num_threads)
1480 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1481 CGM.Int32Ty};
1482 llvm::FunctionType *FnTy =
1483 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1484 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1485 break;
1486 }
1487 case OMPRTL__kmpc_fork_teams: {
1488 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1489 // microtask, ...);
1490 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1491 getKmpc_MicroPointerTy()};
1492 llvm::FunctionType *FnTy =
1493 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1494 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1495 break;
1496 }
Alexey Bataev7292c292016-04-25 12:22:29 +00001497 case OMPRTL__kmpc_taskloop: {
1498 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
1499 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
1500 // sched, kmp_uint64 grainsize, void *task_dup);
1501 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1502 CGM.IntTy,
1503 CGM.VoidPtrTy,
1504 CGM.IntTy,
1505 CGM.Int64Ty->getPointerTo(),
1506 CGM.Int64Ty->getPointerTo(),
1507 CGM.Int64Ty,
1508 CGM.IntTy,
1509 CGM.IntTy,
1510 CGM.Int64Ty,
1511 CGM.VoidPtrTy};
1512 llvm::FunctionType *FnTy =
1513 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1514 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
1515 break;
1516 }
Alexey Bataev8b427062016-05-25 12:36:08 +00001517 case OMPRTL__kmpc_doacross_init: {
1518 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
1519 // num_dims, struct kmp_dim *dims);
1520 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1521 CGM.Int32Ty,
1522 CGM.Int32Ty,
1523 CGM.VoidPtrTy};
1524 llvm::FunctionType *FnTy =
1525 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1526 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
1527 break;
1528 }
1529 case OMPRTL__kmpc_doacross_fini: {
1530 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
1531 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1532 llvm::FunctionType *FnTy =
1533 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1534 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
1535 break;
1536 }
1537 case OMPRTL__kmpc_doacross_post: {
1538 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
1539 // *vec);
1540 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1541 CGM.Int64Ty->getPointerTo()};
1542 llvm::FunctionType *FnTy =
1543 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1544 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
1545 break;
1546 }
1547 case OMPRTL__kmpc_doacross_wait: {
1548 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
1549 // *vec);
1550 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1551 CGM.Int64Ty->getPointerTo()};
1552 llvm::FunctionType *FnTy =
1553 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1554 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
1555 break;
1556 }
Samuel Antaobed3c462015-10-02 16:14:20 +00001557 case OMPRTL__tgt_target: {
1558 // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
1559 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
1560 // *arg_types);
1561 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1562 CGM.VoidPtrTy,
1563 CGM.Int32Ty,
1564 CGM.VoidPtrPtrTy,
1565 CGM.VoidPtrPtrTy,
1566 CGM.SizeTy->getPointerTo(),
1567 CGM.Int32Ty->getPointerTo()};
1568 llvm::FunctionType *FnTy =
1569 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1570 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
1571 break;
1572 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00001573 case OMPRTL__tgt_target_teams: {
1574 // Build int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
1575 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
1576 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
1577 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1578 CGM.VoidPtrTy,
1579 CGM.Int32Ty,
1580 CGM.VoidPtrPtrTy,
1581 CGM.VoidPtrPtrTy,
1582 CGM.SizeTy->getPointerTo(),
1583 CGM.Int32Ty->getPointerTo(),
1584 CGM.Int32Ty,
1585 CGM.Int32Ty};
1586 llvm::FunctionType *FnTy =
1587 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1588 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
1589 break;
1590 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00001591 case OMPRTL__tgt_register_lib: {
1592 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
1593 QualType ParamTy =
1594 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1595 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1596 llvm::FunctionType *FnTy =
1597 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1598 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
1599 break;
1600 }
1601 case OMPRTL__tgt_unregister_lib: {
1602 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
1603 QualType ParamTy =
1604 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1605 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1606 llvm::FunctionType *FnTy =
1607 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1608 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
1609 break;
1610 }
Samuel Antaodf158d52016-04-27 22:58:19 +00001611 case OMPRTL__tgt_target_data_begin: {
1612 // Build void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
1613 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1614 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1615 CGM.Int32Ty,
1616 CGM.VoidPtrPtrTy,
1617 CGM.VoidPtrPtrTy,
1618 CGM.SizeTy->getPointerTo(),
1619 CGM.Int32Ty->getPointerTo()};
1620 llvm::FunctionType *FnTy =
1621 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1622 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
1623 break;
1624 }
1625 case OMPRTL__tgt_target_data_end: {
1626 // Build void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
1627 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1628 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1629 CGM.Int32Ty,
1630 CGM.VoidPtrPtrTy,
1631 CGM.VoidPtrPtrTy,
1632 CGM.SizeTy->getPointerTo(),
1633 CGM.Int32Ty->getPointerTo()};
1634 llvm::FunctionType *FnTy =
1635 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1636 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
1637 break;
1638 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00001639 case OMPRTL__tgt_target_data_update: {
1640 // Build void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
1641 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1642 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1643 CGM.Int32Ty,
1644 CGM.VoidPtrPtrTy,
1645 CGM.VoidPtrPtrTy,
1646 CGM.SizeTy->getPointerTo(),
1647 CGM.Int32Ty->getPointerTo()};
1648 llvm::FunctionType *FnTy =
1649 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1650 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
1651 break;
1652 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001653 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00001654 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00001655 return RTLFn;
1656}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001657
Alexander Musman21212e42015-03-13 10:38:23 +00001658llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
1659 bool IVSigned) {
1660 assert((IVSize == 32 || IVSize == 64) &&
1661 "IV size is not compatible with the omp runtime");
1662 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
1663 : "__kmpc_for_static_init_4u")
1664 : (IVSigned ? "__kmpc_for_static_init_8"
1665 : "__kmpc_for_static_init_8u");
1666 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1667 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1668 llvm::Type *TypeParams[] = {
1669 getIdentTyPointerTy(), // loc
1670 CGM.Int32Ty, // tid
1671 CGM.Int32Ty, // schedtype
1672 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1673 PtrTy, // p_lower
1674 PtrTy, // p_upper
1675 PtrTy, // p_stride
1676 ITy, // incr
1677 ITy // chunk
1678 };
1679 llvm::FunctionType *FnTy =
1680 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1681 return CGM.CreateRuntimeFunction(FnTy, Name);
1682}
1683
Alexander Musman92bdaab2015-03-12 13:37:50 +00001684llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
1685 bool IVSigned) {
1686 assert((IVSize == 32 || IVSize == 64) &&
1687 "IV size is not compatible with the omp runtime");
1688 auto Name =
1689 IVSize == 32
1690 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
1691 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
1692 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1693 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
1694 CGM.Int32Ty, // tid
1695 CGM.Int32Ty, // schedtype
1696 ITy, // lower
1697 ITy, // upper
1698 ITy, // stride
1699 ITy // chunk
1700 };
1701 llvm::FunctionType *FnTy =
1702 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1703 return CGM.CreateRuntimeFunction(FnTy, Name);
1704}
1705
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001706llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
1707 bool IVSigned) {
1708 assert((IVSize == 32 || IVSize == 64) &&
1709 "IV size is not compatible with the omp runtime");
1710 auto Name =
1711 IVSize == 32
1712 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
1713 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
1714 llvm::Type *TypeParams[] = {
1715 getIdentTyPointerTy(), // loc
1716 CGM.Int32Ty, // tid
1717 };
1718 llvm::FunctionType *FnTy =
1719 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1720 return CGM.CreateRuntimeFunction(FnTy, Name);
1721}
1722
Alexander Musman92bdaab2015-03-12 13:37:50 +00001723llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
1724 bool IVSigned) {
1725 assert((IVSize == 32 || IVSize == 64) &&
1726 "IV size is not compatible with the omp runtime");
1727 auto Name =
1728 IVSize == 32
1729 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
1730 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
1731 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1732 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1733 llvm::Type *TypeParams[] = {
1734 getIdentTyPointerTy(), // loc
1735 CGM.Int32Ty, // tid
1736 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1737 PtrTy, // p_lower
1738 PtrTy, // p_upper
1739 PtrTy // p_stride
1740 };
1741 llvm::FunctionType *FnTy =
1742 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1743 return CGM.CreateRuntimeFunction(FnTy, Name);
1744}
1745
Alexey Bataev97720002014-11-11 04:05:39 +00001746llvm::Constant *
1747CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001748 assert(!CGM.getLangOpts().OpenMPUseTLS ||
1749 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00001750 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001751 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001752 Twine(CGM.getMangledName(VD)) + ".cache.");
1753}
1754
John McCall7f416cc2015-09-08 08:05:57 +00001755Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
1756 const VarDecl *VD,
1757 Address VDAddr,
1758 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001759 if (CGM.getLangOpts().OpenMPUseTLS &&
1760 CGM.getContext().getTargetInfo().isTLSSupported())
1761 return VDAddr;
1762
John McCall7f416cc2015-09-08 08:05:57 +00001763 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001764 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00001765 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1766 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001767 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
1768 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00001769 return Address(CGF.EmitRuntimeCall(
1770 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
1771 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00001772}
1773
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001774void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00001775 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00001776 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
1777 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
1778 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001779 auto OMPLoc = emitUpdateLocation(CGF, Loc);
1780 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00001781 OMPLoc);
1782 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
1783 // to register constructor/destructor for variable.
1784 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00001785 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1786 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001787 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001788 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001789 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001790}
1791
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001792llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00001793 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00001794 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001795 if (CGM.getLangOpts().OpenMPUseTLS &&
1796 CGM.getContext().getTargetInfo().isTLSSupported())
1797 return nullptr;
1798
Alexey Bataev97720002014-11-11 04:05:39 +00001799 VD = VD->getDefinition(CGM.getContext());
1800 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
1801 ThreadPrivateWithDefinition.insert(VD);
1802 QualType ASTTy = VD->getType();
1803
1804 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
1805 auto Init = VD->getAnyInitializer();
1806 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
1807 // Generate function that re-emits the declaration's initializer into the
1808 // threadprivate copy of the variable VD
1809 CodeGenFunction CtorCGF(CGM);
1810 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00001811 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
1812 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00001813 Args.push_back(&Dst);
1814
John McCallc56a8b32016-03-11 04:30:31 +00001815 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1816 CGM.getContext().VoidPtrTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001817 auto FTy = CGM.getTypes().GetFunctionType(FI);
1818 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001819 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001820 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
1821 Args, SourceLocation());
1822 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001823 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001824 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001825 Address Arg = Address(ArgVal, VDAddr.getAlignment());
1826 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
1827 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00001828 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
1829 /*IsInitializer=*/true);
1830 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001831 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001832 CGM.getContext().VoidPtrTy, Dst.getLocation());
1833 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
1834 CtorCGF.FinishFunction();
1835 Ctor = Fn;
1836 }
1837 if (VD->getType().isDestructedType() != QualType::DK_none) {
1838 // Generate function that emits destructor call for the threadprivate copy
1839 // of the variable VD
1840 CodeGenFunction DtorCGF(CGM);
1841 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00001842 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
1843 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00001844 Args.push_back(&Dst);
1845
John McCallc56a8b32016-03-11 04:30:31 +00001846 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1847 CGM.getContext().VoidTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001848 auto FTy = CGM.getTypes().GetFunctionType(FI);
1849 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001850 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00001851 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00001852 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
1853 SourceLocation());
Adrian Prantl1858c662016-04-24 22:22:29 +00001854 // Create a scope with an artificial location for the body of this function.
1855 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00001856 auto ArgVal = DtorCGF.EmitLoadOfScalar(
1857 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00001858 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
1859 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001860 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
1861 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
1862 DtorCGF.FinishFunction();
1863 Dtor = Fn;
1864 }
1865 // Do not emit init function if it is not required.
1866 if (!Ctor && !Dtor)
1867 return nullptr;
1868
1869 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1870 auto CopyCtorTy =
1871 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
1872 /*isVarArg=*/false)->getPointerTo();
1873 // Copying constructor for the threadprivate variable.
1874 // Must be NULL - reserved by runtime, but currently it requires that this
1875 // parameter is always NULL. Otherwise it fires assertion.
1876 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
1877 if (Ctor == nullptr) {
1878 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1879 /*isVarArg=*/false)->getPointerTo();
1880 Ctor = llvm::Constant::getNullValue(CtorTy);
1881 }
1882 if (Dtor == nullptr) {
1883 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
1884 /*isVarArg=*/false)->getPointerTo();
1885 Dtor = llvm::Constant::getNullValue(DtorTy);
1886 }
1887 if (!CGF) {
1888 auto InitFunctionTy =
1889 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
1890 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001891 InitFunctionTy, ".__omp_threadprivate_init_.",
1892 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00001893 CodeGenFunction InitCGF(CGM);
1894 FunctionArgList ArgList;
1895 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
1896 CGM.getTypes().arrangeNullaryFunction(), ArgList,
1897 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001898 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001899 InitCGF.FinishFunction();
1900 return InitFunction;
1901 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001902 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001903 }
1904 return nullptr;
1905}
1906
Alexey Bataev1d677132015-04-22 13:57:31 +00001907/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
1908/// function. Here is the logic:
1909/// if (Cond) {
1910/// ThenGen();
1911/// } else {
1912/// ElseGen();
1913/// }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001914void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
1915 const RegionCodeGenTy &ThenGen,
1916 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001917 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
1918
1919 // If the condition constant folds and can be elided, try to avoid emitting
1920 // the condition and the dead arm of the if/else.
1921 bool CondConstant;
1922 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001923 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00001924 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001925 else
Alexey Bataev1d677132015-04-22 13:57:31 +00001926 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001927 return;
1928 }
1929
1930 // Otherwise, the condition did not fold, or we couldn't elide it. Just
1931 // emit the conditional branch.
1932 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
1933 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
1934 auto ContBlock = CGF.createBasicBlock("omp_if.end");
1935 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
1936
1937 // Emit the 'then' code.
1938 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001939 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001940 CGF.EmitBranch(ContBlock);
1941 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001942 // There is no need to emit line number for unconditional branch.
1943 (void)ApplyDebugLocation::CreateEmpty(CGF);
1944 CGF.EmitBlock(ElseBlock);
1945 ElseGen(CGF);
1946 // There is no need to emit line number for unconditional branch.
1947 (void)ApplyDebugLocation::CreateEmpty(CGF);
1948 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00001949 // Emit the continuation block for code after the if.
1950 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001951}
1952
Alexey Bataev1d677132015-04-22 13:57:31 +00001953void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
1954 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001955 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00001956 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001957 if (!CGF.HaveInsertPoint())
1958 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00001959 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001960 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
1961 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001962 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001963 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00001964 llvm::Value *Args[] = {
1965 RTLoc,
1966 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001967 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00001968 llvm::SmallVector<llvm::Value *, 16> RealArgs;
1969 RealArgs.append(std::begin(Args), std::end(Args));
1970 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
1971
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001972 auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001973 CGF.EmitRuntimeCall(RTLFn, RealArgs);
1974 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001975 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
1976 PrePostActionTy &) {
1977 auto &RT = CGF.CGM.getOpenMPRuntime();
1978 auto ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00001979 // Build calls:
1980 // __kmpc_serialized_parallel(&Loc, GTid);
1981 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001982 CGF.EmitRuntimeCall(
1983 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001984
Alexey Bataev1d677132015-04-22 13:57:31 +00001985 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001986 auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00001987 Address ZeroAddr =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001988 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
1989 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00001990 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00001991 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
1992 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
1993 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1994 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev1d677132015-04-22 13:57:31 +00001995 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001996
Alexey Bataev1d677132015-04-22 13:57:31 +00001997 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001998 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00001999 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002000 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2001 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002002 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002003 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00002004 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002005 else {
2006 RegionCodeGenTy ThenRCG(ThenGen);
2007 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002008 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002009}
2010
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002011// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002012// thread-ID variable (it is passed in a first argument of the outlined function
2013// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2014// regular serial code region, get thread ID by calling kmp_int32
2015// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2016// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002017Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2018 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002019 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002020 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002021 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002022 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002023
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002024 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002025 auto Int32Ty =
2026 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2027 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2028 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002029 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002030
2031 return ThreadIDTemp;
2032}
2033
Alexey Bataev97720002014-11-11 04:05:39 +00002034llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002035CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002036 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002037 SmallString<256> Buffer;
2038 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002039 Out << Name;
2040 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00002041 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
2042 if (Elem.second) {
2043 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002044 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002045 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002046 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002047
David Blaikie13156b62014-11-19 03:06:06 +00002048 return Elem.second = new llvm::GlobalVariable(
2049 CGM.getModule(), Ty, /*IsConstant*/ false,
2050 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2051 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002052}
2053
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002054llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00002055 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002056 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002057}
2058
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002059namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002060/// Common pre(post)-action for different OpenMP constructs.
2061class CommonActionTy final : public PrePostActionTy {
2062 llvm::Value *EnterCallee;
2063 ArrayRef<llvm::Value *> EnterArgs;
2064 llvm::Value *ExitCallee;
2065 ArrayRef<llvm::Value *> ExitArgs;
2066 bool Conditional;
2067 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002068
2069public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002070 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2071 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2072 bool Conditional = false)
2073 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2074 ExitArgs(ExitArgs), Conditional(Conditional) {}
2075 void Enter(CodeGenFunction &CGF) override {
2076 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2077 if (Conditional) {
2078 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2079 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2080 ContBlock = CGF.createBasicBlock("omp_if.end");
2081 // Generate the branch (If-stmt)
2082 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2083 CGF.EmitBlock(ThenBlock);
2084 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002085 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002086 void Done(CodeGenFunction &CGF) {
2087 // Emit the rest of blocks/branches
2088 CGF.EmitBranch(ContBlock);
2089 CGF.EmitBlock(ContBlock, true);
2090 }
2091 void Exit(CodeGenFunction &CGF) override {
2092 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002093 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002094};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002095} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002096
2097void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2098 StringRef CriticalName,
2099 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002100 SourceLocation Loc, const Expr *Hint) {
2101 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002102 // CriticalOpGen();
2103 // __kmpc_end_critical(ident_t *, gtid, Lock);
2104 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002105 if (!CGF.HaveInsertPoint())
2106 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002107 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2108 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002109 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2110 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002111 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002112 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2113 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2114 }
2115 CommonActionTy Action(
2116 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2117 : OMPRTL__kmpc_critical),
2118 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2119 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002120 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002121}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002122
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002123void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002124 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002125 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002126 if (!CGF.HaveInsertPoint())
2127 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002128 // if(__kmpc_master(ident_t *, gtid)) {
2129 // MasterOpGen();
2130 // __kmpc_end_master(ident_t *, gtid);
2131 // }
2132 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002133 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002134 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2135 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2136 /*Conditional=*/true);
2137 MasterOpGen.setAction(Action);
2138 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2139 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002140}
2141
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002142void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2143 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002144 if (!CGF.HaveInsertPoint())
2145 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00002146 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2147 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002148 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00002149 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002150 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002151 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2152 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00002153}
2154
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002155void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2156 const RegionCodeGenTy &TaskgroupOpGen,
2157 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002158 if (!CGF.HaveInsertPoint())
2159 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002160 // __kmpc_taskgroup(ident_t *, gtid);
2161 // TaskgroupOpGen();
2162 // __kmpc_end_taskgroup(ident_t *, gtid);
2163 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002164 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2165 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2166 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2167 Args);
2168 TaskgroupOpGen.setAction(Action);
2169 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002170}
2171
John McCall7f416cc2015-09-08 08:05:57 +00002172/// Given an array of pointers to variables, project the address of a
2173/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002174static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2175 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00002176 // Pull out the pointer to the variable.
2177 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002178 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00002179 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2180
2181 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002182 Addr = CGF.Builder.CreateElementBitCast(
2183 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002184 return Addr;
2185}
2186
Alexey Bataeva63048e2015-03-23 06:18:07 +00002187static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00002188 CodeGenModule &CGM, llvm::Type *ArgsType,
2189 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
2190 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002191 auto &C = CGM.getContext();
2192 // void copy_func(void *LHSArg, void *RHSArg);
2193 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002194 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
2195 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002196 Args.push_back(&LHSArg);
2197 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00002198 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002199 auto *Fn = llvm::Function::Create(
2200 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2201 ".omp.copyprivate.copy_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002202 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002203 CodeGenFunction CGF(CGM);
2204 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00002205 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002206 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00002207 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2208 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2209 ArgsType), CGF.getPointerAlign());
2210 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2211 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2212 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002213 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2214 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2215 // ...
2216 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00002217 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002218 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2219 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2220
2221 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2222 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2223
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002224 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2225 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00002226 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002227 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002228 CGF.FinishFunction();
2229 return Fn;
2230}
2231
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002232void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002233 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00002234 SourceLocation Loc,
2235 ArrayRef<const Expr *> CopyprivateVars,
2236 ArrayRef<const Expr *> SrcExprs,
2237 ArrayRef<const Expr *> DstExprs,
2238 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002239 if (!CGF.HaveInsertPoint())
2240 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002241 assert(CopyprivateVars.size() == SrcExprs.size() &&
2242 CopyprivateVars.size() == DstExprs.size() &&
2243 CopyprivateVars.size() == AssignmentOps.size());
2244 auto &C = CGM.getContext();
2245 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002246 // if(__kmpc_single(ident_t *, gtid)) {
2247 // SingleOpGen();
2248 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002249 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002250 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002251 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2252 // <copy_func>, did_it);
2253
John McCall7f416cc2015-09-08 08:05:57 +00002254 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00002255 if (!CopyprivateVars.empty()) {
2256 // int32 did_it = 0;
2257 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2258 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00002259 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002260 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002261 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002262 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002263 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
2264 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
2265 /*Conditional=*/true);
2266 SingleOpGen.setAction(Action);
2267 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2268 if (DidIt.isValid()) {
2269 // did_it = 1;
2270 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2271 }
2272 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002273 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2274 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00002275 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002276 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2277 auto CopyprivateArrayTy =
2278 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2279 /*IndexTypeQuals=*/0);
2280 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00002281 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00002282 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2283 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002284 Address Elem = CGF.Builder.CreateConstArrayGEP(
2285 CopyprivateList, I, CGF.getPointerSize());
2286 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00002287 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002288 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2289 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002290 }
2291 // Build function that copies private values from single region to all other
2292 // threads in the corresponding parallel region.
2293 auto *CpyFn = emitCopyprivateCopyFunction(
2294 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00002295 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev1189bd02016-01-26 12:20:39 +00002296 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00002297 Address CL =
2298 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2299 CGF.VoidPtrTy);
2300 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002301 llvm::Value *Args[] = {
2302 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2303 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00002304 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00002305 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00002306 CpyFn, // void (*) (void *, void *) <copy_func>
2307 DidItVal // i32 did_it
2308 };
2309 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2310 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002311}
2312
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002313void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2314 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00002315 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002316 if (!CGF.HaveInsertPoint())
2317 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002318 // __kmpc_ordered(ident_t *, gtid);
2319 // OrderedOpGen();
2320 // __kmpc_end_ordered(ident_t *, gtid);
2321 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00002322 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002323 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002324 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
2325 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2326 Args);
2327 OrderedOpGen.setAction(Action);
2328 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2329 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002330 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002331 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002332}
2333
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002334void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002335 OpenMPDirectiveKind Kind, bool EmitChecks,
2336 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002337 if (!CGF.HaveInsertPoint())
2338 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002339 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002340 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002341 unsigned Flags;
2342 if (Kind == OMPD_for)
2343 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2344 else if (Kind == OMPD_sections)
2345 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2346 else if (Kind == OMPD_single)
2347 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2348 else if (Kind == OMPD_barrier)
2349 Flags = OMP_IDENT_BARRIER_EXPL;
2350 else
2351 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002352 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2353 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002354 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2355 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002356 if (auto *OMPRegionInfo =
2357 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00002358 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002359 auto *Result = CGF.EmitRuntimeCall(
2360 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002361 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002362 // if (__kmpc_cancel_barrier()) {
2363 // exit from construct;
2364 // }
2365 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2366 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2367 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2368 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2369 CGF.EmitBlock(ExitBB);
2370 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002371 auto CancelDestination =
2372 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002373 CGF.EmitBranchThroughCleanup(CancelDestination);
2374 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2375 }
2376 return;
2377 }
2378 }
2379 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002380}
2381
Alexander Musmanc6388682014-12-15 07:07:06 +00002382/// \brief Map the OpenMP loop schedule to the runtime enumeration.
2383static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002384 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002385 switch (ScheduleKind) {
2386 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002387 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2388 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00002389 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002390 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002391 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002392 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002393 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002394 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2395 case OMPC_SCHEDULE_auto:
2396 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00002397 case OMPC_SCHEDULE_unknown:
2398 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002399 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00002400 }
2401 llvm_unreachable("Unexpected runtime schedule");
2402}
2403
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002404/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
2405static OpenMPSchedType
2406getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2407 // only static is allowed for dist_schedule
2408 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
2409}
2410
Alexander Musmanc6388682014-12-15 07:07:06 +00002411bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2412 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002413 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00002414 return Schedule == OMP_sch_static;
2415}
2416
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002417bool CGOpenMPRuntime::isStaticNonchunked(
2418 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2419 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2420 return Schedule == OMP_dist_sch_static;
2421}
2422
2423
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002424bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002425 auto Schedule =
2426 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002427 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2428 return Schedule != OMP_sch_static;
2429}
2430
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002431static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
2432 OpenMPScheduleClauseModifier M1,
2433 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00002434 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002435 switch (M1) {
2436 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002437 Modifier = OMP_sch_modifier_monotonic;
2438 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002439 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002440 Modifier = OMP_sch_modifier_nonmonotonic;
2441 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002442 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002443 if (Schedule == OMP_sch_static_chunked)
2444 Schedule = OMP_sch_static_balanced_chunked;
2445 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002446 case OMPC_SCHEDULE_MODIFIER_last:
2447 case OMPC_SCHEDULE_MODIFIER_unknown:
2448 break;
2449 }
2450 switch (M2) {
2451 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002452 Modifier = OMP_sch_modifier_monotonic;
2453 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002454 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002455 Modifier = OMP_sch_modifier_nonmonotonic;
2456 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002457 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002458 if (Schedule == OMP_sch_static_chunked)
2459 Schedule = OMP_sch_static_balanced_chunked;
2460 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002461 case OMPC_SCHEDULE_MODIFIER_last:
2462 case OMPC_SCHEDULE_MODIFIER_unknown:
2463 break;
2464 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00002465 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002466}
2467
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002468void CGOpenMPRuntime::emitForDispatchInit(
2469 CodeGenFunction &CGF, SourceLocation Loc,
2470 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
2471 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002472 if (!CGF.HaveInsertPoint())
2473 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002474 OpenMPSchedType Schedule = getRuntimeSchedule(
2475 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00002476 assert(Ordered ||
2477 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00002478 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
2479 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00002480 // Call __kmpc_dispatch_init(
2481 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2482 // kmp_int[32|64] lower, kmp_int[32|64] upper,
2483 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002484
John McCall7f416cc2015-09-08 08:05:57 +00002485 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002486 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
2487 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00002488 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002489 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2490 CGF.Builder.getInt32(addMonoNonMonoModifier(
2491 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002492 DispatchValues.LB, // Lower
2493 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002494 CGF.Builder.getIntN(IVSize, 1), // Stride
2495 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00002496 };
2497 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2498}
2499
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002500static void emitForStaticInitCall(
2501 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
2502 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
2503 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
2504 unsigned IVSize, bool Ordered, Address IL, Address LB, Address UB,
2505 Address ST, llvm::Value *Chunk) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002506 if (!CGF.HaveInsertPoint())
2507 return;
2508
2509 assert(!Ordered);
2510 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
Alexey Bataev6cff6242016-05-30 13:05:14 +00002511 Schedule == OMP_sch_static_balanced_chunked ||
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002512 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
2513 Schedule == OMP_dist_sch_static ||
2514 Schedule == OMP_dist_sch_static_chunked);
2515
2516 // Call __kmpc_for_static_init(
2517 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2518 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2519 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2520 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
2521 if (Chunk == nullptr) {
2522 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
2523 Schedule == OMP_dist_sch_static) &&
2524 "expected static non-chunked schedule");
2525 // If the Chunk was not specified in the clause - use default value 1.
2526 Chunk = CGF.Builder.getIntN(IVSize, 1);
2527 } else {
2528 assert((Schedule == OMP_sch_static_chunked ||
Alexey Bataev6cff6242016-05-30 13:05:14 +00002529 Schedule == OMP_sch_static_balanced_chunked ||
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002530 Schedule == OMP_ord_static_chunked ||
2531 Schedule == OMP_dist_sch_static_chunked) &&
2532 "expected static chunked schedule");
2533 }
2534 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002535 UpdateLocation, ThreadId, CGF.Builder.getInt32(addMonoNonMonoModifier(
2536 Schedule, M1, M2)), // Schedule type
2537 IL.getPointer(), // &isLastIter
2538 LB.getPointer(), // &LB
2539 UB.getPointer(), // &UB
2540 ST.getPointer(), // &Stride
2541 CGF.Builder.getIntN(IVSize, 1), // Incr
2542 Chunk // Chunk
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002543 };
2544 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
2545}
2546
John McCall7f416cc2015-09-08 08:05:57 +00002547void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
2548 SourceLocation Loc,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002549 const OpenMPScheduleTy &ScheduleKind,
John McCall7f416cc2015-09-08 08:05:57 +00002550 unsigned IVSize, bool IVSigned,
2551 bool Ordered, Address IL, Address LB,
2552 Address UB, Address ST,
2553 llvm::Value *Chunk) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002554 OpenMPSchedType ScheduleNum =
2555 getRuntimeSchedule(ScheduleKind.Schedule, Chunk != nullptr, Ordered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002556 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2557 auto *ThreadId = getThreadID(CGF, Loc);
2558 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002559 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
2560 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, IVSize,
2561 Ordered, IL, LB, UB, ST, Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002562}
John McCall7f416cc2015-09-08 08:05:57 +00002563
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002564void CGOpenMPRuntime::emitDistributeStaticInit(
2565 CodeGenFunction &CGF, SourceLocation Loc,
2566 OpenMPDistScheduleClauseKind SchedKind, unsigned IVSize, bool IVSigned,
2567 bool Ordered, Address IL, Address LB, Address UB, Address ST,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002568 llvm::Value *Chunk) {
2569 OpenMPSchedType ScheduleNum = getRuntimeSchedule(SchedKind, Chunk != nullptr);
2570 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2571 auto *ThreadId = getThreadID(CGF, Loc);
2572 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002573 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
2574 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
2575 OMPC_SCHEDULE_MODIFIER_unknown, IVSize, Ordered, IL, LB,
2576 UB, ST, Chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002577}
2578
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002579void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
2580 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002581 if (!CGF.HaveInsertPoint())
2582 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00002583 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002584 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002585 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
2586 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00002587}
2588
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002589void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
2590 SourceLocation Loc,
2591 unsigned IVSize,
2592 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002593 if (!CGF.HaveInsertPoint())
2594 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002595 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002596 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002597 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
2598}
2599
Alexander Musman92bdaab2015-03-12 13:37:50 +00002600llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
2601 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00002602 bool IVSigned, Address IL,
2603 Address LB, Address UB,
2604 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00002605 // Call __kmpc_dispatch_next(
2606 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
2607 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
2608 // kmp_int[32|64] *p_stride);
2609 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00002610 emitUpdateLocation(CGF, Loc),
2611 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002612 IL.getPointer(), // &isLastIter
2613 LB.getPointer(), // &Lower
2614 UB.getPointer(), // &Upper
2615 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00002616 };
2617 llvm::Value *Call =
2618 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
2619 return CGF.EmitScalarConversion(
2620 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002621 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002622}
2623
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002624void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
2625 llvm::Value *NumThreads,
2626 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002627 if (!CGF.HaveInsertPoint())
2628 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00002629 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
2630 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002631 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00002632 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002633 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
2634 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00002635}
2636
Alexey Bataev7f210c62015-06-18 13:40:03 +00002637void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
2638 OpenMPProcBindClauseKind ProcBind,
2639 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002640 if (!CGF.HaveInsertPoint())
2641 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00002642 // Constants for proc bind value accepted by the runtime.
2643 enum ProcBindTy {
2644 ProcBindFalse = 0,
2645 ProcBindTrue,
2646 ProcBindMaster,
2647 ProcBindClose,
2648 ProcBindSpread,
2649 ProcBindIntel,
2650 ProcBindDefault
2651 } RuntimeProcBind;
2652 switch (ProcBind) {
2653 case OMPC_PROC_BIND_master:
2654 RuntimeProcBind = ProcBindMaster;
2655 break;
2656 case OMPC_PROC_BIND_close:
2657 RuntimeProcBind = ProcBindClose;
2658 break;
2659 case OMPC_PROC_BIND_spread:
2660 RuntimeProcBind = ProcBindSpread;
2661 break;
2662 case OMPC_PROC_BIND_unknown:
2663 llvm_unreachable("Unsupported proc_bind value.");
2664 }
2665 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
2666 llvm::Value *Args[] = {
2667 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2668 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
2669 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
2670}
2671
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002672void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
2673 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002674 if (!CGF.HaveInsertPoint())
2675 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00002676 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002677 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
2678 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002679}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002680
Alexey Bataev62b63b12015-03-10 07:28:44 +00002681namespace {
2682/// \brief Indexes of fields for type kmp_task_t.
2683enum KmpTaskTFields {
2684 /// \brief List of shared variables.
2685 KmpTaskTShareds,
2686 /// \brief Task routine.
2687 KmpTaskTRoutine,
2688 /// \brief Partition id for the untied tasks.
2689 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00002690 /// Function with call of destructors for private variables.
2691 Data1,
2692 /// Task priority.
2693 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00002694 /// (Taskloops only) Lower bound.
2695 KmpTaskTLowerBound,
2696 /// (Taskloops only) Upper bound.
2697 KmpTaskTUpperBound,
2698 /// (Taskloops only) Stride.
2699 KmpTaskTStride,
2700 /// (Taskloops only) Is last iteration flag.
2701 KmpTaskTLastIter,
Alexey Bataev62b63b12015-03-10 07:28:44 +00002702};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002703} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00002704
Samuel Antaoee8fb302016-01-06 13:42:12 +00002705bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
2706 // FIXME: Add other entries type when they become supported.
2707 return OffloadEntriesTargetRegion.empty();
2708}
2709
2710/// \brief Initialize target region entry.
2711void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2712 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2713 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00002714 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002715 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
2716 "only required for the device "
2717 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00002718 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00002719 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
2720 /*Flags=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002721 ++OffloadingEntriesNum;
2722}
2723
2724void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2725 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2726 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00002727 llvm::Constant *Addr, llvm::Constant *ID,
2728 int32_t Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002729 // If we are emitting code for a target, the entry is already initialized,
2730 // only has to be registered.
2731 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00002732 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00002733 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00002734 auto &Entry =
2735 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00002736 assert(Entry.isValid() && "Entry not initialized!");
2737 Entry.setAddress(Addr);
2738 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00002739 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002740 return;
2741 } else {
Samuel Antaof83efdb2017-01-05 16:02:49 +00002742 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00002743 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002744 }
2745}
2746
2747bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00002748 unsigned DeviceID, unsigned FileID, StringRef ParentName,
2749 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002750 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
2751 if (PerDevice == OffloadEntriesTargetRegion.end())
2752 return false;
2753 auto PerFile = PerDevice->second.find(FileID);
2754 if (PerFile == PerDevice->second.end())
2755 return false;
2756 auto PerParentName = PerFile->second.find(ParentName);
2757 if (PerParentName == PerFile->second.end())
2758 return false;
2759 auto PerLine = PerParentName->second.find(LineNum);
2760 if (PerLine == PerParentName->second.end())
2761 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002762 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00002763 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00002764 return false;
2765 return true;
2766}
2767
2768void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
2769 const OffloadTargetRegionEntryInfoActTy &Action) {
2770 // Scan all target region entries and perform the provided action.
2771 for (auto &D : OffloadEntriesTargetRegion)
2772 for (auto &F : D.second)
2773 for (auto &P : F.second)
2774 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00002775 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002776}
2777
2778/// \brief Create a Ctor/Dtor-like function whose body is emitted through
2779/// \a Codegen. This is used to emit the two functions that register and
2780/// unregister the descriptor of the current compilation unit.
2781static llvm::Function *
2782createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
2783 const RegionCodeGenTy &Codegen) {
2784 auto &C = CGM.getContext();
2785 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002786 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002787 Args.push_back(&DummyPtr);
2788
2789 CodeGenFunction CGF(CGM);
John McCallc56a8b32016-03-11 04:30:31 +00002790 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002791 auto FTy = CGM.getTypes().GetFunctionType(FI);
2792 auto *Fn =
2793 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
2794 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
2795 Codegen(CGF);
2796 CGF.FinishFunction();
2797 return Fn;
2798}
2799
2800llvm::Function *
2801CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
2802
2803 // If we don't have entries or if we are emitting code for the device, we
2804 // don't need to do anything.
2805 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
2806 return nullptr;
2807
2808 auto &M = CGM.getModule();
2809 auto &C = CGM.getContext();
2810
2811 // Get list of devices we care about
2812 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
2813
2814 // We should be creating an offloading descriptor only if there are devices
2815 // specified.
2816 assert(!Devices.empty() && "No OpenMP offloading devices??");
2817
2818 // Create the external variables that will point to the begin and end of the
2819 // host entries section. These will be defined by the linker.
2820 auto *OffloadEntryTy =
2821 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
2822 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
2823 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002824 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002825 ".omp_offloading.entries_begin");
2826 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
2827 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002828 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002829 ".omp_offloading.entries_end");
2830
2831 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00002832 auto *DeviceImageTy = cast<llvm::StructType>(
2833 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00002834 ConstantInitBuilder DeviceImagesBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002835 auto DeviceImagesEntries = DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002836
2837 for (unsigned i = 0; i < Devices.size(); ++i) {
2838 StringRef T = Devices[i].getTriple();
2839 auto *ImgBegin = new llvm::GlobalVariable(
2840 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002841 /*Initializer=*/nullptr,
2842 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002843 auto *ImgEnd = new llvm::GlobalVariable(
2844 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002845 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002846
John McCall6c9f1fdb2016-11-19 08:17:24 +00002847 auto Dev = DeviceImagesEntries.beginStruct(DeviceImageTy);
2848 Dev.add(ImgBegin);
2849 Dev.add(ImgEnd);
2850 Dev.add(HostEntriesBegin);
2851 Dev.add(HostEntriesEnd);
John McCallf1788632016-11-28 22:18:30 +00002852 Dev.finishAndAddTo(DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002853 }
2854
2855 // Create device images global array.
John McCall6c9f1fdb2016-11-19 08:17:24 +00002856 llvm::GlobalVariable *DeviceImages =
2857 DeviceImagesEntries.finishAndCreateGlobal(".omp_offloading.device_images",
2858 CGM.getPointerAlign(),
2859 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002860 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002861
2862 // This is a Zero array to be used in the creation of the constant expressions
2863 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
2864 llvm::Constant::getNullValue(CGM.Int32Ty)};
2865
2866 // Create the target region descriptor.
2867 auto *BinaryDescriptorTy = cast<llvm::StructType>(
2868 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00002869 ConstantInitBuilder DescBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002870 auto DescInit = DescBuilder.beginStruct(BinaryDescriptorTy);
2871 DescInit.addInt(CGM.Int32Ty, Devices.size());
2872 DescInit.add(llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
2873 DeviceImages,
2874 Index));
2875 DescInit.add(HostEntriesBegin);
2876 DescInit.add(HostEntriesEnd);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002877
John McCall6c9f1fdb2016-11-19 08:17:24 +00002878 auto *Desc = DescInit.finishAndCreateGlobal(".omp_offloading.descriptor",
2879 CGM.getPointerAlign(),
2880 /*isConstant=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002881
2882 // Emit code to register or unregister the descriptor at execution
2883 // startup or closing, respectively.
2884
2885 // Create a variable to drive the registration and unregistration of the
2886 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
2887 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
2888 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00002889 IdentInfo, C.CharTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002890
2891 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002892 CGM, ".omp_offloading.descriptor_unreg",
2893 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002894 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
2895 Desc);
2896 });
2897 auto *RegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002898 CGM, ".omp_offloading.descriptor_reg",
2899 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002900 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_register_lib),
2901 Desc);
2902 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
2903 });
George Rokos29d0f002017-05-27 03:03:13 +00002904 if (CGM.supportsCOMDAT()) {
2905 // It is sufficient to call registration function only once, so create a
2906 // COMDAT group for registration/unregistration functions and associated
2907 // data. That would reduce startup time and code size. Registration
2908 // function serves as a COMDAT group key.
2909 auto ComdatKey = M.getOrInsertComdat(RegFn->getName());
2910 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
2911 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
2912 RegFn->setComdat(ComdatKey);
2913 UnRegFn->setComdat(ComdatKey);
2914 DeviceImages->setComdat(ComdatKey);
2915 Desc->setComdat(ComdatKey);
2916 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002917 return RegFn;
2918}
2919
Samuel Antao2de62b02016-02-13 23:35:10 +00002920void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
Samuel Antaof83efdb2017-01-05 16:02:49 +00002921 llvm::Constant *Addr, uint64_t Size,
2922 int32_t Flags) {
Samuel Antao2de62b02016-02-13 23:35:10 +00002923 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00002924 auto *TgtOffloadEntryType = cast<llvm::StructType>(
2925 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
2926 llvm::LLVMContext &C = CGM.getModule().getContext();
2927 llvm::Module &M = CGM.getModule();
2928
2929 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00002930 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002931
2932 // Create constant string with the name.
2933 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
2934
2935 llvm::GlobalVariable *Str =
2936 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
2937 llvm::GlobalValue::InternalLinkage, StrPtrInit,
2938 ".omp_offloading.entry_name");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002939 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002940 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
2941
John McCall6c9f1fdb2016-11-19 08:17:24 +00002942 // We can't have any padding between symbols, so we need to have 1-byte
2943 // alignment.
2944 auto Align = CharUnits::fromQuantity(1);
2945
Samuel Antaoee8fb302016-01-06 13:42:12 +00002946 // Create the entry struct.
John McCall23c9dc62016-11-28 22:18:27 +00002947 ConstantInitBuilder EntryBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002948 auto EntryInit = EntryBuilder.beginStruct(TgtOffloadEntryType);
2949 EntryInit.add(AddrPtr);
2950 EntryInit.add(StrPtr);
2951 EntryInit.addInt(CGM.SizeTy, Size);
Samuel Antaof83efdb2017-01-05 16:02:49 +00002952 EntryInit.addInt(CGM.Int32Ty, Flags);
2953 EntryInit.addInt(CGM.Int32Ty, 0);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002954 llvm::GlobalVariable *Entry =
2955 EntryInit.finishAndCreateGlobal(".omp_offloading.entry",
2956 Align,
2957 /*constant*/ true,
2958 llvm::GlobalValue::ExternalLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002959
2960 // The entry has to be created in the section the linker expects it to be.
2961 Entry->setSection(".omp_offloading.entries");
Samuel Antaoee8fb302016-01-06 13:42:12 +00002962}
2963
2964void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
2965 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00002966 // can easily figure out what to emit. The produced metadata looks like
2967 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00002968 //
2969 // !omp_offload.info = !{!1, ...}
2970 //
2971 // Right now we only generate metadata for function that contain target
2972 // regions.
2973
2974 // If we do not have entries, we dont need to do anything.
2975 if (OffloadEntriesInfoManager.empty())
2976 return;
2977
2978 llvm::Module &M = CGM.getModule();
2979 llvm::LLVMContext &C = M.getContext();
2980 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
2981 OrderedEntries(OffloadEntriesInfoManager.size());
2982
2983 // Create the offloading info metadata node.
2984 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
2985
Simon Pilgrim2c518802017-03-30 14:13:19 +00002986 // Auxiliary methods to create metadata values and strings.
Samuel Antaoee8fb302016-01-06 13:42:12 +00002987 auto getMDInt = [&](unsigned v) {
2988 return llvm::ConstantAsMetadata::get(
2989 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
2990 };
2991
2992 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
2993
2994 // Create function that emits metadata for each target region entry;
2995 auto &&TargetRegionMetadataEmitter = [&](
2996 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002997 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
2998 llvm::SmallVector<llvm::Metadata *, 32> Ops;
2999 // Generate metadata for target regions. Each entry of this metadata
3000 // contains:
3001 // - Entry 0 -> Kind of this type of metadata (0).
3002 // - Entry 1 -> Device ID of the file where the entry was identified.
3003 // - Entry 2 -> File ID of the file where the entry was identified.
3004 // - Entry 3 -> Mangled name of the function where the entry was identified.
3005 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00003006 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003007 // The first element of the metadata node is the kind.
3008 Ops.push_back(getMDInt(E.getKind()));
3009 Ops.push_back(getMDInt(DeviceID));
3010 Ops.push_back(getMDInt(FileID));
3011 Ops.push_back(getMDString(ParentName));
3012 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003013 Ops.push_back(getMDInt(E.getOrder()));
3014
3015 // Save this entry in the right position of the ordered entries array.
3016 OrderedEntries[E.getOrder()] = &E;
3017
3018 // Add metadata to the named metadata node.
3019 MD->addOperand(llvm::MDNode::get(C, Ops));
3020 };
3021
3022 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3023 TargetRegionMetadataEmitter);
3024
3025 for (auto *E : OrderedEntries) {
3026 assert(E && "All ordered entries must exist!");
3027 if (auto *CE =
3028 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3029 E)) {
3030 assert(CE->getID() && CE->getAddress() &&
3031 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00003032 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003033 } else
3034 llvm_unreachable("Unsupported entry kind.");
3035 }
3036}
3037
3038/// \brief Loads all the offload entries information from the host IR
3039/// metadata.
3040void CGOpenMPRuntime::loadOffloadInfoMetadata() {
3041 // If we are in target mode, load the metadata from the host IR. This code has
3042 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
3043
3044 if (!CGM.getLangOpts().OpenMPIsDevice)
3045 return;
3046
3047 if (CGM.getLangOpts().OMPHostIRFile.empty())
3048 return;
3049
3050 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
3051 if (Buf.getError())
3052 return;
3053
3054 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00003055 auto ME = expectedToErrorOrAndEmitErrors(
3056 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003057
3058 if (ME.getError())
3059 return;
3060
3061 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
3062 if (!MD)
3063 return;
3064
3065 for (auto I : MD->operands()) {
3066 llvm::MDNode *MN = cast<llvm::MDNode>(I);
3067
3068 auto getMDInt = [&](unsigned Idx) {
3069 llvm::ConstantAsMetadata *V =
3070 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
3071 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
3072 };
3073
3074 auto getMDString = [&](unsigned Idx) {
3075 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
3076 return V->getString();
3077 };
3078
3079 switch (getMDInt(0)) {
3080 default:
3081 llvm_unreachable("Unexpected metadata!");
3082 break;
3083 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3084 OFFLOAD_ENTRY_INFO_TARGET_REGION:
3085 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
3086 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
3087 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00003088 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003089 break;
3090 }
3091 }
3092}
3093
Alexey Bataev62b63b12015-03-10 07:28:44 +00003094void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
3095 if (!KmpRoutineEntryPtrTy) {
3096 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
3097 auto &C = CGM.getContext();
3098 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
3099 FunctionProtoType::ExtProtoInfo EPI;
3100 KmpRoutineEntryPtrQTy = C.getPointerType(
3101 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
3102 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
3103 }
3104}
3105
Alexey Bataevc71a4092015-09-11 10:29:41 +00003106static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
3107 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003108 auto *Field = FieldDecl::Create(
3109 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
3110 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
3111 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
3112 Field->setAccess(AS_public);
3113 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003114 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003115}
3116
Samuel Antaoee8fb302016-01-06 13:42:12 +00003117QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
3118
3119 // Make sure the type of the entry is already created. This is the type we
3120 // have to create:
3121 // struct __tgt_offload_entry{
3122 // void *addr; // Pointer to the offload entry info.
3123 // // (function or global)
3124 // char *name; // Name of the function or global.
3125 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00003126 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
3127 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003128 // };
3129 if (TgtOffloadEntryQTy.isNull()) {
3130 ASTContext &C = CGM.getContext();
3131 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
3132 RD->startDefinition();
3133 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3134 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
3135 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00003136 addFieldToRecordDecl(
3137 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3138 addFieldToRecordDecl(
3139 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003140 RD->completeDefinition();
3141 TgtOffloadEntryQTy = C.getRecordType(RD);
3142 }
3143 return TgtOffloadEntryQTy;
3144}
3145
3146QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
3147 // These are the types we need to build:
3148 // struct __tgt_device_image{
3149 // void *ImageStart; // Pointer to the target code start.
3150 // void *ImageEnd; // Pointer to the target code end.
3151 // // We also add the host entries to the device image, as it may be useful
3152 // // for the target runtime to have access to that information.
3153 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
3154 // // the entries.
3155 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3156 // // entries (non inclusive).
3157 // };
3158 if (TgtDeviceImageQTy.isNull()) {
3159 ASTContext &C = CGM.getContext();
3160 auto *RD = C.buildImplicitRecord("__tgt_device_image");
3161 RD->startDefinition();
3162 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3163 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3164 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3165 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3166 RD->completeDefinition();
3167 TgtDeviceImageQTy = C.getRecordType(RD);
3168 }
3169 return TgtDeviceImageQTy;
3170}
3171
3172QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
3173 // struct __tgt_bin_desc{
3174 // int32_t NumDevices; // Number of devices supported.
3175 // __tgt_device_image *DeviceImages; // Arrays of device images
3176 // // (one per device).
3177 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
3178 // // entries.
3179 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3180 // // entries (non inclusive).
3181 // };
3182 if (TgtBinaryDescriptorQTy.isNull()) {
3183 ASTContext &C = CGM.getContext();
3184 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
3185 RD->startDefinition();
3186 addFieldToRecordDecl(
3187 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3188 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
3189 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3190 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3191 RD->completeDefinition();
3192 TgtBinaryDescriptorQTy = C.getRecordType(RD);
3193 }
3194 return TgtBinaryDescriptorQTy;
3195}
3196
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003197namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00003198struct PrivateHelpersTy {
3199 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
3200 const VarDecl *PrivateElemInit)
3201 : Original(Original), PrivateCopy(PrivateCopy),
3202 PrivateElemInit(PrivateElemInit) {}
3203 const VarDecl *Original;
3204 const VarDecl *PrivateCopy;
3205 const VarDecl *PrivateElemInit;
3206};
3207typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00003208} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003209
Alexey Bataev9e034042015-05-05 04:05:12 +00003210static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00003211createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003212 if (!Privates.empty()) {
3213 auto &C = CGM.getContext();
3214 // Build struct .kmp_privates_t. {
3215 // /* private vars */
3216 // };
3217 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
3218 RD->startDefinition();
3219 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00003220 auto *VD = Pair.second.Original;
3221 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003222 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00003223 auto *FD = addFieldToRecordDecl(C, RD, Type);
3224 if (VD->hasAttrs()) {
3225 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
3226 E(VD->getAttrs().end());
3227 I != E; ++I)
3228 FD->addAttr(*I);
3229 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003230 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003231 RD->completeDefinition();
3232 return RD;
3233 }
3234 return nullptr;
3235}
3236
Alexey Bataev9e034042015-05-05 04:05:12 +00003237static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00003238createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
3239 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003240 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003241 auto &C = CGM.getContext();
3242 // Build struct kmp_task_t {
3243 // void * shareds;
3244 // kmp_routine_entry_t routine;
3245 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00003246 // kmp_cmplrdata_t data1;
3247 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00003248 // For taskloops additional fields:
3249 // kmp_uint64 lb;
3250 // kmp_uint64 ub;
3251 // kmp_int64 st;
3252 // kmp_int32 liter;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003253 // };
Alexey Bataevad537bb2016-05-30 09:06:50 +00003254 auto *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
3255 UD->startDefinition();
3256 addFieldToRecordDecl(C, UD, KmpInt32Ty);
3257 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
3258 UD->completeDefinition();
3259 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003260 auto *RD = C.buildImplicitRecord("kmp_task_t");
3261 RD->startDefinition();
3262 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3263 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
3264 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00003265 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3266 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003267 if (isOpenMPTaskLoopDirective(Kind)) {
3268 QualType KmpUInt64Ty =
3269 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3270 QualType KmpInt64Ty =
3271 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3272 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3273 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3274 addFieldToRecordDecl(C, RD, KmpInt64Ty);
3275 addFieldToRecordDecl(C, RD, KmpInt32Ty);
3276 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003277 RD->completeDefinition();
3278 return RD;
3279}
3280
3281static RecordDecl *
3282createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003283 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003284 auto &C = CGM.getContext();
3285 // Build struct kmp_task_t_with_privates {
3286 // kmp_task_t task_data;
3287 // .kmp_privates_t. privates;
3288 // };
3289 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
3290 RD->startDefinition();
3291 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003292 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
3293 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
3294 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003295 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003296 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003297}
3298
3299/// \brief Emit a proxy function which accepts kmp_task_t as the second
3300/// argument.
3301/// \code
3302/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003303/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00003304/// For taskloops:
3305/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003306/// tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003307/// return 0;
3308/// }
3309/// \endcode
3310static llvm::Value *
3311emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00003312 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
3313 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003314 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003315 QualType SharedsPtrTy, llvm::Value *TaskFunction,
3316 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003317 auto &C = CGM.getContext();
3318 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003319 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3320 ImplicitParamDecl::Other);
3321 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3322 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3323 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003324 Args.push_back(&GtidArg);
3325 Args.push_back(&TaskTypeArg);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003326 auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003327 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003328 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
3329 auto *TaskEntry =
3330 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
3331 ".omp_task_entry.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003332 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003333 CodeGenFunction CGF(CGM);
3334 CGF.disableDebugInfo();
3335 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
3336
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003337 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00003338 // tt,
3339 // For taskloops:
3340 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3341 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003342 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00003343 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003344 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3345 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3346 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003347 auto *KmpTaskTWithPrivatesQTyRD =
3348 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003349 LValue Base =
3350 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003351 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3352 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3353 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003354 auto *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003355
3356 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3357 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003358 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003359 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003360 CGF.ConvertTypeForMem(SharedsPtrTy));
3361
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003362 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3363 llvm::Value *PrivatesParam;
3364 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3365 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3366 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003367 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003368 } else
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003369 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003370
Alexey Bataev7292c292016-04-25 12:22:29 +00003371 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
3372 TaskPrivatesMap,
3373 CGF.Builder
3374 .CreatePointerBitCastOrAddrSpaceCast(
3375 TDBase.getAddress(), CGF.VoidPtrTy)
3376 .getPointer()};
3377 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
3378 std::end(CommonArgs));
3379 if (isOpenMPTaskLoopDirective(Kind)) {
3380 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
3381 auto LBLVal = CGF.EmitLValueForField(Base, *LBFI);
3382 auto *LBParam = CGF.EmitLoadOfLValue(LBLVal, Loc).getScalarVal();
3383 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
3384 auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
3385 auto *UBParam = CGF.EmitLoadOfLValue(UBLVal, Loc).getScalarVal();
3386 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
3387 auto StLVal = CGF.EmitLValueForField(Base, *StFI);
3388 auto *StParam = CGF.EmitLoadOfLValue(StLVal, Loc).getScalarVal();
3389 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3390 auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
3391 auto *LIParam = CGF.EmitLoadOfLValue(LILVal, Loc).getScalarVal();
3392 CallArgs.push_back(LBParam);
3393 CallArgs.push_back(UBParam);
3394 CallArgs.push_back(StParam);
3395 CallArgs.push_back(LIParam);
3396 }
3397 CallArgs.push_back(SharedsParam);
3398
Alexey Bataev62b63b12015-03-10 07:28:44 +00003399 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
3400 CGF.EmitStoreThroughLValue(
3401 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00003402 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00003403 CGF.FinishFunction();
3404 return TaskEntry;
3405}
3406
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003407static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
3408 SourceLocation Loc,
3409 QualType KmpInt32Ty,
3410 QualType KmpTaskTWithPrivatesPtrQTy,
3411 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003412 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003413 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003414 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3415 ImplicitParamDecl::Other);
3416 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3417 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3418 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003419 Args.push_back(&GtidArg);
3420 Args.push_back(&TaskTypeArg);
3421 FunctionType::ExtInfo Info;
3422 auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003423 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003424 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
3425 auto *DestructorFn =
3426 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
3427 ".omp_task_destructor.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003428 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
3429 DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003430 CodeGenFunction CGF(CGM);
3431 CGF.disableDebugInfo();
3432 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
3433 Args);
3434
Alexey Bataev31300ed2016-02-04 11:27:03 +00003435 LValue Base = CGF.EmitLoadOfPointerLValue(
3436 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3437 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003438 auto *KmpTaskTWithPrivatesQTyRD =
3439 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3440 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003441 Base = CGF.EmitLValueForField(Base, *FI);
3442 for (auto *Field :
3443 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
3444 if (auto DtorKind = Field->getType().isDestructedType()) {
3445 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
3446 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
3447 }
3448 }
3449 CGF.FinishFunction();
3450 return DestructorFn;
3451}
3452
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003453/// \brief Emit a privates mapping function for correct handling of private and
3454/// firstprivate variables.
3455/// \code
3456/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
3457/// **noalias priv1,..., <tyn> **noalias privn) {
3458/// *priv1 = &.privates.priv1;
3459/// ...;
3460/// *privn = &.privates.privn;
3461/// }
3462/// \endcode
3463static llvm::Value *
3464emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00003465 ArrayRef<const Expr *> PrivateVars,
3466 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00003467 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003468 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003469 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003470 auto &C = CGM.getContext();
3471 FunctionArgList Args;
3472 ImplicitParamDecl TaskPrivatesArg(
3473 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003474 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
3475 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003476 Args.push_back(&TaskPrivatesArg);
3477 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
3478 unsigned Counter = 1;
3479 for (auto *E: PrivateVars) {
3480 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003481 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3482 C.getPointerType(C.getPointerType(E->getType()))
3483 .withConst()
3484 .withRestrict(),
3485 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003486 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3487 PrivateVarsPos[VD] = Counter;
3488 ++Counter;
3489 }
3490 for (auto *E : FirstprivateVars) {
3491 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003492 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3493 C.getPointerType(C.getPointerType(E->getType()))
3494 .withConst()
3495 .withRestrict(),
3496 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003497 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3498 PrivateVarsPos[VD] = Counter;
3499 ++Counter;
3500 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003501 for (auto *E: LastprivateVars) {
3502 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003503 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3504 C.getPointerType(C.getPointerType(E->getType()))
3505 .withConst()
3506 .withRestrict(),
3507 ImplicitParamDecl::Other));
Alexey Bataevf93095a2016-05-05 08:46:22 +00003508 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3509 PrivateVarsPos[VD] = Counter;
3510 ++Counter;
3511 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003512 auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003513 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003514 auto *TaskPrivatesMapTy =
3515 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
3516 auto *TaskPrivatesMap = llvm::Function::Create(
3517 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
3518 ".omp_task_privates_map.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003519 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
3520 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00003521 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00003522 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00003523 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003524 CodeGenFunction CGF(CGM);
3525 CGF.disableDebugInfo();
3526 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
3527 TaskPrivatesMapFnInfo, Args);
3528
3529 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003530 LValue Base = CGF.EmitLoadOfPointerLValue(
3531 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
3532 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003533 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
3534 Counter = 0;
3535 for (auto *Field : PrivatesQTyRD->fields()) {
3536 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
3537 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00003538 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00003539 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
3540 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00003541 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003542 ++Counter;
3543 }
3544 CGF.FinishFunction();
3545 return TaskPrivatesMap;
3546}
3547
Alexey Bataev9e034042015-05-05 04:05:12 +00003548static int array_pod_sort_comparator(const PrivateDataTy *P1,
3549 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003550 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
3551}
3552
Alexey Bataevf93095a2016-05-05 08:46:22 +00003553/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00003554static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00003555 const OMPExecutableDirective &D,
3556 Address KmpTaskSharedsPtr, LValue TDBase,
3557 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
3558 QualType SharedsTy, QualType SharedsPtrTy,
3559 const OMPTaskDataTy &Data,
3560 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
3561 auto &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00003562 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3563 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
3564 LValue SrcBase;
3565 if (!Data.FirstprivateVars.empty()) {
3566 SrcBase = CGF.MakeAddrLValue(
3567 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3568 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
3569 SharedsTy);
3570 }
3571 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
3572 cast<CapturedStmt>(*D.getAssociatedStmt()));
3573 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
3574 for (auto &&Pair : Privates) {
3575 auto *VD = Pair.second.PrivateCopy;
3576 auto *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00003577 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
3578 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00003579 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003580 if (auto *Elem = Pair.second.PrivateElemInit) {
3581 auto *OriginalVD = Pair.second.Original;
3582 auto *SharedField = CapturesInfo.lookup(OriginalVD);
3583 auto SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
3584 SharedRefLValue = CGF.MakeAddrLValue(
3585 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003586 SharedRefLValue.getType(),
3587 LValueBaseInfo(AlignmentSource::Decl,
3588 SharedRefLValue.getBaseInfo().getMayAlias()));
Alexey Bataevf93095a2016-05-05 08:46:22 +00003589 QualType Type = OriginalVD->getType();
3590 if (Type->isArrayType()) {
3591 // Initialize firstprivate array.
3592 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
3593 // Perform simple memcpy.
3594 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
3595 SharedRefLValue.getAddress(), Type);
3596 } else {
3597 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00003598 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00003599 CGF.EmitOMPAggregateAssign(
3600 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
3601 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
3602 Address SrcElement) {
3603 // Clean up any temporaries needed by the initialization.
3604 CodeGenFunction::OMPPrivateScope InitScope(CGF);
3605 InitScope.addPrivate(
3606 Elem, [SrcElement]() -> Address { return SrcElement; });
3607 (void)InitScope.Privatize();
3608 // Emit initialization for single element.
3609 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
3610 CGF, &CapturesInfo);
3611 CGF.EmitAnyExprToMem(Init, DestElement,
3612 Init->getType().getQualifiers(),
3613 /*IsInitializer=*/false);
3614 });
3615 }
3616 } else {
3617 CodeGenFunction::OMPPrivateScope InitScope(CGF);
3618 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
3619 return SharedRefLValue.getAddress();
3620 });
3621 (void)InitScope.Privatize();
3622 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
3623 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
3624 /*capturedByInit=*/false);
3625 }
3626 } else
3627 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
3628 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003629 ++FI;
3630 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003631}
3632
3633/// Check if duplication function is required for taskloops.
3634static bool checkInitIsRequired(CodeGenFunction &CGF,
3635 ArrayRef<PrivateDataTy> Privates) {
3636 bool InitRequired = false;
3637 for (auto &&Pair : Privates) {
3638 auto *VD = Pair.second.PrivateCopy;
3639 auto *Init = VD->getAnyInitializer();
3640 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
3641 !CGF.isTrivialInitializer(Init));
3642 }
3643 return InitRequired;
3644}
3645
3646
3647/// Emit task_dup function (for initialization of
3648/// private/firstprivate/lastprivate vars and last_iter flag)
3649/// \code
3650/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
3651/// lastpriv) {
3652/// // setup lastprivate flag
3653/// task_dst->last = lastpriv;
3654/// // could be constructor calls here...
3655/// }
3656/// \endcode
3657static llvm::Value *
3658emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
3659 const OMPExecutableDirective &D,
3660 QualType KmpTaskTWithPrivatesPtrQTy,
3661 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
3662 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
3663 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
3664 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
3665 auto &C = CGM.getContext();
3666 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003667 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3668 KmpTaskTWithPrivatesPtrQTy,
3669 ImplicitParamDecl::Other);
3670 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3671 KmpTaskTWithPrivatesPtrQTy,
3672 ImplicitParamDecl::Other);
3673 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3674 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003675 Args.push_back(&DstArg);
3676 Args.push_back(&SrcArg);
3677 Args.push_back(&LastprivArg);
3678 auto &TaskDupFnInfo =
3679 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3680 auto *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
3681 auto *TaskDup =
3682 llvm::Function::Create(TaskDupTy, llvm::GlobalValue::InternalLinkage,
3683 ".omp_task_dup.", &CGM.getModule());
3684 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskDup, TaskDupFnInfo);
3685 CodeGenFunction CGF(CGM);
3686 CGF.disableDebugInfo();
3687 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args);
3688
3689 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3690 CGF.GetAddrOfLocalVar(&DstArg),
3691 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3692 // task_dst->liter = lastpriv;
3693 if (WithLastIter) {
3694 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3695 LValue Base = CGF.EmitLValueForField(
3696 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
3697 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
3698 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
3699 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
3700 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
3701 }
3702
3703 // Emit initial values for private copies (if any).
3704 assert(!Privates.empty());
3705 Address KmpTaskSharedsPtr = Address::invalid();
3706 if (!Data.FirstprivateVars.empty()) {
3707 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3708 CGF.GetAddrOfLocalVar(&SrcArg),
3709 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3710 LValue Base = CGF.EmitLValueForField(
3711 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
3712 KmpTaskSharedsPtr = Address(
3713 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
3714 Base, *std::next(KmpTaskTQTyRD->field_begin(),
3715 KmpTaskTShareds)),
3716 Loc),
3717 CGF.getNaturalTypeAlignment(SharedsTy));
3718 }
Alexey Bataev8a831592016-05-10 10:36:51 +00003719 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
3720 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003721 CGF.FinishFunction();
3722 return TaskDup;
3723}
3724
Alexey Bataev8a831592016-05-10 10:36:51 +00003725/// Checks if destructor function is required to be generated.
3726/// \return true if cleanups are required, false otherwise.
3727static bool
3728checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
3729 bool NeedsCleanup = false;
3730 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3731 auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
3732 for (auto *FD : PrivateRD->fields()) {
3733 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
3734 if (NeedsCleanup)
3735 break;
3736 }
3737 return NeedsCleanup;
3738}
3739
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003740CGOpenMPRuntime::TaskResultTy
3741CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
3742 const OMPExecutableDirective &D,
3743 llvm::Value *TaskFunction, QualType SharedsTy,
3744 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003745 auto &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00003746 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003747 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003748 auto I = Data.PrivateCopies.begin();
3749 for (auto *E : Data.PrivateVars) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003750 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3751 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00003752 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00003753 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3754 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003755 ++I;
3756 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003757 I = Data.FirstprivateCopies.begin();
3758 auto IElemInitRef = Data.FirstprivateInits.begin();
3759 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003760 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3761 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00003762 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00003763 PrivateHelpersTy(
3764 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3765 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
Richard Trieucc3949d2016-02-18 22:34:54 +00003766 ++I;
3767 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00003768 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003769 I = Data.LastprivateCopies.begin();
3770 for (auto *E : Data.LastprivateVars) {
3771 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3772 Privates.push_back(std::make_pair(
3773 C.getDeclAlign(VD),
3774 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3775 /*PrivateElemInit=*/nullptr)));
3776 ++I;
3777 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003778 llvm::array_pod_sort(Privates.begin(), Privates.end(),
3779 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003780 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
3781 // Build type kmp_routine_entry_t (if not built yet).
3782 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003783 // Build type kmp_task_t (if not built yet).
3784 if (KmpTaskTQTy.isNull()) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003785 KmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
3786 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003787 }
3788 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003789 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003790 auto *KmpTaskTWithPrivatesQTyRD =
3791 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
3792 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
3793 QualType KmpTaskTWithPrivatesPtrQTy =
3794 C.getPointerType(KmpTaskTWithPrivatesQTy);
3795 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
3796 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00003797 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003798 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
3799
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003800 // Emit initial values for private copies (if any).
3801 llvm::Value *TaskPrivatesMap = nullptr;
3802 auto *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00003803 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003804 if (!Privates.empty()) {
3805 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00003806 TaskPrivatesMap = emitTaskPrivateMappingFunction(
3807 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
3808 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003809 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3810 TaskPrivatesMap, TaskPrivatesMapTy);
3811 } else {
3812 TaskPrivatesMap = llvm::ConstantPointerNull::get(
3813 cast<llvm::PointerType>(TaskPrivatesMapTy));
3814 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003815 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
3816 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003817 auto *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00003818 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
3819 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
3820 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003821
3822 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
3823 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
3824 // kmp_routine_entry_t *task_entry);
3825 // Task flags. Format is taken from
3826 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
3827 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00003828 enum {
3829 TiedFlag = 0x1,
3830 FinalFlag = 0x2,
3831 DestructorsFlag = 0x8,
3832 PriorityFlag = 0x20
3833 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003834 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00003835 bool NeedsCleanup = false;
3836 if (!Privates.empty()) {
3837 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
3838 if (NeedsCleanup)
3839 Flags = Flags | DestructorsFlag;
3840 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00003841 if (Data.Priority.getInt())
3842 Flags = Flags | PriorityFlag;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003843 auto *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003844 Data.Final.getPointer()
3845 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00003846 CGF.Builder.getInt32(FinalFlag),
3847 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003848 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003849 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00003850 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003851 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
3852 getThreadID(CGF, Loc), TaskFlags,
3853 KmpTaskTWithPrivatesTySize, SharedsSize,
3854 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3855 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00003856 auto *NewTask = CGF.EmitRuntimeCall(
3857 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003858 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3859 NewTask, KmpTaskTWithPrivatesPtrTy);
3860 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
3861 KmpTaskTWithPrivatesQTy);
3862 LValue TDBase =
3863 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003864 // Fill the data in the resulting kmp_task_t record.
3865 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00003866 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003867 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00003868 KmpTaskSharedsPtr =
3869 Address(CGF.EmitLoadOfScalar(
3870 CGF.EmitLValueForField(
3871 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
3872 KmpTaskTShareds)),
3873 Loc),
3874 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003875 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003876 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003877 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00003878 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003879 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00003880 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
3881 SharedsTy, SharedsPtrTy, Data, Privates,
3882 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003883 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
3884 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
3885 Result.TaskDupFn = emitTaskDupFunction(
3886 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
3887 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
3888 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003889 }
3890 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00003891 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
3892 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00003893 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00003894 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
3895 auto *KmpCmplrdataUD = (*FI)->getType()->getAsUnionType()->getDecl();
3896 if (NeedsCleanup) {
3897 llvm::Value *DestructorFn = emitDestructorsFunction(
3898 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
3899 KmpTaskTWithPrivatesQTy);
3900 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
3901 LValue DestructorsLV = CGF.EmitLValueForField(
3902 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
3903 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3904 DestructorFn, KmpRoutineEntryPtrTy),
3905 DestructorsLV);
3906 }
3907 // Set priority.
3908 if (Data.Priority.getInt()) {
3909 LValue Data2LV = CGF.EmitLValueForField(
3910 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
3911 LValue PriorityLV = CGF.EmitLValueForField(
3912 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
3913 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
3914 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003915 Result.NewTask = NewTask;
3916 Result.TaskEntry = TaskEntry;
3917 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
3918 Result.TDBase = TDBase;
3919 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
3920 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00003921}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003922
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003923void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
3924 const OMPExecutableDirective &D,
3925 llvm::Value *TaskFunction,
3926 QualType SharedsTy, Address Shareds,
3927 const Expr *IfCond,
3928 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003929 if (!CGF.HaveInsertPoint())
3930 return;
3931
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003932 TaskResultTy Result =
3933 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
3934 llvm::Value *NewTask = Result.NewTask;
3935 llvm::Value *TaskEntry = Result.TaskEntry;
3936 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
3937 LValue TDBase = Result.TDBase;
3938 RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
Alexey Bataev7292c292016-04-25 12:22:29 +00003939 auto &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003940 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00003941 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003942 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00003943 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003944 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00003945 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003946 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
3947 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003948 QualType FlagsTy =
3949 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003950 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
3951 if (KmpDependInfoTy.isNull()) {
3952 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
3953 KmpDependInfoRD->startDefinition();
3954 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
3955 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
3956 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
3957 KmpDependInfoRD->completeDefinition();
3958 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003959 } else
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003960 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003961 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003962 // Define type kmp_depend_info[<Dependences.size()>];
3963 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00003964 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003965 ArrayType::Normal, /*IndexTypeQuals=*/0);
3966 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00003967 DependenciesArray =
3968 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
John McCall7f416cc2015-09-08 08:05:57 +00003969 for (unsigned i = 0; i < NumDependencies; ++i) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003970 const Expr *E = Data.Dependences[i].second;
John McCall7f416cc2015-09-08 08:05:57 +00003971 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003972 llvm::Value *Size;
3973 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003974 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
3975 LValue UpAddrLVal =
3976 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
3977 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00003978 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003979 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00003980 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003981 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
3982 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003983 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00003984 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003985 auto Base = CGF.MakeAddrLValue(
3986 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003987 KmpDependInfoTy);
3988 // deps[i].base_addr = &<Dependences[i].second>;
3989 auto BaseAddrLVal = CGF.EmitLValueForField(
3990 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00003991 CGF.EmitStoreOfScalar(
3992 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
3993 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003994 // deps[i].len = sizeof(<Dependences[i].second>);
3995 auto LenLVal = CGF.EmitLValueForField(
3996 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
3997 CGF.EmitStoreOfScalar(Size, LenLVal);
3998 // deps[i].flags = <Dependences[i].first>;
3999 RTLDependenceKindTy DepKind;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004000 switch (Data.Dependences[i].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004001 case OMPC_DEPEND_in:
4002 DepKind = DepIn;
4003 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00004004 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004005 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004006 case OMPC_DEPEND_inout:
4007 DepKind = DepInOut;
4008 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00004009 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004010 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004011 case OMPC_DEPEND_unknown:
4012 llvm_unreachable("Unknown task dependence type");
4013 }
4014 auto FlagsLVal = CGF.EmitLValueForField(
4015 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
4016 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
4017 FlagsLVal);
4018 }
John McCall7f416cc2015-09-08 08:05:57 +00004019 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4020 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004021 CGF.VoidPtrTy);
4022 }
4023
Alexey Bataev62b63b12015-03-10 07:28:44 +00004024 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4025 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004026 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
4027 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
4028 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
4029 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00004030 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004031 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00004032 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
4033 llvm::Value *DepTaskArgs[7];
4034 if (NumDependencies) {
4035 DepTaskArgs[0] = UpLoc;
4036 DepTaskArgs[1] = ThreadID;
4037 DepTaskArgs[2] = NewTask;
4038 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
4039 DepTaskArgs[4] = DependenciesArray.getPointer();
4040 DepTaskArgs[5] = CGF.Builder.getInt32(0);
4041 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4042 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00004043 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
4044 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004045 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004046 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004047 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4048 auto PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
4049 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
4050 }
John McCall7f416cc2015-09-08 08:05:57 +00004051 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004052 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00004053 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00004054 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004055 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00004056 TaskArgs);
4057 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00004058 // Check if parent region is untied and build return for untied task;
4059 if (auto *Region =
4060 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4061 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00004062 };
John McCall7f416cc2015-09-08 08:05:57 +00004063
4064 llvm::Value *DepWaitTaskArgs[6];
4065 if (NumDependencies) {
4066 DepWaitTaskArgs[0] = UpLoc;
4067 DepWaitTaskArgs[1] = ThreadID;
4068 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
4069 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
4070 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
4071 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4072 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004073 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
4074 NumDependencies, &DepWaitTaskArgs](CodeGenFunction &CGF,
4075 PrePostActionTy &) {
4076 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004077 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
4078 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
4079 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
4080 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
4081 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00004082 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004083 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004084 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004085 // Call proxy_task_entry(gtid, new_task);
4086 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy](
4087 CodeGenFunction &CGF, PrePostActionTy &Action) {
4088 Action.Enter(CGF);
4089 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
4090 CGF.EmitCallOrInvoke(TaskEntry, OutlinedFnArgs);
4091 };
4092
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004093 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
4094 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004095 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
4096 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004097 RegionCodeGenTy RCG(CodeGen);
4098 CommonActionTy Action(
4099 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
4100 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
4101 RCG.setAction(Action);
4102 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004103 };
John McCall7f416cc2015-09-08 08:05:57 +00004104
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004105 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00004106 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004107 else {
4108 RegionCodeGenTy ThenRCG(ThenCodeGen);
4109 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00004110 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004111}
4112
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004113void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
4114 const OMPLoopDirective &D,
4115 llvm::Value *TaskFunction,
4116 QualType SharedsTy, Address Shareds,
4117 const Expr *IfCond,
4118 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004119 if (!CGF.HaveInsertPoint())
4120 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004121 TaskResultTy Result =
4122 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004123 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4124 // libcall.
4125 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
4126 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
4127 // sched, kmp_uint64 grainsize, void *task_dup);
4128 llvm::Value *ThreadID = getThreadID(CGF, Loc);
4129 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
4130 llvm::Value *IfVal;
4131 if (IfCond) {
4132 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
4133 /*isSigned=*/true);
4134 } else
4135 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
4136
4137 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004138 Result.TDBase,
4139 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004140 auto *LBVar =
4141 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
4142 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
4143 /*IsInitializer=*/true);
4144 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004145 Result.TDBase,
4146 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004147 auto *UBVar =
4148 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
4149 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
4150 /*IsInitializer=*/true);
4151 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004152 Result.TDBase,
4153 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataev7292c292016-04-25 12:22:29 +00004154 auto *StVar =
4155 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
4156 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
4157 /*IsInitializer=*/true);
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004158 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00004159 llvm::Value *TaskArgs[] = {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004160 UpLoc, ThreadID, Result.NewTask, IfVal, LBLVal.getPointer(),
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004161 UBLVal.getPointer(), CGF.EmitLoadOfScalar(StLVal, SourceLocation()),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004162 llvm::ConstantInt::getSigned(CGF.IntTy, Data.Nogroup ? 1 : 0),
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004163 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004164 CGF.IntTy, Data.Schedule.getPointer()
4165 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004166 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004167 Data.Schedule.getPointer()
4168 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004169 /*isSigned=*/false)
4170 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataevf93095a2016-05-05 08:46:22 +00004171 Result.TaskDupFn
4172 ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Result.TaskDupFn,
4173 CGF.VoidPtrTy)
4174 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00004175 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
4176}
4177
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004178/// \brief Emit reduction operation for each element of array (required for
4179/// array sections) LHS op = RHS.
4180/// \param Type Type of array.
4181/// \param LHSVar Variable on the left side of the reduction operation
4182/// (references element of array in original variable).
4183/// \param RHSVar Variable on the right side of the reduction operation
4184/// (references element of array in original variable).
4185/// \param RedOpGen Generator of reduction operation with use of LHSVar and
4186/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00004187static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004188 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
4189 const VarDecl *RHSVar,
4190 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
4191 const Expr *, const Expr *)> &RedOpGen,
4192 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
4193 const Expr *UpExpr = nullptr) {
4194 // Perform element-by-element initialization.
4195 QualType ElementTy;
4196 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
4197 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
4198
4199 // Drill down to the base element type on both arrays.
4200 auto ArrayTy = Type->getAsArrayTypeUnsafe();
4201 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
4202
4203 auto RHSBegin = RHSAddr.getPointer();
4204 auto LHSBegin = LHSAddr.getPointer();
4205 // Cast from pointer to array type to pointer to single element.
4206 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
4207 // The basic structure here is a while-do loop.
4208 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
4209 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
4210 auto IsEmpty =
4211 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
4212 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
4213
4214 // Enter the loop body, making that address the current address.
4215 auto EntryBB = CGF.Builder.GetInsertBlock();
4216 CGF.EmitBlock(BodyBB);
4217
4218 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
4219
4220 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
4221 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
4222 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
4223 Address RHSElementCurrent =
4224 Address(RHSElementPHI,
4225 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4226
4227 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
4228 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
4229 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
4230 Address LHSElementCurrent =
4231 Address(LHSElementPHI,
4232 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4233
4234 // Emit copy.
4235 CodeGenFunction::OMPPrivateScope Scope(CGF);
4236 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
4237 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
4238 Scope.Privatize();
4239 RedOpGen(CGF, XExpr, EExpr, UpExpr);
4240 Scope.ForceCleanup();
4241
4242 // Shift the address forward by one element.
4243 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
4244 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
4245 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
4246 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
4247 // Check whether we've reached the end.
4248 auto Done =
4249 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
4250 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
4251 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
4252 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
4253
4254 // Done.
4255 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
4256}
4257
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004258/// Emit reduction combiner. If the combiner is a simple expression emit it as
4259/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
4260/// UDR combiner function.
4261static void emitReductionCombiner(CodeGenFunction &CGF,
4262 const Expr *ReductionOp) {
4263 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
4264 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
4265 if (auto *DRE =
4266 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
4267 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
4268 std::pair<llvm::Function *, llvm::Function *> Reduction =
4269 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
4270 RValue Func = RValue::get(Reduction.first);
4271 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
4272 CGF.EmitIgnoredExpr(ReductionOp);
4273 return;
4274 }
4275 CGF.EmitIgnoredExpr(ReductionOp);
4276}
4277
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004278llvm::Value *CGOpenMPRuntime::emitReductionFunction(
4279 CodeGenModule &CGM, llvm::Type *ArgsType, ArrayRef<const Expr *> Privates,
4280 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4281 ArrayRef<const Expr *> ReductionOps) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004282 auto &C = CGM.getContext();
4283
4284 // void reduction_func(void *LHSArg, void *RHSArg);
4285 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004286 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
4287 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004288 Args.push_back(&LHSArg);
4289 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00004290 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004291 auto *Fn = llvm::Function::Create(
4292 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
4293 ".omp.reduction.reduction_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004294 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004295 CodeGenFunction CGF(CGM);
4296 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
4297
4298 // Dst = (void*[n])(LHSArg);
4299 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00004300 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4301 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
4302 ArgsType), CGF.getPointerAlign());
4303 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4304 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
4305 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004306
4307 // ...
4308 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
4309 // ...
4310 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004311 auto IPriv = Privates.begin();
4312 unsigned Idx = 0;
4313 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004314 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
4315 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004316 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004317 });
4318 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
4319 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004320 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004321 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004322 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004323 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004324 // Get array size and emit VLA type.
4325 ++Idx;
4326 Address Elem =
4327 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
4328 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004329 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
4330 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004331 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00004332 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004333 CGF.EmitVariablyModifiedType(PrivTy);
4334 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004335 }
4336 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004337 IPriv = Privates.begin();
4338 auto ILHS = LHSExprs.begin();
4339 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004340 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004341 if ((*IPriv)->getType()->isArrayType()) {
4342 // Emit reduction for array section.
4343 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4344 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004345 EmitOMPAggregateReduction(
4346 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4347 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4348 emitReductionCombiner(CGF, E);
4349 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004350 } else
4351 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004352 emitReductionCombiner(CGF, E);
Richard Trieucc3949d2016-02-18 22:34:54 +00004353 ++IPriv;
4354 ++ILHS;
4355 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004356 }
4357 Scope.ForceCleanup();
4358 CGF.FinishFunction();
4359 return Fn;
4360}
4361
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004362void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
4363 const Expr *ReductionOp,
4364 const Expr *PrivateRef,
4365 const DeclRefExpr *LHS,
4366 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004367 if (PrivateRef->getType()->isArrayType()) {
4368 // Emit reduction for array section.
4369 auto *LHSVar = cast<VarDecl>(LHS->getDecl());
4370 auto *RHSVar = cast<VarDecl>(RHS->getDecl());
4371 EmitOMPAggregateReduction(
4372 CGF, PrivateRef->getType(), LHSVar, RHSVar,
4373 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4374 emitReductionCombiner(CGF, ReductionOp);
4375 });
4376 } else
4377 // Emit reduction for array subscript or single variable.
4378 emitReductionCombiner(CGF, ReductionOp);
4379}
4380
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004381void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004382 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004383 ArrayRef<const Expr *> LHSExprs,
4384 ArrayRef<const Expr *> RHSExprs,
4385 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004386 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004387 if (!CGF.HaveInsertPoint())
4388 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004389
4390 bool WithNowait = Options.WithNowait;
4391 bool SimpleReduction = Options.SimpleReduction;
4392
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004393 // Next code should be emitted for reduction:
4394 //
4395 // static kmp_critical_name lock = { 0 };
4396 //
4397 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
4398 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
4399 // ...
4400 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
4401 // *(Type<n>-1*)rhs[<n>-1]);
4402 // }
4403 //
4404 // ...
4405 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
4406 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4407 // RedList, reduce_func, &<lock>)) {
4408 // case 1:
4409 // ...
4410 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4411 // ...
4412 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4413 // break;
4414 // case 2:
4415 // ...
4416 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4417 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00004418 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004419 // break;
4420 // default:;
4421 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004422 //
4423 // if SimpleReduction is true, only the next code is generated:
4424 // ...
4425 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4426 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004427
4428 auto &C = CGM.getContext();
4429
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004430 if (SimpleReduction) {
4431 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004432 auto IPriv = Privates.begin();
4433 auto ILHS = LHSExprs.begin();
4434 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004435 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004436 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4437 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00004438 ++IPriv;
4439 ++ILHS;
4440 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004441 }
4442 return;
4443 }
4444
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004445 // 1. Build a list of reduction variables.
4446 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004447 auto Size = RHSExprs.size();
4448 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00004449 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004450 // Reserve place for array size.
4451 ++Size;
4452 }
4453 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004454 QualType ReductionArrayTy =
4455 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4456 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00004457 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004458 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004459 auto IPriv = Privates.begin();
4460 unsigned Idx = 0;
4461 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004462 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004463 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00004464 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004465 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004466 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4467 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004468 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004469 // Store array size.
4470 ++Idx;
4471 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
4472 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00004473 llvm::Value *Size = CGF.Builder.CreateIntCast(
4474 CGF.getVLASize(
4475 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4476 .first,
4477 CGF.SizeTy, /*isSigned=*/false);
4478 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4479 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004480 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004481 }
4482
4483 // 2. Emit reduce_func().
4484 auto *ReductionFn = emitReductionFunction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004485 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
4486 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004487
4488 // 3. Create static kmp_critical_name lock = { 0 };
4489 auto *Lock = getCriticalRegionLock(".reduction");
4490
4491 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4492 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00004493 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004494 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004495 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
Samuel Antao4c8035b2016-12-12 18:00:20 +00004496 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4497 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004498 llvm::Value *Args[] = {
4499 IdentTLoc, // ident_t *<loc>
4500 ThreadId, // i32 <gtid>
4501 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
4502 ReductionArrayTySize, // size_type sizeof(RedList)
4503 RL, // void *RedList
4504 ReductionFn, // void (*) (void *, void *) <reduce_func>
4505 Lock // kmp_critical_name *&<lock>
4506 };
4507 auto Res = CGF.EmitRuntimeCall(
4508 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
4509 : OMPRTL__kmpc_reduce),
4510 Args);
4511
4512 // 5. Build switch(res)
4513 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
4514 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
4515
4516 // 6. Build case 1:
4517 // ...
4518 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4519 // ...
4520 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4521 // break;
4522 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
4523 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
4524 CGF.EmitBlock(Case1BB);
4525
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004526 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4527 llvm::Value *EndArgs[] = {
4528 IdentTLoc, // ident_t *<loc>
4529 ThreadId, // i32 <gtid>
4530 Lock // kmp_critical_name *&<lock>
4531 };
4532 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
4533 CodeGenFunction &CGF, PrePostActionTy &Action) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004534 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004535 auto IPriv = Privates.begin();
4536 auto ILHS = LHSExprs.begin();
4537 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004538 for (auto *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004539 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4540 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00004541 ++IPriv;
4542 ++ILHS;
4543 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004544 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004545 };
4546 RegionCodeGenTy RCG(CodeGen);
4547 CommonActionTy Action(
4548 nullptr, llvm::None,
4549 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
4550 : OMPRTL__kmpc_end_reduce),
4551 EndArgs);
4552 RCG.setAction(Action);
4553 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004554
4555 CGF.EmitBranch(DefaultBB);
4556
4557 // 7. Build case 2:
4558 // ...
4559 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4560 // ...
4561 // break;
4562 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
4563 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
4564 CGF.EmitBlock(Case2BB);
4565
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004566 auto &&AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs, &ReductionOps](
4567 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004568 auto ILHS = LHSExprs.begin();
4569 auto IRHS = RHSExprs.begin();
4570 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004571 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004572 const Expr *XExpr = nullptr;
4573 const Expr *EExpr = nullptr;
4574 const Expr *UpExpr = nullptr;
4575 BinaryOperatorKind BO = BO_Comma;
4576 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
4577 if (BO->getOpcode() == BO_Assign) {
4578 XExpr = BO->getLHS();
4579 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004580 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004581 }
4582 // Try to emit update expression as a simple atomic.
4583 auto *RHSExpr = UpExpr;
4584 if (RHSExpr) {
4585 // Analyze RHS part of the whole expression.
4586 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
4587 RHSExpr->IgnoreParenImpCasts())) {
4588 // If this is a conditional operator, analyze its condition for
4589 // min/max reduction operator.
4590 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00004591 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004592 if (auto *BORHS =
4593 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
4594 EExpr = BORHS->getRHS();
4595 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004596 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004597 }
4598 if (XExpr) {
4599 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00004600 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004601 Loc](CodeGenFunction &CGF, const Expr *XExpr,
4602 const Expr *EExpr, const Expr *UpExpr) {
4603 LValue X = CGF.EmitLValue(XExpr);
4604 RValue E;
4605 if (EExpr)
4606 E = CGF.EmitAnyExpr(EExpr);
4607 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00004608 X, E, BO, /*IsXLHSInRHSPart=*/true,
4609 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00004610 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004611 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4612 PrivateScope.addPrivate(
4613 VD, [&CGF, VD, XRValue, Loc]() -> Address {
4614 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
4615 CGF.emitOMPSimpleStore(
4616 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
4617 VD->getType().getNonReferenceType(), Loc);
4618 return LHSTemp;
4619 });
4620 (void)PrivateScope.Privatize();
4621 return CGF.EmitAnyExpr(UpExpr);
4622 });
4623 };
4624 if ((*IPriv)->getType()->isArrayType()) {
4625 // Emit atomic reduction for array section.
4626 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
4627 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
4628 AtomicRedGen, XExpr, EExpr, UpExpr);
4629 } else
4630 // Emit atomic reduction for array subscript or single variable.
4631 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
4632 } else {
4633 // Emit as a critical region.
4634 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
4635 const Expr *, const Expr *) {
4636 auto &RT = CGF.CGM.getOpenMPRuntime();
4637 RT.emitCriticalRegion(
4638 CGF, ".atomic_reduction",
4639 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
4640 Action.Enter(CGF);
4641 emitReductionCombiner(CGF, E);
4642 },
4643 Loc);
4644 };
4645 if ((*IPriv)->getType()->isArrayType()) {
4646 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4647 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
4648 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4649 CritRedGen);
4650 } else
4651 CritRedGen(CGF, nullptr, nullptr, nullptr);
4652 }
Richard Trieucc3949d2016-02-18 22:34:54 +00004653 ++ILHS;
4654 ++IRHS;
4655 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004656 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004657 };
4658 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
4659 if (!WithNowait) {
4660 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
4661 llvm::Value *EndArgs[] = {
4662 IdentTLoc, // ident_t *<loc>
4663 ThreadId, // i32 <gtid>
4664 Lock // kmp_critical_name *&<lock>
4665 };
4666 CommonActionTy Action(nullptr, llvm::None,
4667 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
4668 EndArgs);
4669 AtomicRCG.setAction(Action);
4670 AtomicRCG(CGF);
4671 } else
4672 AtomicRCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004673
4674 CGF.EmitBranch(DefaultBB);
4675 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
4676}
4677
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004678void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
4679 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004680 if (!CGF.HaveInsertPoint())
4681 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004682 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
4683 // global_tid);
4684 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
4685 // Ignore return result until untied tasks are supported.
4686 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00004687 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4688 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004689}
4690
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00004691void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004692 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004693 const RegionCodeGenTy &CodeGen,
4694 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004695 if (!CGF.HaveInsertPoint())
4696 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004697 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00004698 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00004699}
4700
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004701namespace {
4702enum RTCancelKind {
4703 CancelNoreq = 0,
4704 CancelParallel = 1,
4705 CancelLoop = 2,
4706 CancelSections = 3,
4707 CancelTaskgroup = 4
4708};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00004709} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004710
4711static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
4712 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00004713 if (CancelRegion == OMPD_parallel)
4714 CancelKind = CancelParallel;
4715 else if (CancelRegion == OMPD_for)
4716 CancelKind = CancelLoop;
4717 else if (CancelRegion == OMPD_sections)
4718 CancelKind = CancelSections;
4719 else {
4720 assert(CancelRegion == OMPD_taskgroup);
4721 CancelKind = CancelTaskgroup;
4722 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004723 return CancelKind;
4724}
4725
4726void CGOpenMPRuntime::emitCancellationPointCall(
4727 CodeGenFunction &CGF, SourceLocation Loc,
4728 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004729 if (!CGF.HaveInsertPoint())
4730 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004731 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
4732 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004733 if (auto *OMPRegionInfo =
4734 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00004735 // For 'cancellation point taskgroup', the task region info may not have a
4736 // cancel. This may instead happen in another adjacent task.
4737 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004738 llvm::Value *Args[] = {
4739 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
4740 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004741 // Ignore return result until untied tasks are supported.
4742 auto *Result = CGF.EmitRuntimeCall(
4743 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
4744 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004745 // exit from construct;
4746 // }
4747 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4748 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4749 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4750 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4751 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004752 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004753 auto CancelDest =
4754 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004755 CGF.EmitBranchThroughCleanup(CancelDest);
4756 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4757 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00004758 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00004759}
4760
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004761void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00004762 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004763 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004764 if (!CGF.HaveInsertPoint())
4765 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004766 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
4767 // kmp_int32 cncl_kind);
4768 if (auto *OMPRegionInfo =
4769 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004770 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
4771 PrePostActionTy &) {
4772 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00004773 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004774 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00004775 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
4776 // Ignore return result until untied tasks are supported.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004777 auto *Result = CGF.EmitRuntimeCall(
4778 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00004779 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00004780 // exit from construct;
4781 // }
4782 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4783 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4784 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4785 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4786 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00004787 // exit from construct;
4788 auto CancelDest =
4789 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
4790 CGF.EmitBranchThroughCleanup(CancelDest);
4791 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4792 };
4793 if (IfCond)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004794 emitOMPIfClause(CGF, IfCond, ThenGen,
4795 [](CodeGenFunction &, PrePostActionTy &) {});
4796 else {
4797 RegionCodeGenTy ThenRCG(ThenGen);
4798 ThenRCG(CGF);
4799 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004800 }
4801}
Samuel Antaobed3c462015-10-02 16:14:20 +00004802
Samuel Antaoee8fb302016-01-06 13:42:12 +00004803/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00004804/// consists of the file and device IDs as well as line number associated with
4805/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004806static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
4807 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004808 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004809
4810 auto &SM = C.getSourceManager();
4811
4812 // The loc should be always valid and have a file ID (the user cannot use
4813 // #pragma directives in macros)
4814
4815 assert(Loc.isValid() && "Source location is expected to be always valid.");
4816 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
4817
4818 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
4819 assert(PLoc.isValid() && "Source location is expected to be always valid.");
4820
4821 llvm::sys::fs::UniqueID ID;
4822 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
4823 llvm_unreachable("Source file with target region no longer exists!");
4824
4825 DeviceID = ID.getDevice();
4826 FileID = ID.getFile();
4827 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004828}
4829
4830void CGOpenMPRuntime::emitTargetOutlinedFunction(
4831 const OMPExecutableDirective &D, StringRef ParentName,
4832 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004833 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004834 assert(!ParentName.empty() && "Invalid target region parent name!");
4835
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00004836 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
4837 IsOffloadEntry, CodeGen);
4838}
4839
4840void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
4841 const OMPExecutableDirective &D, StringRef ParentName,
4842 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
4843 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00004844 // Create a unique name for the entry function using the source location
4845 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00004846 //
Samuel Antao2de62b02016-02-13 23:35:10 +00004847 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00004848 //
4849 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00004850 // mangled name of the function that encloses the target region and BB is the
4851 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004852
4853 unsigned DeviceID;
4854 unsigned FileID;
4855 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004856 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004857 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004858 SmallString<64> EntryFnName;
4859 {
4860 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00004861 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
4862 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004863 }
4864
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00004865 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4866
Samuel Antaobed3c462015-10-02 16:14:20 +00004867 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004868 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00004869 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004870
Samuel Antao6d004262016-06-16 18:39:34 +00004871 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004872
4873 // If this target outline function is not an offload entry, we don't need to
4874 // register it.
4875 if (!IsOffloadEntry)
4876 return;
4877
4878 // The target region ID is used by the runtime library to identify the current
4879 // target region, so it only has to be unique and not necessarily point to
4880 // anything. It could be the pointer to the outlined function that implements
4881 // the target region, but we aren't using that so that the compiler doesn't
4882 // need to keep that, and could therefore inline the host function if proven
4883 // worthwhile during optimization. In the other hand, if emitting code for the
4884 // device, the ID has to be the function address so that it can retrieved from
4885 // the offloading entry and launched by the runtime library. We also mark the
4886 // outlined function to have external linkage in case we are emitting code for
4887 // the device, because these functions will be entry points to the device.
4888
4889 if (CGM.getLangOpts().OpenMPIsDevice) {
4890 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
4891 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
4892 } else
4893 OutlinedFnID = new llvm::GlobalVariable(
4894 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
4895 llvm::GlobalValue::PrivateLinkage,
4896 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
4897
4898 // Register the information for the entry associated with this target region.
4899 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00004900 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
4901 /*Flags=*/0);
Samuel Antaobed3c462015-10-02 16:14:20 +00004902}
4903
Carlo Bertolli6eee9062016-04-29 01:37:30 +00004904/// discard all CompoundStmts intervening between two constructs
4905static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
4906 while (auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
4907 Body = CS->body_front();
4908
4909 return Body;
4910}
4911
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00004912/// Emit the number of teams for a target directive. Inspect the num_teams
4913/// clause associated with a teams construct combined or closely nested
4914/// with the target directive.
4915///
4916/// Emit a team of size one for directives such as 'target parallel' that
4917/// have no associated teams construct.
4918///
4919/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00004920static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00004921emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4922 CodeGenFunction &CGF,
4923 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00004924
4925 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4926 "teams directive expected to be "
4927 "emitted only for the host!");
4928
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004929 auto &Bld = CGF.Builder;
4930
4931 // If the target directive is combined with a teams directive:
4932 // Return the value in the num_teams clause, if any.
4933 // Otherwise, return 0 to denote the runtime default.
4934 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
4935 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
4936 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
4937 auto NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
4938 /*IgnoreResultAssign*/ true);
4939 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
4940 /*IsSigned=*/true);
4941 }
4942
4943 // The default value is 0.
4944 return Bld.getInt32(0);
4945 }
4946
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00004947 // If the target directive is combined with a parallel directive but not a
4948 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004949 if (isOpenMPParallelDirective(D.getDirectiveKind()))
4950 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00004951
4952 // If the current target region has a teams region enclosed, we need to get
4953 // the number of teams to pass to the runtime function call. This is done
4954 // by generating the expression in a inlined region. This is required because
4955 // the expression is captured in the enclosing target environment when the
4956 // teams directive is not combined with target.
4957
4958 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4959
4960 // FIXME: Accommodate other combined directives with teams when they become
4961 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00004962 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
4963 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00004964 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
4965 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4966 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4967 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004968 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
4969 /*IsSigned=*/true);
Samuel Antaob68e2db2016-03-03 16:20:23 +00004970 }
4971
4972 // If we have an enclosed teams directive but no num_teams clause we use
4973 // the default value 0.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004974 return Bld.getInt32(0);
Samuel Antaob68e2db2016-03-03 16:20:23 +00004975 }
4976
4977 // No teams associated with the directive.
4978 return nullptr;
4979}
4980
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00004981/// Emit the number of threads for a target directive. Inspect the
4982/// thread_limit clause associated with a teams construct combined or closely
4983/// nested with the target directive.
4984///
4985/// Emit the num_threads clause for directives such as 'target parallel' that
4986/// have no associated teams construct.
4987///
4988/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00004989static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00004990emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4991 CodeGenFunction &CGF,
4992 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00004993
4994 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4995 "teams directive expected to be "
4996 "emitted only for the host!");
4997
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00004998 auto &Bld = CGF.Builder;
4999
5000 //
5001 // If the target directive is combined with a teams directive:
5002 // Return the value in the thread_limit clause, if any.
5003 //
5004 // If the target directive is combined with a parallel directive:
5005 // Return the value in the num_threads clause, if any.
5006 //
5007 // If both clauses are set, select the minimum of the two.
5008 //
5009 // If neither teams or parallel combined directives set the number of threads
5010 // in a team, return 0 to denote the runtime default.
5011 //
5012 // If this is not a teams directive return nullptr.
5013
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005014 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
5015 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005016 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
5017 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005018 llvm::Value *ThreadLimitVal = nullptr;
5019
5020 if (const auto *ThreadLimitClause =
5021 D.getSingleClause<OMPThreadLimitClause>()) {
5022 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
5023 auto ThreadLimit = CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
5024 /*IgnoreResultAssign*/ true);
5025 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5026 /*IsSigned=*/true);
5027 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005028
5029 if (const auto *NumThreadsClause =
5030 D.getSingleClause<OMPNumThreadsClause>()) {
5031 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
5032 llvm::Value *NumThreads =
5033 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
5034 /*IgnoreResultAssign*/ true);
5035 NumThreadsVal =
5036 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
5037 }
5038
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005039 // Select the lesser of thread_limit and num_threads.
5040 if (NumThreadsVal)
5041 ThreadLimitVal = ThreadLimitVal
5042 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
5043 ThreadLimitVal),
5044 NumThreadsVal, ThreadLimitVal)
5045 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00005046
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005047 // Set default value passed to the runtime if either teams or a target
5048 // parallel type directive is found but no clause is specified.
5049 if (!ThreadLimitVal)
5050 ThreadLimitVal = DefaultThreadLimitVal;
5051
5052 return ThreadLimitVal;
5053 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00005054
Samuel Antaob68e2db2016-03-03 16:20:23 +00005055 // If the current target region has a teams region enclosed, we need to get
5056 // the thread limit to pass to the runtime function call. This is done
5057 // by generating the expression in a inlined region. This is required because
5058 // the expression is captured in the enclosing target environment when the
5059 // teams directive is not combined with target.
5060
5061 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5062
5063 // FIXME: Accommodate other combined directives with teams when they become
5064 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005065 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
5066 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005067 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
5068 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5069 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5070 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
5071 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5072 /*IsSigned=*/true);
5073 }
5074
5075 // If we have an enclosed teams directive but no thread_limit clause we use
5076 // the default value 0.
5077 return CGF.Builder.getInt32(0);
5078 }
5079
5080 // No teams associated with the directive.
5081 return nullptr;
5082}
5083
Samuel Antao86ace552016-04-27 22:40:57 +00005084namespace {
5085// \brief Utility to handle information from clauses associated with a given
5086// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
5087// It provides a convenient interface to obtain the information and generate
5088// code for that information.
5089class MappableExprsHandler {
5090public:
5091 /// \brief Values for bit flags used to specify the mapping type for
5092 /// offloading.
5093 enum OpenMPOffloadMappingFlags {
Samuel Antao86ace552016-04-27 22:40:57 +00005094 /// \brief Allocate memory on the device and move data from host to device.
5095 OMP_MAP_TO = 0x01,
5096 /// \brief Allocate memory on the device and move data from device to host.
5097 OMP_MAP_FROM = 0x02,
5098 /// \brief Always perform the requested mapping action on the element, even
5099 /// if it was already mapped before.
5100 OMP_MAP_ALWAYS = 0x04,
Samuel Antao86ace552016-04-27 22:40:57 +00005101 /// \brief Delete the element from the device environment, ignoring the
5102 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00005103 OMP_MAP_DELETE = 0x08,
5104 /// \brief The element being mapped is a pointer, therefore the pointee
5105 /// should be mapped as well.
5106 OMP_MAP_IS_PTR = 0x10,
5107 /// \brief This flags signals that an argument is the first one relating to
5108 /// a map/private clause expression. For some cases a single
5109 /// map/privatization results in multiple arguments passed to the runtime
5110 /// library.
5111 OMP_MAP_FIRST_REF = 0x20,
Samuel Antaocc10b852016-07-28 14:23:26 +00005112 /// \brief Signal that the runtime library has to return the device pointer
5113 /// in the current position for the data being mapped.
5114 OMP_MAP_RETURN_PTR = 0x40,
Samuel Antaod486f842016-05-26 16:53:38 +00005115 /// \brief This flag signals that the reference being passed is a pointer to
5116 /// private data.
5117 OMP_MAP_PRIVATE_PTR = 0x80,
Samuel Antao86ace552016-04-27 22:40:57 +00005118 /// \brief Pass the element to the device by value.
Samuel Antao6782e942016-05-26 16:48:10 +00005119 OMP_MAP_PRIVATE_VAL = 0x100,
Samuel Antao86ace552016-04-27 22:40:57 +00005120 };
5121
Samuel Antaocc10b852016-07-28 14:23:26 +00005122 /// Class that associates information with a base pointer to be passed to the
5123 /// runtime library.
5124 class BasePointerInfo {
5125 /// The base pointer.
5126 llvm::Value *Ptr = nullptr;
5127 /// The base declaration that refers to this device pointer, or null if
5128 /// there is none.
5129 const ValueDecl *DevPtrDecl = nullptr;
5130
5131 public:
5132 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
5133 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
5134 llvm::Value *operator*() const { return Ptr; }
5135 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
5136 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
5137 };
5138
5139 typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00005140 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
5141 typedef SmallVector<unsigned, 16> MapFlagsArrayTy;
5142
5143private:
5144 /// \brief Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00005145 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00005146
5147 /// \brief Function the directive is being generated for.
5148 CodeGenFunction &CGF;
5149
Samuel Antaod486f842016-05-26 16:53:38 +00005150 /// \brief Set of all first private variables in the current directive.
5151 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
5152
Samuel Antao6890b092016-07-28 14:25:09 +00005153 /// Map between device pointer declarations and their expression components.
5154 /// The key value for declarations in 'this' is null.
5155 llvm::DenseMap<
5156 const ValueDecl *,
5157 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
5158 DevPointersMap;
5159
Samuel Antao86ace552016-04-27 22:40:57 +00005160 llvm::Value *getExprTypeSize(const Expr *E) const {
5161 auto ExprTy = E->getType().getCanonicalType();
5162
5163 // Reference types are ignored for mapping purposes.
5164 if (auto *RefTy = ExprTy->getAs<ReferenceType>())
5165 ExprTy = RefTy->getPointeeType().getCanonicalType();
5166
5167 // Given that an array section is considered a built-in type, we need to
5168 // do the calculation based on the length of the section instead of relying
5169 // on CGF.getTypeSize(E->getType()).
5170 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
5171 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
5172 OAE->getBase()->IgnoreParenImpCasts())
5173 .getCanonicalType();
5174
5175 // If there is no length associated with the expression, that means we
5176 // are using the whole length of the base.
5177 if (!OAE->getLength() && OAE->getColonLoc().isValid())
5178 return CGF.getTypeSize(BaseTy);
5179
5180 llvm::Value *ElemSize;
5181 if (auto *PTy = BaseTy->getAs<PointerType>())
5182 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
5183 else {
5184 auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
5185 assert(ATy && "Expecting array type if not a pointer type.");
5186 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
5187 }
5188
5189 // If we don't have a length at this point, that is because we have an
5190 // array section with a single element.
5191 if (!OAE->getLength())
5192 return ElemSize;
5193
5194 auto *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
5195 LengthVal =
5196 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
5197 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
5198 }
5199 return CGF.getTypeSize(ExprTy);
5200 }
5201
5202 /// \brief Return the corresponding bits for a given map clause modifier. Add
5203 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00005204 /// map as the first one of a series of maps that relate to the same map
5205 /// expression.
Samuel Antao86ace552016-04-27 22:40:57 +00005206 unsigned getMapTypeBits(OpenMPMapClauseKind MapType,
5207 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
Samuel Antao6782e942016-05-26 16:48:10 +00005208 bool AddIsFirstFlag) const {
Samuel Antao86ace552016-04-27 22:40:57 +00005209 unsigned Bits = 0u;
5210 switch (MapType) {
5211 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00005212 case OMPC_MAP_release:
5213 // alloc and release is the default behavior in the runtime library, i.e.
5214 // if we don't pass any bits alloc/release that is what the runtime is
5215 // going to do. Therefore, we don't need to signal anything for these two
5216 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00005217 break;
5218 case OMPC_MAP_to:
5219 Bits = OMP_MAP_TO;
5220 break;
5221 case OMPC_MAP_from:
5222 Bits = OMP_MAP_FROM;
5223 break;
5224 case OMPC_MAP_tofrom:
5225 Bits = OMP_MAP_TO | OMP_MAP_FROM;
5226 break;
5227 case OMPC_MAP_delete:
5228 Bits = OMP_MAP_DELETE;
5229 break;
Samuel Antao86ace552016-04-27 22:40:57 +00005230 default:
5231 llvm_unreachable("Unexpected map type!");
5232 break;
5233 }
5234 if (AddPtrFlag)
Samuel Antao6782e942016-05-26 16:48:10 +00005235 Bits |= OMP_MAP_IS_PTR;
5236 if (AddIsFirstFlag)
5237 Bits |= OMP_MAP_FIRST_REF;
Samuel Antao86ace552016-04-27 22:40:57 +00005238 if (MapTypeModifier == OMPC_MAP_always)
5239 Bits |= OMP_MAP_ALWAYS;
5240 return Bits;
5241 }
5242
5243 /// \brief Return true if the provided expression is a final array section. A
5244 /// final array section, is one whose length can't be proved to be one.
5245 bool isFinalArraySectionExpression(const Expr *E) const {
5246 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
5247
5248 // It is not an array section and therefore not a unity-size one.
5249 if (!OASE)
5250 return false;
5251
5252 // An array section with no colon always refer to a single element.
5253 if (OASE->getColonLoc().isInvalid())
5254 return false;
5255
5256 auto *Length = OASE->getLength();
5257
5258 // If we don't have a length we have to check if the array has size 1
5259 // for this dimension. Also, we should always expect a length if the
5260 // base type is pointer.
5261 if (!Length) {
5262 auto BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
5263 OASE->getBase()->IgnoreParenImpCasts())
5264 .getCanonicalType();
5265 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
5266 return ATy->getSize().getSExtValue() != 1;
5267 // If we don't have a constant dimension length, we have to consider
5268 // the current section as having any size, so it is not necessarily
5269 // unitary. If it happen to be unity size, that's user fault.
5270 return true;
5271 }
5272
5273 // Check if the length evaluates to 1.
5274 llvm::APSInt ConstLength;
5275 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
5276 return true; // Can have more that size 1.
5277
5278 return ConstLength.getSExtValue() != 1;
5279 }
5280
5281 /// \brief Generate the base pointers, section pointers, sizes and map type
5282 /// bits for the provided map type, map modifier, and expression components.
5283 /// \a IsFirstComponent should be set to true if the provided set of
5284 /// components is the first associated with a capture.
5285 void generateInfoForComponentList(
5286 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
5287 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00005288 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00005289 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
5290 bool IsFirstComponentList) const {
5291
5292 // The following summarizes what has to be generated for each map and the
5293 // types bellow. The generated information is expressed in this order:
5294 // base pointer, section pointer, size, flags
5295 // (to add to the ones that come from the map type and modifier).
5296 //
5297 // double d;
5298 // int i[100];
5299 // float *p;
5300 //
5301 // struct S1 {
5302 // int i;
5303 // float f[50];
5304 // }
5305 // struct S2 {
5306 // int i;
5307 // float f[50];
5308 // S1 s;
5309 // double *p;
5310 // struct S2 *ps;
5311 // }
5312 // S2 s;
5313 // S2 *ps;
5314 //
5315 // map(d)
5316 // &d, &d, sizeof(double), noflags
5317 //
5318 // map(i)
5319 // &i, &i, 100*sizeof(int), noflags
5320 //
5321 // map(i[1:23])
5322 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
5323 //
5324 // map(p)
5325 // &p, &p, sizeof(float*), noflags
5326 //
5327 // map(p[1:24])
5328 // p, &p[1], 24*sizeof(float), noflags
5329 //
5330 // map(s)
5331 // &s, &s, sizeof(S2), noflags
5332 //
5333 // map(s.i)
5334 // &s, &(s.i), sizeof(int), noflags
5335 //
5336 // map(s.s.f)
5337 // &s, &(s.i.f), 50*sizeof(int), noflags
5338 //
5339 // map(s.p)
5340 // &s, &(s.p), sizeof(double*), noflags
5341 //
5342 // map(s.p[:22], s.a s.b)
5343 // &s, &(s.p), sizeof(double*), noflags
5344 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag + extra_flag
5345 //
5346 // map(s.ps)
5347 // &s, &(s.ps), sizeof(S2*), noflags
5348 //
5349 // map(s.ps->s.i)
5350 // &s, &(s.ps), sizeof(S2*), noflags
5351 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag + extra_flag
5352 //
5353 // map(s.ps->ps)
5354 // &s, &(s.ps), sizeof(S2*), noflags
5355 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5356 //
5357 // map(s.ps->ps->ps)
5358 // &s, &(s.ps), sizeof(S2*), noflags
5359 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5360 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5361 //
5362 // map(s.ps->ps->s.f[:22])
5363 // &s, &(s.ps), sizeof(S2*), noflags
5364 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5365 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag + extra_flag
5366 //
5367 // map(ps)
5368 // &ps, &ps, sizeof(S2*), noflags
5369 //
5370 // map(ps->i)
5371 // ps, &(ps->i), sizeof(int), noflags
5372 //
5373 // map(ps->s.f)
5374 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
5375 //
5376 // map(ps->p)
5377 // ps, &(ps->p), sizeof(double*), noflags
5378 //
5379 // map(ps->p[:22])
5380 // ps, &(ps->p), sizeof(double*), noflags
5381 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag + extra_flag
5382 //
5383 // map(ps->ps)
5384 // ps, &(ps->ps), sizeof(S2*), noflags
5385 //
5386 // map(ps->ps->s.i)
5387 // ps, &(ps->ps), sizeof(S2*), noflags
5388 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag + extra_flag
5389 //
5390 // map(ps->ps->ps)
5391 // ps, &(ps->ps), sizeof(S2*), noflags
5392 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5393 //
5394 // map(ps->ps->ps->ps)
5395 // ps, &(ps->ps), sizeof(S2*), noflags
5396 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5397 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5398 //
5399 // map(ps->ps->ps->s.f[:22])
5400 // ps, &(ps->ps), sizeof(S2*), noflags
5401 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5402 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag +
5403 // extra_flag
5404
5405 // Track if the map information being generated is the first for a capture.
5406 bool IsCaptureFirstInfo = IsFirstComponentList;
5407
5408 // Scan the components from the base to the complete expression.
5409 auto CI = Components.rbegin();
5410 auto CE = Components.rend();
5411 auto I = CI;
5412
5413 // Track if the map information being generated is the first for a list of
5414 // components.
5415 bool IsExpressionFirstInfo = true;
5416 llvm::Value *BP = nullptr;
5417
5418 if (auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
5419 // The base is the 'this' pointer. The content of the pointer is going
5420 // to be the base of the field being mapped.
5421 BP = CGF.EmitScalarExpr(ME->getBase());
5422 } else {
5423 // The base is the reference to the variable.
5424 // BP = &Var.
5425 BP = CGF.EmitLValue(cast<DeclRefExpr>(I->getAssociatedExpression()))
5426 .getPointer();
5427
5428 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00005429 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00005430 // reference. References are ignored for mapping purposes.
5431 QualType Ty =
5432 I->getAssociatedDeclaration()->getType().getNonReferenceType();
5433 if (Ty->isAnyPointerType() && std::next(I) != CE) {
5434 auto PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
Samuel Antao86ace552016-04-27 22:40:57 +00005435 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
Samuel Antao403ffd42016-07-27 22:49:49 +00005436 Ty->castAs<PointerType>())
Samuel Antao86ace552016-04-27 22:40:57 +00005437 .getPointer();
5438
5439 // We do not need to generate individual map information for the
5440 // pointer, it can be associated with the combined storage.
5441 ++I;
5442 }
5443 }
5444
5445 for (; I != CE; ++I) {
5446 auto Next = std::next(I);
5447
5448 // We need to generate the addresses and sizes if this is the last
5449 // component, if the component is a pointer or if it is an array section
5450 // whose length can't be proved to be one. If this is a pointer, it
5451 // becomes the base address for the following components.
5452
5453 // A final array section, is one whose length can't be proved to be one.
5454 bool IsFinalArraySection =
5455 isFinalArraySectionExpression(I->getAssociatedExpression());
5456
5457 // Get information on whether the element is a pointer. Have to do a
5458 // special treatment for array sections given that they are built-in
5459 // types.
5460 const auto *OASE =
5461 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
5462 bool IsPointer =
5463 (OASE &&
5464 OMPArraySectionExpr::getBaseOriginalType(OASE)
5465 .getCanonicalType()
5466 ->isAnyPointerType()) ||
5467 I->getAssociatedExpression()->getType()->isAnyPointerType();
5468
5469 if (Next == CE || IsPointer || IsFinalArraySection) {
5470
5471 // If this is not the last component, we expect the pointer to be
5472 // associated with an array expression or member expression.
5473 assert((Next == CE ||
5474 isa<MemberExpr>(Next->getAssociatedExpression()) ||
5475 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
5476 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
5477 "Unexpected expression");
5478
Samuel Antao86ace552016-04-27 22:40:57 +00005479 auto *LB = CGF.EmitLValue(I->getAssociatedExpression()).getPointer();
5480 auto *Size = getExprTypeSize(I->getAssociatedExpression());
5481
Samuel Antao03a3cec2016-07-27 22:52:16 +00005482 // If we have a member expression and the current component is a
5483 // reference, we have to map the reference too. Whenever we have a
5484 // reference, the section that reference refers to is going to be a
5485 // load instruction from the storage assigned to the reference.
5486 if (isa<MemberExpr>(I->getAssociatedExpression()) &&
5487 I->getAssociatedDeclaration()->getType()->isReferenceType()) {
5488 auto *LI = cast<llvm::LoadInst>(LB);
5489 auto *RefAddr = LI->getPointerOperand();
5490
5491 BasePointers.push_back(BP);
5492 Pointers.push_back(RefAddr);
5493 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
5494 Types.push_back(getMapTypeBits(
5495 /*MapType*/ OMPC_MAP_alloc, /*MapTypeModifier=*/OMPC_MAP_unknown,
5496 !IsExpressionFirstInfo, IsCaptureFirstInfo));
5497 IsExpressionFirstInfo = false;
5498 IsCaptureFirstInfo = false;
5499 // The reference will be the next base address.
5500 BP = RefAddr;
5501 }
5502
5503 BasePointers.push_back(BP);
Samuel Antao86ace552016-04-27 22:40:57 +00005504 Pointers.push_back(LB);
5505 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00005506
Samuel Antao6782e942016-05-26 16:48:10 +00005507 // We need to add a pointer flag for each map that comes from the
5508 // same expression except for the first one. We also need to signal
5509 // this map is the first one that relates with the current capture
5510 // (there is a set of entries for each capture).
Samuel Antao86ace552016-04-27 22:40:57 +00005511 Types.push_back(getMapTypeBits(MapType, MapTypeModifier,
5512 !IsExpressionFirstInfo,
Samuel Antao6782e942016-05-26 16:48:10 +00005513 IsCaptureFirstInfo));
Samuel Antao86ace552016-04-27 22:40:57 +00005514
5515 // If we have a final array section, we are done with this expression.
5516 if (IsFinalArraySection)
5517 break;
5518
5519 // The pointer becomes the base for the next element.
5520 if (Next != CE)
5521 BP = LB;
5522
5523 IsExpressionFirstInfo = false;
5524 IsCaptureFirstInfo = false;
5525 continue;
5526 }
5527 }
5528 }
5529
Samuel Antaod486f842016-05-26 16:53:38 +00005530 /// \brief Return the adjusted map modifiers if the declaration a capture
5531 /// refers to appears in a first-private clause. This is expected to be used
5532 /// only with directives that start with 'target'.
5533 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
5534 unsigned CurrentModifiers) {
5535 assert(Cap.capturesVariable() && "Expected capture by reference only!");
5536
5537 // A first private variable captured by reference will use only the
5538 // 'private ptr' and 'map to' flag. Return the right flags if the captured
5539 // declaration is known as first-private in this handler.
5540 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
5541 return MappableExprsHandler::OMP_MAP_PRIVATE_PTR |
5542 MappableExprsHandler::OMP_MAP_TO;
5543
5544 // We didn't modify anything.
5545 return CurrentModifiers;
5546 }
5547
Samuel Antao86ace552016-04-27 22:40:57 +00005548public:
5549 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
Samuel Antao44bcdb32016-07-28 15:31:29 +00005550 : CurDir(Dir), CGF(CGF) {
Samuel Antaod486f842016-05-26 16:53:38 +00005551 // Extract firstprivate clause information.
5552 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
5553 for (const auto *D : C->varlists())
5554 FirstPrivateDecls.insert(
5555 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
Samuel Antao6890b092016-07-28 14:25:09 +00005556 // Extract device pointer clause information.
5557 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
5558 for (auto L : C->component_lists())
5559 DevPointersMap[L.first].push_back(L.second);
Samuel Antaod486f842016-05-26 16:53:38 +00005560 }
Samuel Antao86ace552016-04-27 22:40:57 +00005561
5562 /// \brief Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00005563 /// types for the extracted mappable expressions. Also, for each item that
5564 /// relates with a device pointer, a pair of the relevant declaration and
5565 /// index where it occurs is appended to the device pointers info array.
5566 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00005567 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
5568 MapFlagsArrayTy &Types) const {
5569 BasePointers.clear();
5570 Pointers.clear();
5571 Sizes.clear();
5572 Types.clear();
5573
5574 struct MapInfo {
Samuel Antaocc10b852016-07-28 14:23:26 +00005575 /// Kind that defines how a device pointer has to be returned.
5576 enum ReturnPointerKind {
5577 // Don't have to return any pointer.
5578 RPK_None,
5579 // Pointer is the base of the declaration.
5580 RPK_Base,
5581 // Pointer is a member of the base declaration - 'this'
5582 RPK_Member,
5583 // Pointer is a reference and a member of the base declaration - 'this'
5584 RPK_MemberReference,
5585 };
Samuel Antao86ace552016-04-27 22:40:57 +00005586 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
Hans Wennborgbc1b58d2016-07-30 00:41:37 +00005587 OpenMPMapClauseKind MapType;
5588 OpenMPMapClauseKind MapTypeModifier;
5589 ReturnPointerKind ReturnDevicePointer;
5590
5591 MapInfo()
5592 : MapType(OMPC_MAP_unknown), MapTypeModifier(OMPC_MAP_unknown),
5593 ReturnDevicePointer(RPK_None) {}
Samuel Antaocc10b852016-07-28 14:23:26 +00005594 MapInfo(
5595 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
5596 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
5597 ReturnPointerKind ReturnDevicePointer)
5598 : Components(Components), MapType(MapType),
5599 MapTypeModifier(MapTypeModifier),
5600 ReturnDevicePointer(ReturnDevicePointer) {}
Samuel Antao86ace552016-04-27 22:40:57 +00005601 };
5602
5603 // We have to process the component lists that relate with the same
5604 // declaration in a single chunk so that we can generate the map flags
5605 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00005606 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00005607
5608 // Helper function to fill the information map for the different supported
5609 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00005610 auto &&InfoGen = [&Info](
5611 const ValueDecl *D,
5612 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
5613 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Samuel Antaocf3f83e2016-07-28 14:47:35 +00005614 MapInfo::ReturnPointerKind ReturnDevicePointer) {
Samuel Antaocc10b852016-07-28 14:23:26 +00005615 const ValueDecl *VD =
5616 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
5617 Info[VD].push_back({L, MapType, MapModifier, ReturnDevicePointer});
5618 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00005619
Paul Robinson78fb1322016-08-01 22:12:46 +00005620 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00005621 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005622 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00005623 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
5624 MapInfo::RPK_None);
Paul Robinson15c84002016-07-29 20:46:16 +00005625 for (auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005626 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00005627 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
5628 MapInfo::RPK_None);
Paul Robinson15c84002016-07-29 20:46:16 +00005629 for (auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005630 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00005631 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
5632 MapInfo::RPK_None);
Samuel Antao86ace552016-04-27 22:40:57 +00005633
Samuel Antaocc10b852016-07-28 14:23:26 +00005634 // Look at the use_device_ptr clause information and mark the existing map
5635 // entries as such. If there is no map information for an entry in the
5636 // use_device_ptr list, we create one with map type 'alloc' and zero size
5637 // section. It is the user fault if that was not mapped before.
Paul Robinson78fb1322016-08-01 22:12:46 +00005638 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00005639 for (auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
Samuel Antaocc10b852016-07-28 14:23:26 +00005640 for (auto L : C->component_lists()) {
5641 assert(!L.second.empty() && "Not expecting empty list of components!");
5642 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
5643 VD = cast<ValueDecl>(VD->getCanonicalDecl());
5644 auto *IE = L.second.back().getAssociatedExpression();
5645 // If the first component is a member expression, we have to look into
5646 // 'this', which maps to null in the map of map information. Otherwise
5647 // look directly for the information.
5648 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
5649
5650 // We potentially have map information for this declaration already.
5651 // Look for the first set of components that refer to it.
5652 if (It != Info.end()) {
5653 auto CI = std::find_if(
5654 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
5655 return MI.Components.back().getAssociatedDeclaration() == VD;
5656 });
5657 // If we found a map entry, signal that the pointer has to be returned
5658 // and move on to the next declaration.
5659 if (CI != It->second.end()) {
5660 CI->ReturnDevicePointer = isa<MemberExpr>(IE)
5661 ? (VD->getType()->isReferenceType()
5662 ? MapInfo::RPK_MemberReference
5663 : MapInfo::RPK_Member)
5664 : MapInfo::RPK_Base;
5665 continue;
5666 }
5667 }
5668
5669 // We didn't find any match in our map information - generate a zero
5670 // size array section.
Paul Robinson78fb1322016-08-01 22:12:46 +00005671 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Samuel Antaocc10b852016-07-28 14:23:26 +00005672 llvm::Value *Ptr =
Paul Robinson15c84002016-07-29 20:46:16 +00005673 this->CGF
5674 .EmitLoadOfLValue(this->CGF.EmitLValue(IE), SourceLocation())
Samuel Antaocc10b852016-07-28 14:23:26 +00005675 .getScalarVal();
5676 BasePointers.push_back({Ptr, VD});
5677 Pointers.push_back(Ptr);
Paul Robinson15c84002016-07-29 20:46:16 +00005678 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
Samuel Antaocc10b852016-07-28 14:23:26 +00005679 Types.push_back(OMP_MAP_RETURN_PTR | OMP_MAP_FIRST_REF);
5680 }
5681
Samuel Antao86ace552016-04-27 22:40:57 +00005682 for (auto &M : Info) {
5683 // We need to know when we generate information for the first component
5684 // associated with a capture, because the mapping flags depend on it.
5685 bool IsFirstComponentList = true;
5686 for (MapInfo &L : M.second) {
5687 assert(!L.Components.empty() &&
5688 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00005689
5690 // Remember the current base pointer index.
5691 unsigned CurrentBasePointersIdx = BasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00005692 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Paul Robinson15c84002016-07-29 20:46:16 +00005693 this->generateInfoForComponentList(L.MapType, L.MapTypeModifier,
5694 L.Components, BasePointers, Pointers,
5695 Sizes, Types, IsFirstComponentList);
Samuel Antaocc10b852016-07-28 14:23:26 +00005696
5697 // If this entry relates with a device pointer, set the relevant
5698 // declaration and add the 'return pointer' flag.
5699 if (IsFirstComponentList &&
5700 L.ReturnDevicePointer != MapInfo::RPK_None) {
5701 // If the pointer is not the base of the map, we need to skip the
5702 // base. If it is a reference in a member field, we also need to skip
5703 // the map of the reference.
5704 if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
5705 ++CurrentBasePointersIdx;
5706 if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
5707 ++CurrentBasePointersIdx;
5708 }
5709 assert(BasePointers.size() > CurrentBasePointersIdx &&
5710 "Unexpected number of mapped base pointers.");
5711
5712 auto *RelevantVD = L.Components.back().getAssociatedDeclaration();
5713 assert(RelevantVD &&
5714 "No relevant declaration related with device pointer??");
5715
5716 BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
5717 Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PTR;
5718 }
Samuel Antao86ace552016-04-27 22:40:57 +00005719 IsFirstComponentList = false;
5720 }
5721 }
5722 }
5723
5724 /// \brief Generate the base pointers, section pointers, sizes and map types
5725 /// associated to a given capture.
5726 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00005727 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00005728 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00005729 MapValuesArrayTy &Pointers,
5730 MapValuesArrayTy &Sizes,
5731 MapFlagsArrayTy &Types) const {
5732 assert(!Cap->capturesVariableArrayType() &&
5733 "Not expecting to generate map info for a variable array type!");
5734
5735 BasePointers.clear();
5736 Pointers.clear();
5737 Sizes.clear();
5738 Types.clear();
5739
Samuel Antao6890b092016-07-28 14:25:09 +00005740 // We need to know when we generating information for the first component
5741 // associated with a capture, because the mapping flags depend on it.
5742 bool IsFirstComponentList = true;
5743
Samuel Antao86ace552016-04-27 22:40:57 +00005744 const ValueDecl *VD =
5745 Cap->capturesThis()
5746 ? nullptr
5747 : cast<ValueDecl>(Cap->getCapturedVar()->getCanonicalDecl());
5748
Samuel Antao6890b092016-07-28 14:25:09 +00005749 // If this declaration appears in a is_device_ptr clause we just have to
5750 // pass the pointer by value. If it is a reference to a declaration, we just
5751 // pass its value, otherwise, if it is a member expression, we need to map
5752 // 'to' the field.
5753 if (!VD) {
5754 auto It = DevPointersMap.find(VD);
5755 if (It != DevPointersMap.end()) {
5756 for (auto L : It->second) {
5757 generateInfoForComponentList(
5758 /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
5759 BasePointers, Pointers, Sizes, Types, IsFirstComponentList);
5760 IsFirstComponentList = false;
5761 }
5762 return;
5763 }
5764 } else if (DevPointersMap.count(VD)) {
5765 BasePointers.push_back({Arg, VD});
5766 Pointers.push_back(Arg);
5767 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
5768 Types.push_back(OMP_MAP_PRIVATE_VAL | OMP_MAP_FIRST_REF);
5769 return;
5770 }
5771
Paul Robinson78fb1322016-08-01 22:12:46 +00005772 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00005773 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao86ace552016-04-27 22:40:57 +00005774 for (auto L : C->decl_component_lists(VD)) {
5775 assert(L.first == VD &&
5776 "We got information for the wrong declaration??");
5777 assert(!L.second.empty() &&
5778 "Not expecting declaration with no component lists.");
5779 generateInfoForComponentList(C->getMapType(), C->getMapTypeModifier(),
5780 L.second, BasePointers, Pointers, Sizes,
5781 Types, IsFirstComponentList);
5782 IsFirstComponentList = false;
5783 }
5784
5785 return;
5786 }
Samuel Antaod486f842016-05-26 16:53:38 +00005787
5788 /// \brief Generate the default map information for a given capture \a CI,
5789 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00005790 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
5791 const FieldDecl &RI, llvm::Value *CV,
5792 MapBaseValuesArrayTy &CurBasePointers,
5793 MapValuesArrayTy &CurPointers,
5794 MapValuesArrayTy &CurSizes,
5795 MapFlagsArrayTy &CurMapTypes) {
Samuel Antaod486f842016-05-26 16:53:38 +00005796
5797 // Do the default mapping.
5798 if (CI.capturesThis()) {
5799 CurBasePointers.push_back(CV);
5800 CurPointers.push_back(CV);
5801 const PointerType *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
5802 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
5803 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00005804 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00005805 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00005806 CurBasePointers.push_back(CV);
5807 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00005808 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00005809 // We have to signal to the runtime captures passed by value that are
5810 // not pointers.
Samuel Antaocc10b852016-07-28 14:23:26 +00005811 CurMapTypes.push_back(OMP_MAP_PRIVATE_VAL);
Samuel Antaod486f842016-05-26 16:53:38 +00005812 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
5813 } else {
5814 // Pointers are implicitly mapped with a zero size and no flags
5815 // (other than first map that is added for all implicit maps).
5816 CurMapTypes.push_back(0u);
Samuel Antaod486f842016-05-26 16:53:38 +00005817 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
5818 }
5819 } else {
5820 assert(CI.capturesVariable() && "Expected captured reference.");
5821 CurBasePointers.push_back(CV);
5822 CurPointers.push_back(CV);
5823
5824 const ReferenceType *PtrTy =
5825 cast<ReferenceType>(RI.getType().getTypePtr());
5826 QualType ElementType = PtrTy->getPointeeType();
5827 CurSizes.push_back(CGF.getTypeSize(ElementType));
5828 // The default map type for a scalar/complex type is 'to' because by
5829 // default the value doesn't have to be retrieved. For an aggregate
5830 // type, the default is 'tofrom'.
5831 CurMapTypes.push_back(ElementType->isAggregateType()
Samuel Antaocc10b852016-07-28 14:23:26 +00005832 ? (OMP_MAP_TO | OMP_MAP_FROM)
5833 : OMP_MAP_TO);
Samuel Antaod486f842016-05-26 16:53:38 +00005834
5835 // If we have a capture by reference we may need to add the private
5836 // pointer flag if the base declaration shows in some first-private
5837 // clause.
5838 CurMapTypes.back() =
5839 adjustMapModifiersForPrivateClauses(CI, CurMapTypes.back());
5840 }
5841 // Every default map produces a single argument, so, it is always the
5842 // first one.
Samuel Antaocc10b852016-07-28 14:23:26 +00005843 CurMapTypes.back() |= OMP_MAP_FIRST_REF;
Samuel Antaod486f842016-05-26 16:53:38 +00005844 }
Samuel Antao86ace552016-04-27 22:40:57 +00005845};
Samuel Antaodf158d52016-04-27 22:58:19 +00005846
5847enum OpenMPOffloadingReservedDeviceIDs {
5848 /// \brief Device ID if the device was not defined, runtime should get it
5849 /// from environment variables in the spec.
5850 OMP_DEVICEID_UNDEF = -1,
5851};
5852} // anonymous namespace
5853
5854/// \brief Emit the arrays used to pass the captures and map information to the
5855/// offloading runtime library. If there is no map or capture information,
5856/// return nullptr by reference.
5857static void
Samuel Antaocc10b852016-07-28 14:23:26 +00005858emitOffloadingArrays(CodeGenFunction &CGF,
5859 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00005860 MappableExprsHandler::MapValuesArrayTy &Pointers,
5861 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00005862 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
5863 CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00005864 auto &CGM = CGF.CGM;
5865 auto &Ctx = CGF.getContext();
5866
Samuel Antaocc10b852016-07-28 14:23:26 +00005867 // Reset the array information.
5868 Info.clearArrayInfo();
5869 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00005870
Samuel Antaocc10b852016-07-28 14:23:26 +00005871 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00005872 // Detect if we have any capture size requiring runtime evaluation of the
5873 // size so that a constant array could be eventually used.
5874 bool hasRuntimeEvaluationCaptureSize = false;
5875 for (auto *S : Sizes)
5876 if (!isa<llvm::Constant>(S)) {
5877 hasRuntimeEvaluationCaptureSize = true;
5878 break;
5879 }
5880
Samuel Antaocc10b852016-07-28 14:23:26 +00005881 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00005882 QualType PointerArrayType =
5883 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
5884 /*IndexTypeQuals=*/0);
5885
Samuel Antaocc10b852016-07-28 14:23:26 +00005886 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00005887 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00005888 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00005889 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
5890
5891 // If we don't have any VLA types or other types that require runtime
5892 // evaluation, we can use a constant array for the map sizes, otherwise we
5893 // need to fill up the arrays as we do for the pointers.
5894 if (hasRuntimeEvaluationCaptureSize) {
5895 QualType SizeArrayType = Ctx.getConstantArrayType(
5896 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
5897 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00005898 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00005899 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
5900 } else {
5901 // We expect all the sizes to be constant, so we collect them to create
5902 // a constant array.
5903 SmallVector<llvm::Constant *, 16> ConstSizes;
5904 for (auto S : Sizes)
5905 ConstSizes.push_back(cast<llvm::Constant>(S));
5906
5907 auto *SizesArrayInit = llvm::ConstantArray::get(
5908 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
5909 auto *SizesArrayGbl = new llvm::GlobalVariable(
5910 CGM.getModule(), SizesArrayInit->getType(),
5911 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
5912 SizesArrayInit, ".offload_sizes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00005913 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00005914 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00005915 }
5916
5917 // The map types are always constant so we don't need to generate code to
5918 // fill arrays. Instead, we create an array constant.
5919 llvm::Constant *MapTypesArrayInit =
5920 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
5921 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
5922 CGM.getModule(), MapTypesArrayInit->getType(),
5923 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
5924 MapTypesArrayInit, ".offload_maptypes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00005925 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00005926 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00005927
Samuel Antaocc10b852016-07-28 14:23:26 +00005928 for (unsigned i = 0; i < Info.NumberOfPtrs; ++i) {
5929 llvm::Value *BPVal = *BasePointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00005930 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005931 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5932 Info.BasePointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00005933 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5934 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00005935 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
5936 CGF.Builder.CreateStore(BPVal, BPAddr);
5937
Samuel Antaocc10b852016-07-28 14:23:26 +00005938 if (Info.requiresDevicePointerInfo())
5939 if (auto *DevVD = BasePointers[i].getDevicePtrDecl())
5940 Info.CaptureDeviceAddrMap.insert(std::make_pair(DevVD, BPAddr));
5941
Samuel Antaodf158d52016-04-27 22:58:19 +00005942 llvm::Value *PVal = Pointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00005943 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005944 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5945 Info.PointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00005946 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5947 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00005948 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
5949 CGF.Builder.CreateStore(PVal, PAddr);
5950
5951 if (hasRuntimeEvaluationCaptureSize) {
5952 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005953 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
5954 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005955 /*Idx0=*/0,
5956 /*Idx1=*/i);
5957 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
5958 CGF.Builder.CreateStore(
5959 CGF.Builder.CreateIntCast(Sizes[i], CGM.SizeTy, /*isSigned=*/true),
5960 SAddr);
5961 }
5962 }
5963 }
5964}
5965/// \brief Emit the arguments to be passed to the runtime library based on the
5966/// arrays of pointers, sizes and map types.
5967static void emitOffloadingArraysArgument(
5968 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
5969 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00005970 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00005971 auto &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00005972 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00005973 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005974 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5975 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005976 /*Idx0=*/0, /*Idx1=*/0);
5977 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005978 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5979 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005980 /*Idx0=*/0,
5981 /*Idx1=*/0);
5982 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005983 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005984 /*Idx0=*/0, /*Idx1=*/0);
5985 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005986 llvm::ArrayType::get(CGM.Int32Ty, Info.NumberOfPtrs),
5987 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005988 /*Idx0=*/0,
5989 /*Idx1=*/0);
5990 } else {
5991 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
5992 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
5993 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
5994 MapTypesArrayArg =
5995 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo());
5996 }
Samuel Antao86ace552016-04-27 22:40:57 +00005997}
5998
Samuel Antaobed3c462015-10-02 16:14:20 +00005999void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
6000 const OMPExecutableDirective &D,
6001 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00006002 llvm::Value *OutlinedFnID,
Samuel Antaobed3c462015-10-02 16:14:20 +00006003 const Expr *IfCond, const Expr *Device,
6004 ArrayRef<llvm::Value *> CapturedVars) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006005 if (!CGF.HaveInsertPoint())
6006 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00006007
Samuel Antaoee8fb302016-01-06 13:42:12 +00006008 assert(OutlinedFn && "Invalid outlined function!");
6009
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006010 auto &Ctx = CGF.getContext();
6011
Samuel Antao86ace552016-04-27 22:40:57 +00006012 // Fill up the arrays with all the captured variables.
6013 MappableExprsHandler::MapValuesArrayTy KernelArgs;
Samuel Antaocc10b852016-07-28 14:23:26 +00006014 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00006015 MappableExprsHandler::MapValuesArrayTy Pointers;
6016 MappableExprsHandler::MapValuesArrayTy Sizes;
6017 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobed3c462015-10-02 16:14:20 +00006018
Samuel Antaocc10b852016-07-28 14:23:26 +00006019 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00006020 MappableExprsHandler::MapValuesArrayTy CurPointers;
6021 MappableExprsHandler::MapValuesArrayTy CurSizes;
6022 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
6023
Samuel Antaod486f842016-05-26 16:53:38 +00006024 // Get mappable expression information.
6025 MappableExprsHandler MEHandler(D, CGF);
Samuel Antaobed3c462015-10-02 16:14:20 +00006026
6027 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
6028 auto RI = CS.getCapturedRecordDecl()->field_begin();
Samuel Antaobed3c462015-10-02 16:14:20 +00006029 auto CV = CapturedVars.begin();
6030 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
6031 CE = CS.capture_end();
6032 CI != CE; ++CI, ++RI, ++CV) {
6033 StringRef Name;
6034 QualType Ty;
Samuel Antaobed3c462015-10-02 16:14:20 +00006035
Samuel Antao86ace552016-04-27 22:40:57 +00006036 CurBasePointers.clear();
6037 CurPointers.clear();
6038 CurSizes.clear();
6039 CurMapTypes.clear();
6040
6041 // VLA sizes are passed to the outlined region by copy and do not have map
6042 // information associated.
Samuel Antaobed3c462015-10-02 16:14:20 +00006043 if (CI->capturesVariableArrayType()) {
Samuel Antao86ace552016-04-27 22:40:57 +00006044 CurBasePointers.push_back(*CV);
6045 CurPointers.push_back(*CV);
6046 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006047 // Copy to the device as an argument. No need to retrieve it.
Samuel Antao6782e942016-05-26 16:48:10 +00006048 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_PRIVATE_VAL |
6049 MappableExprsHandler::OMP_MAP_FIRST_REF);
Samuel Antaobed3c462015-10-02 16:14:20 +00006050 } else {
Samuel Antao86ace552016-04-27 22:40:57 +00006051 // If we have any information in the map clause, we use it, otherwise we
6052 // just do a default mapping.
Samuel Antao6890b092016-07-28 14:25:09 +00006053 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006054 CurSizes, CurMapTypes);
Samuel Antaod486f842016-05-26 16:53:38 +00006055 if (CurBasePointers.empty())
6056 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
6057 CurPointers, CurSizes, CurMapTypes);
Samuel Antaobed3c462015-10-02 16:14:20 +00006058 }
Samuel Antao86ace552016-04-27 22:40:57 +00006059 // We expect to have at least an element of information for this capture.
6060 assert(!CurBasePointers.empty() && "Non-existing map pointer for capture!");
6061 assert(CurBasePointers.size() == CurPointers.size() &&
6062 CurBasePointers.size() == CurSizes.size() &&
6063 CurBasePointers.size() == CurMapTypes.size() &&
6064 "Inconsistent map information sizes!");
Samuel Antaobed3c462015-10-02 16:14:20 +00006065
Samuel Antao86ace552016-04-27 22:40:57 +00006066 // The kernel args are always the first elements of the base pointers
6067 // associated with a capture.
Samuel Antaocc10b852016-07-28 14:23:26 +00006068 KernelArgs.push_back(*CurBasePointers.front());
Samuel Antao86ace552016-04-27 22:40:57 +00006069 // We need to append the results of this capture to what we already have.
6070 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
6071 Pointers.append(CurPointers.begin(), CurPointers.end());
6072 Sizes.append(CurSizes.begin(), CurSizes.end());
6073 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
Samuel Antaobed3c462015-10-02 16:14:20 +00006074 }
6075
6076 // Keep track on whether the host function has to be executed.
6077 auto OffloadErrorQType =
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006078 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006079 auto OffloadError = CGF.MakeAddrLValue(
6080 CGF.CreateMemTemp(OffloadErrorQType, ".run_host_version"),
6081 OffloadErrorQType);
6082 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty),
6083 OffloadError);
6084
6085 // Fill up the pointer arrays and transfer execution to the device.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00006086 auto &&ThenGen = [&BasePointers, &Pointers, &Sizes, &MapTypes, Device,
6087 OutlinedFnID, OffloadError,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006088 &D](CodeGenFunction &CGF, PrePostActionTy &) {
6089 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antaodf158d52016-04-27 22:58:19 +00006090 // Emit the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00006091 TargetDataInfo Info;
6092 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
6093 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
6094 Info.PointersArray, Info.SizesArray,
6095 Info.MapTypesArray, Info);
Samuel Antaobed3c462015-10-02 16:14:20 +00006096
6097 // On top of the arrays that were filled up, the target offloading call
6098 // takes as arguments the device id as well as the host pointer. The host
6099 // pointer is used by the runtime library to identify the current target
6100 // region, so it only has to be unique and not necessarily point to
6101 // anything. It could be the pointer to the outlined function that
6102 // implements the target region, but we aren't using that so that the
6103 // compiler doesn't need to keep that, and could therefore inline the host
6104 // function if proven worthwhile during optimization.
6105
Samuel Antaoee8fb302016-01-06 13:42:12 +00006106 // From this point on, we need to have an ID of the target region defined.
6107 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00006108
6109 // Emit device ID if any.
6110 llvm::Value *DeviceID;
6111 if (Device)
6112 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006113 CGF.Int32Ty, /*isSigned=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006114 else
6115 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6116
Samuel Antaodf158d52016-04-27 22:58:19 +00006117 // Emit the number of elements in the offloading arrays.
6118 llvm::Value *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6119
Samuel Antaob68e2db2016-03-03 16:20:23 +00006120 // Return value of the runtime offloading call.
6121 llvm::Value *Return;
6122
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006123 auto *NumTeams = emitNumTeamsForTargetDirective(RT, CGF, D);
6124 auto *NumThreads = emitNumThreadsForTargetDirective(RT, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006125
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006126 // The target region is an outlined function launched by the runtime
6127 // via calls __tgt_target() or __tgt_target_teams().
6128 //
6129 // __tgt_target() launches a target region with one team and one thread,
6130 // executing a serial region. This master thread may in turn launch
6131 // more threads within its team upon encountering a parallel region,
6132 // however, no additional teams can be launched on the device.
6133 //
6134 // __tgt_target_teams() launches a target region with one or more teams,
6135 // each with one or more threads. This call is required for target
6136 // constructs such as:
6137 // 'target teams'
6138 // 'target' / 'teams'
6139 // 'target teams distribute parallel for'
6140 // 'target parallel'
6141 // and so on.
6142 //
6143 // Note that on the host and CPU targets, the runtime implementation of
6144 // these calls simply call the outlined function without forking threads.
6145 // The outlined functions themselves have runtime calls to
6146 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
6147 // the compiler in emitTeamsCall() and emitParallelCall().
6148 //
6149 // In contrast, on the NVPTX target, the implementation of
6150 // __tgt_target_teams() launches a GPU kernel with the requested number
6151 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006152 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006153 // If we have NumTeams defined this means that we have an enclosed teams
6154 // region. Therefore we also expect to have NumThreads defined. These two
6155 // values should be defined in the presence of a teams directive,
6156 // regardless of having any clauses associated. If the user is using teams
6157 // but no clauses, these two values will be the default that should be
6158 // passed to the runtime library - a 32-bit integer with the value zero.
6159 assert(NumThreads && "Thread limit expression should be available along "
6160 "with number of teams.");
Samuel Antaob68e2db2016-03-03 16:20:23 +00006161 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00006162 DeviceID, OutlinedFnID,
6163 PointerNum, Info.BasePointersArray,
6164 Info.PointersArray, Info.SizesArray,
6165 Info.MapTypesArray, NumTeams,
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006166 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00006167 Return = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006168 RT.createRuntimeFunction(OMPRTL__tgt_target_teams), OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006169 } else {
6170 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00006171 DeviceID, OutlinedFnID,
6172 PointerNum, Info.BasePointersArray,
6173 Info.PointersArray, Info.SizesArray,
6174 Info.MapTypesArray};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006175 Return = CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target),
Samuel Antaob68e2db2016-03-03 16:20:23 +00006176 OffloadingArgs);
6177 }
Samuel Antaobed3c462015-10-02 16:14:20 +00006178
6179 CGF.EmitStoreOfScalar(Return, OffloadError);
6180 };
6181
Samuel Antaoee8fb302016-01-06 13:42:12 +00006182 // Notify that the host version must be executed.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006183 auto &&ElseGen = [OffloadError](CodeGenFunction &CGF, PrePostActionTy &) {
6184 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/-1u),
Samuel Antaoee8fb302016-01-06 13:42:12 +00006185 OffloadError);
6186 };
6187
6188 // If we have a target function ID it means that we need to support
6189 // offloading, otherwise, just execute on the host. We need to execute on host
6190 // regardless of the conditional in the if clause if, e.g., the user do not
6191 // specify target triples.
6192 if (OutlinedFnID) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006193 if (IfCond)
Samuel Antaoee8fb302016-01-06 13:42:12 +00006194 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006195 else {
6196 RegionCodeGenTy ThenRCG(ThenGen);
6197 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00006198 }
6199 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006200 RegionCodeGenTy ElseRCG(ElseGen);
6201 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00006202 }
Samuel Antaobed3c462015-10-02 16:14:20 +00006203
6204 // Check the error code and execute the host version if required.
6205 auto OffloadFailedBlock = CGF.createBasicBlock("omp_offload.failed");
6206 auto OffloadContBlock = CGF.createBasicBlock("omp_offload.cont");
6207 auto OffloadErrorVal = CGF.EmitLoadOfScalar(OffloadError, SourceLocation());
6208 auto Failed = CGF.Builder.CreateIsNotNull(OffloadErrorVal);
6209 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
6210
6211 CGF.EmitBlock(OffloadFailedBlock);
Samuel Antao86ace552016-04-27 22:40:57 +00006212 CGF.Builder.CreateCall(OutlinedFn, KernelArgs);
Samuel Antaobed3c462015-10-02 16:14:20 +00006213 CGF.EmitBranch(OffloadContBlock);
6214
6215 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006216}
Samuel Antaoee8fb302016-01-06 13:42:12 +00006217
6218void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
6219 StringRef ParentName) {
6220 if (!S)
6221 return;
6222
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00006223 // Codegen OMP target directives that offload compute to the device.
6224 bool requiresDeviceCodegen =
6225 isa<OMPExecutableDirective>(S) &&
6226 isOpenMPTargetExecutionDirective(
6227 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00006228
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00006229 if (requiresDeviceCodegen) {
6230 auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006231 unsigned DeviceID;
6232 unsigned FileID;
6233 unsigned Line;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00006234 getTargetEntryUniqueInfo(CGM.getContext(), E.getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00006235 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006236
6237 // Is this a target region that should not be emitted as an entry point? If
6238 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00006239 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
6240 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00006241 return;
6242
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00006243 switch (S->getStmtClass()) {
6244 case Stmt::OMPTargetDirectiveClass:
6245 CodeGenFunction::EmitOMPTargetDeviceFunction(
6246 CGM, ParentName, cast<OMPTargetDirective>(*S));
6247 break;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00006248 case Stmt::OMPTargetParallelDirectiveClass:
6249 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
6250 CGM, ParentName, cast<OMPTargetParallelDirective>(*S));
6251 break;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006252 case Stmt::OMPTargetTeamsDirectiveClass:
6253 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
6254 CGM, ParentName, cast<OMPTargetTeamsDirective>(*S));
6255 break;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00006256 default:
6257 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
6258 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00006259 return;
6260 }
6261
6262 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
Samuel Antaoe49645c2016-05-08 06:43:56 +00006263 if (!E->hasAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00006264 return;
6265
6266 scanForTargetRegionsFunctions(
6267 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
6268 ParentName);
6269 return;
6270 }
6271
6272 // If this is a lambda function, look into its body.
6273 if (auto *L = dyn_cast<LambdaExpr>(S))
6274 S = L->getBody();
6275
6276 // Keep looking for target regions recursively.
6277 for (auto *II : S->children())
6278 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006279}
6280
6281bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
6282 auto &FD = *cast<FunctionDecl>(GD.getDecl());
6283
6284 // If emitting code for the host, we do not process FD here. Instead we do
6285 // the normal code generation.
6286 if (!CGM.getLangOpts().OpenMPIsDevice)
6287 return false;
6288
6289 // Try to detect target regions in the function.
6290 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
6291
Samuel Antao4b75b872016-12-12 19:26:31 +00006292 // We should not emit any function other that the ones created during the
Samuel Antaoee8fb302016-01-06 13:42:12 +00006293 // scanning. Therefore, we signal that this function is completely dealt
6294 // with.
6295 return true;
6296}
6297
6298bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
6299 if (!CGM.getLangOpts().OpenMPIsDevice)
6300 return false;
6301
6302 // Check if there are Ctors/Dtors in this declaration and look for target
6303 // regions in it. We use the complete variant to produce the kernel name
6304 // mangling.
6305 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
6306 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
6307 for (auto *Ctor : RD->ctors()) {
6308 StringRef ParentName =
6309 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
6310 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
6311 }
6312 auto *Dtor = RD->getDestructor();
6313 if (Dtor) {
6314 StringRef ParentName =
6315 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
6316 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
6317 }
6318 }
6319
Gheorghe-Teodor Bercea47633db2017-06-13 15:35:27 +00006320 // If we are in target mode, we do not emit any global (declare target is not
Samuel Antaoee8fb302016-01-06 13:42:12 +00006321 // implemented yet). Therefore we signal that GD was processed in this case.
6322 return true;
6323}
6324
6325bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
6326 auto *VD = GD.getDecl();
6327 if (isa<FunctionDecl>(VD))
6328 return emitTargetFunctions(GD);
6329
6330 return emitTargetGlobalVariable(GD);
6331}
6332
6333llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
6334 // If we have offloading in the current module, we need to emit the entries
6335 // now and register the offloading descriptor.
6336 createOffloadEntriesAndInfoMetadata();
6337
6338 // Create and register the offloading binary descriptors. This is the main
6339 // entity that captures all the information about offloading in the current
6340 // compilation unit.
6341 return createOffloadingBinaryDescriptorRegistration();
6342}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006343
6344void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
6345 const OMPExecutableDirective &D,
6346 SourceLocation Loc,
6347 llvm::Value *OutlinedFn,
6348 ArrayRef<llvm::Value *> CapturedVars) {
6349 if (!CGF.HaveInsertPoint())
6350 return;
6351
6352 auto *RTLoc = emitUpdateLocation(CGF, Loc);
6353 CodeGenFunction::RunCleanupsScope Scope(CGF);
6354
6355 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
6356 llvm::Value *Args[] = {
6357 RTLoc,
6358 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
6359 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
6360 llvm::SmallVector<llvm::Value *, 16> RealArgs;
6361 RealArgs.append(std::begin(Args), std::end(Args));
6362 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
6363
6364 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
6365 CGF.EmitRuntimeCall(RTLFn, RealArgs);
6366}
6367
6368void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00006369 const Expr *NumTeams,
6370 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006371 SourceLocation Loc) {
6372 if (!CGF.HaveInsertPoint())
6373 return;
6374
6375 auto *RTLoc = emitUpdateLocation(CGF, Loc);
6376
Carlo Bertollic6872252016-04-04 15:55:02 +00006377 llvm::Value *NumTeamsVal =
6378 (NumTeams)
6379 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
6380 CGF.CGM.Int32Ty, /* isSigned = */ true)
6381 : CGF.Builder.getInt32(0);
6382
6383 llvm::Value *ThreadLimitVal =
6384 (ThreadLimit)
6385 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
6386 CGF.CGM.Int32Ty, /* isSigned = */ true)
6387 : CGF.Builder.getInt32(0);
6388
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006389 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00006390 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
6391 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006392 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
6393 PushNumTeamsArgs);
6394}
Samuel Antaodf158d52016-04-27 22:58:19 +00006395
Samuel Antaocc10b852016-07-28 14:23:26 +00006396void CGOpenMPRuntime::emitTargetDataCalls(
6397 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
6398 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006399 if (!CGF.HaveInsertPoint())
6400 return;
6401
Samuel Antaocc10b852016-07-28 14:23:26 +00006402 // Action used to replace the default codegen action and turn privatization
6403 // off.
6404 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00006405
6406 // Generate the code for the opening of the data environment. Capture all the
6407 // arguments of the runtime call by reference because they are used in the
6408 // closing of the region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00006409 auto &&BeginThenGen = [&D, Device, &Info, &CodeGen](CodeGenFunction &CGF,
6410 PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006411 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00006412 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00006413 MappableExprsHandler::MapValuesArrayTy Pointers;
6414 MappableExprsHandler::MapValuesArrayTy Sizes;
6415 MappableExprsHandler::MapFlagsArrayTy MapTypes;
6416
6417 // Get map clause information.
6418 MappableExprsHandler MCHandler(D, CGF);
6419 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00006420
6421 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00006422 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00006423
6424 llvm::Value *BasePointersArrayArg = nullptr;
6425 llvm::Value *PointersArrayArg = nullptr;
6426 llvm::Value *SizesArrayArg = nullptr;
6427 llvm::Value *MapTypesArrayArg = nullptr;
6428 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006429 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00006430
6431 // Emit device ID if any.
6432 llvm::Value *DeviceID = nullptr;
6433 if (Device)
6434 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6435 CGF.Int32Ty, /*isSigned=*/true);
6436 else
6437 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6438
6439 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00006440 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00006441
6442 llvm::Value *OffloadingArgs[] = {
6443 DeviceID, PointerNum, BasePointersArrayArg,
6444 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
6445 auto &RT = CGF.CGM.getOpenMPRuntime();
6446 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_begin),
6447 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00006448
6449 // If device pointer privatization is required, emit the body of the region
6450 // here. It will have to be duplicated: with and without privatization.
6451 if (!Info.CaptureDeviceAddrMap.empty())
6452 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00006453 };
6454
6455 // Generate code for the closing of the data region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00006456 auto &&EndThenGen = [Device, &Info](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006457 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00006458
6459 llvm::Value *BasePointersArrayArg = nullptr;
6460 llvm::Value *PointersArrayArg = nullptr;
6461 llvm::Value *SizesArrayArg = nullptr;
6462 llvm::Value *MapTypesArrayArg = nullptr;
6463 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006464 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00006465
6466 // Emit device ID if any.
6467 llvm::Value *DeviceID = nullptr;
6468 if (Device)
6469 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6470 CGF.Int32Ty, /*isSigned=*/true);
6471 else
6472 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6473
6474 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00006475 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00006476
6477 llvm::Value *OffloadingArgs[] = {
6478 DeviceID, PointerNum, BasePointersArrayArg,
6479 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
6480 auto &RT = CGF.CGM.getOpenMPRuntime();
6481 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_end),
6482 OffloadingArgs);
6483 };
6484
Samuel Antaocc10b852016-07-28 14:23:26 +00006485 // If we need device pointer privatization, we need to emit the body of the
6486 // region with no privatization in the 'else' branch of the conditional.
6487 // Otherwise, we don't have to do anything.
6488 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
6489 PrePostActionTy &) {
6490 if (!Info.CaptureDeviceAddrMap.empty()) {
6491 CodeGen.setAction(NoPrivAction);
6492 CodeGen(CGF);
6493 }
6494 };
6495
6496 // We don't have to do anything to close the region if the if clause evaluates
6497 // to false.
6498 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00006499
6500 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006501 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00006502 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00006503 RegionCodeGenTy RCG(BeginThenGen);
6504 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00006505 }
6506
Samuel Antaocc10b852016-07-28 14:23:26 +00006507 // If we don't require privatization of device pointers, we emit the body in
6508 // between the runtime calls. This avoids duplicating the body code.
6509 if (Info.CaptureDeviceAddrMap.empty()) {
6510 CodeGen.setAction(NoPrivAction);
6511 CodeGen(CGF);
6512 }
Samuel Antaodf158d52016-04-27 22:58:19 +00006513
6514 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006515 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00006516 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00006517 RegionCodeGenTy RCG(EndThenGen);
6518 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00006519 }
6520}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006521
Samuel Antao8d2d7302016-05-26 18:30:22 +00006522void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00006523 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
6524 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006525 if (!CGF.HaveInsertPoint())
6526 return;
6527
Samuel Antao8dd66282016-04-27 23:14:30 +00006528 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00006529 isa<OMPTargetExitDataDirective>(D) ||
6530 isa<OMPTargetUpdateDirective>(D)) &&
6531 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00006532
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006533 // Generate the code for the opening of the data environment.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00006534 auto &&ThenGen = [&D, Device](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006535 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00006536 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006537 MappableExprsHandler::MapValuesArrayTy Pointers;
6538 MappableExprsHandler::MapValuesArrayTy Sizes;
6539 MappableExprsHandler::MapFlagsArrayTy MapTypes;
6540
6541 // Get map clause information.
Samuel Antao8d2d7302016-05-26 18:30:22 +00006542 MappableExprsHandler MEHandler(D, CGF);
6543 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006544
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006545 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00006546 TargetDataInfo Info;
6547 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
6548 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
6549 Info.PointersArray, Info.SizesArray,
6550 Info.MapTypesArray, Info);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006551
6552 // Emit device ID if any.
6553 llvm::Value *DeviceID = nullptr;
6554 if (Device)
6555 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6556 CGF.Int32Ty, /*isSigned=*/true);
6557 else
6558 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6559
6560 // Emit the number of elements in the offloading arrays.
6561 auto *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6562
6563 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00006564 DeviceID, PointerNum, Info.BasePointersArray,
6565 Info.PointersArray, Info.SizesArray, Info.MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00006566
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006567 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antao8d2d7302016-05-26 18:30:22 +00006568 // Select the right runtime function call for each expected standalone
6569 // directive.
6570 OpenMPRTLFunction RTLFn;
6571 switch (D.getDirectiveKind()) {
6572 default:
6573 llvm_unreachable("Unexpected standalone target data directive.");
6574 break;
6575 case OMPD_target_enter_data:
6576 RTLFn = OMPRTL__tgt_target_data_begin;
6577 break;
6578 case OMPD_target_exit_data:
6579 RTLFn = OMPRTL__tgt_target_data_end;
6580 break;
6581 case OMPD_target_update:
6582 RTLFn = OMPRTL__tgt_target_data_update;
6583 break;
6584 }
6585 CGF.EmitRuntimeCall(RT.createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006586 };
6587
6588 // In the event we get an if clause, we don't have to take any action on the
6589 // else side.
6590 auto &&ElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
6591
6592 if (IfCond) {
6593 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
6594 } else {
6595 RegionCodeGenTy ThenGenRCG(ThenGen);
6596 ThenGenRCG(CGF);
6597 }
6598}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00006599
6600namespace {
6601 /// Kind of parameter in a function with 'declare simd' directive.
6602 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
6603 /// Attribute set of the parameter.
6604 struct ParamAttrTy {
6605 ParamKindTy Kind = Vector;
6606 llvm::APSInt StrideOrArg;
6607 llvm::APSInt Alignment;
6608 };
6609} // namespace
6610
6611static unsigned evaluateCDTSize(const FunctionDecl *FD,
6612 ArrayRef<ParamAttrTy> ParamAttrs) {
6613 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
6614 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
6615 // of that clause. The VLEN value must be power of 2.
6616 // In other case the notion of the function`s "characteristic data type" (CDT)
6617 // is used to compute the vector length.
6618 // CDT is defined in the following order:
6619 // a) For non-void function, the CDT is the return type.
6620 // b) If the function has any non-uniform, non-linear parameters, then the
6621 // CDT is the type of the first such parameter.
6622 // c) If the CDT determined by a) or b) above is struct, union, or class
6623 // type which is pass-by-value (except for the type that maps to the
6624 // built-in complex data type), the characteristic data type is int.
6625 // d) If none of the above three cases is applicable, the CDT is int.
6626 // The VLEN is then determined based on the CDT and the size of vector
6627 // register of that ISA for which current vector version is generated. The
6628 // VLEN is computed using the formula below:
6629 // VLEN = sizeof(vector_register) / sizeof(CDT),
6630 // where vector register size specified in section 3.2.1 Registers and the
6631 // Stack Frame of original AMD64 ABI document.
6632 QualType RetType = FD->getReturnType();
6633 if (RetType.isNull())
6634 return 0;
6635 ASTContext &C = FD->getASTContext();
6636 QualType CDT;
6637 if (!RetType.isNull() && !RetType->isVoidType())
6638 CDT = RetType;
6639 else {
6640 unsigned Offset = 0;
6641 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6642 if (ParamAttrs[Offset].Kind == Vector)
6643 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
6644 ++Offset;
6645 }
6646 if (CDT.isNull()) {
6647 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
6648 if (ParamAttrs[I + Offset].Kind == Vector) {
6649 CDT = FD->getParamDecl(I)->getType();
6650 break;
6651 }
6652 }
6653 }
6654 }
6655 if (CDT.isNull())
6656 CDT = C.IntTy;
6657 CDT = CDT->getCanonicalTypeUnqualified();
6658 if (CDT->isRecordType() || CDT->isUnionType())
6659 CDT = C.IntTy;
6660 return C.getTypeSize(CDT);
6661}
6662
6663static void
6664emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00006665 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00006666 ArrayRef<ParamAttrTy> ParamAttrs,
6667 OMPDeclareSimdDeclAttr::BranchStateTy State) {
6668 struct ISADataTy {
6669 char ISA;
6670 unsigned VecRegSize;
6671 };
6672 ISADataTy ISAData[] = {
6673 {
6674 'b', 128
6675 }, // SSE
6676 {
6677 'c', 256
6678 }, // AVX
6679 {
6680 'd', 256
6681 }, // AVX2
6682 {
6683 'e', 512
6684 }, // AVX512
6685 };
6686 llvm::SmallVector<char, 2> Masked;
6687 switch (State) {
6688 case OMPDeclareSimdDeclAttr::BS_Undefined:
6689 Masked.push_back('N');
6690 Masked.push_back('M');
6691 break;
6692 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
6693 Masked.push_back('N');
6694 break;
6695 case OMPDeclareSimdDeclAttr::BS_Inbranch:
6696 Masked.push_back('M');
6697 break;
6698 }
6699 for (auto Mask : Masked) {
6700 for (auto &Data : ISAData) {
6701 SmallString<256> Buffer;
6702 llvm::raw_svector_ostream Out(Buffer);
6703 Out << "_ZGV" << Data.ISA << Mask;
6704 if (!VLENVal) {
6705 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
6706 evaluateCDTSize(FD, ParamAttrs));
6707 } else
6708 Out << VLENVal;
6709 for (auto &ParamAttr : ParamAttrs) {
6710 switch (ParamAttr.Kind){
6711 case LinearWithVarStride:
6712 Out << 's' << ParamAttr.StrideOrArg;
6713 break;
6714 case Linear:
6715 Out << 'l';
6716 if (!!ParamAttr.StrideOrArg)
6717 Out << ParamAttr.StrideOrArg;
6718 break;
6719 case Uniform:
6720 Out << 'u';
6721 break;
6722 case Vector:
6723 Out << 'v';
6724 break;
6725 }
6726 if (!!ParamAttr.Alignment)
6727 Out << 'a' << ParamAttr.Alignment;
6728 }
6729 Out << '_' << Fn->getName();
6730 Fn->addFnAttr(Out.str());
6731 }
6732 }
6733}
6734
6735void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
6736 llvm::Function *Fn) {
6737 ASTContext &C = CGM.getContext();
6738 FD = FD->getCanonicalDecl();
6739 // Map params to their positions in function decl.
6740 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
6741 if (isa<CXXMethodDecl>(FD))
6742 ParamPositions.insert({FD, 0});
6743 unsigned ParamPos = ParamPositions.size();
David Majnemer59f77922016-06-24 04:05:48 +00006744 for (auto *P : FD->parameters()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00006745 ParamPositions.insert({P->getCanonicalDecl(), ParamPos});
6746 ++ParamPos;
6747 }
6748 for (auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
6749 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
6750 // Mark uniform parameters.
6751 for (auto *E : Attr->uniforms()) {
6752 E = E->IgnoreParenImpCasts();
6753 unsigned Pos;
6754 if (isa<CXXThisExpr>(E))
6755 Pos = ParamPositions[FD];
6756 else {
6757 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
6758 ->getCanonicalDecl();
6759 Pos = ParamPositions[PVD];
6760 }
6761 ParamAttrs[Pos].Kind = Uniform;
6762 }
6763 // Get alignment info.
6764 auto NI = Attr->alignments_begin();
6765 for (auto *E : Attr->aligneds()) {
6766 E = E->IgnoreParenImpCasts();
6767 unsigned Pos;
6768 QualType ParmTy;
6769 if (isa<CXXThisExpr>(E)) {
6770 Pos = ParamPositions[FD];
6771 ParmTy = E->getType();
6772 } else {
6773 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
6774 ->getCanonicalDecl();
6775 Pos = ParamPositions[PVD];
6776 ParmTy = PVD->getType();
6777 }
6778 ParamAttrs[Pos].Alignment =
6779 (*NI) ? (*NI)->EvaluateKnownConstInt(C)
6780 : llvm::APSInt::getUnsigned(
6781 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
6782 .getQuantity());
6783 ++NI;
6784 }
6785 // Mark linear parameters.
6786 auto SI = Attr->steps_begin();
6787 auto MI = Attr->modifiers_begin();
6788 for (auto *E : Attr->linears()) {
6789 E = E->IgnoreParenImpCasts();
6790 unsigned Pos;
6791 if (isa<CXXThisExpr>(E))
6792 Pos = ParamPositions[FD];
6793 else {
6794 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
6795 ->getCanonicalDecl();
6796 Pos = ParamPositions[PVD];
6797 }
6798 auto &ParamAttr = ParamAttrs[Pos];
6799 ParamAttr.Kind = Linear;
6800 if (*SI) {
6801 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
6802 Expr::SE_AllowSideEffects)) {
6803 if (auto *DRE = cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
6804 if (auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
6805 ParamAttr.Kind = LinearWithVarStride;
6806 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
6807 ParamPositions[StridePVD->getCanonicalDecl()]);
6808 }
6809 }
6810 }
6811 }
6812 ++SI;
6813 ++MI;
6814 }
6815 llvm::APSInt VLENVal;
6816 if (const Expr *VLEN = Attr->getSimdlen())
6817 VLENVal = VLEN->EvaluateKnownConstInt(C);
6818 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
6819 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
6820 CGM.getTriple().getArch() == llvm::Triple::x86_64)
6821 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
6822 }
6823}
Alexey Bataev8b427062016-05-25 12:36:08 +00006824
6825namespace {
6826/// Cleanup action for doacross support.
6827class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
6828public:
6829 static const int DoacrossFinArgs = 2;
6830
6831private:
6832 llvm::Value *RTLFn;
6833 llvm::Value *Args[DoacrossFinArgs];
6834
6835public:
6836 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
6837 : RTLFn(RTLFn) {
6838 assert(CallArgs.size() == DoacrossFinArgs);
6839 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
6840 }
6841 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
6842 if (!CGF.HaveInsertPoint())
6843 return;
6844 CGF.EmitRuntimeCall(RTLFn, Args);
6845 }
6846};
6847} // namespace
6848
6849void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
6850 const OMPLoopDirective &D) {
6851 if (!CGF.HaveInsertPoint())
6852 return;
6853
6854 ASTContext &C = CGM.getContext();
6855 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
6856 RecordDecl *RD;
6857 if (KmpDimTy.isNull()) {
6858 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
6859 // kmp_int64 lo; // lower
6860 // kmp_int64 up; // upper
6861 // kmp_int64 st; // stride
6862 // };
6863 RD = C.buildImplicitRecord("kmp_dim");
6864 RD->startDefinition();
6865 addFieldToRecordDecl(C, RD, Int64Ty);
6866 addFieldToRecordDecl(C, RD, Int64Ty);
6867 addFieldToRecordDecl(C, RD, Int64Ty);
6868 RD->completeDefinition();
6869 KmpDimTy = C.getRecordType(RD);
6870 } else
6871 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
6872
6873 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
6874 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
6875 enum { LowerFD = 0, UpperFD, StrideFD };
6876 // Fill dims with data.
6877 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
6878 // dims.upper = num_iterations;
6879 LValue UpperLVal =
6880 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
6881 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
6882 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
6883 Int64Ty, D.getNumIterations()->getExprLoc());
6884 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
6885 // dims.stride = 1;
6886 LValue StrideLVal =
6887 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
6888 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
6889 StrideLVal);
6890
6891 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
6892 // kmp_int32 num_dims, struct kmp_dim * dims);
6893 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
6894 getThreadID(CGF, D.getLocStart()),
6895 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
6896 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6897 DimsAddr.getPointer(), CGM.VoidPtrTy)};
6898
6899 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
6900 CGF.EmitRuntimeCall(RTLFn, Args);
6901 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
6902 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
6903 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
6904 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
6905 llvm::makeArrayRef(FiniArgs));
6906}
6907
6908void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
6909 const OMPDependClause *C) {
6910 QualType Int64Ty =
6911 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
6912 const Expr *CounterVal = C->getCounterValue();
6913 assert(CounterVal);
6914 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
6915 CounterVal->getType(), Int64Ty,
6916 CounterVal->getExprLoc());
6917 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
6918 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
6919 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
6920 getThreadID(CGF, C->getLocStart()),
6921 CntAddr.getPointer()};
6922 llvm::Value *RTLFn;
6923 if (C->getDependencyKind() == OMPC_DEPEND_source)
6924 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
6925 else {
6926 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
6927 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
6928 }
6929 CGF.EmitRuntimeCall(RTLFn, Args);
6930}
6931