blob: 0644d1b2834bbe4996c9fac37a854d49da19aaef [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(),
750 /*Id=*/nullptr, PtrTy);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000751 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
752 /*Id=*/nullptr, PtrTy);
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);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000763 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000764 CodeGenFunction CGF(CGM);
765 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
766 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
767 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
768 CodeGenFunction::OMPPrivateScope Scope(CGF);
769 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
770 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
771 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
772 .getAddress();
773 });
774 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
775 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
776 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
777 .getAddress();
778 });
779 (void)Scope.Privatize();
780 CGF.EmitIgnoredExpr(CombinerInitializer);
781 Scope.ForceCleanup();
782 CGF.FinishFunction();
783 return Fn;
784}
785
786void CGOpenMPRuntime::emitUserDefinedReduction(
787 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
788 if (UDRMap.count(D) > 0)
789 return;
790 auto &C = CGM.getContext();
791 if (!In || !Out) {
792 In = &C.Idents.get("omp_in");
793 Out = &C.Idents.get("omp_out");
794 }
795 llvm::Function *Combiner = emitCombinerOrInitializer(
796 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
797 cast<VarDecl>(D->lookup(Out).front()),
798 /*IsCombiner=*/true);
799 llvm::Function *Initializer = nullptr;
800 if (auto *Init = D->getInitializer()) {
801 if (!Priv || !Orig) {
802 Priv = &C.Idents.get("omp_priv");
803 Orig = &C.Idents.get("omp_orig");
804 }
805 Initializer = emitCombinerOrInitializer(
806 CGM, D->getType(), Init, cast<VarDecl>(D->lookup(Orig).front()),
807 cast<VarDecl>(D->lookup(Priv).front()),
808 /*IsCombiner=*/false);
809 }
810 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
811 if (CGF) {
812 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
813 Decls.second.push_back(D);
814 }
815}
816
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000817std::pair<llvm::Function *, llvm::Function *>
818CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
819 auto I = UDRMap.find(D);
820 if (I != UDRMap.end())
821 return I->second;
822 emitUserDefinedReduction(/*CGF=*/nullptr, D);
823 return UDRMap.lookup(D);
824}
825
John McCall7f416cc2015-09-08 08:05:57 +0000826// Layout information for ident_t.
827static CharUnits getIdentAlign(CodeGenModule &CGM) {
828 return CGM.getPointerAlign();
829}
830static CharUnits getIdentSize(CodeGenModule &CGM) {
831 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
832 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
833}
Alexey Bataev50b3c952016-02-19 10:38:26 +0000834static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
John McCall7f416cc2015-09-08 08:05:57 +0000835 // All the fields except the last are i32, so this works beautifully.
836 return unsigned(Field) * CharUnits::fromQuantity(4);
837}
838static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000839 IdentFieldIndex Field,
John McCall7f416cc2015-09-08 08:05:57 +0000840 const llvm::Twine &Name = "") {
841 auto Offset = getOffsetOfIdentField(Field);
842 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
843}
844
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +0000845static llvm::Value *emitParallelOrTeamsOutlinedFunction(
846 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
847 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
848 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000849 assert(ThreadIDVar->getType()->isPointerType() &&
850 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +0000851 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +0000852 bool HasCancel = false;
853 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
854 HasCancel = OPD->hasCancel();
855 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
856 HasCancel = OPSD->hasCancel();
857 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
858 HasCancel = OPFD->hasCancel();
859 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +0000860 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +0000861 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000862 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +0000863}
864
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +0000865llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
866 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
867 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
868 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
869 return emitParallelOrTeamsOutlinedFunction(
870 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
871}
872
873llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
874 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
875 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
876 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
877 return emitParallelOrTeamsOutlinedFunction(
878 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
879}
880
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000881llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
882 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +0000883 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
884 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
885 bool Tied, unsigned &NumberOfParts) {
886 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
887 PrePostActionTy &) {
888 auto *ThreadID = getThreadID(CGF, D.getLocStart());
889 auto *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
890 llvm::Value *TaskArgs[] = {
891 UpLoc, ThreadID,
892 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
893 TaskTVar->getType()->castAs<PointerType>())
894 .getPointer()};
895 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
896 };
897 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
898 UntiedCodeGen);
899 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000900 assert(!ThreadIDVar->getType()->isPointerType() &&
901 "thread id variable must be of type kmp_int32 for tasks");
902 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
Alexey Bataev7292c292016-04-25 12:22:29 +0000903 auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000904 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +0000905 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
906 InnermostKind,
907 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +0000908 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev48591dd2016-04-20 04:01:36 +0000909 auto *Res = CGF.GenerateCapturedStmtFunction(*CS);
910 if (!Tied)
911 NumberOfParts = Action.getNumberOfParts();
912 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000913}
914
Alexey Bataev50b3c952016-02-19 10:38:26 +0000915Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +0000916 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +0000917 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000918 if (!Entry) {
919 if (!DefaultOpenMPPSource) {
920 // Initialize default location for psource field of ident_t structure of
921 // all ident_t objects. Format is ";file;function;line;column;;".
922 // Taken from
923 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
924 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +0000925 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000926 DefaultOpenMPPSource =
927 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
928 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000929
John McCall23c9dc62016-11-28 22:18:27 +0000930 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +0000931 auto fields = builder.beginStruct(IdentTy);
932 fields.addInt(CGM.Int32Ty, 0);
933 fields.addInt(CGM.Int32Ty, Flags);
934 fields.addInt(CGM.Int32Ty, 0);
935 fields.addInt(CGM.Int32Ty, 0);
936 fields.add(DefaultOpenMPPSource);
937 auto DefaultOpenMPLocation =
938 fields.finishAndCreateGlobal("", Align, /*isConstant*/ true,
939 llvm::GlobalValue::PrivateLinkage);
940 DefaultOpenMPLocation->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
941
John McCall7f416cc2015-09-08 08:05:57 +0000942 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +0000943 }
John McCall7f416cc2015-09-08 08:05:57 +0000944 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +0000945}
946
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000947llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
948 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000949 unsigned Flags) {
950 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +0000951 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +0000952 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +0000953 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +0000954 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000955
956 assert(CGF.CurFn && "No function in current CodeGenFunction.");
957
John McCall7f416cc2015-09-08 08:05:57 +0000958 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000959 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
960 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +0000961 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
962
Alexander Musmanc6388682014-12-15 07:07:06 +0000963 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
964 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +0000965 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000966 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +0000967 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
968 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +0000969 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +0000970 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000971 LocValue = AI;
972
973 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
974 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000975 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +0000976 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +0000977 }
978
979 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +0000980 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +0000981
Alexey Bataevf002aca2014-05-30 05:48:40 +0000982 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
983 if (OMPDebugLoc == nullptr) {
984 SmallString<128> Buffer2;
985 llvm::raw_svector_ostream OS2(Buffer2);
986 // Build debug location
987 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
988 OS2 << ";" << PLoc.getFilename() << ";";
989 if (const FunctionDecl *FD =
990 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
991 OS2 << FD->getQualifiedNameAsString();
992 }
993 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
994 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
995 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +0000996 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000997 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +0000998 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
999
John McCall7f416cc2015-09-08 08:05:57 +00001000 // Our callers always pass this to a runtime function, so for
1001 // convenience, go ahead and return a naked pointer.
1002 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001003}
1004
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001005llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1006 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001007 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1008
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001009 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001010 // Check whether we've already cached a load of the thread id in this
1011 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001012 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001013 if (I != OpenMPLocThreadIDMap.end()) {
1014 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001015 if (ThreadID != nullptr)
1016 return ThreadID;
1017 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001018 if (auto *OMPRegionInfo =
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001019 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001020 if (OMPRegionInfo->getThreadIDVariable()) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001021 // Check if this an outlined function with thread id passed as argument.
1022 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001023 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
1024 // If value loaded in entry block, cache it and use it everywhere in
1025 // function.
1026 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1027 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1028 Elem.second.ThreadID = ThreadID;
1029 }
1030 return ThreadID;
Alexey Bataevd6c57552014-07-25 07:55:17 +00001031 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001032 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001033
1034 // This is not an outlined function region - need to call __kmpc_int32
1035 // kmpc_global_thread_num(ident_t *loc).
1036 // Generate thread id value and cache this value for use across the
1037 // function.
1038 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1039 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
1040 ThreadID =
1041 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1042 emitUpdateLocation(CGF, Loc));
1043 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1044 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001045 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +00001046}
1047
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001048void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001049 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001050 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1051 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001052 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1053 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
1054 UDRMap.erase(D);
1055 }
1056 FunctionUDRMap.erase(CGF.CurFn);
1057 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001058}
1059
1060llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001061 if (!IdentTy) {
1062 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001063 return llvm::PointerType::getUnqual(IdentTy);
1064}
1065
1066llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001067 if (!Kmpc_MicroTy) {
1068 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1069 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1070 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1071 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1072 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001073 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1074}
1075
1076llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001077CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001078 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001079 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001080 case OMPRTL__kmpc_fork_call: {
1081 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1082 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001083 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1084 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001085 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001086 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001087 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1088 break;
1089 }
1090 case OMPRTL__kmpc_global_thread_num: {
1091 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001092 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001093 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001094 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001095 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1096 break;
1097 }
Alexey Bataev97720002014-11-11 04:05:39 +00001098 case OMPRTL__kmpc_threadprivate_cached: {
1099 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1100 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1101 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1102 CGM.VoidPtrTy, CGM.SizeTy,
1103 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1104 llvm::FunctionType *FnTy =
1105 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1106 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1107 break;
1108 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001109 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001110 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1111 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001112 llvm::Type *TypeParams[] = {
1113 getIdentTyPointerTy(), CGM.Int32Ty,
1114 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1115 llvm::FunctionType *FnTy =
1116 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1117 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1118 break;
1119 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001120 case OMPRTL__kmpc_critical_with_hint: {
1121 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1122 // kmp_critical_name *crit, uintptr_t hint);
1123 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1124 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1125 CGM.IntPtrTy};
1126 llvm::FunctionType *FnTy =
1127 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1128 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1129 break;
1130 }
Alexey Bataev97720002014-11-11 04:05:39 +00001131 case OMPRTL__kmpc_threadprivate_register: {
1132 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1133 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1134 // typedef void *(*kmpc_ctor)(void *);
1135 auto KmpcCtorTy =
1136 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1137 /*isVarArg*/ false)->getPointerTo();
1138 // typedef void *(*kmpc_cctor)(void *, void *);
1139 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1140 auto KmpcCopyCtorTy =
1141 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1142 /*isVarArg*/ false)->getPointerTo();
1143 // typedef void (*kmpc_dtor)(void *);
1144 auto KmpcDtorTy =
1145 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1146 ->getPointerTo();
1147 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1148 KmpcCopyCtorTy, KmpcDtorTy};
1149 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1150 /*isVarArg*/ false);
1151 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1152 break;
1153 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001154 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001155 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1156 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001157 llvm::Type *TypeParams[] = {
1158 getIdentTyPointerTy(), CGM.Int32Ty,
1159 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1160 llvm::FunctionType *FnTy =
1161 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1162 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1163 break;
1164 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001165 case OMPRTL__kmpc_cancel_barrier: {
1166 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1167 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001168 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1169 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001170 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1171 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001172 break;
1173 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001174 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001175 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001176 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1177 llvm::FunctionType *FnTy =
1178 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1179 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1180 break;
1181 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001182 case OMPRTL__kmpc_for_static_fini: {
1183 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1184 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1185 llvm::FunctionType *FnTy =
1186 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1187 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1188 break;
1189 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001190 case OMPRTL__kmpc_push_num_threads: {
1191 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1192 // kmp_int32 num_threads)
1193 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1194 CGM.Int32Ty};
1195 llvm::FunctionType *FnTy =
1196 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1197 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1198 break;
1199 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001200 case OMPRTL__kmpc_serialized_parallel: {
1201 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1202 // global_tid);
1203 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1204 llvm::FunctionType *FnTy =
1205 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1206 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1207 break;
1208 }
1209 case OMPRTL__kmpc_end_serialized_parallel: {
1210 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1211 // global_tid);
1212 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1213 llvm::FunctionType *FnTy =
1214 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1215 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1216 break;
1217 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001218 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001219 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001220 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1221 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001222 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001223 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1224 break;
1225 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001226 case OMPRTL__kmpc_master: {
1227 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1228 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1229 llvm::FunctionType *FnTy =
1230 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1231 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1232 break;
1233 }
1234 case OMPRTL__kmpc_end_master: {
1235 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1236 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1237 llvm::FunctionType *FnTy =
1238 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1239 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1240 break;
1241 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001242 case OMPRTL__kmpc_omp_taskyield: {
1243 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1244 // int end_part);
1245 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1246 llvm::FunctionType *FnTy =
1247 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1248 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1249 break;
1250 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001251 case OMPRTL__kmpc_single: {
1252 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1253 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1254 llvm::FunctionType *FnTy =
1255 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1256 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1257 break;
1258 }
1259 case OMPRTL__kmpc_end_single: {
1260 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1261 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1262 llvm::FunctionType *FnTy =
1263 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1264 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1265 break;
1266 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001267 case OMPRTL__kmpc_omp_task_alloc: {
1268 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1269 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1270 // kmp_routine_entry_t *task_entry);
1271 assert(KmpRoutineEntryPtrTy != nullptr &&
1272 "Type kmp_routine_entry_t must be created.");
1273 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1274 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1275 // Return void * and then cast to particular kmp_task_t type.
1276 llvm::FunctionType *FnTy =
1277 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1278 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1279 break;
1280 }
1281 case OMPRTL__kmpc_omp_task: {
1282 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1283 // *new_task);
1284 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1285 CGM.VoidPtrTy};
1286 llvm::FunctionType *FnTy =
1287 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1288 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1289 break;
1290 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001291 case OMPRTL__kmpc_copyprivate: {
1292 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001293 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001294 // kmp_int32 didit);
1295 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1296 auto *CpyFnTy =
1297 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001298 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001299 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1300 CGM.Int32Ty};
1301 llvm::FunctionType *FnTy =
1302 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1303 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1304 break;
1305 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001306 case OMPRTL__kmpc_reduce: {
1307 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1308 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1309 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1310 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1311 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1312 /*isVarArg=*/false);
1313 llvm::Type *TypeParams[] = {
1314 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1315 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1316 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1317 llvm::FunctionType *FnTy =
1318 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1319 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1320 break;
1321 }
1322 case OMPRTL__kmpc_reduce_nowait: {
1323 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1324 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1325 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1326 // *lck);
1327 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1328 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1329 /*isVarArg=*/false);
1330 llvm::Type *TypeParams[] = {
1331 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1332 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1333 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1334 llvm::FunctionType *FnTy =
1335 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1336 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1337 break;
1338 }
1339 case OMPRTL__kmpc_end_reduce: {
1340 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1341 // kmp_critical_name *lck);
1342 llvm::Type *TypeParams[] = {
1343 getIdentTyPointerTy(), CGM.Int32Ty,
1344 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1345 llvm::FunctionType *FnTy =
1346 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1347 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1348 break;
1349 }
1350 case OMPRTL__kmpc_end_reduce_nowait: {
1351 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1352 // kmp_critical_name *lck);
1353 llvm::Type *TypeParams[] = {
1354 getIdentTyPointerTy(), CGM.Int32Ty,
1355 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1356 llvm::FunctionType *FnTy =
1357 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1358 RTLFn =
1359 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1360 break;
1361 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001362 case OMPRTL__kmpc_omp_task_begin_if0: {
1363 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1364 // *new_task);
1365 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1366 CGM.VoidPtrTy};
1367 llvm::FunctionType *FnTy =
1368 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1369 RTLFn =
1370 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1371 break;
1372 }
1373 case OMPRTL__kmpc_omp_task_complete_if0: {
1374 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1375 // *new_task);
1376 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1377 CGM.VoidPtrTy};
1378 llvm::FunctionType *FnTy =
1379 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1380 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1381 /*Name=*/"__kmpc_omp_task_complete_if0");
1382 break;
1383 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001384 case OMPRTL__kmpc_ordered: {
1385 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1386 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1387 llvm::FunctionType *FnTy =
1388 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1389 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1390 break;
1391 }
1392 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001393 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001394 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1395 llvm::FunctionType *FnTy =
1396 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1397 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1398 break;
1399 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001400 case OMPRTL__kmpc_omp_taskwait: {
1401 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1402 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1403 llvm::FunctionType *FnTy =
1404 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1405 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1406 break;
1407 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001408 case OMPRTL__kmpc_taskgroup: {
1409 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1410 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1411 llvm::FunctionType *FnTy =
1412 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1413 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1414 break;
1415 }
1416 case OMPRTL__kmpc_end_taskgroup: {
1417 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1418 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1419 llvm::FunctionType *FnTy =
1420 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1421 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1422 break;
1423 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001424 case OMPRTL__kmpc_push_proc_bind: {
1425 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1426 // int proc_bind)
1427 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1428 llvm::FunctionType *FnTy =
1429 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1430 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1431 break;
1432 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001433 case OMPRTL__kmpc_omp_task_with_deps: {
1434 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1435 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1436 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1437 llvm::Type *TypeParams[] = {
1438 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1439 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1440 llvm::FunctionType *FnTy =
1441 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1442 RTLFn =
1443 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1444 break;
1445 }
1446 case OMPRTL__kmpc_omp_wait_deps: {
1447 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1448 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1449 // kmp_depend_info_t *noalias_dep_list);
1450 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1451 CGM.Int32Ty, CGM.VoidPtrTy,
1452 CGM.Int32Ty, CGM.VoidPtrTy};
1453 llvm::FunctionType *FnTy =
1454 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1455 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1456 break;
1457 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001458 case OMPRTL__kmpc_cancellationpoint: {
1459 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1460 // global_tid, kmp_int32 cncl_kind)
1461 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1462 llvm::FunctionType *FnTy =
1463 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1464 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1465 break;
1466 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001467 case OMPRTL__kmpc_cancel: {
1468 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1469 // kmp_int32 cncl_kind)
1470 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1471 llvm::FunctionType *FnTy =
1472 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1473 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1474 break;
1475 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001476 case OMPRTL__kmpc_push_num_teams: {
1477 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1478 // kmp_int32 num_teams, kmp_int32 num_threads)
1479 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1480 CGM.Int32Ty};
1481 llvm::FunctionType *FnTy =
1482 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1483 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1484 break;
1485 }
1486 case OMPRTL__kmpc_fork_teams: {
1487 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1488 // microtask, ...);
1489 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1490 getKmpc_MicroPointerTy()};
1491 llvm::FunctionType *FnTy =
1492 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1493 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1494 break;
1495 }
Alexey Bataev7292c292016-04-25 12:22:29 +00001496 case OMPRTL__kmpc_taskloop: {
1497 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
1498 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
1499 // sched, kmp_uint64 grainsize, void *task_dup);
1500 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1501 CGM.IntTy,
1502 CGM.VoidPtrTy,
1503 CGM.IntTy,
1504 CGM.Int64Ty->getPointerTo(),
1505 CGM.Int64Ty->getPointerTo(),
1506 CGM.Int64Ty,
1507 CGM.IntTy,
1508 CGM.IntTy,
1509 CGM.Int64Ty,
1510 CGM.VoidPtrTy};
1511 llvm::FunctionType *FnTy =
1512 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1513 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
1514 break;
1515 }
Alexey Bataev8b427062016-05-25 12:36:08 +00001516 case OMPRTL__kmpc_doacross_init: {
1517 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
1518 // num_dims, struct kmp_dim *dims);
1519 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1520 CGM.Int32Ty,
1521 CGM.Int32Ty,
1522 CGM.VoidPtrTy};
1523 llvm::FunctionType *FnTy =
1524 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1525 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
1526 break;
1527 }
1528 case OMPRTL__kmpc_doacross_fini: {
1529 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
1530 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1531 llvm::FunctionType *FnTy =
1532 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1533 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
1534 break;
1535 }
1536 case OMPRTL__kmpc_doacross_post: {
1537 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
1538 // *vec);
1539 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1540 CGM.Int64Ty->getPointerTo()};
1541 llvm::FunctionType *FnTy =
1542 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1543 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
1544 break;
1545 }
1546 case OMPRTL__kmpc_doacross_wait: {
1547 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
1548 // *vec);
1549 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1550 CGM.Int64Ty->getPointerTo()};
1551 llvm::FunctionType *FnTy =
1552 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1553 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
1554 break;
1555 }
Samuel Antaobed3c462015-10-02 16:14:20 +00001556 case OMPRTL__tgt_target: {
1557 // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
1558 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
1559 // *arg_types);
1560 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1561 CGM.VoidPtrTy,
1562 CGM.Int32Ty,
1563 CGM.VoidPtrPtrTy,
1564 CGM.VoidPtrPtrTy,
1565 CGM.SizeTy->getPointerTo(),
1566 CGM.Int32Ty->getPointerTo()};
1567 llvm::FunctionType *FnTy =
1568 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1569 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
1570 break;
1571 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00001572 case OMPRTL__tgt_target_teams: {
1573 // Build int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
1574 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
1575 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
1576 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1577 CGM.VoidPtrTy,
1578 CGM.Int32Ty,
1579 CGM.VoidPtrPtrTy,
1580 CGM.VoidPtrPtrTy,
1581 CGM.SizeTy->getPointerTo(),
1582 CGM.Int32Ty->getPointerTo(),
1583 CGM.Int32Ty,
1584 CGM.Int32Ty};
1585 llvm::FunctionType *FnTy =
1586 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1587 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
1588 break;
1589 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00001590 case OMPRTL__tgt_register_lib: {
1591 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
1592 QualType ParamTy =
1593 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1594 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1595 llvm::FunctionType *FnTy =
1596 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1597 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
1598 break;
1599 }
1600 case OMPRTL__tgt_unregister_lib: {
1601 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
1602 QualType ParamTy =
1603 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1604 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1605 llvm::FunctionType *FnTy =
1606 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1607 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
1608 break;
1609 }
Samuel Antaodf158d52016-04-27 22:58:19 +00001610 case OMPRTL__tgt_target_data_begin: {
1611 // Build void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
1612 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1613 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1614 CGM.Int32Ty,
1615 CGM.VoidPtrPtrTy,
1616 CGM.VoidPtrPtrTy,
1617 CGM.SizeTy->getPointerTo(),
1618 CGM.Int32Ty->getPointerTo()};
1619 llvm::FunctionType *FnTy =
1620 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1621 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
1622 break;
1623 }
1624 case OMPRTL__tgt_target_data_end: {
1625 // Build void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
1626 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1627 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1628 CGM.Int32Ty,
1629 CGM.VoidPtrPtrTy,
1630 CGM.VoidPtrPtrTy,
1631 CGM.SizeTy->getPointerTo(),
1632 CGM.Int32Ty->getPointerTo()};
1633 llvm::FunctionType *FnTy =
1634 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1635 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
1636 break;
1637 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00001638 case OMPRTL__tgt_target_data_update: {
1639 // Build void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
1640 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1641 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1642 CGM.Int32Ty,
1643 CGM.VoidPtrPtrTy,
1644 CGM.VoidPtrPtrTy,
1645 CGM.SizeTy->getPointerTo(),
1646 CGM.Int32Ty->getPointerTo()};
1647 llvm::FunctionType *FnTy =
1648 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1649 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
1650 break;
1651 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001652 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00001653 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00001654 return RTLFn;
1655}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001656
Alexander Musman21212e42015-03-13 10:38:23 +00001657llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
1658 bool IVSigned) {
1659 assert((IVSize == 32 || IVSize == 64) &&
1660 "IV size is not compatible with the omp runtime");
1661 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
1662 : "__kmpc_for_static_init_4u")
1663 : (IVSigned ? "__kmpc_for_static_init_8"
1664 : "__kmpc_for_static_init_8u");
1665 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1666 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1667 llvm::Type *TypeParams[] = {
1668 getIdentTyPointerTy(), // loc
1669 CGM.Int32Ty, // tid
1670 CGM.Int32Ty, // schedtype
1671 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1672 PtrTy, // p_lower
1673 PtrTy, // p_upper
1674 PtrTy, // p_stride
1675 ITy, // incr
1676 ITy // chunk
1677 };
1678 llvm::FunctionType *FnTy =
1679 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1680 return CGM.CreateRuntimeFunction(FnTy, Name);
1681}
1682
Alexander Musman92bdaab2015-03-12 13:37:50 +00001683llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
1684 bool IVSigned) {
1685 assert((IVSize == 32 || IVSize == 64) &&
1686 "IV size is not compatible with the omp runtime");
1687 auto Name =
1688 IVSize == 32
1689 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
1690 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
1691 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1692 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
1693 CGM.Int32Ty, // tid
1694 CGM.Int32Ty, // schedtype
1695 ITy, // lower
1696 ITy, // upper
1697 ITy, // stride
1698 ITy // chunk
1699 };
1700 llvm::FunctionType *FnTy =
1701 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1702 return CGM.CreateRuntimeFunction(FnTy, Name);
1703}
1704
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001705llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
1706 bool IVSigned) {
1707 assert((IVSize == 32 || IVSize == 64) &&
1708 "IV size is not compatible with the omp runtime");
1709 auto Name =
1710 IVSize == 32
1711 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
1712 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
1713 llvm::Type *TypeParams[] = {
1714 getIdentTyPointerTy(), // loc
1715 CGM.Int32Ty, // tid
1716 };
1717 llvm::FunctionType *FnTy =
1718 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1719 return CGM.CreateRuntimeFunction(FnTy, Name);
1720}
1721
Alexander Musman92bdaab2015-03-12 13:37:50 +00001722llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
1723 bool IVSigned) {
1724 assert((IVSize == 32 || IVSize == 64) &&
1725 "IV size is not compatible with the omp runtime");
1726 auto Name =
1727 IVSize == 32
1728 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
1729 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
1730 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1731 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1732 llvm::Type *TypeParams[] = {
1733 getIdentTyPointerTy(), // loc
1734 CGM.Int32Ty, // tid
1735 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1736 PtrTy, // p_lower
1737 PtrTy, // p_upper
1738 PtrTy // p_stride
1739 };
1740 llvm::FunctionType *FnTy =
1741 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1742 return CGM.CreateRuntimeFunction(FnTy, Name);
1743}
1744
Alexey Bataev97720002014-11-11 04:05:39 +00001745llvm::Constant *
1746CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001747 assert(!CGM.getLangOpts().OpenMPUseTLS ||
1748 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00001749 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001750 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001751 Twine(CGM.getMangledName(VD)) + ".cache.");
1752}
1753
John McCall7f416cc2015-09-08 08:05:57 +00001754Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
1755 const VarDecl *VD,
1756 Address VDAddr,
1757 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001758 if (CGM.getLangOpts().OpenMPUseTLS &&
1759 CGM.getContext().getTargetInfo().isTLSSupported())
1760 return VDAddr;
1761
John McCall7f416cc2015-09-08 08:05:57 +00001762 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001763 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00001764 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1765 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001766 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
1767 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00001768 return Address(CGF.EmitRuntimeCall(
1769 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
1770 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00001771}
1772
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001773void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00001774 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00001775 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
1776 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
1777 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001778 auto OMPLoc = emitUpdateLocation(CGF, Loc);
1779 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00001780 OMPLoc);
1781 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
1782 // to register constructor/destructor for variable.
1783 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00001784 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1785 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001786 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001787 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001788 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001789}
1790
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001791llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00001792 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00001793 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001794 if (CGM.getLangOpts().OpenMPUseTLS &&
1795 CGM.getContext().getTargetInfo().isTLSSupported())
1796 return nullptr;
1797
Alexey Bataev97720002014-11-11 04:05:39 +00001798 VD = VD->getDefinition(CGM.getContext());
1799 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
1800 ThreadPrivateWithDefinition.insert(VD);
1801 QualType ASTTy = VD->getType();
1802
1803 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
1804 auto Init = VD->getAnyInitializer();
1805 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
1806 // Generate function that re-emits the declaration's initializer into the
1807 // threadprivate copy of the variable VD
1808 CodeGenFunction CtorCGF(CGM);
1809 FunctionArgList Args;
1810 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1811 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1812 Args.push_back(&Dst);
1813
John McCallc56a8b32016-03-11 04:30:31 +00001814 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1815 CGM.getContext().VoidPtrTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001816 auto FTy = CGM.getTypes().GetFunctionType(FI);
1817 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001818 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001819 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
1820 Args, SourceLocation());
1821 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001822 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001823 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001824 Address Arg = Address(ArgVal, VDAddr.getAlignment());
1825 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
1826 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00001827 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
1828 /*IsInitializer=*/true);
1829 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001830 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001831 CGM.getContext().VoidPtrTy, Dst.getLocation());
1832 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
1833 CtorCGF.FinishFunction();
1834 Ctor = Fn;
1835 }
1836 if (VD->getType().isDestructedType() != QualType::DK_none) {
1837 // Generate function that emits destructor call for the threadprivate copy
1838 // of the variable VD
1839 CodeGenFunction DtorCGF(CGM);
1840 FunctionArgList Args;
1841 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1842 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1843 Args.push_back(&Dst);
1844
John McCallc56a8b32016-03-11 04:30:31 +00001845 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1846 CGM.getContext().VoidTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001847 auto FTy = CGM.getTypes().GetFunctionType(FI);
1848 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001849 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00001850 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00001851 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
1852 SourceLocation());
Adrian Prantl1858c662016-04-24 22:22:29 +00001853 // Create a scope with an artificial location for the body of this function.
1854 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00001855 auto ArgVal = DtorCGF.EmitLoadOfScalar(
1856 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00001857 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
1858 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001859 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
1860 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
1861 DtorCGF.FinishFunction();
1862 Dtor = Fn;
1863 }
1864 // Do not emit init function if it is not required.
1865 if (!Ctor && !Dtor)
1866 return nullptr;
1867
1868 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1869 auto CopyCtorTy =
1870 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
1871 /*isVarArg=*/false)->getPointerTo();
1872 // Copying constructor for the threadprivate variable.
1873 // Must be NULL - reserved by runtime, but currently it requires that this
1874 // parameter is always NULL. Otherwise it fires assertion.
1875 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
1876 if (Ctor == nullptr) {
1877 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1878 /*isVarArg=*/false)->getPointerTo();
1879 Ctor = llvm::Constant::getNullValue(CtorTy);
1880 }
1881 if (Dtor == nullptr) {
1882 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
1883 /*isVarArg=*/false)->getPointerTo();
1884 Dtor = llvm::Constant::getNullValue(DtorTy);
1885 }
1886 if (!CGF) {
1887 auto InitFunctionTy =
1888 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
1889 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001890 InitFunctionTy, ".__omp_threadprivate_init_.",
1891 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00001892 CodeGenFunction InitCGF(CGM);
1893 FunctionArgList ArgList;
1894 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
1895 CGM.getTypes().arrangeNullaryFunction(), ArgList,
1896 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001897 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001898 InitCGF.FinishFunction();
1899 return InitFunction;
1900 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001901 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001902 }
1903 return nullptr;
1904}
1905
Alexey Bataev1d677132015-04-22 13:57:31 +00001906/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
1907/// function. Here is the logic:
1908/// if (Cond) {
1909/// ThenGen();
1910/// } else {
1911/// ElseGen();
1912/// }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001913void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
1914 const RegionCodeGenTy &ThenGen,
1915 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001916 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
1917
1918 // If the condition constant folds and can be elided, try to avoid emitting
1919 // the condition and the dead arm of the if/else.
1920 bool CondConstant;
1921 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001922 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00001923 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001924 else
Alexey Bataev1d677132015-04-22 13:57:31 +00001925 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001926 return;
1927 }
1928
1929 // Otherwise, the condition did not fold, or we couldn't elide it. Just
1930 // emit the conditional branch.
1931 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
1932 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
1933 auto ContBlock = CGF.createBasicBlock("omp_if.end");
1934 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
1935
1936 // Emit the 'then' code.
1937 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001938 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001939 CGF.EmitBranch(ContBlock);
1940 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001941 // There is no need to emit line number for unconditional branch.
1942 (void)ApplyDebugLocation::CreateEmpty(CGF);
1943 CGF.EmitBlock(ElseBlock);
1944 ElseGen(CGF);
1945 // There is no need to emit line number for unconditional branch.
1946 (void)ApplyDebugLocation::CreateEmpty(CGF);
1947 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00001948 // Emit the continuation block for code after the if.
1949 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001950}
1951
Alexey Bataev1d677132015-04-22 13:57:31 +00001952void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
1953 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001954 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00001955 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001956 if (!CGF.HaveInsertPoint())
1957 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00001958 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001959 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
1960 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001961 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001962 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00001963 llvm::Value *Args[] = {
1964 RTLoc,
1965 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001966 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00001967 llvm::SmallVector<llvm::Value *, 16> RealArgs;
1968 RealArgs.append(std::begin(Args), std::end(Args));
1969 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
1970
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001971 auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001972 CGF.EmitRuntimeCall(RTLFn, RealArgs);
1973 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001974 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
1975 PrePostActionTy &) {
1976 auto &RT = CGF.CGM.getOpenMPRuntime();
1977 auto ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00001978 // Build calls:
1979 // __kmpc_serialized_parallel(&Loc, GTid);
1980 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001981 CGF.EmitRuntimeCall(
1982 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001983
Alexey Bataev1d677132015-04-22 13:57:31 +00001984 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001985 auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00001986 Address ZeroAddr =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001987 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
1988 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00001989 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00001990 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
1991 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
1992 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1993 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev1d677132015-04-22 13:57:31 +00001994 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001995
Alexey Bataev1d677132015-04-22 13:57:31 +00001996 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001997 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00001998 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001999 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2000 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002001 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002002 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00002003 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002004 else {
2005 RegionCodeGenTy ThenRCG(ThenGen);
2006 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002007 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002008}
2009
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002010// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002011// thread-ID variable (it is passed in a first argument of the outlined function
2012// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2013// regular serial code region, get thread ID by calling kmp_int32
2014// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2015// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002016Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2017 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002018 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002019 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002020 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002021 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002022
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002023 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002024 auto Int32Ty =
2025 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2026 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2027 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002028 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002029
2030 return ThreadIDTemp;
2031}
2032
Alexey Bataev97720002014-11-11 04:05:39 +00002033llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002034CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002035 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002036 SmallString<256> Buffer;
2037 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002038 Out << Name;
2039 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00002040 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
2041 if (Elem.second) {
2042 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002043 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002044 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002045 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002046
David Blaikie13156b62014-11-19 03:06:06 +00002047 return Elem.second = new llvm::GlobalVariable(
2048 CGM.getModule(), Ty, /*IsConstant*/ false,
2049 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2050 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002051}
2052
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002053llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00002054 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002055 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002056}
2057
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002058namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002059/// Common pre(post)-action for different OpenMP constructs.
2060class CommonActionTy final : public PrePostActionTy {
2061 llvm::Value *EnterCallee;
2062 ArrayRef<llvm::Value *> EnterArgs;
2063 llvm::Value *ExitCallee;
2064 ArrayRef<llvm::Value *> ExitArgs;
2065 bool Conditional;
2066 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002067
2068public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002069 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2070 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2071 bool Conditional = false)
2072 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2073 ExitArgs(ExitArgs), Conditional(Conditional) {}
2074 void Enter(CodeGenFunction &CGF) override {
2075 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2076 if (Conditional) {
2077 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2078 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2079 ContBlock = CGF.createBasicBlock("omp_if.end");
2080 // Generate the branch (If-stmt)
2081 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2082 CGF.EmitBlock(ThenBlock);
2083 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002084 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002085 void Done(CodeGenFunction &CGF) {
2086 // Emit the rest of blocks/branches
2087 CGF.EmitBranch(ContBlock);
2088 CGF.EmitBlock(ContBlock, true);
2089 }
2090 void Exit(CodeGenFunction &CGF) override {
2091 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002092 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002093};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002094} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002095
2096void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2097 StringRef CriticalName,
2098 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002099 SourceLocation Loc, const Expr *Hint) {
2100 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002101 // CriticalOpGen();
2102 // __kmpc_end_critical(ident_t *, gtid, Lock);
2103 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002104 if (!CGF.HaveInsertPoint())
2105 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002106 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2107 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002108 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2109 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002110 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002111 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2112 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2113 }
2114 CommonActionTy Action(
2115 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2116 : OMPRTL__kmpc_critical),
2117 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2118 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002119 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002120}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002121
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002122void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002123 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002124 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002125 if (!CGF.HaveInsertPoint())
2126 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002127 // if(__kmpc_master(ident_t *, gtid)) {
2128 // MasterOpGen();
2129 // __kmpc_end_master(ident_t *, gtid);
2130 // }
2131 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002132 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002133 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2134 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2135 /*Conditional=*/true);
2136 MasterOpGen.setAction(Action);
2137 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2138 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002139}
2140
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002141void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2142 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002143 if (!CGF.HaveInsertPoint())
2144 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00002145 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2146 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002147 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00002148 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002149 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002150 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2151 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00002152}
2153
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002154void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2155 const RegionCodeGenTy &TaskgroupOpGen,
2156 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002157 if (!CGF.HaveInsertPoint())
2158 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002159 // __kmpc_taskgroup(ident_t *, gtid);
2160 // TaskgroupOpGen();
2161 // __kmpc_end_taskgroup(ident_t *, gtid);
2162 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002163 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2164 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2165 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2166 Args);
2167 TaskgroupOpGen.setAction(Action);
2168 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002169}
2170
John McCall7f416cc2015-09-08 08:05:57 +00002171/// Given an array of pointers to variables, project the address of a
2172/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002173static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2174 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00002175 // Pull out the pointer to the variable.
2176 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002177 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00002178 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2179
2180 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002181 Addr = CGF.Builder.CreateElementBitCast(
2182 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002183 return Addr;
2184}
2185
Alexey Bataeva63048e2015-03-23 06:18:07 +00002186static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00002187 CodeGenModule &CGM, llvm::Type *ArgsType,
2188 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
2189 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002190 auto &C = CGM.getContext();
2191 // void copy_func(void *LHSArg, void *RHSArg);
2192 FunctionArgList Args;
2193 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2194 C.VoidPtrTy);
2195 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2196 C.VoidPtrTy);
2197 Args.push_back(&LHSArg);
2198 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00002199 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002200 auto *Fn = llvm::Function::Create(
2201 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2202 ".omp.copyprivate.copy_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002203 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002204 CodeGenFunction CGF(CGM);
2205 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00002206 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002207 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00002208 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2209 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2210 ArgsType), CGF.getPointerAlign());
2211 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2212 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2213 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002214 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2215 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2216 // ...
2217 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00002218 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002219 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2220 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2221
2222 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2223 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2224
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002225 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2226 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00002227 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002228 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002229 CGF.FinishFunction();
2230 return Fn;
2231}
2232
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002233void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002234 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00002235 SourceLocation Loc,
2236 ArrayRef<const Expr *> CopyprivateVars,
2237 ArrayRef<const Expr *> SrcExprs,
2238 ArrayRef<const Expr *> DstExprs,
2239 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002240 if (!CGF.HaveInsertPoint())
2241 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002242 assert(CopyprivateVars.size() == SrcExprs.size() &&
2243 CopyprivateVars.size() == DstExprs.size() &&
2244 CopyprivateVars.size() == AssignmentOps.size());
2245 auto &C = CGM.getContext();
2246 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002247 // if(__kmpc_single(ident_t *, gtid)) {
2248 // SingleOpGen();
2249 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002250 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002251 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002252 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2253 // <copy_func>, did_it);
2254
John McCall7f416cc2015-09-08 08:05:57 +00002255 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00002256 if (!CopyprivateVars.empty()) {
2257 // int32 did_it = 0;
2258 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2259 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00002260 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002261 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002262 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002263 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002264 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
2265 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
2266 /*Conditional=*/true);
2267 SingleOpGen.setAction(Action);
2268 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2269 if (DidIt.isValid()) {
2270 // did_it = 1;
2271 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2272 }
2273 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002274 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2275 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00002276 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002277 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2278 auto CopyprivateArrayTy =
2279 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2280 /*IndexTypeQuals=*/0);
2281 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00002282 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00002283 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2284 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002285 Address Elem = CGF.Builder.CreateConstArrayGEP(
2286 CopyprivateList, I, CGF.getPointerSize());
2287 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00002288 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002289 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2290 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002291 }
2292 // Build function that copies private values from single region to all other
2293 // threads in the corresponding parallel region.
2294 auto *CpyFn = emitCopyprivateCopyFunction(
2295 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00002296 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev1189bd02016-01-26 12:20:39 +00002297 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00002298 Address CL =
2299 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2300 CGF.VoidPtrTy);
2301 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002302 llvm::Value *Args[] = {
2303 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2304 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00002305 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00002306 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00002307 CpyFn, // void (*) (void *, void *) <copy_func>
2308 DidItVal // i32 did_it
2309 };
2310 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2311 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002312}
2313
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002314void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2315 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00002316 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002317 if (!CGF.HaveInsertPoint())
2318 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002319 // __kmpc_ordered(ident_t *, gtid);
2320 // OrderedOpGen();
2321 // __kmpc_end_ordered(ident_t *, gtid);
2322 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00002323 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002324 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002325 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
2326 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2327 Args);
2328 OrderedOpGen.setAction(Action);
2329 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2330 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002331 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002332 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002333}
2334
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002335void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002336 OpenMPDirectiveKind Kind, bool EmitChecks,
2337 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002338 if (!CGF.HaveInsertPoint())
2339 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002340 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002341 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002342 unsigned Flags;
2343 if (Kind == OMPD_for)
2344 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2345 else if (Kind == OMPD_sections)
2346 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2347 else if (Kind == OMPD_single)
2348 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2349 else if (Kind == OMPD_barrier)
2350 Flags = OMP_IDENT_BARRIER_EXPL;
2351 else
2352 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002353 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2354 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002355 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2356 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002357 if (auto *OMPRegionInfo =
2358 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00002359 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002360 auto *Result = CGF.EmitRuntimeCall(
2361 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002362 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002363 // if (__kmpc_cancel_barrier()) {
2364 // exit from construct;
2365 // }
2366 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2367 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2368 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2369 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2370 CGF.EmitBlock(ExitBB);
2371 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002372 auto CancelDestination =
2373 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002374 CGF.EmitBranchThroughCleanup(CancelDestination);
2375 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2376 }
2377 return;
2378 }
2379 }
2380 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002381}
2382
Alexander Musmanc6388682014-12-15 07:07:06 +00002383/// \brief Map the OpenMP loop schedule to the runtime enumeration.
2384static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002385 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002386 switch (ScheduleKind) {
2387 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002388 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2389 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00002390 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002391 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002392 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002393 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002394 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002395 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2396 case OMPC_SCHEDULE_auto:
2397 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00002398 case OMPC_SCHEDULE_unknown:
2399 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002400 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00002401 }
2402 llvm_unreachable("Unexpected runtime schedule");
2403}
2404
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002405/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
2406static OpenMPSchedType
2407getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2408 // only static is allowed for dist_schedule
2409 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
2410}
2411
Alexander Musmanc6388682014-12-15 07:07:06 +00002412bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2413 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002414 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00002415 return Schedule == OMP_sch_static;
2416}
2417
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002418bool CGOpenMPRuntime::isStaticNonchunked(
2419 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2420 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2421 return Schedule == OMP_dist_sch_static;
2422}
2423
2424
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002425bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002426 auto Schedule =
2427 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002428 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2429 return Schedule != OMP_sch_static;
2430}
2431
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002432static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
2433 OpenMPScheduleClauseModifier M1,
2434 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00002435 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002436 switch (M1) {
2437 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002438 Modifier = OMP_sch_modifier_monotonic;
2439 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002440 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002441 Modifier = OMP_sch_modifier_nonmonotonic;
2442 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002443 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002444 if (Schedule == OMP_sch_static_chunked)
2445 Schedule = OMP_sch_static_balanced_chunked;
2446 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002447 case OMPC_SCHEDULE_MODIFIER_last:
2448 case OMPC_SCHEDULE_MODIFIER_unknown:
2449 break;
2450 }
2451 switch (M2) {
2452 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002453 Modifier = OMP_sch_modifier_monotonic;
2454 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002455 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002456 Modifier = OMP_sch_modifier_nonmonotonic;
2457 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002458 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002459 if (Schedule == OMP_sch_static_chunked)
2460 Schedule = OMP_sch_static_balanced_chunked;
2461 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002462 case OMPC_SCHEDULE_MODIFIER_last:
2463 case OMPC_SCHEDULE_MODIFIER_unknown:
2464 break;
2465 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00002466 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002467}
2468
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002469void CGOpenMPRuntime::emitForDispatchInit(
2470 CodeGenFunction &CGF, SourceLocation Loc,
2471 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
2472 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002473 if (!CGF.HaveInsertPoint())
2474 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002475 OpenMPSchedType Schedule = getRuntimeSchedule(
2476 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00002477 assert(Ordered ||
2478 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00002479 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
2480 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00002481 // Call __kmpc_dispatch_init(
2482 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2483 // kmp_int[32|64] lower, kmp_int[32|64] upper,
2484 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002485
John McCall7f416cc2015-09-08 08:05:57 +00002486 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002487 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
2488 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00002489 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002490 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2491 CGF.Builder.getInt32(addMonoNonMonoModifier(
2492 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002493 DispatchValues.LB, // Lower
2494 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002495 CGF.Builder.getIntN(IVSize, 1), // Stride
2496 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00002497 };
2498 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2499}
2500
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002501static void emitForStaticInitCall(
2502 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
2503 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
2504 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
2505 unsigned IVSize, bool Ordered, Address IL, Address LB, Address UB,
2506 Address ST, llvm::Value *Chunk) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002507 if (!CGF.HaveInsertPoint())
2508 return;
2509
2510 assert(!Ordered);
2511 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
Alexey Bataev6cff6242016-05-30 13:05:14 +00002512 Schedule == OMP_sch_static_balanced_chunked ||
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002513 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
2514 Schedule == OMP_dist_sch_static ||
2515 Schedule == OMP_dist_sch_static_chunked);
2516
2517 // Call __kmpc_for_static_init(
2518 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2519 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2520 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2521 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
2522 if (Chunk == nullptr) {
2523 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
2524 Schedule == OMP_dist_sch_static) &&
2525 "expected static non-chunked schedule");
2526 // If the Chunk was not specified in the clause - use default value 1.
2527 Chunk = CGF.Builder.getIntN(IVSize, 1);
2528 } else {
2529 assert((Schedule == OMP_sch_static_chunked ||
Alexey Bataev6cff6242016-05-30 13:05:14 +00002530 Schedule == OMP_sch_static_balanced_chunked ||
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002531 Schedule == OMP_ord_static_chunked ||
2532 Schedule == OMP_dist_sch_static_chunked) &&
2533 "expected static chunked schedule");
2534 }
2535 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002536 UpdateLocation, ThreadId, CGF.Builder.getInt32(addMonoNonMonoModifier(
2537 Schedule, M1, M2)), // Schedule type
2538 IL.getPointer(), // &isLastIter
2539 LB.getPointer(), // &LB
2540 UB.getPointer(), // &UB
2541 ST.getPointer(), // &Stride
2542 CGF.Builder.getIntN(IVSize, 1), // Incr
2543 Chunk // Chunk
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002544 };
2545 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
2546}
2547
John McCall7f416cc2015-09-08 08:05:57 +00002548void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
2549 SourceLocation Loc,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002550 const OpenMPScheduleTy &ScheduleKind,
John McCall7f416cc2015-09-08 08:05:57 +00002551 unsigned IVSize, bool IVSigned,
2552 bool Ordered, Address IL, Address LB,
2553 Address UB, Address ST,
2554 llvm::Value *Chunk) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002555 OpenMPSchedType ScheduleNum =
2556 getRuntimeSchedule(ScheduleKind.Schedule, Chunk != nullptr, Ordered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002557 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2558 auto *ThreadId = getThreadID(CGF, Loc);
2559 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002560 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
2561 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, IVSize,
2562 Ordered, IL, LB, UB, ST, Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002563}
John McCall7f416cc2015-09-08 08:05:57 +00002564
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002565void CGOpenMPRuntime::emitDistributeStaticInit(
2566 CodeGenFunction &CGF, SourceLocation Loc,
2567 OpenMPDistScheduleClauseKind SchedKind, unsigned IVSize, bool IVSigned,
2568 bool Ordered, Address IL, Address LB, Address UB, Address ST,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002569 llvm::Value *Chunk) {
2570 OpenMPSchedType ScheduleNum = getRuntimeSchedule(SchedKind, Chunk != nullptr);
2571 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2572 auto *ThreadId = getThreadID(CGF, Loc);
2573 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002574 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
2575 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
2576 OMPC_SCHEDULE_MODIFIER_unknown, IVSize, Ordered, IL, LB,
2577 UB, ST, Chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002578}
2579
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002580void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
2581 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002582 if (!CGF.HaveInsertPoint())
2583 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00002584 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002585 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002586 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
2587 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00002588}
2589
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002590void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
2591 SourceLocation Loc,
2592 unsigned IVSize,
2593 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002594 if (!CGF.HaveInsertPoint())
2595 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002596 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002597 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002598 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
2599}
2600
Alexander Musman92bdaab2015-03-12 13:37:50 +00002601llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
2602 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00002603 bool IVSigned, Address IL,
2604 Address LB, Address UB,
2605 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00002606 // Call __kmpc_dispatch_next(
2607 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
2608 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
2609 // kmp_int[32|64] *p_stride);
2610 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00002611 emitUpdateLocation(CGF, Loc),
2612 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002613 IL.getPointer(), // &isLastIter
2614 LB.getPointer(), // &Lower
2615 UB.getPointer(), // &Upper
2616 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00002617 };
2618 llvm::Value *Call =
2619 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
2620 return CGF.EmitScalarConversion(
2621 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002622 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002623}
2624
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002625void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
2626 llvm::Value *NumThreads,
2627 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002628 if (!CGF.HaveInsertPoint())
2629 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00002630 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
2631 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002632 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00002633 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002634 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
2635 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00002636}
2637
Alexey Bataev7f210c62015-06-18 13:40:03 +00002638void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
2639 OpenMPProcBindClauseKind ProcBind,
2640 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002641 if (!CGF.HaveInsertPoint())
2642 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00002643 // Constants for proc bind value accepted by the runtime.
2644 enum ProcBindTy {
2645 ProcBindFalse = 0,
2646 ProcBindTrue,
2647 ProcBindMaster,
2648 ProcBindClose,
2649 ProcBindSpread,
2650 ProcBindIntel,
2651 ProcBindDefault
2652 } RuntimeProcBind;
2653 switch (ProcBind) {
2654 case OMPC_PROC_BIND_master:
2655 RuntimeProcBind = ProcBindMaster;
2656 break;
2657 case OMPC_PROC_BIND_close:
2658 RuntimeProcBind = ProcBindClose;
2659 break;
2660 case OMPC_PROC_BIND_spread:
2661 RuntimeProcBind = ProcBindSpread;
2662 break;
2663 case OMPC_PROC_BIND_unknown:
2664 llvm_unreachable("Unsupported proc_bind value.");
2665 }
2666 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
2667 llvm::Value *Args[] = {
2668 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2669 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
2670 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
2671}
2672
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002673void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
2674 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002675 if (!CGF.HaveInsertPoint())
2676 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00002677 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002678 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
2679 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002680}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002681
Alexey Bataev62b63b12015-03-10 07:28:44 +00002682namespace {
2683/// \brief Indexes of fields for type kmp_task_t.
2684enum KmpTaskTFields {
2685 /// \brief List of shared variables.
2686 KmpTaskTShareds,
2687 /// \brief Task routine.
2688 KmpTaskTRoutine,
2689 /// \brief Partition id for the untied tasks.
2690 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00002691 /// Function with call of destructors for private variables.
2692 Data1,
2693 /// Task priority.
2694 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00002695 /// (Taskloops only) Lower bound.
2696 KmpTaskTLowerBound,
2697 /// (Taskloops only) Upper bound.
2698 KmpTaskTUpperBound,
2699 /// (Taskloops only) Stride.
2700 KmpTaskTStride,
2701 /// (Taskloops only) Is last iteration flag.
2702 KmpTaskTLastIter,
Alexey Bataev62b63b12015-03-10 07:28:44 +00002703};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002704} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00002705
Samuel Antaoee8fb302016-01-06 13:42:12 +00002706bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
2707 // FIXME: Add other entries type when they become supported.
2708 return OffloadEntriesTargetRegion.empty();
2709}
2710
2711/// \brief Initialize target region entry.
2712void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2713 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2714 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00002715 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002716 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
2717 "only required for the device "
2718 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00002719 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00002720 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
2721 /*Flags=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002722 ++OffloadingEntriesNum;
2723}
2724
2725void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2726 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2727 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00002728 llvm::Constant *Addr, llvm::Constant *ID,
2729 int32_t Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002730 // If we are emitting code for a target, the entry is already initialized,
2731 // only has to be registered.
2732 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00002733 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00002734 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00002735 auto &Entry =
2736 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00002737 assert(Entry.isValid() && "Entry not initialized!");
2738 Entry.setAddress(Addr);
2739 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00002740 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002741 return;
2742 } else {
Samuel Antaof83efdb2017-01-05 16:02:49 +00002743 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00002744 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002745 }
2746}
2747
2748bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00002749 unsigned DeviceID, unsigned FileID, StringRef ParentName,
2750 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002751 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
2752 if (PerDevice == OffloadEntriesTargetRegion.end())
2753 return false;
2754 auto PerFile = PerDevice->second.find(FileID);
2755 if (PerFile == PerDevice->second.end())
2756 return false;
2757 auto PerParentName = PerFile->second.find(ParentName);
2758 if (PerParentName == PerFile->second.end())
2759 return false;
2760 auto PerLine = PerParentName->second.find(LineNum);
2761 if (PerLine == PerParentName->second.end())
2762 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002763 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00002764 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00002765 return false;
2766 return true;
2767}
2768
2769void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
2770 const OffloadTargetRegionEntryInfoActTy &Action) {
2771 // Scan all target region entries and perform the provided action.
2772 for (auto &D : OffloadEntriesTargetRegion)
2773 for (auto &F : D.second)
2774 for (auto &P : F.second)
2775 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00002776 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002777}
2778
2779/// \brief Create a Ctor/Dtor-like function whose body is emitted through
2780/// \a Codegen. This is used to emit the two functions that register and
2781/// unregister the descriptor of the current compilation unit.
2782static llvm::Function *
2783createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
2784 const RegionCodeGenTy &Codegen) {
2785 auto &C = CGM.getContext();
2786 FunctionArgList Args;
2787 ImplicitParamDecl DummyPtr(C, /*DC=*/nullptr, SourceLocation(),
2788 /*Id=*/nullptr, C.VoidPtrTy);
2789 Args.push_back(&DummyPtr);
2790
2791 CodeGenFunction CGF(CGM);
John McCallc56a8b32016-03-11 04:30:31 +00002792 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002793 auto FTy = CGM.getTypes().GetFunctionType(FI);
2794 auto *Fn =
2795 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
2796 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
2797 Codegen(CGF);
2798 CGF.FinishFunction();
2799 return Fn;
2800}
2801
2802llvm::Function *
2803CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
2804
2805 // If we don't have entries or if we are emitting code for the device, we
2806 // don't need to do anything.
2807 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
2808 return nullptr;
2809
2810 auto &M = CGM.getModule();
2811 auto &C = CGM.getContext();
2812
2813 // Get list of devices we care about
2814 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
2815
2816 // We should be creating an offloading descriptor only if there are devices
2817 // specified.
2818 assert(!Devices.empty() && "No OpenMP offloading devices??");
2819
2820 // Create the external variables that will point to the begin and end of the
2821 // host entries section. These will be defined by the linker.
2822 auto *OffloadEntryTy =
2823 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
2824 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
2825 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002826 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002827 ".omp_offloading.entries_begin");
2828 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
2829 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002830 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002831 ".omp_offloading.entries_end");
2832
2833 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00002834 auto *DeviceImageTy = cast<llvm::StructType>(
2835 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00002836 ConstantInitBuilder DeviceImagesBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002837 auto DeviceImagesEntries = DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002838
2839 for (unsigned i = 0; i < Devices.size(); ++i) {
2840 StringRef T = Devices[i].getTriple();
2841 auto *ImgBegin = new llvm::GlobalVariable(
2842 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002843 /*Initializer=*/nullptr,
2844 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002845 auto *ImgEnd = new llvm::GlobalVariable(
2846 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002847 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002848
John McCall6c9f1fdb2016-11-19 08:17:24 +00002849 auto Dev = DeviceImagesEntries.beginStruct(DeviceImageTy);
2850 Dev.add(ImgBegin);
2851 Dev.add(ImgEnd);
2852 Dev.add(HostEntriesBegin);
2853 Dev.add(HostEntriesEnd);
John McCallf1788632016-11-28 22:18:30 +00002854 Dev.finishAndAddTo(DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002855 }
2856
2857 // Create device images global array.
John McCall6c9f1fdb2016-11-19 08:17:24 +00002858 llvm::GlobalVariable *DeviceImages =
2859 DeviceImagesEntries.finishAndCreateGlobal(".omp_offloading.device_images",
2860 CGM.getPointerAlign(),
2861 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002862 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002863
2864 // This is a Zero array to be used in the creation of the constant expressions
2865 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
2866 llvm::Constant::getNullValue(CGM.Int32Ty)};
2867
2868 // Create the target region descriptor.
2869 auto *BinaryDescriptorTy = cast<llvm::StructType>(
2870 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00002871 ConstantInitBuilder DescBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002872 auto DescInit = DescBuilder.beginStruct(BinaryDescriptorTy);
2873 DescInit.addInt(CGM.Int32Ty, Devices.size());
2874 DescInit.add(llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
2875 DeviceImages,
2876 Index));
2877 DescInit.add(HostEntriesBegin);
2878 DescInit.add(HostEntriesEnd);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002879
John McCall6c9f1fdb2016-11-19 08:17:24 +00002880 auto *Desc = DescInit.finishAndCreateGlobal(".omp_offloading.descriptor",
2881 CGM.getPointerAlign(),
2882 /*isConstant=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002883
2884 // Emit code to register or unregister the descriptor at execution
2885 // startup or closing, respectively.
2886
2887 // Create a variable to drive the registration and unregistration of the
2888 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
2889 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
2890 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
2891 IdentInfo, C.CharTy);
2892
2893 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002894 CGM, ".omp_offloading.descriptor_unreg",
2895 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002896 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
2897 Desc);
2898 });
2899 auto *RegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002900 CGM, ".omp_offloading.descriptor_reg",
2901 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002902 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_register_lib),
2903 Desc);
2904 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
2905 });
George Rokos29d0f002017-05-27 03:03:13 +00002906 if (CGM.supportsCOMDAT()) {
2907 // It is sufficient to call registration function only once, so create a
2908 // COMDAT group for registration/unregistration functions and associated
2909 // data. That would reduce startup time and code size. Registration
2910 // function serves as a COMDAT group key.
2911 auto ComdatKey = M.getOrInsertComdat(RegFn->getName());
2912 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
2913 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
2914 RegFn->setComdat(ComdatKey);
2915 UnRegFn->setComdat(ComdatKey);
2916 DeviceImages->setComdat(ComdatKey);
2917 Desc->setComdat(ComdatKey);
2918 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002919 return RegFn;
2920}
2921
Samuel Antao2de62b02016-02-13 23:35:10 +00002922void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
Samuel Antaof83efdb2017-01-05 16:02:49 +00002923 llvm::Constant *Addr, uint64_t Size,
2924 int32_t Flags) {
Samuel Antao2de62b02016-02-13 23:35:10 +00002925 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00002926 auto *TgtOffloadEntryType = cast<llvm::StructType>(
2927 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
2928 llvm::LLVMContext &C = CGM.getModule().getContext();
2929 llvm::Module &M = CGM.getModule();
2930
2931 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00002932 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002933
2934 // Create constant string with the name.
2935 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
2936
2937 llvm::GlobalVariable *Str =
2938 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
2939 llvm::GlobalValue::InternalLinkage, StrPtrInit,
2940 ".omp_offloading.entry_name");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002941 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002942 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
2943
John McCall6c9f1fdb2016-11-19 08:17:24 +00002944 // We can't have any padding between symbols, so we need to have 1-byte
2945 // alignment.
2946 auto Align = CharUnits::fromQuantity(1);
2947
Samuel Antaoee8fb302016-01-06 13:42:12 +00002948 // Create the entry struct.
John McCall23c9dc62016-11-28 22:18:27 +00002949 ConstantInitBuilder EntryBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002950 auto EntryInit = EntryBuilder.beginStruct(TgtOffloadEntryType);
2951 EntryInit.add(AddrPtr);
2952 EntryInit.add(StrPtr);
2953 EntryInit.addInt(CGM.SizeTy, Size);
Samuel Antaof83efdb2017-01-05 16:02:49 +00002954 EntryInit.addInt(CGM.Int32Ty, Flags);
2955 EntryInit.addInt(CGM.Int32Ty, 0);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002956 llvm::GlobalVariable *Entry =
2957 EntryInit.finishAndCreateGlobal(".omp_offloading.entry",
2958 Align,
2959 /*constant*/ true,
2960 llvm::GlobalValue::ExternalLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002961
2962 // The entry has to be created in the section the linker expects it to be.
2963 Entry->setSection(".omp_offloading.entries");
Samuel Antaoee8fb302016-01-06 13:42:12 +00002964}
2965
2966void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
2967 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00002968 // can easily figure out what to emit. The produced metadata looks like
2969 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00002970 //
2971 // !omp_offload.info = !{!1, ...}
2972 //
2973 // Right now we only generate metadata for function that contain target
2974 // regions.
2975
2976 // If we do not have entries, we dont need to do anything.
2977 if (OffloadEntriesInfoManager.empty())
2978 return;
2979
2980 llvm::Module &M = CGM.getModule();
2981 llvm::LLVMContext &C = M.getContext();
2982 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
2983 OrderedEntries(OffloadEntriesInfoManager.size());
2984
2985 // Create the offloading info metadata node.
2986 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
2987
Simon Pilgrim2c518802017-03-30 14:13:19 +00002988 // Auxiliary methods to create metadata values and strings.
Samuel Antaoee8fb302016-01-06 13:42:12 +00002989 auto getMDInt = [&](unsigned v) {
2990 return llvm::ConstantAsMetadata::get(
2991 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
2992 };
2993
2994 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
2995
2996 // Create function that emits metadata for each target region entry;
2997 auto &&TargetRegionMetadataEmitter = [&](
2998 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002999 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3000 llvm::SmallVector<llvm::Metadata *, 32> Ops;
3001 // Generate metadata for target regions. Each entry of this metadata
3002 // contains:
3003 // - Entry 0 -> Kind of this type of metadata (0).
3004 // - Entry 1 -> Device ID of the file where the entry was identified.
3005 // - Entry 2 -> File ID of the file where the entry was identified.
3006 // - Entry 3 -> Mangled name of the function where the entry was identified.
3007 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00003008 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003009 // The first element of the metadata node is the kind.
3010 Ops.push_back(getMDInt(E.getKind()));
3011 Ops.push_back(getMDInt(DeviceID));
3012 Ops.push_back(getMDInt(FileID));
3013 Ops.push_back(getMDString(ParentName));
3014 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003015 Ops.push_back(getMDInt(E.getOrder()));
3016
3017 // Save this entry in the right position of the ordered entries array.
3018 OrderedEntries[E.getOrder()] = &E;
3019
3020 // Add metadata to the named metadata node.
3021 MD->addOperand(llvm::MDNode::get(C, Ops));
3022 };
3023
3024 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3025 TargetRegionMetadataEmitter);
3026
3027 for (auto *E : OrderedEntries) {
3028 assert(E && "All ordered entries must exist!");
3029 if (auto *CE =
3030 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3031 E)) {
3032 assert(CE->getID() && CE->getAddress() &&
3033 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00003034 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003035 } else
3036 llvm_unreachable("Unsupported entry kind.");
3037 }
3038}
3039
3040/// \brief Loads all the offload entries information from the host IR
3041/// metadata.
3042void CGOpenMPRuntime::loadOffloadInfoMetadata() {
3043 // If we are in target mode, load the metadata from the host IR. This code has
3044 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
3045
3046 if (!CGM.getLangOpts().OpenMPIsDevice)
3047 return;
3048
3049 if (CGM.getLangOpts().OMPHostIRFile.empty())
3050 return;
3051
3052 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
3053 if (Buf.getError())
3054 return;
3055
3056 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00003057 auto ME = expectedToErrorOrAndEmitErrors(
3058 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003059
3060 if (ME.getError())
3061 return;
3062
3063 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
3064 if (!MD)
3065 return;
3066
3067 for (auto I : MD->operands()) {
3068 llvm::MDNode *MN = cast<llvm::MDNode>(I);
3069
3070 auto getMDInt = [&](unsigned Idx) {
3071 llvm::ConstantAsMetadata *V =
3072 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
3073 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
3074 };
3075
3076 auto getMDString = [&](unsigned Idx) {
3077 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
3078 return V->getString();
3079 };
3080
3081 switch (getMDInt(0)) {
3082 default:
3083 llvm_unreachable("Unexpected metadata!");
3084 break;
3085 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3086 OFFLOAD_ENTRY_INFO_TARGET_REGION:
3087 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
3088 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
3089 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00003090 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003091 break;
3092 }
3093 }
3094}
3095
Alexey Bataev62b63b12015-03-10 07:28:44 +00003096void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
3097 if (!KmpRoutineEntryPtrTy) {
3098 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
3099 auto &C = CGM.getContext();
3100 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
3101 FunctionProtoType::ExtProtoInfo EPI;
3102 KmpRoutineEntryPtrQTy = C.getPointerType(
3103 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
3104 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
3105 }
3106}
3107
Alexey Bataevc71a4092015-09-11 10:29:41 +00003108static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
3109 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003110 auto *Field = FieldDecl::Create(
3111 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
3112 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
3113 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
3114 Field->setAccess(AS_public);
3115 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003116 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003117}
3118
Samuel Antaoee8fb302016-01-06 13:42:12 +00003119QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
3120
3121 // Make sure the type of the entry is already created. This is the type we
3122 // have to create:
3123 // struct __tgt_offload_entry{
3124 // void *addr; // Pointer to the offload entry info.
3125 // // (function or global)
3126 // char *name; // Name of the function or global.
3127 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00003128 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
3129 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003130 // };
3131 if (TgtOffloadEntryQTy.isNull()) {
3132 ASTContext &C = CGM.getContext();
3133 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
3134 RD->startDefinition();
3135 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3136 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
3137 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00003138 addFieldToRecordDecl(
3139 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3140 addFieldToRecordDecl(
3141 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003142 RD->completeDefinition();
3143 TgtOffloadEntryQTy = C.getRecordType(RD);
3144 }
3145 return TgtOffloadEntryQTy;
3146}
3147
3148QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
3149 // These are the types we need to build:
3150 // struct __tgt_device_image{
3151 // void *ImageStart; // Pointer to the target code start.
3152 // void *ImageEnd; // Pointer to the target code end.
3153 // // We also add the host entries to the device image, as it may be useful
3154 // // for the target runtime to have access to that information.
3155 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
3156 // // the entries.
3157 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3158 // // entries (non inclusive).
3159 // };
3160 if (TgtDeviceImageQTy.isNull()) {
3161 ASTContext &C = CGM.getContext();
3162 auto *RD = C.buildImplicitRecord("__tgt_device_image");
3163 RD->startDefinition();
3164 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3165 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3166 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3167 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3168 RD->completeDefinition();
3169 TgtDeviceImageQTy = C.getRecordType(RD);
3170 }
3171 return TgtDeviceImageQTy;
3172}
3173
3174QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
3175 // struct __tgt_bin_desc{
3176 // int32_t NumDevices; // Number of devices supported.
3177 // __tgt_device_image *DeviceImages; // Arrays of device images
3178 // // (one per device).
3179 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
3180 // // entries.
3181 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3182 // // entries (non inclusive).
3183 // };
3184 if (TgtBinaryDescriptorQTy.isNull()) {
3185 ASTContext &C = CGM.getContext();
3186 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
3187 RD->startDefinition();
3188 addFieldToRecordDecl(
3189 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3190 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
3191 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3192 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3193 RD->completeDefinition();
3194 TgtBinaryDescriptorQTy = C.getRecordType(RD);
3195 }
3196 return TgtBinaryDescriptorQTy;
3197}
3198
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003199namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00003200struct PrivateHelpersTy {
3201 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
3202 const VarDecl *PrivateElemInit)
3203 : Original(Original), PrivateCopy(PrivateCopy),
3204 PrivateElemInit(PrivateElemInit) {}
3205 const VarDecl *Original;
3206 const VarDecl *PrivateCopy;
3207 const VarDecl *PrivateElemInit;
3208};
3209typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00003210} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003211
Alexey Bataev9e034042015-05-05 04:05:12 +00003212static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00003213createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003214 if (!Privates.empty()) {
3215 auto &C = CGM.getContext();
3216 // Build struct .kmp_privates_t. {
3217 // /* private vars */
3218 // };
3219 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
3220 RD->startDefinition();
3221 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00003222 auto *VD = Pair.second.Original;
3223 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003224 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00003225 auto *FD = addFieldToRecordDecl(C, RD, Type);
3226 if (VD->hasAttrs()) {
3227 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
3228 E(VD->getAttrs().end());
3229 I != E; ++I)
3230 FD->addAttr(*I);
3231 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003232 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003233 RD->completeDefinition();
3234 return RD;
3235 }
3236 return nullptr;
3237}
3238
Alexey Bataev9e034042015-05-05 04:05:12 +00003239static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00003240createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
3241 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003242 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003243 auto &C = CGM.getContext();
3244 // Build struct kmp_task_t {
3245 // void * shareds;
3246 // kmp_routine_entry_t routine;
3247 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00003248 // kmp_cmplrdata_t data1;
3249 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00003250 // For taskloops additional fields:
3251 // kmp_uint64 lb;
3252 // kmp_uint64 ub;
3253 // kmp_int64 st;
3254 // kmp_int32 liter;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003255 // };
Alexey Bataevad537bb2016-05-30 09:06:50 +00003256 auto *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
3257 UD->startDefinition();
3258 addFieldToRecordDecl(C, UD, KmpInt32Ty);
3259 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
3260 UD->completeDefinition();
3261 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003262 auto *RD = C.buildImplicitRecord("kmp_task_t");
3263 RD->startDefinition();
3264 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3265 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
3266 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00003267 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3268 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003269 if (isOpenMPTaskLoopDirective(Kind)) {
3270 QualType KmpUInt64Ty =
3271 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3272 QualType KmpInt64Ty =
3273 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3274 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3275 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3276 addFieldToRecordDecl(C, RD, KmpInt64Ty);
3277 addFieldToRecordDecl(C, RD, KmpInt32Ty);
3278 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003279 RD->completeDefinition();
3280 return RD;
3281}
3282
3283static RecordDecl *
3284createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003285 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003286 auto &C = CGM.getContext();
3287 // Build struct kmp_task_t_with_privates {
3288 // kmp_task_t task_data;
3289 // .kmp_privates_t. privates;
3290 // };
3291 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
3292 RD->startDefinition();
3293 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003294 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
3295 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
3296 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003297 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003298 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003299}
3300
3301/// \brief Emit a proxy function which accepts kmp_task_t as the second
3302/// argument.
3303/// \code
3304/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003305/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00003306/// For taskloops:
3307/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003308/// tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003309/// return 0;
3310/// }
3311/// \endcode
3312static llvm::Value *
3313emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00003314 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
3315 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003316 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003317 QualType SharedsPtrTy, llvm::Value *TaskFunction,
3318 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003319 auto &C = CGM.getContext();
3320 FunctionArgList Args;
3321 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
3322 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00003323 /*Id=*/nullptr,
3324 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003325 Args.push_back(&GtidArg);
3326 Args.push_back(&TaskTypeArg);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003327 auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003328 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003329 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
3330 auto *TaskEntry =
3331 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
3332 ".omp_task_entry.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003333 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003334 CodeGenFunction CGF(CGM);
3335 CGF.disableDebugInfo();
3336 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
3337
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003338 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00003339 // tt,
3340 // For taskloops:
3341 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3342 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003343 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00003344 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003345 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3346 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3347 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003348 auto *KmpTaskTWithPrivatesQTyRD =
3349 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003350 LValue Base =
3351 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003352 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3353 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3354 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003355 auto *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003356
3357 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3358 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003359 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003360 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003361 CGF.ConvertTypeForMem(SharedsPtrTy));
3362
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003363 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3364 llvm::Value *PrivatesParam;
3365 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3366 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3367 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003368 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003369 } else
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003370 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003371
Alexey Bataev7292c292016-04-25 12:22:29 +00003372 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
3373 TaskPrivatesMap,
3374 CGF.Builder
3375 .CreatePointerBitCastOrAddrSpaceCast(
3376 TDBase.getAddress(), CGF.VoidPtrTy)
3377 .getPointer()};
3378 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
3379 std::end(CommonArgs));
3380 if (isOpenMPTaskLoopDirective(Kind)) {
3381 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
3382 auto LBLVal = CGF.EmitLValueForField(Base, *LBFI);
3383 auto *LBParam = CGF.EmitLoadOfLValue(LBLVal, Loc).getScalarVal();
3384 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
3385 auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
3386 auto *UBParam = CGF.EmitLoadOfLValue(UBLVal, Loc).getScalarVal();
3387 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
3388 auto StLVal = CGF.EmitLValueForField(Base, *StFI);
3389 auto *StParam = CGF.EmitLoadOfLValue(StLVal, Loc).getScalarVal();
3390 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3391 auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
3392 auto *LIParam = CGF.EmitLoadOfLValue(LILVal, Loc).getScalarVal();
3393 CallArgs.push_back(LBParam);
3394 CallArgs.push_back(UBParam);
3395 CallArgs.push_back(StParam);
3396 CallArgs.push_back(LIParam);
3397 }
3398 CallArgs.push_back(SharedsParam);
3399
Alexey Bataev62b63b12015-03-10 07:28:44 +00003400 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
3401 CGF.EmitStoreThroughLValue(
3402 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00003403 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00003404 CGF.FinishFunction();
3405 return TaskEntry;
3406}
3407
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003408static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
3409 SourceLocation Loc,
3410 QualType KmpInt32Ty,
3411 QualType KmpTaskTWithPrivatesPtrQTy,
3412 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003413 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003414 FunctionArgList Args;
3415 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
3416 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00003417 /*Id=*/nullptr,
3418 KmpTaskTWithPrivatesPtrQTy.withRestrict());
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,
3474 C.getPointerType(PrivatesQTy).withConst().withRestrict());
3475 Args.push_back(&TaskPrivatesArg);
3476 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
3477 unsigned Counter = 1;
3478 for (auto *E: PrivateVars) {
3479 Args.push_back(ImplicitParamDecl::Create(
3480 C, /*DC=*/nullptr, Loc,
3481 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3482 .withConst()
3483 .withRestrict()));
3484 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3485 PrivateVarsPos[VD] = Counter;
3486 ++Counter;
3487 }
3488 for (auto *E : FirstprivateVars) {
3489 Args.push_back(ImplicitParamDecl::Create(
3490 C, /*DC=*/nullptr, Loc,
3491 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3492 .withConst()
3493 .withRestrict()));
3494 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3495 PrivateVarsPos[VD] = Counter;
3496 ++Counter;
3497 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003498 for (auto *E: LastprivateVars) {
3499 Args.push_back(ImplicitParamDecl::Create(
3500 C, /*DC=*/nullptr, Loc,
3501 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3502 .withConst()
3503 .withRestrict()));
3504 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3505 PrivateVarsPos[VD] = Counter;
3506 ++Counter;
3507 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003508 auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003509 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003510 auto *TaskPrivatesMapTy =
3511 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
3512 auto *TaskPrivatesMap = llvm::Function::Create(
3513 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
3514 ".omp_task_privates_map.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003515 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
3516 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00003517 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00003518 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003519 CodeGenFunction CGF(CGM);
3520 CGF.disableDebugInfo();
3521 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
3522 TaskPrivatesMapFnInfo, Args);
3523
3524 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003525 LValue Base = CGF.EmitLoadOfPointerLValue(
3526 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
3527 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003528 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
3529 Counter = 0;
3530 for (auto *Field : PrivatesQTyRD->fields()) {
3531 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
3532 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00003533 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00003534 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
3535 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00003536 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003537 ++Counter;
3538 }
3539 CGF.FinishFunction();
3540 return TaskPrivatesMap;
3541}
3542
Alexey Bataev9e034042015-05-05 04:05:12 +00003543static int array_pod_sort_comparator(const PrivateDataTy *P1,
3544 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003545 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
3546}
3547
Alexey Bataevf93095a2016-05-05 08:46:22 +00003548/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00003549static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00003550 const OMPExecutableDirective &D,
3551 Address KmpTaskSharedsPtr, LValue TDBase,
3552 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
3553 QualType SharedsTy, QualType SharedsPtrTy,
3554 const OMPTaskDataTy &Data,
3555 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
3556 auto &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00003557 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3558 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
3559 LValue SrcBase;
3560 if (!Data.FirstprivateVars.empty()) {
3561 SrcBase = CGF.MakeAddrLValue(
3562 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3563 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
3564 SharedsTy);
3565 }
3566 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
3567 cast<CapturedStmt>(*D.getAssociatedStmt()));
3568 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
3569 for (auto &&Pair : Privates) {
3570 auto *VD = Pair.second.PrivateCopy;
3571 auto *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00003572 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
3573 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00003574 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003575 if (auto *Elem = Pair.second.PrivateElemInit) {
3576 auto *OriginalVD = Pair.second.Original;
3577 auto *SharedField = CapturesInfo.lookup(OriginalVD);
3578 auto SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
3579 SharedRefLValue = CGF.MakeAddrLValue(
3580 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003581 SharedRefLValue.getType(),
3582 LValueBaseInfo(AlignmentSource::Decl,
3583 SharedRefLValue.getBaseInfo().getMayAlias()));
Alexey Bataevf93095a2016-05-05 08:46:22 +00003584 QualType Type = OriginalVD->getType();
3585 if (Type->isArrayType()) {
3586 // Initialize firstprivate array.
3587 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
3588 // Perform simple memcpy.
3589 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
3590 SharedRefLValue.getAddress(), Type);
3591 } else {
3592 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00003593 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00003594 CGF.EmitOMPAggregateAssign(
3595 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
3596 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
3597 Address SrcElement) {
3598 // Clean up any temporaries needed by the initialization.
3599 CodeGenFunction::OMPPrivateScope InitScope(CGF);
3600 InitScope.addPrivate(
3601 Elem, [SrcElement]() -> Address { return SrcElement; });
3602 (void)InitScope.Privatize();
3603 // Emit initialization for single element.
3604 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
3605 CGF, &CapturesInfo);
3606 CGF.EmitAnyExprToMem(Init, DestElement,
3607 Init->getType().getQualifiers(),
3608 /*IsInitializer=*/false);
3609 });
3610 }
3611 } else {
3612 CodeGenFunction::OMPPrivateScope InitScope(CGF);
3613 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
3614 return SharedRefLValue.getAddress();
3615 });
3616 (void)InitScope.Privatize();
3617 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
3618 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
3619 /*capturedByInit=*/false);
3620 }
3621 } else
3622 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
3623 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003624 ++FI;
3625 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003626}
3627
3628/// Check if duplication function is required for taskloops.
3629static bool checkInitIsRequired(CodeGenFunction &CGF,
3630 ArrayRef<PrivateDataTy> Privates) {
3631 bool InitRequired = false;
3632 for (auto &&Pair : Privates) {
3633 auto *VD = Pair.second.PrivateCopy;
3634 auto *Init = VD->getAnyInitializer();
3635 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
3636 !CGF.isTrivialInitializer(Init));
3637 }
3638 return InitRequired;
3639}
3640
3641
3642/// Emit task_dup function (for initialization of
3643/// private/firstprivate/lastprivate vars and last_iter flag)
3644/// \code
3645/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
3646/// lastpriv) {
3647/// // setup lastprivate flag
3648/// task_dst->last = lastpriv;
3649/// // could be constructor calls here...
3650/// }
3651/// \endcode
3652static llvm::Value *
3653emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
3654 const OMPExecutableDirective &D,
3655 QualType KmpTaskTWithPrivatesPtrQTy,
3656 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
3657 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
3658 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
3659 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
3660 auto &C = CGM.getContext();
3661 FunctionArgList Args;
3662 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc,
3663 /*Id=*/nullptr, KmpTaskTWithPrivatesPtrQTy);
3664 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc,
3665 /*Id=*/nullptr, KmpTaskTWithPrivatesPtrQTy);
3666 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc,
3667 /*Id=*/nullptr, C.IntTy);
3668 Args.push_back(&DstArg);
3669 Args.push_back(&SrcArg);
3670 Args.push_back(&LastprivArg);
3671 auto &TaskDupFnInfo =
3672 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3673 auto *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
3674 auto *TaskDup =
3675 llvm::Function::Create(TaskDupTy, llvm::GlobalValue::InternalLinkage,
3676 ".omp_task_dup.", &CGM.getModule());
3677 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskDup, TaskDupFnInfo);
3678 CodeGenFunction CGF(CGM);
3679 CGF.disableDebugInfo();
3680 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args);
3681
3682 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3683 CGF.GetAddrOfLocalVar(&DstArg),
3684 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3685 // task_dst->liter = lastpriv;
3686 if (WithLastIter) {
3687 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3688 LValue Base = CGF.EmitLValueForField(
3689 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
3690 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
3691 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
3692 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
3693 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
3694 }
3695
3696 // Emit initial values for private copies (if any).
3697 assert(!Privates.empty());
3698 Address KmpTaskSharedsPtr = Address::invalid();
3699 if (!Data.FirstprivateVars.empty()) {
3700 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3701 CGF.GetAddrOfLocalVar(&SrcArg),
3702 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3703 LValue Base = CGF.EmitLValueForField(
3704 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
3705 KmpTaskSharedsPtr = Address(
3706 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
3707 Base, *std::next(KmpTaskTQTyRD->field_begin(),
3708 KmpTaskTShareds)),
3709 Loc),
3710 CGF.getNaturalTypeAlignment(SharedsTy));
3711 }
Alexey Bataev8a831592016-05-10 10:36:51 +00003712 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
3713 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003714 CGF.FinishFunction();
3715 return TaskDup;
3716}
3717
Alexey Bataev8a831592016-05-10 10:36:51 +00003718/// Checks if destructor function is required to be generated.
3719/// \return true if cleanups are required, false otherwise.
3720static bool
3721checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
3722 bool NeedsCleanup = false;
3723 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3724 auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
3725 for (auto *FD : PrivateRD->fields()) {
3726 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
3727 if (NeedsCleanup)
3728 break;
3729 }
3730 return NeedsCleanup;
3731}
3732
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003733CGOpenMPRuntime::TaskResultTy
3734CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
3735 const OMPExecutableDirective &D,
3736 llvm::Value *TaskFunction, QualType SharedsTy,
3737 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003738 auto &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00003739 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003740 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003741 auto I = Data.PrivateCopies.begin();
3742 for (auto *E : Data.PrivateVars) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003743 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3744 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00003745 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00003746 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3747 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003748 ++I;
3749 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003750 I = Data.FirstprivateCopies.begin();
3751 auto IElemInitRef = Data.FirstprivateInits.begin();
3752 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003753 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3754 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00003755 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00003756 PrivateHelpersTy(
3757 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3758 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
Richard Trieucc3949d2016-02-18 22:34:54 +00003759 ++I;
3760 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00003761 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003762 I = Data.LastprivateCopies.begin();
3763 for (auto *E : Data.LastprivateVars) {
3764 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3765 Privates.push_back(std::make_pair(
3766 C.getDeclAlign(VD),
3767 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3768 /*PrivateElemInit=*/nullptr)));
3769 ++I;
3770 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003771 llvm::array_pod_sort(Privates.begin(), Privates.end(),
3772 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003773 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
3774 // Build type kmp_routine_entry_t (if not built yet).
3775 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003776 // Build type kmp_task_t (if not built yet).
3777 if (KmpTaskTQTy.isNull()) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003778 KmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
3779 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003780 }
3781 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003782 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003783 auto *KmpTaskTWithPrivatesQTyRD =
3784 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
3785 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
3786 QualType KmpTaskTWithPrivatesPtrQTy =
3787 C.getPointerType(KmpTaskTWithPrivatesQTy);
3788 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
3789 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00003790 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003791 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
3792
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003793 // Emit initial values for private copies (if any).
3794 llvm::Value *TaskPrivatesMap = nullptr;
3795 auto *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00003796 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003797 if (!Privates.empty()) {
3798 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00003799 TaskPrivatesMap = emitTaskPrivateMappingFunction(
3800 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
3801 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003802 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3803 TaskPrivatesMap, TaskPrivatesMapTy);
3804 } else {
3805 TaskPrivatesMap = llvm::ConstantPointerNull::get(
3806 cast<llvm::PointerType>(TaskPrivatesMapTy));
3807 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003808 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
3809 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003810 auto *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00003811 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
3812 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
3813 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003814
3815 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
3816 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
3817 // kmp_routine_entry_t *task_entry);
3818 // Task flags. Format is taken from
3819 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
3820 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00003821 enum {
3822 TiedFlag = 0x1,
3823 FinalFlag = 0x2,
3824 DestructorsFlag = 0x8,
3825 PriorityFlag = 0x20
3826 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003827 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00003828 bool NeedsCleanup = false;
3829 if (!Privates.empty()) {
3830 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
3831 if (NeedsCleanup)
3832 Flags = Flags | DestructorsFlag;
3833 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00003834 if (Data.Priority.getInt())
3835 Flags = Flags | PriorityFlag;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003836 auto *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003837 Data.Final.getPointer()
3838 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00003839 CGF.Builder.getInt32(FinalFlag),
3840 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003841 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003842 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00003843 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003844 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
3845 getThreadID(CGF, Loc), TaskFlags,
3846 KmpTaskTWithPrivatesTySize, SharedsSize,
3847 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3848 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00003849 auto *NewTask = CGF.EmitRuntimeCall(
3850 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003851 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3852 NewTask, KmpTaskTWithPrivatesPtrTy);
3853 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
3854 KmpTaskTWithPrivatesQTy);
3855 LValue TDBase =
3856 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003857 // Fill the data in the resulting kmp_task_t record.
3858 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00003859 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003860 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00003861 KmpTaskSharedsPtr =
3862 Address(CGF.EmitLoadOfScalar(
3863 CGF.EmitLValueForField(
3864 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
3865 KmpTaskTShareds)),
3866 Loc),
3867 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003868 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003869 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003870 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00003871 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003872 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00003873 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
3874 SharedsTy, SharedsPtrTy, Data, Privates,
3875 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003876 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
3877 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
3878 Result.TaskDupFn = emitTaskDupFunction(
3879 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
3880 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
3881 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003882 }
3883 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00003884 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
3885 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00003886 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00003887 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
3888 auto *KmpCmplrdataUD = (*FI)->getType()->getAsUnionType()->getDecl();
3889 if (NeedsCleanup) {
3890 llvm::Value *DestructorFn = emitDestructorsFunction(
3891 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
3892 KmpTaskTWithPrivatesQTy);
3893 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
3894 LValue DestructorsLV = CGF.EmitLValueForField(
3895 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
3896 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3897 DestructorFn, KmpRoutineEntryPtrTy),
3898 DestructorsLV);
3899 }
3900 // Set priority.
3901 if (Data.Priority.getInt()) {
3902 LValue Data2LV = CGF.EmitLValueForField(
3903 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
3904 LValue PriorityLV = CGF.EmitLValueForField(
3905 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
3906 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
3907 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003908 Result.NewTask = NewTask;
3909 Result.TaskEntry = TaskEntry;
3910 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
3911 Result.TDBase = TDBase;
3912 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
3913 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00003914}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003915
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003916void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
3917 const OMPExecutableDirective &D,
3918 llvm::Value *TaskFunction,
3919 QualType SharedsTy, Address Shareds,
3920 const Expr *IfCond,
3921 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003922 if (!CGF.HaveInsertPoint())
3923 return;
3924
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003925 TaskResultTy Result =
3926 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
3927 llvm::Value *NewTask = Result.NewTask;
3928 llvm::Value *TaskEntry = Result.TaskEntry;
3929 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
3930 LValue TDBase = Result.TDBase;
3931 RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
Alexey Bataev7292c292016-04-25 12:22:29 +00003932 auto &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003933 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00003934 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003935 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00003936 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003937 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00003938 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003939 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
3940 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003941 QualType FlagsTy =
3942 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003943 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
3944 if (KmpDependInfoTy.isNull()) {
3945 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
3946 KmpDependInfoRD->startDefinition();
3947 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
3948 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
3949 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
3950 KmpDependInfoRD->completeDefinition();
3951 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003952 } else
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003953 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003954 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003955 // Define type kmp_depend_info[<Dependences.size()>];
3956 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00003957 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003958 ArrayType::Normal, /*IndexTypeQuals=*/0);
3959 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00003960 DependenciesArray =
3961 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
John McCall7f416cc2015-09-08 08:05:57 +00003962 for (unsigned i = 0; i < NumDependencies; ++i) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003963 const Expr *E = Data.Dependences[i].second;
John McCall7f416cc2015-09-08 08:05:57 +00003964 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003965 llvm::Value *Size;
3966 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003967 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
3968 LValue UpAddrLVal =
3969 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
3970 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00003971 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003972 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00003973 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003974 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
3975 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003976 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00003977 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003978 auto Base = CGF.MakeAddrLValue(
3979 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003980 KmpDependInfoTy);
3981 // deps[i].base_addr = &<Dependences[i].second>;
3982 auto BaseAddrLVal = CGF.EmitLValueForField(
3983 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00003984 CGF.EmitStoreOfScalar(
3985 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
3986 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003987 // deps[i].len = sizeof(<Dependences[i].second>);
3988 auto LenLVal = CGF.EmitLValueForField(
3989 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
3990 CGF.EmitStoreOfScalar(Size, LenLVal);
3991 // deps[i].flags = <Dependences[i].first>;
3992 RTLDependenceKindTy DepKind;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003993 switch (Data.Dependences[i].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003994 case OMPC_DEPEND_in:
3995 DepKind = DepIn;
3996 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00003997 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003998 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003999 case OMPC_DEPEND_inout:
4000 DepKind = DepInOut;
4001 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00004002 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004003 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004004 case OMPC_DEPEND_unknown:
4005 llvm_unreachable("Unknown task dependence type");
4006 }
4007 auto FlagsLVal = CGF.EmitLValueForField(
4008 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
4009 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
4010 FlagsLVal);
4011 }
John McCall7f416cc2015-09-08 08:05:57 +00004012 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4013 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004014 CGF.VoidPtrTy);
4015 }
4016
Alexey Bataev62b63b12015-03-10 07:28:44 +00004017 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4018 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004019 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
4020 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
4021 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
4022 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00004023 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004024 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00004025 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
4026 llvm::Value *DepTaskArgs[7];
4027 if (NumDependencies) {
4028 DepTaskArgs[0] = UpLoc;
4029 DepTaskArgs[1] = ThreadID;
4030 DepTaskArgs[2] = NewTask;
4031 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
4032 DepTaskArgs[4] = DependenciesArray.getPointer();
4033 DepTaskArgs[5] = CGF.Builder.getInt32(0);
4034 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4035 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00004036 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
4037 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004038 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004039 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004040 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4041 auto PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
4042 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
4043 }
John McCall7f416cc2015-09-08 08:05:57 +00004044 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004045 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00004046 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00004047 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004048 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00004049 TaskArgs);
4050 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00004051 // Check if parent region is untied and build return for untied task;
4052 if (auto *Region =
4053 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4054 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00004055 };
John McCall7f416cc2015-09-08 08:05:57 +00004056
4057 llvm::Value *DepWaitTaskArgs[6];
4058 if (NumDependencies) {
4059 DepWaitTaskArgs[0] = UpLoc;
4060 DepWaitTaskArgs[1] = ThreadID;
4061 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
4062 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
4063 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
4064 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4065 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004066 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
4067 NumDependencies, &DepWaitTaskArgs](CodeGenFunction &CGF,
4068 PrePostActionTy &) {
4069 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004070 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
4071 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
4072 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
4073 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
4074 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00004075 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004076 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004077 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004078 // Call proxy_task_entry(gtid, new_task);
4079 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy](
4080 CodeGenFunction &CGF, PrePostActionTy &Action) {
4081 Action.Enter(CGF);
4082 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
4083 CGF.EmitCallOrInvoke(TaskEntry, OutlinedFnArgs);
4084 };
4085
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004086 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
4087 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004088 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
4089 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004090 RegionCodeGenTy RCG(CodeGen);
4091 CommonActionTy Action(
4092 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
4093 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
4094 RCG.setAction(Action);
4095 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004096 };
John McCall7f416cc2015-09-08 08:05:57 +00004097
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004098 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00004099 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004100 else {
4101 RegionCodeGenTy ThenRCG(ThenCodeGen);
4102 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00004103 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004104}
4105
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004106void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
4107 const OMPLoopDirective &D,
4108 llvm::Value *TaskFunction,
4109 QualType SharedsTy, Address Shareds,
4110 const Expr *IfCond,
4111 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004112 if (!CGF.HaveInsertPoint())
4113 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004114 TaskResultTy Result =
4115 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004116 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4117 // libcall.
4118 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
4119 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
4120 // sched, kmp_uint64 grainsize, void *task_dup);
4121 llvm::Value *ThreadID = getThreadID(CGF, Loc);
4122 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
4123 llvm::Value *IfVal;
4124 if (IfCond) {
4125 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
4126 /*isSigned=*/true);
4127 } else
4128 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
4129
4130 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004131 Result.TDBase,
4132 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004133 auto *LBVar =
4134 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
4135 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
4136 /*IsInitializer=*/true);
4137 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004138 Result.TDBase,
4139 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004140 auto *UBVar =
4141 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
4142 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
4143 /*IsInitializer=*/true);
4144 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004145 Result.TDBase,
4146 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataev7292c292016-04-25 12:22:29 +00004147 auto *StVar =
4148 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
4149 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
4150 /*IsInitializer=*/true);
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004151 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00004152 llvm::Value *TaskArgs[] = {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004153 UpLoc, ThreadID, Result.NewTask, IfVal, LBLVal.getPointer(),
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004154 UBLVal.getPointer(), CGF.EmitLoadOfScalar(StLVal, SourceLocation()),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004155 llvm::ConstantInt::getSigned(CGF.IntTy, Data.Nogroup ? 1 : 0),
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004156 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004157 CGF.IntTy, Data.Schedule.getPointer()
4158 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004159 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004160 Data.Schedule.getPointer()
4161 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004162 /*isSigned=*/false)
4163 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataevf93095a2016-05-05 08:46:22 +00004164 Result.TaskDupFn
4165 ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Result.TaskDupFn,
4166 CGF.VoidPtrTy)
4167 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00004168 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
4169}
4170
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004171/// \brief Emit reduction operation for each element of array (required for
4172/// array sections) LHS op = RHS.
4173/// \param Type Type of array.
4174/// \param LHSVar Variable on the left side of the reduction operation
4175/// (references element of array in original variable).
4176/// \param RHSVar Variable on the right side of the reduction operation
4177/// (references element of array in original variable).
4178/// \param RedOpGen Generator of reduction operation with use of LHSVar and
4179/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00004180static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004181 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
4182 const VarDecl *RHSVar,
4183 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
4184 const Expr *, const Expr *)> &RedOpGen,
4185 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
4186 const Expr *UpExpr = nullptr) {
4187 // Perform element-by-element initialization.
4188 QualType ElementTy;
4189 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
4190 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
4191
4192 // Drill down to the base element type on both arrays.
4193 auto ArrayTy = Type->getAsArrayTypeUnsafe();
4194 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
4195
4196 auto RHSBegin = RHSAddr.getPointer();
4197 auto LHSBegin = LHSAddr.getPointer();
4198 // Cast from pointer to array type to pointer to single element.
4199 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
4200 // The basic structure here is a while-do loop.
4201 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
4202 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
4203 auto IsEmpty =
4204 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
4205 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
4206
4207 // Enter the loop body, making that address the current address.
4208 auto EntryBB = CGF.Builder.GetInsertBlock();
4209 CGF.EmitBlock(BodyBB);
4210
4211 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
4212
4213 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
4214 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
4215 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
4216 Address RHSElementCurrent =
4217 Address(RHSElementPHI,
4218 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4219
4220 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
4221 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
4222 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
4223 Address LHSElementCurrent =
4224 Address(LHSElementPHI,
4225 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4226
4227 // Emit copy.
4228 CodeGenFunction::OMPPrivateScope Scope(CGF);
4229 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
4230 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
4231 Scope.Privatize();
4232 RedOpGen(CGF, XExpr, EExpr, UpExpr);
4233 Scope.ForceCleanup();
4234
4235 // Shift the address forward by one element.
4236 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
4237 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
4238 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
4239 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
4240 // Check whether we've reached the end.
4241 auto Done =
4242 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
4243 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
4244 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
4245 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
4246
4247 // Done.
4248 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
4249}
4250
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004251/// Emit reduction combiner. If the combiner is a simple expression emit it as
4252/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
4253/// UDR combiner function.
4254static void emitReductionCombiner(CodeGenFunction &CGF,
4255 const Expr *ReductionOp) {
4256 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
4257 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
4258 if (auto *DRE =
4259 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
4260 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
4261 std::pair<llvm::Function *, llvm::Function *> Reduction =
4262 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
4263 RValue Func = RValue::get(Reduction.first);
4264 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
4265 CGF.EmitIgnoredExpr(ReductionOp);
4266 return;
4267 }
4268 CGF.EmitIgnoredExpr(ReductionOp);
4269}
4270
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004271llvm::Value *CGOpenMPRuntime::emitReductionFunction(
4272 CodeGenModule &CGM, llvm::Type *ArgsType, ArrayRef<const Expr *> Privates,
4273 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4274 ArrayRef<const Expr *> ReductionOps) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004275 auto &C = CGM.getContext();
4276
4277 // void reduction_func(void *LHSArg, void *RHSArg);
4278 FunctionArgList Args;
4279 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
4280 C.VoidPtrTy);
4281 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
4282 C.VoidPtrTy);
4283 Args.push_back(&LHSArg);
4284 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00004285 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004286 auto *Fn = llvm::Function::Create(
4287 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
4288 ".omp.reduction.reduction_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004289 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004290 CodeGenFunction CGF(CGM);
4291 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
4292
4293 // Dst = (void*[n])(LHSArg);
4294 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00004295 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4296 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
4297 ArgsType), CGF.getPointerAlign());
4298 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4299 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
4300 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004301
4302 // ...
4303 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
4304 // ...
4305 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004306 auto IPriv = Privates.begin();
4307 unsigned Idx = 0;
4308 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004309 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
4310 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004311 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004312 });
4313 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
4314 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004315 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004316 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004317 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004318 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004319 // Get array size and emit VLA type.
4320 ++Idx;
4321 Address Elem =
4322 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
4323 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004324 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
4325 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004326 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00004327 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004328 CGF.EmitVariablyModifiedType(PrivTy);
4329 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004330 }
4331 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004332 IPriv = Privates.begin();
4333 auto ILHS = LHSExprs.begin();
4334 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004335 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004336 if ((*IPriv)->getType()->isArrayType()) {
4337 // Emit reduction for array section.
4338 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4339 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004340 EmitOMPAggregateReduction(
4341 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4342 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4343 emitReductionCombiner(CGF, E);
4344 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004345 } else
4346 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004347 emitReductionCombiner(CGF, E);
Richard Trieucc3949d2016-02-18 22:34:54 +00004348 ++IPriv;
4349 ++ILHS;
4350 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004351 }
4352 Scope.ForceCleanup();
4353 CGF.FinishFunction();
4354 return Fn;
4355}
4356
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004357void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
4358 const Expr *ReductionOp,
4359 const Expr *PrivateRef,
4360 const DeclRefExpr *LHS,
4361 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004362 if (PrivateRef->getType()->isArrayType()) {
4363 // Emit reduction for array section.
4364 auto *LHSVar = cast<VarDecl>(LHS->getDecl());
4365 auto *RHSVar = cast<VarDecl>(RHS->getDecl());
4366 EmitOMPAggregateReduction(
4367 CGF, PrivateRef->getType(), LHSVar, RHSVar,
4368 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4369 emitReductionCombiner(CGF, ReductionOp);
4370 });
4371 } else
4372 // Emit reduction for array subscript or single variable.
4373 emitReductionCombiner(CGF, ReductionOp);
4374}
4375
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004376void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004377 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004378 ArrayRef<const Expr *> LHSExprs,
4379 ArrayRef<const Expr *> RHSExprs,
4380 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004381 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004382 if (!CGF.HaveInsertPoint())
4383 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004384
4385 bool WithNowait = Options.WithNowait;
4386 bool SimpleReduction = Options.SimpleReduction;
4387
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004388 // Next code should be emitted for reduction:
4389 //
4390 // static kmp_critical_name lock = { 0 };
4391 //
4392 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
4393 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
4394 // ...
4395 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
4396 // *(Type<n>-1*)rhs[<n>-1]);
4397 // }
4398 //
4399 // ...
4400 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
4401 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4402 // RedList, reduce_func, &<lock>)) {
4403 // case 1:
4404 // ...
4405 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4406 // ...
4407 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4408 // break;
4409 // case 2:
4410 // ...
4411 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4412 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00004413 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004414 // break;
4415 // default:;
4416 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004417 //
4418 // if SimpleReduction is true, only the next code is generated:
4419 // ...
4420 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4421 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004422
4423 auto &C = CGM.getContext();
4424
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004425 if (SimpleReduction) {
4426 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004427 auto IPriv = Privates.begin();
4428 auto ILHS = LHSExprs.begin();
4429 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004430 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004431 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4432 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00004433 ++IPriv;
4434 ++ILHS;
4435 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004436 }
4437 return;
4438 }
4439
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004440 // 1. Build a list of reduction variables.
4441 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004442 auto Size = RHSExprs.size();
4443 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00004444 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004445 // Reserve place for array size.
4446 ++Size;
4447 }
4448 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004449 QualType ReductionArrayTy =
4450 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4451 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00004452 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004453 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004454 auto IPriv = Privates.begin();
4455 unsigned Idx = 0;
4456 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004457 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004458 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00004459 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004460 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004461 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4462 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004463 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004464 // Store array size.
4465 ++Idx;
4466 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
4467 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00004468 llvm::Value *Size = CGF.Builder.CreateIntCast(
4469 CGF.getVLASize(
4470 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4471 .first,
4472 CGF.SizeTy, /*isSigned=*/false);
4473 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4474 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004475 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004476 }
4477
4478 // 2. Emit reduce_func().
4479 auto *ReductionFn = emitReductionFunction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004480 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
4481 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004482
4483 // 3. Create static kmp_critical_name lock = { 0 };
4484 auto *Lock = getCriticalRegionLock(".reduction");
4485
4486 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4487 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00004488 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004489 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004490 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
Samuel Antao4c8035b2016-12-12 18:00:20 +00004491 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4492 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004493 llvm::Value *Args[] = {
4494 IdentTLoc, // ident_t *<loc>
4495 ThreadId, // i32 <gtid>
4496 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
4497 ReductionArrayTySize, // size_type sizeof(RedList)
4498 RL, // void *RedList
4499 ReductionFn, // void (*) (void *, void *) <reduce_func>
4500 Lock // kmp_critical_name *&<lock>
4501 };
4502 auto Res = CGF.EmitRuntimeCall(
4503 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
4504 : OMPRTL__kmpc_reduce),
4505 Args);
4506
4507 // 5. Build switch(res)
4508 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
4509 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
4510
4511 // 6. Build case 1:
4512 // ...
4513 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4514 // ...
4515 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4516 // break;
4517 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
4518 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
4519 CGF.EmitBlock(Case1BB);
4520
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004521 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4522 llvm::Value *EndArgs[] = {
4523 IdentTLoc, // ident_t *<loc>
4524 ThreadId, // i32 <gtid>
4525 Lock // kmp_critical_name *&<lock>
4526 };
4527 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
4528 CodeGenFunction &CGF, PrePostActionTy &Action) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004529 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004530 auto IPriv = Privates.begin();
4531 auto ILHS = LHSExprs.begin();
4532 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004533 for (auto *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004534 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4535 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00004536 ++IPriv;
4537 ++ILHS;
4538 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004539 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004540 };
4541 RegionCodeGenTy RCG(CodeGen);
4542 CommonActionTy Action(
4543 nullptr, llvm::None,
4544 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
4545 : OMPRTL__kmpc_end_reduce),
4546 EndArgs);
4547 RCG.setAction(Action);
4548 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004549
4550 CGF.EmitBranch(DefaultBB);
4551
4552 // 7. Build case 2:
4553 // ...
4554 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4555 // ...
4556 // break;
4557 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
4558 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
4559 CGF.EmitBlock(Case2BB);
4560
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004561 auto &&AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs, &ReductionOps](
4562 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004563 auto ILHS = LHSExprs.begin();
4564 auto IRHS = RHSExprs.begin();
4565 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004566 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004567 const Expr *XExpr = nullptr;
4568 const Expr *EExpr = nullptr;
4569 const Expr *UpExpr = nullptr;
4570 BinaryOperatorKind BO = BO_Comma;
4571 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
4572 if (BO->getOpcode() == BO_Assign) {
4573 XExpr = BO->getLHS();
4574 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004575 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004576 }
4577 // Try to emit update expression as a simple atomic.
4578 auto *RHSExpr = UpExpr;
4579 if (RHSExpr) {
4580 // Analyze RHS part of the whole expression.
4581 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
4582 RHSExpr->IgnoreParenImpCasts())) {
4583 // If this is a conditional operator, analyze its condition for
4584 // min/max reduction operator.
4585 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00004586 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004587 if (auto *BORHS =
4588 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
4589 EExpr = BORHS->getRHS();
4590 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004591 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004592 }
4593 if (XExpr) {
4594 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00004595 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004596 Loc](CodeGenFunction &CGF, const Expr *XExpr,
4597 const Expr *EExpr, const Expr *UpExpr) {
4598 LValue X = CGF.EmitLValue(XExpr);
4599 RValue E;
4600 if (EExpr)
4601 E = CGF.EmitAnyExpr(EExpr);
4602 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00004603 X, E, BO, /*IsXLHSInRHSPart=*/true,
4604 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00004605 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004606 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4607 PrivateScope.addPrivate(
4608 VD, [&CGF, VD, XRValue, Loc]() -> Address {
4609 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
4610 CGF.emitOMPSimpleStore(
4611 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
4612 VD->getType().getNonReferenceType(), Loc);
4613 return LHSTemp;
4614 });
4615 (void)PrivateScope.Privatize();
4616 return CGF.EmitAnyExpr(UpExpr);
4617 });
4618 };
4619 if ((*IPriv)->getType()->isArrayType()) {
4620 // Emit atomic reduction for array section.
4621 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
4622 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
4623 AtomicRedGen, XExpr, EExpr, UpExpr);
4624 } else
4625 // Emit atomic reduction for array subscript or single variable.
4626 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
4627 } else {
4628 // Emit as a critical region.
4629 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
4630 const Expr *, const Expr *) {
4631 auto &RT = CGF.CGM.getOpenMPRuntime();
4632 RT.emitCriticalRegion(
4633 CGF, ".atomic_reduction",
4634 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
4635 Action.Enter(CGF);
4636 emitReductionCombiner(CGF, E);
4637 },
4638 Loc);
4639 };
4640 if ((*IPriv)->getType()->isArrayType()) {
4641 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4642 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
4643 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4644 CritRedGen);
4645 } else
4646 CritRedGen(CGF, nullptr, nullptr, nullptr);
4647 }
Richard Trieucc3949d2016-02-18 22:34:54 +00004648 ++ILHS;
4649 ++IRHS;
4650 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004651 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004652 };
4653 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
4654 if (!WithNowait) {
4655 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
4656 llvm::Value *EndArgs[] = {
4657 IdentTLoc, // ident_t *<loc>
4658 ThreadId, // i32 <gtid>
4659 Lock // kmp_critical_name *&<lock>
4660 };
4661 CommonActionTy Action(nullptr, llvm::None,
4662 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
4663 EndArgs);
4664 AtomicRCG.setAction(Action);
4665 AtomicRCG(CGF);
4666 } else
4667 AtomicRCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004668
4669 CGF.EmitBranch(DefaultBB);
4670 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
4671}
4672
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004673void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
4674 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004675 if (!CGF.HaveInsertPoint())
4676 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004677 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
4678 // global_tid);
4679 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
4680 // Ignore return result until untied tasks are supported.
4681 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00004682 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4683 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004684}
4685
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00004686void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004687 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004688 const RegionCodeGenTy &CodeGen,
4689 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004690 if (!CGF.HaveInsertPoint())
4691 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004692 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00004693 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00004694}
4695
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004696namespace {
4697enum RTCancelKind {
4698 CancelNoreq = 0,
4699 CancelParallel = 1,
4700 CancelLoop = 2,
4701 CancelSections = 3,
4702 CancelTaskgroup = 4
4703};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00004704} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004705
4706static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
4707 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00004708 if (CancelRegion == OMPD_parallel)
4709 CancelKind = CancelParallel;
4710 else if (CancelRegion == OMPD_for)
4711 CancelKind = CancelLoop;
4712 else if (CancelRegion == OMPD_sections)
4713 CancelKind = CancelSections;
4714 else {
4715 assert(CancelRegion == OMPD_taskgroup);
4716 CancelKind = CancelTaskgroup;
4717 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004718 return CancelKind;
4719}
4720
4721void CGOpenMPRuntime::emitCancellationPointCall(
4722 CodeGenFunction &CGF, SourceLocation Loc,
4723 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004724 if (!CGF.HaveInsertPoint())
4725 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004726 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
4727 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004728 if (auto *OMPRegionInfo =
4729 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00004730 // For 'cancellation point taskgroup', the task region info may not have a
4731 // cancel. This may instead happen in another adjacent task.
4732 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004733 llvm::Value *Args[] = {
4734 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
4735 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004736 // Ignore return result until untied tasks are supported.
4737 auto *Result = CGF.EmitRuntimeCall(
4738 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
4739 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004740 // exit from construct;
4741 // }
4742 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4743 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4744 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4745 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4746 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004747 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004748 auto CancelDest =
4749 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004750 CGF.EmitBranchThroughCleanup(CancelDest);
4751 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4752 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00004753 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00004754}
4755
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004756void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00004757 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004758 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004759 if (!CGF.HaveInsertPoint())
4760 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004761 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
4762 // kmp_int32 cncl_kind);
4763 if (auto *OMPRegionInfo =
4764 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004765 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
4766 PrePostActionTy &) {
4767 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00004768 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004769 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00004770 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
4771 // Ignore return result until untied tasks are supported.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004772 auto *Result = CGF.EmitRuntimeCall(
4773 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00004774 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00004775 // exit from construct;
4776 // }
4777 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4778 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4779 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4780 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4781 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00004782 // exit from construct;
4783 auto CancelDest =
4784 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
4785 CGF.EmitBranchThroughCleanup(CancelDest);
4786 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4787 };
4788 if (IfCond)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004789 emitOMPIfClause(CGF, IfCond, ThenGen,
4790 [](CodeGenFunction &, PrePostActionTy &) {});
4791 else {
4792 RegionCodeGenTy ThenRCG(ThenGen);
4793 ThenRCG(CGF);
4794 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004795 }
4796}
Samuel Antaobed3c462015-10-02 16:14:20 +00004797
Samuel Antaoee8fb302016-01-06 13:42:12 +00004798/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00004799/// consists of the file and device IDs as well as line number associated with
4800/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004801static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
4802 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004803 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004804
4805 auto &SM = C.getSourceManager();
4806
4807 // The loc should be always valid and have a file ID (the user cannot use
4808 // #pragma directives in macros)
4809
4810 assert(Loc.isValid() && "Source location is expected to be always valid.");
4811 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
4812
4813 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
4814 assert(PLoc.isValid() && "Source location is expected to be always valid.");
4815
4816 llvm::sys::fs::UniqueID ID;
4817 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
4818 llvm_unreachable("Source file with target region no longer exists!");
4819
4820 DeviceID = ID.getDevice();
4821 FileID = ID.getFile();
4822 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004823}
4824
4825void CGOpenMPRuntime::emitTargetOutlinedFunction(
4826 const OMPExecutableDirective &D, StringRef ParentName,
4827 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004828 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004829 assert(!ParentName.empty() && "Invalid target region parent name!");
4830
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00004831 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
4832 IsOffloadEntry, CodeGen);
4833}
4834
4835void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
4836 const OMPExecutableDirective &D, StringRef ParentName,
4837 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
4838 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00004839 // Create a unique name for the entry function using the source location
4840 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00004841 //
Samuel Antao2de62b02016-02-13 23:35:10 +00004842 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00004843 //
4844 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00004845 // mangled name of the function that encloses the target region and BB is the
4846 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004847
4848 unsigned DeviceID;
4849 unsigned FileID;
4850 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004851 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004852 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004853 SmallString<64> EntryFnName;
4854 {
4855 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00004856 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
4857 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004858 }
4859
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00004860 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4861
Samuel Antaobed3c462015-10-02 16:14:20 +00004862 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004863 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00004864 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004865
Samuel Antao6d004262016-06-16 18:39:34 +00004866 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004867
4868 // If this target outline function is not an offload entry, we don't need to
4869 // register it.
4870 if (!IsOffloadEntry)
4871 return;
4872
4873 // The target region ID is used by the runtime library to identify the current
4874 // target region, so it only has to be unique and not necessarily point to
4875 // anything. It could be the pointer to the outlined function that implements
4876 // the target region, but we aren't using that so that the compiler doesn't
4877 // need to keep that, and could therefore inline the host function if proven
4878 // worthwhile during optimization. In the other hand, if emitting code for the
4879 // device, the ID has to be the function address so that it can retrieved from
4880 // the offloading entry and launched by the runtime library. We also mark the
4881 // outlined function to have external linkage in case we are emitting code for
4882 // the device, because these functions will be entry points to the device.
4883
4884 if (CGM.getLangOpts().OpenMPIsDevice) {
4885 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
4886 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
4887 } else
4888 OutlinedFnID = new llvm::GlobalVariable(
4889 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
4890 llvm::GlobalValue::PrivateLinkage,
4891 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
4892
4893 // Register the information for the entry associated with this target region.
4894 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00004895 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
4896 /*Flags=*/0);
Samuel Antaobed3c462015-10-02 16:14:20 +00004897}
4898
Carlo Bertolli6eee9062016-04-29 01:37:30 +00004899/// discard all CompoundStmts intervening between two constructs
4900static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
4901 while (auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
4902 Body = CS->body_front();
4903
4904 return Body;
4905}
4906
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00004907/// Emit the number of teams for a target directive. Inspect the num_teams
4908/// clause associated with a teams construct combined or closely nested
4909/// with the target directive.
4910///
4911/// Emit a team of size one for directives such as 'target parallel' that
4912/// have no associated teams construct.
4913///
4914/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00004915static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00004916emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4917 CodeGenFunction &CGF,
4918 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00004919
4920 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4921 "teams directive expected to be "
4922 "emitted only for the host!");
4923
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004924 auto &Bld = CGF.Builder;
4925
4926 // If the target directive is combined with a teams directive:
4927 // Return the value in the num_teams clause, if any.
4928 // Otherwise, return 0 to denote the runtime default.
4929 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
4930 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
4931 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
4932 auto NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
4933 /*IgnoreResultAssign*/ true);
4934 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
4935 /*IsSigned=*/true);
4936 }
4937
4938 // The default value is 0.
4939 return Bld.getInt32(0);
4940 }
4941
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00004942 // If the target directive is combined with a parallel directive but not a
4943 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004944 if (isOpenMPParallelDirective(D.getDirectiveKind()))
4945 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00004946
4947 // If the current target region has a teams region enclosed, we need to get
4948 // the number of teams to pass to the runtime function call. This is done
4949 // by generating the expression in a inlined region. This is required because
4950 // the expression is captured in the enclosing target environment when the
4951 // teams directive is not combined with target.
4952
4953 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4954
4955 // FIXME: Accommodate other combined directives with teams when they become
4956 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00004957 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
4958 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00004959 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
4960 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4961 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4962 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004963 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
4964 /*IsSigned=*/true);
Samuel Antaob68e2db2016-03-03 16:20:23 +00004965 }
4966
4967 // If we have an enclosed teams directive but no num_teams clause we use
4968 // the default value 0.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00004969 return Bld.getInt32(0);
Samuel Antaob68e2db2016-03-03 16:20:23 +00004970 }
4971
4972 // No teams associated with the directive.
4973 return nullptr;
4974}
4975
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00004976/// Emit the number of threads for a target directive. Inspect the
4977/// thread_limit clause associated with a teams construct combined or closely
4978/// nested with the target directive.
4979///
4980/// Emit the num_threads clause for directives such as 'target parallel' that
4981/// have no associated teams construct.
4982///
4983/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00004984static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00004985emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4986 CodeGenFunction &CGF,
4987 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00004988
4989 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4990 "teams directive expected to be "
4991 "emitted only for the host!");
4992
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00004993 auto &Bld = CGF.Builder;
4994
4995 //
4996 // If the target directive is combined with a teams directive:
4997 // Return the value in the thread_limit clause, if any.
4998 //
4999 // If the target directive is combined with a parallel directive:
5000 // Return the value in the num_threads clause, if any.
5001 //
5002 // If both clauses are set, select the minimum of the two.
5003 //
5004 // If neither teams or parallel combined directives set the number of threads
5005 // in a team, return 0 to denote the runtime default.
5006 //
5007 // If this is not a teams directive return nullptr.
5008
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005009 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
5010 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005011 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
5012 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005013 llvm::Value *ThreadLimitVal = nullptr;
5014
5015 if (const auto *ThreadLimitClause =
5016 D.getSingleClause<OMPThreadLimitClause>()) {
5017 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
5018 auto ThreadLimit = CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
5019 /*IgnoreResultAssign*/ true);
5020 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5021 /*IsSigned=*/true);
5022 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005023
5024 if (const auto *NumThreadsClause =
5025 D.getSingleClause<OMPNumThreadsClause>()) {
5026 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
5027 llvm::Value *NumThreads =
5028 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
5029 /*IgnoreResultAssign*/ true);
5030 NumThreadsVal =
5031 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
5032 }
5033
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005034 // Select the lesser of thread_limit and num_threads.
5035 if (NumThreadsVal)
5036 ThreadLimitVal = ThreadLimitVal
5037 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
5038 ThreadLimitVal),
5039 NumThreadsVal, ThreadLimitVal)
5040 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00005041
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005042 // Set default value passed to the runtime if either teams or a target
5043 // parallel type directive is found but no clause is specified.
5044 if (!ThreadLimitVal)
5045 ThreadLimitVal = DefaultThreadLimitVal;
5046
5047 return ThreadLimitVal;
5048 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00005049
Samuel Antaob68e2db2016-03-03 16:20:23 +00005050 // If the current target region has a teams region enclosed, we need to get
5051 // the thread limit to pass to the runtime function call. This is done
5052 // by generating the expression in a inlined region. This is required because
5053 // the expression is captured in the enclosing target environment when the
5054 // teams directive is not combined with target.
5055
5056 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5057
5058 // FIXME: Accommodate other combined directives with teams when they become
5059 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005060 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
5061 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005062 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
5063 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5064 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5065 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
5066 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5067 /*IsSigned=*/true);
5068 }
5069
5070 // If we have an enclosed teams directive but no thread_limit clause we use
5071 // the default value 0.
5072 return CGF.Builder.getInt32(0);
5073 }
5074
5075 // No teams associated with the directive.
5076 return nullptr;
5077}
5078
Samuel Antao86ace552016-04-27 22:40:57 +00005079namespace {
5080// \brief Utility to handle information from clauses associated with a given
5081// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
5082// It provides a convenient interface to obtain the information and generate
5083// code for that information.
5084class MappableExprsHandler {
5085public:
5086 /// \brief Values for bit flags used to specify the mapping type for
5087 /// offloading.
5088 enum OpenMPOffloadMappingFlags {
Samuel Antao86ace552016-04-27 22:40:57 +00005089 /// \brief Allocate memory on the device and move data from host to device.
5090 OMP_MAP_TO = 0x01,
5091 /// \brief Allocate memory on the device and move data from device to host.
5092 OMP_MAP_FROM = 0x02,
5093 /// \brief Always perform the requested mapping action on the element, even
5094 /// if it was already mapped before.
5095 OMP_MAP_ALWAYS = 0x04,
Samuel Antao86ace552016-04-27 22:40:57 +00005096 /// \brief Delete the element from the device environment, ignoring the
5097 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00005098 OMP_MAP_DELETE = 0x08,
5099 /// \brief The element being mapped is a pointer, therefore the pointee
5100 /// should be mapped as well.
5101 OMP_MAP_IS_PTR = 0x10,
5102 /// \brief This flags signals that an argument is the first one relating to
5103 /// a map/private clause expression. For some cases a single
5104 /// map/privatization results in multiple arguments passed to the runtime
5105 /// library.
5106 OMP_MAP_FIRST_REF = 0x20,
Samuel Antaocc10b852016-07-28 14:23:26 +00005107 /// \brief Signal that the runtime library has to return the device pointer
5108 /// in the current position for the data being mapped.
5109 OMP_MAP_RETURN_PTR = 0x40,
Samuel Antaod486f842016-05-26 16:53:38 +00005110 /// \brief This flag signals that the reference being passed is a pointer to
5111 /// private data.
5112 OMP_MAP_PRIVATE_PTR = 0x80,
Samuel Antao86ace552016-04-27 22:40:57 +00005113 /// \brief Pass the element to the device by value.
Samuel Antao6782e942016-05-26 16:48:10 +00005114 OMP_MAP_PRIVATE_VAL = 0x100,
Samuel Antao86ace552016-04-27 22:40:57 +00005115 };
5116
Samuel Antaocc10b852016-07-28 14:23:26 +00005117 /// Class that associates information with a base pointer to be passed to the
5118 /// runtime library.
5119 class BasePointerInfo {
5120 /// The base pointer.
5121 llvm::Value *Ptr = nullptr;
5122 /// The base declaration that refers to this device pointer, or null if
5123 /// there is none.
5124 const ValueDecl *DevPtrDecl = nullptr;
5125
5126 public:
5127 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
5128 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
5129 llvm::Value *operator*() const { return Ptr; }
5130 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
5131 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
5132 };
5133
5134 typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00005135 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
5136 typedef SmallVector<unsigned, 16> MapFlagsArrayTy;
5137
5138private:
5139 /// \brief Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00005140 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00005141
5142 /// \brief Function the directive is being generated for.
5143 CodeGenFunction &CGF;
5144
Samuel Antaod486f842016-05-26 16:53:38 +00005145 /// \brief Set of all first private variables in the current directive.
5146 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
5147
Samuel Antao6890b092016-07-28 14:25:09 +00005148 /// Map between device pointer declarations and their expression components.
5149 /// The key value for declarations in 'this' is null.
5150 llvm::DenseMap<
5151 const ValueDecl *,
5152 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
5153 DevPointersMap;
5154
Samuel Antao86ace552016-04-27 22:40:57 +00005155 llvm::Value *getExprTypeSize(const Expr *E) const {
5156 auto ExprTy = E->getType().getCanonicalType();
5157
5158 // Reference types are ignored for mapping purposes.
5159 if (auto *RefTy = ExprTy->getAs<ReferenceType>())
5160 ExprTy = RefTy->getPointeeType().getCanonicalType();
5161
5162 // Given that an array section is considered a built-in type, we need to
5163 // do the calculation based on the length of the section instead of relying
5164 // on CGF.getTypeSize(E->getType()).
5165 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
5166 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
5167 OAE->getBase()->IgnoreParenImpCasts())
5168 .getCanonicalType();
5169
5170 // If there is no length associated with the expression, that means we
5171 // are using the whole length of the base.
5172 if (!OAE->getLength() && OAE->getColonLoc().isValid())
5173 return CGF.getTypeSize(BaseTy);
5174
5175 llvm::Value *ElemSize;
5176 if (auto *PTy = BaseTy->getAs<PointerType>())
5177 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
5178 else {
5179 auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
5180 assert(ATy && "Expecting array type if not a pointer type.");
5181 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
5182 }
5183
5184 // If we don't have a length at this point, that is because we have an
5185 // array section with a single element.
5186 if (!OAE->getLength())
5187 return ElemSize;
5188
5189 auto *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
5190 LengthVal =
5191 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
5192 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
5193 }
5194 return CGF.getTypeSize(ExprTy);
5195 }
5196
5197 /// \brief Return the corresponding bits for a given map clause modifier. Add
5198 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00005199 /// map as the first one of a series of maps that relate to the same map
5200 /// expression.
Samuel Antao86ace552016-04-27 22:40:57 +00005201 unsigned getMapTypeBits(OpenMPMapClauseKind MapType,
5202 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
Samuel Antao6782e942016-05-26 16:48:10 +00005203 bool AddIsFirstFlag) const {
Samuel Antao86ace552016-04-27 22:40:57 +00005204 unsigned Bits = 0u;
5205 switch (MapType) {
5206 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00005207 case OMPC_MAP_release:
5208 // alloc and release is the default behavior in the runtime library, i.e.
5209 // if we don't pass any bits alloc/release that is what the runtime is
5210 // going to do. Therefore, we don't need to signal anything for these two
5211 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00005212 break;
5213 case OMPC_MAP_to:
5214 Bits = OMP_MAP_TO;
5215 break;
5216 case OMPC_MAP_from:
5217 Bits = OMP_MAP_FROM;
5218 break;
5219 case OMPC_MAP_tofrom:
5220 Bits = OMP_MAP_TO | OMP_MAP_FROM;
5221 break;
5222 case OMPC_MAP_delete:
5223 Bits = OMP_MAP_DELETE;
5224 break;
Samuel Antao86ace552016-04-27 22:40:57 +00005225 default:
5226 llvm_unreachable("Unexpected map type!");
5227 break;
5228 }
5229 if (AddPtrFlag)
Samuel Antao6782e942016-05-26 16:48:10 +00005230 Bits |= OMP_MAP_IS_PTR;
5231 if (AddIsFirstFlag)
5232 Bits |= OMP_MAP_FIRST_REF;
Samuel Antao86ace552016-04-27 22:40:57 +00005233 if (MapTypeModifier == OMPC_MAP_always)
5234 Bits |= OMP_MAP_ALWAYS;
5235 return Bits;
5236 }
5237
5238 /// \brief Return true if the provided expression is a final array section. A
5239 /// final array section, is one whose length can't be proved to be one.
5240 bool isFinalArraySectionExpression(const Expr *E) const {
5241 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
5242
5243 // It is not an array section and therefore not a unity-size one.
5244 if (!OASE)
5245 return false;
5246
5247 // An array section with no colon always refer to a single element.
5248 if (OASE->getColonLoc().isInvalid())
5249 return false;
5250
5251 auto *Length = OASE->getLength();
5252
5253 // If we don't have a length we have to check if the array has size 1
5254 // for this dimension. Also, we should always expect a length if the
5255 // base type is pointer.
5256 if (!Length) {
5257 auto BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
5258 OASE->getBase()->IgnoreParenImpCasts())
5259 .getCanonicalType();
5260 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
5261 return ATy->getSize().getSExtValue() != 1;
5262 // If we don't have a constant dimension length, we have to consider
5263 // the current section as having any size, so it is not necessarily
5264 // unitary. If it happen to be unity size, that's user fault.
5265 return true;
5266 }
5267
5268 // Check if the length evaluates to 1.
5269 llvm::APSInt ConstLength;
5270 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
5271 return true; // Can have more that size 1.
5272
5273 return ConstLength.getSExtValue() != 1;
5274 }
5275
5276 /// \brief Generate the base pointers, section pointers, sizes and map type
5277 /// bits for the provided map type, map modifier, and expression components.
5278 /// \a IsFirstComponent should be set to true if the provided set of
5279 /// components is the first associated with a capture.
5280 void generateInfoForComponentList(
5281 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
5282 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00005283 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00005284 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
5285 bool IsFirstComponentList) const {
5286
5287 // The following summarizes what has to be generated for each map and the
5288 // types bellow. The generated information is expressed in this order:
5289 // base pointer, section pointer, size, flags
5290 // (to add to the ones that come from the map type and modifier).
5291 //
5292 // double d;
5293 // int i[100];
5294 // float *p;
5295 //
5296 // struct S1 {
5297 // int i;
5298 // float f[50];
5299 // }
5300 // struct S2 {
5301 // int i;
5302 // float f[50];
5303 // S1 s;
5304 // double *p;
5305 // struct S2 *ps;
5306 // }
5307 // S2 s;
5308 // S2 *ps;
5309 //
5310 // map(d)
5311 // &d, &d, sizeof(double), noflags
5312 //
5313 // map(i)
5314 // &i, &i, 100*sizeof(int), noflags
5315 //
5316 // map(i[1:23])
5317 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
5318 //
5319 // map(p)
5320 // &p, &p, sizeof(float*), noflags
5321 //
5322 // map(p[1:24])
5323 // p, &p[1], 24*sizeof(float), noflags
5324 //
5325 // map(s)
5326 // &s, &s, sizeof(S2), noflags
5327 //
5328 // map(s.i)
5329 // &s, &(s.i), sizeof(int), noflags
5330 //
5331 // map(s.s.f)
5332 // &s, &(s.i.f), 50*sizeof(int), noflags
5333 //
5334 // map(s.p)
5335 // &s, &(s.p), sizeof(double*), noflags
5336 //
5337 // map(s.p[:22], s.a s.b)
5338 // &s, &(s.p), sizeof(double*), noflags
5339 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag + extra_flag
5340 //
5341 // map(s.ps)
5342 // &s, &(s.ps), sizeof(S2*), noflags
5343 //
5344 // map(s.ps->s.i)
5345 // &s, &(s.ps), sizeof(S2*), noflags
5346 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag + extra_flag
5347 //
5348 // map(s.ps->ps)
5349 // &s, &(s.ps), sizeof(S2*), noflags
5350 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5351 //
5352 // map(s.ps->ps->ps)
5353 // &s, &(s.ps), sizeof(S2*), noflags
5354 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5355 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5356 //
5357 // map(s.ps->ps->s.f[:22])
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->s.f[0]), 22*sizeof(float), ptr_flag + extra_flag
5361 //
5362 // map(ps)
5363 // &ps, &ps, sizeof(S2*), noflags
5364 //
5365 // map(ps->i)
5366 // ps, &(ps->i), sizeof(int), noflags
5367 //
5368 // map(ps->s.f)
5369 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
5370 //
5371 // map(ps->p)
5372 // ps, &(ps->p), sizeof(double*), noflags
5373 //
5374 // map(ps->p[:22])
5375 // ps, &(ps->p), sizeof(double*), noflags
5376 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag + extra_flag
5377 //
5378 // map(ps->ps)
5379 // ps, &(ps->ps), sizeof(S2*), noflags
5380 //
5381 // map(ps->ps->s.i)
5382 // ps, &(ps->ps), sizeof(S2*), noflags
5383 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag + extra_flag
5384 //
5385 // map(ps->ps->ps)
5386 // ps, &(ps->ps), sizeof(S2*), noflags
5387 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5388 //
5389 // map(ps->ps->ps->ps)
5390 // ps, &(ps->ps), sizeof(S2*), noflags
5391 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5392 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5393 //
5394 // map(ps->ps->ps->s.f[:22])
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->s.f[0]), 22*sizeof(float), ptr_flag +
5398 // extra_flag
5399
5400 // Track if the map information being generated is the first for a capture.
5401 bool IsCaptureFirstInfo = IsFirstComponentList;
5402
5403 // Scan the components from the base to the complete expression.
5404 auto CI = Components.rbegin();
5405 auto CE = Components.rend();
5406 auto I = CI;
5407
5408 // Track if the map information being generated is the first for a list of
5409 // components.
5410 bool IsExpressionFirstInfo = true;
5411 llvm::Value *BP = nullptr;
5412
5413 if (auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
5414 // The base is the 'this' pointer. The content of the pointer is going
5415 // to be the base of the field being mapped.
5416 BP = CGF.EmitScalarExpr(ME->getBase());
5417 } else {
5418 // The base is the reference to the variable.
5419 // BP = &Var.
5420 BP = CGF.EmitLValue(cast<DeclRefExpr>(I->getAssociatedExpression()))
5421 .getPointer();
5422
5423 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00005424 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00005425 // reference. References are ignored for mapping purposes.
5426 QualType Ty =
5427 I->getAssociatedDeclaration()->getType().getNonReferenceType();
5428 if (Ty->isAnyPointerType() && std::next(I) != CE) {
5429 auto PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
Samuel Antao86ace552016-04-27 22:40:57 +00005430 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
Samuel Antao403ffd42016-07-27 22:49:49 +00005431 Ty->castAs<PointerType>())
Samuel Antao86ace552016-04-27 22:40:57 +00005432 .getPointer();
5433
5434 // We do not need to generate individual map information for the
5435 // pointer, it can be associated with the combined storage.
5436 ++I;
5437 }
5438 }
5439
5440 for (; I != CE; ++I) {
5441 auto Next = std::next(I);
5442
5443 // We need to generate the addresses and sizes if this is the last
5444 // component, if the component is a pointer or if it is an array section
5445 // whose length can't be proved to be one. If this is a pointer, it
5446 // becomes the base address for the following components.
5447
5448 // A final array section, is one whose length can't be proved to be one.
5449 bool IsFinalArraySection =
5450 isFinalArraySectionExpression(I->getAssociatedExpression());
5451
5452 // Get information on whether the element is a pointer. Have to do a
5453 // special treatment for array sections given that they are built-in
5454 // types.
5455 const auto *OASE =
5456 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
5457 bool IsPointer =
5458 (OASE &&
5459 OMPArraySectionExpr::getBaseOriginalType(OASE)
5460 .getCanonicalType()
5461 ->isAnyPointerType()) ||
5462 I->getAssociatedExpression()->getType()->isAnyPointerType();
5463
5464 if (Next == CE || IsPointer || IsFinalArraySection) {
5465
5466 // If this is not the last component, we expect the pointer to be
5467 // associated with an array expression or member expression.
5468 assert((Next == CE ||
5469 isa<MemberExpr>(Next->getAssociatedExpression()) ||
5470 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
5471 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
5472 "Unexpected expression");
5473
Samuel Antao86ace552016-04-27 22:40:57 +00005474 auto *LB = CGF.EmitLValue(I->getAssociatedExpression()).getPointer();
5475 auto *Size = getExprTypeSize(I->getAssociatedExpression());
5476
Samuel Antao03a3cec2016-07-27 22:52:16 +00005477 // If we have a member expression and the current component is a
5478 // reference, we have to map the reference too. Whenever we have a
5479 // reference, the section that reference refers to is going to be a
5480 // load instruction from the storage assigned to the reference.
5481 if (isa<MemberExpr>(I->getAssociatedExpression()) &&
5482 I->getAssociatedDeclaration()->getType()->isReferenceType()) {
5483 auto *LI = cast<llvm::LoadInst>(LB);
5484 auto *RefAddr = LI->getPointerOperand();
5485
5486 BasePointers.push_back(BP);
5487 Pointers.push_back(RefAddr);
5488 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
5489 Types.push_back(getMapTypeBits(
5490 /*MapType*/ OMPC_MAP_alloc, /*MapTypeModifier=*/OMPC_MAP_unknown,
5491 !IsExpressionFirstInfo, IsCaptureFirstInfo));
5492 IsExpressionFirstInfo = false;
5493 IsCaptureFirstInfo = false;
5494 // The reference will be the next base address.
5495 BP = RefAddr;
5496 }
5497
5498 BasePointers.push_back(BP);
Samuel Antao86ace552016-04-27 22:40:57 +00005499 Pointers.push_back(LB);
5500 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00005501
Samuel Antao6782e942016-05-26 16:48:10 +00005502 // We need to add a pointer flag for each map that comes from the
5503 // same expression except for the first one. We also need to signal
5504 // this map is the first one that relates with the current capture
5505 // (there is a set of entries for each capture).
Samuel Antao86ace552016-04-27 22:40:57 +00005506 Types.push_back(getMapTypeBits(MapType, MapTypeModifier,
5507 !IsExpressionFirstInfo,
Samuel Antao6782e942016-05-26 16:48:10 +00005508 IsCaptureFirstInfo));
Samuel Antao86ace552016-04-27 22:40:57 +00005509
5510 // If we have a final array section, we are done with this expression.
5511 if (IsFinalArraySection)
5512 break;
5513
5514 // The pointer becomes the base for the next element.
5515 if (Next != CE)
5516 BP = LB;
5517
5518 IsExpressionFirstInfo = false;
5519 IsCaptureFirstInfo = false;
5520 continue;
5521 }
5522 }
5523 }
5524
Samuel Antaod486f842016-05-26 16:53:38 +00005525 /// \brief Return the adjusted map modifiers if the declaration a capture
5526 /// refers to appears in a first-private clause. This is expected to be used
5527 /// only with directives that start with 'target'.
5528 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
5529 unsigned CurrentModifiers) {
5530 assert(Cap.capturesVariable() && "Expected capture by reference only!");
5531
5532 // A first private variable captured by reference will use only the
5533 // 'private ptr' and 'map to' flag. Return the right flags if the captured
5534 // declaration is known as first-private in this handler.
5535 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
5536 return MappableExprsHandler::OMP_MAP_PRIVATE_PTR |
5537 MappableExprsHandler::OMP_MAP_TO;
5538
5539 // We didn't modify anything.
5540 return CurrentModifiers;
5541 }
5542
Samuel Antao86ace552016-04-27 22:40:57 +00005543public:
5544 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
Samuel Antao44bcdb32016-07-28 15:31:29 +00005545 : CurDir(Dir), CGF(CGF) {
Samuel Antaod486f842016-05-26 16:53:38 +00005546 // Extract firstprivate clause information.
5547 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
5548 for (const auto *D : C->varlists())
5549 FirstPrivateDecls.insert(
5550 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
Samuel Antao6890b092016-07-28 14:25:09 +00005551 // Extract device pointer clause information.
5552 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
5553 for (auto L : C->component_lists())
5554 DevPointersMap[L.first].push_back(L.second);
Samuel Antaod486f842016-05-26 16:53:38 +00005555 }
Samuel Antao86ace552016-04-27 22:40:57 +00005556
5557 /// \brief Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00005558 /// types for the extracted mappable expressions. Also, for each item that
5559 /// relates with a device pointer, a pair of the relevant declaration and
5560 /// index where it occurs is appended to the device pointers info array.
5561 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00005562 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
5563 MapFlagsArrayTy &Types) const {
5564 BasePointers.clear();
5565 Pointers.clear();
5566 Sizes.clear();
5567 Types.clear();
5568
5569 struct MapInfo {
Samuel Antaocc10b852016-07-28 14:23:26 +00005570 /// Kind that defines how a device pointer has to be returned.
5571 enum ReturnPointerKind {
5572 // Don't have to return any pointer.
5573 RPK_None,
5574 // Pointer is the base of the declaration.
5575 RPK_Base,
5576 // Pointer is a member of the base declaration - 'this'
5577 RPK_Member,
5578 // Pointer is a reference and a member of the base declaration - 'this'
5579 RPK_MemberReference,
5580 };
Samuel Antao86ace552016-04-27 22:40:57 +00005581 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
Hans Wennborgbc1b58d2016-07-30 00:41:37 +00005582 OpenMPMapClauseKind MapType;
5583 OpenMPMapClauseKind MapTypeModifier;
5584 ReturnPointerKind ReturnDevicePointer;
5585
5586 MapInfo()
5587 : MapType(OMPC_MAP_unknown), MapTypeModifier(OMPC_MAP_unknown),
5588 ReturnDevicePointer(RPK_None) {}
Samuel Antaocc10b852016-07-28 14:23:26 +00005589 MapInfo(
5590 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
5591 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
5592 ReturnPointerKind ReturnDevicePointer)
5593 : Components(Components), MapType(MapType),
5594 MapTypeModifier(MapTypeModifier),
5595 ReturnDevicePointer(ReturnDevicePointer) {}
Samuel Antao86ace552016-04-27 22:40:57 +00005596 };
5597
5598 // We have to process the component lists that relate with the same
5599 // declaration in a single chunk so that we can generate the map flags
5600 // correctly. Therefore, we organize all lists in a map.
5601 llvm::DenseMap<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00005602
5603 // Helper function to fill the information map for the different supported
5604 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00005605 auto &&InfoGen = [&Info](
5606 const ValueDecl *D,
5607 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
5608 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Samuel Antaocf3f83e2016-07-28 14:47:35 +00005609 MapInfo::ReturnPointerKind ReturnDevicePointer) {
Samuel Antaocc10b852016-07-28 14:23:26 +00005610 const ValueDecl *VD =
5611 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
5612 Info[VD].push_back({L, MapType, MapModifier, ReturnDevicePointer});
5613 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00005614
Paul Robinson78fb1322016-08-01 22:12:46 +00005615 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00005616 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005617 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00005618 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
5619 MapInfo::RPK_None);
Paul Robinson15c84002016-07-29 20:46:16 +00005620 for (auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005621 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00005622 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
5623 MapInfo::RPK_None);
Paul Robinson15c84002016-07-29 20:46:16 +00005624 for (auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005625 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00005626 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
5627 MapInfo::RPK_None);
Samuel Antao86ace552016-04-27 22:40:57 +00005628
Samuel Antaocc10b852016-07-28 14:23:26 +00005629 // Look at the use_device_ptr clause information and mark the existing map
5630 // entries as such. If there is no map information for an entry in the
5631 // use_device_ptr list, we create one with map type 'alloc' and zero size
5632 // section. It is the user fault if that was not mapped before.
Paul Robinson78fb1322016-08-01 22:12:46 +00005633 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00005634 for (auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
Samuel Antaocc10b852016-07-28 14:23:26 +00005635 for (auto L : C->component_lists()) {
5636 assert(!L.second.empty() && "Not expecting empty list of components!");
5637 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
5638 VD = cast<ValueDecl>(VD->getCanonicalDecl());
5639 auto *IE = L.second.back().getAssociatedExpression();
5640 // If the first component is a member expression, we have to look into
5641 // 'this', which maps to null in the map of map information. Otherwise
5642 // look directly for the information.
5643 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
5644
5645 // We potentially have map information for this declaration already.
5646 // Look for the first set of components that refer to it.
5647 if (It != Info.end()) {
5648 auto CI = std::find_if(
5649 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
5650 return MI.Components.back().getAssociatedDeclaration() == VD;
5651 });
5652 // If we found a map entry, signal that the pointer has to be returned
5653 // and move on to the next declaration.
5654 if (CI != It->second.end()) {
5655 CI->ReturnDevicePointer = isa<MemberExpr>(IE)
5656 ? (VD->getType()->isReferenceType()
5657 ? MapInfo::RPK_MemberReference
5658 : MapInfo::RPK_Member)
5659 : MapInfo::RPK_Base;
5660 continue;
5661 }
5662 }
5663
5664 // We didn't find any match in our map information - generate a zero
5665 // size array section.
Paul Robinson78fb1322016-08-01 22:12:46 +00005666 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Samuel Antaocc10b852016-07-28 14:23:26 +00005667 llvm::Value *Ptr =
Paul Robinson15c84002016-07-29 20:46:16 +00005668 this->CGF
5669 .EmitLoadOfLValue(this->CGF.EmitLValue(IE), SourceLocation())
Samuel Antaocc10b852016-07-28 14:23:26 +00005670 .getScalarVal();
5671 BasePointers.push_back({Ptr, VD});
5672 Pointers.push_back(Ptr);
Paul Robinson15c84002016-07-29 20:46:16 +00005673 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
Samuel Antaocc10b852016-07-28 14:23:26 +00005674 Types.push_back(OMP_MAP_RETURN_PTR | OMP_MAP_FIRST_REF);
5675 }
5676
Samuel Antao86ace552016-04-27 22:40:57 +00005677 for (auto &M : Info) {
5678 // We need to know when we generate information for the first component
5679 // associated with a capture, because the mapping flags depend on it.
5680 bool IsFirstComponentList = true;
5681 for (MapInfo &L : M.second) {
5682 assert(!L.Components.empty() &&
5683 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00005684
5685 // Remember the current base pointer index.
5686 unsigned CurrentBasePointersIdx = BasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00005687 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Paul Robinson15c84002016-07-29 20:46:16 +00005688 this->generateInfoForComponentList(L.MapType, L.MapTypeModifier,
5689 L.Components, BasePointers, Pointers,
5690 Sizes, Types, IsFirstComponentList);
Samuel Antaocc10b852016-07-28 14:23:26 +00005691
5692 // If this entry relates with a device pointer, set the relevant
5693 // declaration and add the 'return pointer' flag.
5694 if (IsFirstComponentList &&
5695 L.ReturnDevicePointer != MapInfo::RPK_None) {
5696 // If the pointer is not the base of the map, we need to skip the
5697 // base. If it is a reference in a member field, we also need to skip
5698 // the map of the reference.
5699 if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
5700 ++CurrentBasePointersIdx;
5701 if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
5702 ++CurrentBasePointersIdx;
5703 }
5704 assert(BasePointers.size() > CurrentBasePointersIdx &&
5705 "Unexpected number of mapped base pointers.");
5706
5707 auto *RelevantVD = L.Components.back().getAssociatedDeclaration();
5708 assert(RelevantVD &&
5709 "No relevant declaration related with device pointer??");
5710
5711 BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
5712 Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PTR;
5713 }
Samuel Antao86ace552016-04-27 22:40:57 +00005714 IsFirstComponentList = false;
5715 }
5716 }
5717 }
5718
5719 /// \brief Generate the base pointers, section pointers, sizes and map types
5720 /// associated to a given capture.
5721 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00005722 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00005723 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00005724 MapValuesArrayTy &Pointers,
5725 MapValuesArrayTy &Sizes,
5726 MapFlagsArrayTy &Types) const {
5727 assert(!Cap->capturesVariableArrayType() &&
5728 "Not expecting to generate map info for a variable array type!");
5729
5730 BasePointers.clear();
5731 Pointers.clear();
5732 Sizes.clear();
5733 Types.clear();
5734
Samuel Antao6890b092016-07-28 14:25:09 +00005735 // We need to know when we generating information for the first component
5736 // associated with a capture, because the mapping flags depend on it.
5737 bool IsFirstComponentList = true;
5738
Samuel Antao86ace552016-04-27 22:40:57 +00005739 const ValueDecl *VD =
5740 Cap->capturesThis()
5741 ? nullptr
5742 : cast<ValueDecl>(Cap->getCapturedVar()->getCanonicalDecl());
5743
Samuel Antao6890b092016-07-28 14:25:09 +00005744 // If this declaration appears in a is_device_ptr clause we just have to
5745 // pass the pointer by value. If it is a reference to a declaration, we just
5746 // pass its value, otherwise, if it is a member expression, we need to map
5747 // 'to' the field.
5748 if (!VD) {
5749 auto It = DevPointersMap.find(VD);
5750 if (It != DevPointersMap.end()) {
5751 for (auto L : It->second) {
5752 generateInfoForComponentList(
5753 /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
5754 BasePointers, Pointers, Sizes, Types, IsFirstComponentList);
5755 IsFirstComponentList = false;
5756 }
5757 return;
5758 }
5759 } else if (DevPointersMap.count(VD)) {
5760 BasePointers.push_back({Arg, VD});
5761 Pointers.push_back(Arg);
5762 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
5763 Types.push_back(OMP_MAP_PRIVATE_VAL | OMP_MAP_FIRST_REF);
5764 return;
5765 }
5766
Paul Robinson78fb1322016-08-01 22:12:46 +00005767 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00005768 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao86ace552016-04-27 22:40:57 +00005769 for (auto L : C->decl_component_lists(VD)) {
5770 assert(L.first == VD &&
5771 "We got information for the wrong declaration??");
5772 assert(!L.second.empty() &&
5773 "Not expecting declaration with no component lists.");
5774 generateInfoForComponentList(C->getMapType(), C->getMapTypeModifier(),
5775 L.second, BasePointers, Pointers, Sizes,
5776 Types, IsFirstComponentList);
5777 IsFirstComponentList = false;
5778 }
5779
5780 return;
5781 }
Samuel Antaod486f842016-05-26 16:53:38 +00005782
5783 /// \brief Generate the default map information for a given capture \a CI,
5784 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00005785 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
5786 const FieldDecl &RI, llvm::Value *CV,
5787 MapBaseValuesArrayTy &CurBasePointers,
5788 MapValuesArrayTy &CurPointers,
5789 MapValuesArrayTy &CurSizes,
5790 MapFlagsArrayTy &CurMapTypes) {
Samuel Antaod486f842016-05-26 16:53:38 +00005791
5792 // Do the default mapping.
5793 if (CI.capturesThis()) {
5794 CurBasePointers.push_back(CV);
5795 CurPointers.push_back(CV);
5796 const PointerType *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
5797 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
5798 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00005799 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00005800 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00005801 CurBasePointers.push_back(CV);
5802 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00005803 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00005804 // We have to signal to the runtime captures passed by value that are
5805 // not pointers.
Samuel Antaocc10b852016-07-28 14:23:26 +00005806 CurMapTypes.push_back(OMP_MAP_PRIVATE_VAL);
Samuel Antaod486f842016-05-26 16:53:38 +00005807 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
5808 } else {
5809 // Pointers are implicitly mapped with a zero size and no flags
5810 // (other than first map that is added for all implicit maps).
5811 CurMapTypes.push_back(0u);
Samuel Antaod486f842016-05-26 16:53:38 +00005812 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
5813 }
5814 } else {
5815 assert(CI.capturesVariable() && "Expected captured reference.");
5816 CurBasePointers.push_back(CV);
5817 CurPointers.push_back(CV);
5818
5819 const ReferenceType *PtrTy =
5820 cast<ReferenceType>(RI.getType().getTypePtr());
5821 QualType ElementType = PtrTy->getPointeeType();
5822 CurSizes.push_back(CGF.getTypeSize(ElementType));
5823 // The default map type for a scalar/complex type is 'to' because by
5824 // default the value doesn't have to be retrieved. For an aggregate
5825 // type, the default is 'tofrom'.
5826 CurMapTypes.push_back(ElementType->isAggregateType()
Samuel Antaocc10b852016-07-28 14:23:26 +00005827 ? (OMP_MAP_TO | OMP_MAP_FROM)
5828 : OMP_MAP_TO);
Samuel Antaod486f842016-05-26 16:53:38 +00005829
5830 // If we have a capture by reference we may need to add the private
5831 // pointer flag if the base declaration shows in some first-private
5832 // clause.
5833 CurMapTypes.back() =
5834 adjustMapModifiersForPrivateClauses(CI, CurMapTypes.back());
5835 }
5836 // Every default map produces a single argument, so, it is always the
5837 // first one.
Samuel Antaocc10b852016-07-28 14:23:26 +00005838 CurMapTypes.back() |= OMP_MAP_FIRST_REF;
Samuel Antaod486f842016-05-26 16:53:38 +00005839 }
Samuel Antao86ace552016-04-27 22:40:57 +00005840};
Samuel Antaodf158d52016-04-27 22:58:19 +00005841
5842enum OpenMPOffloadingReservedDeviceIDs {
5843 /// \brief Device ID if the device was not defined, runtime should get it
5844 /// from environment variables in the spec.
5845 OMP_DEVICEID_UNDEF = -1,
5846};
5847} // anonymous namespace
5848
5849/// \brief Emit the arrays used to pass the captures and map information to the
5850/// offloading runtime library. If there is no map or capture information,
5851/// return nullptr by reference.
5852static void
Samuel Antaocc10b852016-07-28 14:23:26 +00005853emitOffloadingArrays(CodeGenFunction &CGF,
5854 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00005855 MappableExprsHandler::MapValuesArrayTy &Pointers,
5856 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00005857 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
5858 CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00005859 auto &CGM = CGF.CGM;
5860 auto &Ctx = CGF.getContext();
5861
Samuel Antaocc10b852016-07-28 14:23:26 +00005862 // Reset the array information.
5863 Info.clearArrayInfo();
5864 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00005865
Samuel Antaocc10b852016-07-28 14:23:26 +00005866 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00005867 // Detect if we have any capture size requiring runtime evaluation of the
5868 // size so that a constant array could be eventually used.
5869 bool hasRuntimeEvaluationCaptureSize = false;
5870 for (auto *S : Sizes)
5871 if (!isa<llvm::Constant>(S)) {
5872 hasRuntimeEvaluationCaptureSize = true;
5873 break;
5874 }
5875
Samuel Antaocc10b852016-07-28 14:23:26 +00005876 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00005877 QualType PointerArrayType =
5878 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
5879 /*IndexTypeQuals=*/0);
5880
Samuel Antaocc10b852016-07-28 14:23:26 +00005881 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00005882 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00005883 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00005884 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
5885
5886 // If we don't have any VLA types or other types that require runtime
5887 // evaluation, we can use a constant array for the map sizes, otherwise we
5888 // need to fill up the arrays as we do for the pointers.
5889 if (hasRuntimeEvaluationCaptureSize) {
5890 QualType SizeArrayType = Ctx.getConstantArrayType(
5891 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
5892 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00005893 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00005894 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
5895 } else {
5896 // We expect all the sizes to be constant, so we collect them to create
5897 // a constant array.
5898 SmallVector<llvm::Constant *, 16> ConstSizes;
5899 for (auto S : Sizes)
5900 ConstSizes.push_back(cast<llvm::Constant>(S));
5901
5902 auto *SizesArrayInit = llvm::ConstantArray::get(
5903 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
5904 auto *SizesArrayGbl = new llvm::GlobalVariable(
5905 CGM.getModule(), SizesArrayInit->getType(),
5906 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
5907 SizesArrayInit, ".offload_sizes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00005908 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00005909 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00005910 }
5911
5912 // The map types are always constant so we don't need to generate code to
5913 // fill arrays. Instead, we create an array constant.
5914 llvm::Constant *MapTypesArrayInit =
5915 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
5916 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
5917 CGM.getModule(), MapTypesArrayInit->getType(),
5918 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
5919 MapTypesArrayInit, ".offload_maptypes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00005920 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00005921 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00005922
Samuel Antaocc10b852016-07-28 14:23:26 +00005923 for (unsigned i = 0; i < Info.NumberOfPtrs; ++i) {
5924 llvm::Value *BPVal = *BasePointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00005925 if (BPVal->getType()->isPointerTy())
5926 BPVal = CGF.Builder.CreateBitCast(BPVal, CGM.VoidPtrTy);
5927 else {
5928 assert(BPVal->getType()->isIntegerTy() &&
5929 "If not a pointer, the value type must be an integer.");
5930 BPVal = CGF.Builder.CreateIntToPtr(BPVal, CGM.VoidPtrTy);
5931 }
5932 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005933 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5934 Info.BasePointersArray, 0, i);
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];
5943 if (PVal->getType()->isPointerTy())
5944 PVal = CGF.Builder.CreateBitCast(PVal, CGM.VoidPtrTy);
5945 else {
5946 assert(PVal->getType()->isIntegerTy() &&
5947 "If not a pointer, the value type must be an integer.");
5948 PVal = CGF.Builder.CreateIntToPtr(PVal, CGM.VoidPtrTy);
5949 }
5950 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005951 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5952 Info.PointersArray, 0, i);
Samuel Antaodf158d52016-04-27 22:58:19 +00005953 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
5954 CGF.Builder.CreateStore(PVal, PAddr);
5955
5956 if (hasRuntimeEvaluationCaptureSize) {
5957 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005958 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
5959 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005960 /*Idx0=*/0,
5961 /*Idx1=*/i);
5962 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
5963 CGF.Builder.CreateStore(
5964 CGF.Builder.CreateIntCast(Sizes[i], CGM.SizeTy, /*isSigned=*/true),
5965 SAddr);
5966 }
5967 }
5968 }
5969}
5970/// \brief Emit the arguments to be passed to the runtime library based on the
5971/// arrays of pointers, sizes and map types.
5972static void emitOffloadingArraysArgument(
5973 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
5974 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00005975 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00005976 auto &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00005977 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00005978 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005979 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5980 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005981 /*Idx0=*/0, /*Idx1=*/0);
5982 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005983 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5984 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005985 /*Idx0=*/0,
5986 /*Idx1=*/0);
5987 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005988 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005989 /*Idx0=*/0, /*Idx1=*/0);
5990 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005991 llvm::ArrayType::get(CGM.Int32Ty, Info.NumberOfPtrs),
5992 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005993 /*Idx0=*/0,
5994 /*Idx1=*/0);
5995 } else {
5996 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
5997 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
5998 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
5999 MapTypesArrayArg =
6000 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo());
6001 }
Samuel Antao86ace552016-04-27 22:40:57 +00006002}
6003
Samuel Antaobed3c462015-10-02 16:14:20 +00006004void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
6005 const OMPExecutableDirective &D,
6006 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00006007 llvm::Value *OutlinedFnID,
Samuel Antaobed3c462015-10-02 16:14:20 +00006008 const Expr *IfCond, const Expr *Device,
6009 ArrayRef<llvm::Value *> CapturedVars) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006010 if (!CGF.HaveInsertPoint())
6011 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00006012
Samuel Antaoee8fb302016-01-06 13:42:12 +00006013 assert(OutlinedFn && "Invalid outlined function!");
6014
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006015 auto &Ctx = CGF.getContext();
6016
Samuel Antao86ace552016-04-27 22:40:57 +00006017 // Fill up the arrays with all the captured variables.
6018 MappableExprsHandler::MapValuesArrayTy KernelArgs;
Samuel Antaocc10b852016-07-28 14:23:26 +00006019 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00006020 MappableExprsHandler::MapValuesArrayTy Pointers;
6021 MappableExprsHandler::MapValuesArrayTy Sizes;
6022 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobed3c462015-10-02 16:14:20 +00006023
Samuel Antaocc10b852016-07-28 14:23:26 +00006024 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00006025 MappableExprsHandler::MapValuesArrayTy CurPointers;
6026 MappableExprsHandler::MapValuesArrayTy CurSizes;
6027 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
6028
Samuel Antaod486f842016-05-26 16:53:38 +00006029 // Get mappable expression information.
6030 MappableExprsHandler MEHandler(D, CGF);
Samuel Antaobed3c462015-10-02 16:14:20 +00006031
6032 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
6033 auto RI = CS.getCapturedRecordDecl()->field_begin();
Samuel Antaobed3c462015-10-02 16:14:20 +00006034 auto CV = CapturedVars.begin();
6035 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
6036 CE = CS.capture_end();
6037 CI != CE; ++CI, ++RI, ++CV) {
6038 StringRef Name;
6039 QualType Ty;
Samuel Antaobed3c462015-10-02 16:14:20 +00006040
Samuel Antao86ace552016-04-27 22:40:57 +00006041 CurBasePointers.clear();
6042 CurPointers.clear();
6043 CurSizes.clear();
6044 CurMapTypes.clear();
6045
6046 // VLA sizes are passed to the outlined region by copy and do not have map
6047 // information associated.
Samuel Antaobed3c462015-10-02 16:14:20 +00006048 if (CI->capturesVariableArrayType()) {
Samuel Antao86ace552016-04-27 22:40:57 +00006049 CurBasePointers.push_back(*CV);
6050 CurPointers.push_back(*CV);
6051 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006052 // Copy to the device as an argument. No need to retrieve it.
Samuel Antao6782e942016-05-26 16:48:10 +00006053 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_PRIVATE_VAL |
6054 MappableExprsHandler::OMP_MAP_FIRST_REF);
Samuel Antaobed3c462015-10-02 16:14:20 +00006055 } else {
Samuel Antao86ace552016-04-27 22:40:57 +00006056 // If we have any information in the map clause, we use it, otherwise we
6057 // just do a default mapping.
Samuel Antao6890b092016-07-28 14:25:09 +00006058 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006059 CurSizes, CurMapTypes);
Samuel Antaod486f842016-05-26 16:53:38 +00006060 if (CurBasePointers.empty())
6061 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
6062 CurPointers, CurSizes, CurMapTypes);
Samuel Antaobed3c462015-10-02 16:14:20 +00006063 }
Samuel Antao86ace552016-04-27 22:40:57 +00006064 // We expect to have at least an element of information for this capture.
6065 assert(!CurBasePointers.empty() && "Non-existing map pointer for capture!");
6066 assert(CurBasePointers.size() == CurPointers.size() &&
6067 CurBasePointers.size() == CurSizes.size() &&
6068 CurBasePointers.size() == CurMapTypes.size() &&
6069 "Inconsistent map information sizes!");
Samuel Antaobed3c462015-10-02 16:14:20 +00006070
Samuel Antao86ace552016-04-27 22:40:57 +00006071 // The kernel args are always the first elements of the base pointers
6072 // associated with a capture.
Samuel Antaocc10b852016-07-28 14:23:26 +00006073 KernelArgs.push_back(*CurBasePointers.front());
Samuel Antao86ace552016-04-27 22:40:57 +00006074 // We need to append the results of this capture to what we already have.
6075 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
6076 Pointers.append(CurPointers.begin(), CurPointers.end());
6077 Sizes.append(CurSizes.begin(), CurSizes.end());
6078 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
Samuel Antaobed3c462015-10-02 16:14:20 +00006079 }
6080
6081 // Keep track on whether the host function has to be executed.
6082 auto OffloadErrorQType =
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006083 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006084 auto OffloadError = CGF.MakeAddrLValue(
6085 CGF.CreateMemTemp(OffloadErrorQType, ".run_host_version"),
6086 OffloadErrorQType);
6087 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty),
6088 OffloadError);
6089
6090 // Fill up the pointer arrays and transfer execution to the device.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00006091 auto &&ThenGen = [&BasePointers, &Pointers, &Sizes, &MapTypes, Device,
6092 OutlinedFnID, OffloadError,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006093 &D](CodeGenFunction &CGF, PrePostActionTy &) {
6094 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antaodf158d52016-04-27 22:58:19 +00006095 // Emit the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00006096 TargetDataInfo Info;
6097 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
6098 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
6099 Info.PointersArray, Info.SizesArray,
6100 Info.MapTypesArray, Info);
Samuel Antaobed3c462015-10-02 16:14:20 +00006101
6102 // On top of the arrays that were filled up, the target offloading call
6103 // takes as arguments the device id as well as the host pointer. The host
6104 // pointer is used by the runtime library to identify the current target
6105 // region, so it only has to be unique and not necessarily point to
6106 // anything. It could be the pointer to the outlined function that
6107 // implements the target region, but we aren't using that so that the
6108 // compiler doesn't need to keep that, and could therefore inline the host
6109 // function if proven worthwhile during optimization.
6110
Samuel Antaoee8fb302016-01-06 13:42:12 +00006111 // From this point on, we need to have an ID of the target region defined.
6112 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00006113
6114 // Emit device ID if any.
6115 llvm::Value *DeviceID;
6116 if (Device)
6117 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006118 CGF.Int32Ty, /*isSigned=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006119 else
6120 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6121
Samuel Antaodf158d52016-04-27 22:58:19 +00006122 // Emit the number of elements in the offloading arrays.
6123 llvm::Value *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6124
Samuel Antaob68e2db2016-03-03 16:20:23 +00006125 // Return value of the runtime offloading call.
6126 llvm::Value *Return;
6127
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006128 auto *NumTeams = emitNumTeamsForTargetDirective(RT, CGF, D);
6129 auto *NumThreads = emitNumThreadsForTargetDirective(RT, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006130
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006131 // The target region is an outlined function launched by the runtime
6132 // via calls __tgt_target() or __tgt_target_teams().
6133 //
6134 // __tgt_target() launches a target region with one team and one thread,
6135 // executing a serial region. This master thread may in turn launch
6136 // more threads within its team upon encountering a parallel region,
6137 // however, no additional teams can be launched on the device.
6138 //
6139 // __tgt_target_teams() launches a target region with one or more teams,
6140 // each with one or more threads. This call is required for target
6141 // constructs such as:
6142 // 'target teams'
6143 // 'target' / 'teams'
6144 // 'target teams distribute parallel for'
6145 // 'target parallel'
6146 // and so on.
6147 //
6148 // Note that on the host and CPU targets, the runtime implementation of
6149 // these calls simply call the outlined function without forking threads.
6150 // The outlined functions themselves have runtime calls to
6151 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
6152 // the compiler in emitTeamsCall() and emitParallelCall().
6153 //
6154 // In contrast, on the NVPTX target, the implementation of
6155 // __tgt_target_teams() launches a GPU kernel with the requested number
6156 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006157 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006158 // If we have NumTeams defined this means that we have an enclosed teams
6159 // region. Therefore we also expect to have NumThreads defined. These two
6160 // values should be defined in the presence of a teams directive,
6161 // regardless of having any clauses associated. If the user is using teams
6162 // but no clauses, these two values will be the default that should be
6163 // passed to the runtime library - a 32-bit integer with the value zero.
6164 assert(NumThreads && "Thread limit expression should be available along "
6165 "with number of teams.");
Samuel Antaob68e2db2016-03-03 16:20:23 +00006166 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00006167 DeviceID, OutlinedFnID,
6168 PointerNum, Info.BasePointersArray,
6169 Info.PointersArray, Info.SizesArray,
6170 Info.MapTypesArray, NumTeams,
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006171 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00006172 Return = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006173 RT.createRuntimeFunction(OMPRTL__tgt_target_teams), OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006174 } else {
6175 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00006176 DeviceID, OutlinedFnID,
6177 PointerNum, Info.BasePointersArray,
6178 Info.PointersArray, Info.SizesArray,
6179 Info.MapTypesArray};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006180 Return = CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target),
Samuel Antaob68e2db2016-03-03 16:20:23 +00006181 OffloadingArgs);
6182 }
Samuel Antaobed3c462015-10-02 16:14:20 +00006183
6184 CGF.EmitStoreOfScalar(Return, OffloadError);
6185 };
6186
Samuel Antaoee8fb302016-01-06 13:42:12 +00006187 // Notify that the host version must be executed.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006188 auto &&ElseGen = [OffloadError](CodeGenFunction &CGF, PrePostActionTy &) {
6189 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/-1u),
Samuel Antaoee8fb302016-01-06 13:42:12 +00006190 OffloadError);
6191 };
6192
6193 // If we have a target function ID it means that we need to support
6194 // offloading, otherwise, just execute on the host. We need to execute on host
6195 // regardless of the conditional in the if clause if, e.g., the user do not
6196 // specify target triples.
6197 if (OutlinedFnID) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006198 if (IfCond)
Samuel Antaoee8fb302016-01-06 13:42:12 +00006199 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006200 else {
6201 RegionCodeGenTy ThenRCG(ThenGen);
6202 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00006203 }
6204 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006205 RegionCodeGenTy ElseRCG(ElseGen);
6206 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00006207 }
Samuel Antaobed3c462015-10-02 16:14:20 +00006208
6209 // Check the error code and execute the host version if required.
6210 auto OffloadFailedBlock = CGF.createBasicBlock("omp_offload.failed");
6211 auto OffloadContBlock = CGF.createBasicBlock("omp_offload.cont");
6212 auto OffloadErrorVal = CGF.EmitLoadOfScalar(OffloadError, SourceLocation());
6213 auto Failed = CGF.Builder.CreateIsNotNull(OffloadErrorVal);
6214 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
6215
6216 CGF.EmitBlock(OffloadFailedBlock);
Samuel Antao86ace552016-04-27 22:40:57 +00006217 CGF.Builder.CreateCall(OutlinedFn, KernelArgs);
Samuel Antaobed3c462015-10-02 16:14:20 +00006218 CGF.EmitBranch(OffloadContBlock);
6219
6220 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006221}
Samuel Antaoee8fb302016-01-06 13:42:12 +00006222
6223void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
6224 StringRef ParentName) {
6225 if (!S)
6226 return;
6227
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00006228 // Codegen OMP target directives that offload compute to the device.
6229 bool requiresDeviceCodegen =
6230 isa<OMPExecutableDirective>(S) &&
6231 isOpenMPTargetExecutionDirective(
6232 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00006233
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00006234 if (requiresDeviceCodegen) {
6235 auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006236 unsigned DeviceID;
6237 unsigned FileID;
6238 unsigned Line;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00006239 getTargetEntryUniqueInfo(CGM.getContext(), E.getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00006240 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006241
6242 // Is this a target region that should not be emitted as an entry point? If
6243 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00006244 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
6245 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00006246 return;
6247
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00006248 switch (S->getStmtClass()) {
6249 case Stmt::OMPTargetDirectiveClass:
6250 CodeGenFunction::EmitOMPTargetDeviceFunction(
6251 CGM, ParentName, cast<OMPTargetDirective>(*S));
6252 break;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00006253 case Stmt::OMPTargetParallelDirectiveClass:
6254 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
6255 CGM, ParentName, cast<OMPTargetParallelDirective>(*S));
6256 break;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006257 case Stmt::OMPTargetTeamsDirectiveClass:
6258 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
6259 CGM, ParentName, cast<OMPTargetTeamsDirective>(*S));
6260 break;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00006261 default:
6262 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
6263 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00006264 return;
6265 }
6266
6267 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
Samuel Antaoe49645c2016-05-08 06:43:56 +00006268 if (!E->hasAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00006269 return;
6270
6271 scanForTargetRegionsFunctions(
6272 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
6273 ParentName);
6274 return;
6275 }
6276
6277 // If this is a lambda function, look into its body.
6278 if (auto *L = dyn_cast<LambdaExpr>(S))
6279 S = L->getBody();
6280
6281 // Keep looking for target regions recursively.
6282 for (auto *II : S->children())
6283 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006284}
6285
6286bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
6287 auto &FD = *cast<FunctionDecl>(GD.getDecl());
6288
6289 // If emitting code for the host, we do not process FD here. Instead we do
6290 // the normal code generation.
6291 if (!CGM.getLangOpts().OpenMPIsDevice)
6292 return false;
6293
6294 // Try to detect target regions in the function.
6295 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
6296
Samuel Antao4b75b872016-12-12 19:26:31 +00006297 // We should not emit any function other that the ones created during the
Samuel Antaoee8fb302016-01-06 13:42:12 +00006298 // scanning. Therefore, we signal that this function is completely dealt
6299 // with.
6300 return true;
6301}
6302
6303bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
6304 if (!CGM.getLangOpts().OpenMPIsDevice)
6305 return false;
6306
6307 // Check if there are Ctors/Dtors in this declaration and look for target
6308 // regions in it. We use the complete variant to produce the kernel name
6309 // mangling.
6310 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
6311 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
6312 for (auto *Ctor : RD->ctors()) {
6313 StringRef ParentName =
6314 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
6315 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
6316 }
6317 auto *Dtor = RD->getDestructor();
6318 if (Dtor) {
6319 StringRef ParentName =
6320 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
6321 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
6322 }
6323 }
6324
6325 // If we are in target mode we do not emit any global (declare target is not
6326 // implemented yet). Therefore we signal that GD was processed in this case.
6327 return true;
6328}
6329
6330bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
6331 auto *VD = GD.getDecl();
6332 if (isa<FunctionDecl>(VD))
6333 return emitTargetFunctions(GD);
6334
6335 return emitTargetGlobalVariable(GD);
6336}
6337
6338llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
6339 // If we have offloading in the current module, we need to emit the entries
6340 // now and register the offloading descriptor.
6341 createOffloadEntriesAndInfoMetadata();
6342
6343 // Create and register the offloading binary descriptors. This is the main
6344 // entity that captures all the information about offloading in the current
6345 // compilation unit.
6346 return createOffloadingBinaryDescriptorRegistration();
6347}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006348
6349void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
6350 const OMPExecutableDirective &D,
6351 SourceLocation Loc,
6352 llvm::Value *OutlinedFn,
6353 ArrayRef<llvm::Value *> CapturedVars) {
6354 if (!CGF.HaveInsertPoint())
6355 return;
6356
6357 auto *RTLoc = emitUpdateLocation(CGF, Loc);
6358 CodeGenFunction::RunCleanupsScope Scope(CGF);
6359
6360 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
6361 llvm::Value *Args[] = {
6362 RTLoc,
6363 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
6364 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
6365 llvm::SmallVector<llvm::Value *, 16> RealArgs;
6366 RealArgs.append(std::begin(Args), std::end(Args));
6367 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
6368
6369 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
6370 CGF.EmitRuntimeCall(RTLFn, RealArgs);
6371}
6372
6373void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00006374 const Expr *NumTeams,
6375 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006376 SourceLocation Loc) {
6377 if (!CGF.HaveInsertPoint())
6378 return;
6379
6380 auto *RTLoc = emitUpdateLocation(CGF, Loc);
6381
Carlo Bertollic6872252016-04-04 15:55:02 +00006382 llvm::Value *NumTeamsVal =
6383 (NumTeams)
6384 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
6385 CGF.CGM.Int32Ty, /* isSigned = */ true)
6386 : CGF.Builder.getInt32(0);
6387
6388 llvm::Value *ThreadLimitVal =
6389 (ThreadLimit)
6390 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
6391 CGF.CGM.Int32Ty, /* isSigned = */ true)
6392 : CGF.Builder.getInt32(0);
6393
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006394 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00006395 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
6396 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006397 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
6398 PushNumTeamsArgs);
6399}
Samuel Antaodf158d52016-04-27 22:58:19 +00006400
Samuel Antaocc10b852016-07-28 14:23:26 +00006401void CGOpenMPRuntime::emitTargetDataCalls(
6402 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
6403 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006404 if (!CGF.HaveInsertPoint())
6405 return;
6406
Samuel Antaocc10b852016-07-28 14:23:26 +00006407 // Action used to replace the default codegen action and turn privatization
6408 // off.
6409 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00006410
6411 // Generate the code for the opening of the data environment. Capture all the
6412 // arguments of the runtime call by reference because they are used in the
6413 // closing of the region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00006414 auto &&BeginThenGen = [&D, Device, &Info, &CodeGen](CodeGenFunction &CGF,
6415 PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006416 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00006417 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00006418 MappableExprsHandler::MapValuesArrayTy Pointers;
6419 MappableExprsHandler::MapValuesArrayTy Sizes;
6420 MappableExprsHandler::MapFlagsArrayTy MapTypes;
6421
6422 // Get map clause information.
6423 MappableExprsHandler MCHandler(D, CGF);
6424 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00006425
6426 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00006427 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00006428
6429 llvm::Value *BasePointersArrayArg = nullptr;
6430 llvm::Value *PointersArrayArg = nullptr;
6431 llvm::Value *SizesArrayArg = nullptr;
6432 llvm::Value *MapTypesArrayArg = nullptr;
6433 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006434 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00006435
6436 // Emit device ID if any.
6437 llvm::Value *DeviceID = nullptr;
6438 if (Device)
6439 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6440 CGF.Int32Ty, /*isSigned=*/true);
6441 else
6442 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6443
6444 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00006445 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00006446
6447 llvm::Value *OffloadingArgs[] = {
6448 DeviceID, PointerNum, BasePointersArrayArg,
6449 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
6450 auto &RT = CGF.CGM.getOpenMPRuntime();
6451 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_begin),
6452 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00006453
6454 // If device pointer privatization is required, emit the body of the region
6455 // here. It will have to be duplicated: with and without privatization.
6456 if (!Info.CaptureDeviceAddrMap.empty())
6457 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00006458 };
6459
6460 // Generate code for the closing of the data region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00006461 auto &&EndThenGen = [Device, &Info](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006462 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00006463
6464 llvm::Value *BasePointersArrayArg = nullptr;
6465 llvm::Value *PointersArrayArg = nullptr;
6466 llvm::Value *SizesArrayArg = nullptr;
6467 llvm::Value *MapTypesArrayArg = nullptr;
6468 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006469 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00006470
6471 // Emit device ID if any.
6472 llvm::Value *DeviceID = nullptr;
6473 if (Device)
6474 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6475 CGF.Int32Ty, /*isSigned=*/true);
6476 else
6477 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6478
6479 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00006480 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00006481
6482 llvm::Value *OffloadingArgs[] = {
6483 DeviceID, PointerNum, BasePointersArrayArg,
6484 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
6485 auto &RT = CGF.CGM.getOpenMPRuntime();
6486 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_end),
6487 OffloadingArgs);
6488 };
6489
Samuel Antaocc10b852016-07-28 14:23:26 +00006490 // If we need device pointer privatization, we need to emit the body of the
6491 // region with no privatization in the 'else' branch of the conditional.
6492 // Otherwise, we don't have to do anything.
6493 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
6494 PrePostActionTy &) {
6495 if (!Info.CaptureDeviceAddrMap.empty()) {
6496 CodeGen.setAction(NoPrivAction);
6497 CodeGen(CGF);
6498 }
6499 };
6500
6501 // We don't have to do anything to close the region if the if clause evaluates
6502 // to false.
6503 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00006504
6505 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006506 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00006507 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00006508 RegionCodeGenTy RCG(BeginThenGen);
6509 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00006510 }
6511
Samuel Antaocc10b852016-07-28 14:23:26 +00006512 // If we don't require privatization of device pointers, we emit the body in
6513 // between the runtime calls. This avoids duplicating the body code.
6514 if (Info.CaptureDeviceAddrMap.empty()) {
6515 CodeGen.setAction(NoPrivAction);
6516 CodeGen(CGF);
6517 }
Samuel Antaodf158d52016-04-27 22:58:19 +00006518
6519 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006520 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00006521 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00006522 RegionCodeGenTy RCG(EndThenGen);
6523 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00006524 }
6525}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006526
Samuel Antao8d2d7302016-05-26 18:30:22 +00006527void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00006528 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
6529 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006530 if (!CGF.HaveInsertPoint())
6531 return;
6532
Samuel Antao8dd66282016-04-27 23:14:30 +00006533 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00006534 isa<OMPTargetExitDataDirective>(D) ||
6535 isa<OMPTargetUpdateDirective>(D)) &&
6536 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00006537
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006538 // Generate the code for the opening of the data environment.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00006539 auto &&ThenGen = [&D, Device](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006540 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00006541 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006542 MappableExprsHandler::MapValuesArrayTy Pointers;
6543 MappableExprsHandler::MapValuesArrayTy Sizes;
6544 MappableExprsHandler::MapFlagsArrayTy MapTypes;
6545
6546 // Get map clause information.
Samuel Antao8d2d7302016-05-26 18:30:22 +00006547 MappableExprsHandler MEHandler(D, CGF);
6548 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006549
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006550 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00006551 TargetDataInfo Info;
6552 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
6553 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
6554 Info.PointersArray, Info.SizesArray,
6555 Info.MapTypesArray, Info);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006556
6557 // Emit device ID if any.
6558 llvm::Value *DeviceID = nullptr;
6559 if (Device)
6560 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6561 CGF.Int32Ty, /*isSigned=*/true);
6562 else
6563 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6564
6565 // Emit the number of elements in the offloading arrays.
6566 auto *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6567
6568 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00006569 DeviceID, PointerNum, Info.BasePointersArray,
6570 Info.PointersArray, Info.SizesArray, Info.MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00006571
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006572 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antao8d2d7302016-05-26 18:30:22 +00006573 // Select the right runtime function call for each expected standalone
6574 // directive.
6575 OpenMPRTLFunction RTLFn;
6576 switch (D.getDirectiveKind()) {
6577 default:
6578 llvm_unreachable("Unexpected standalone target data directive.");
6579 break;
6580 case OMPD_target_enter_data:
6581 RTLFn = OMPRTL__tgt_target_data_begin;
6582 break;
6583 case OMPD_target_exit_data:
6584 RTLFn = OMPRTL__tgt_target_data_end;
6585 break;
6586 case OMPD_target_update:
6587 RTLFn = OMPRTL__tgt_target_data_update;
6588 break;
6589 }
6590 CGF.EmitRuntimeCall(RT.createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006591 };
6592
6593 // In the event we get an if clause, we don't have to take any action on the
6594 // else side.
6595 auto &&ElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
6596
6597 if (IfCond) {
6598 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
6599 } else {
6600 RegionCodeGenTy ThenGenRCG(ThenGen);
6601 ThenGenRCG(CGF);
6602 }
6603}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00006604
6605namespace {
6606 /// Kind of parameter in a function with 'declare simd' directive.
6607 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
6608 /// Attribute set of the parameter.
6609 struct ParamAttrTy {
6610 ParamKindTy Kind = Vector;
6611 llvm::APSInt StrideOrArg;
6612 llvm::APSInt Alignment;
6613 };
6614} // namespace
6615
6616static unsigned evaluateCDTSize(const FunctionDecl *FD,
6617 ArrayRef<ParamAttrTy> ParamAttrs) {
6618 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
6619 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
6620 // of that clause. The VLEN value must be power of 2.
6621 // In other case the notion of the function`s "characteristic data type" (CDT)
6622 // is used to compute the vector length.
6623 // CDT is defined in the following order:
6624 // a) For non-void function, the CDT is the return type.
6625 // b) If the function has any non-uniform, non-linear parameters, then the
6626 // CDT is the type of the first such parameter.
6627 // c) If the CDT determined by a) or b) above is struct, union, or class
6628 // type which is pass-by-value (except for the type that maps to the
6629 // built-in complex data type), the characteristic data type is int.
6630 // d) If none of the above three cases is applicable, the CDT is int.
6631 // The VLEN is then determined based on the CDT and the size of vector
6632 // register of that ISA for which current vector version is generated. The
6633 // VLEN is computed using the formula below:
6634 // VLEN = sizeof(vector_register) / sizeof(CDT),
6635 // where vector register size specified in section 3.2.1 Registers and the
6636 // Stack Frame of original AMD64 ABI document.
6637 QualType RetType = FD->getReturnType();
6638 if (RetType.isNull())
6639 return 0;
6640 ASTContext &C = FD->getASTContext();
6641 QualType CDT;
6642 if (!RetType.isNull() && !RetType->isVoidType())
6643 CDT = RetType;
6644 else {
6645 unsigned Offset = 0;
6646 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6647 if (ParamAttrs[Offset].Kind == Vector)
6648 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
6649 ++Offset;
6650 }
6651 if (CDT.isNull()) {
6652 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
6653 if (ParamAttrs[I + Offset].Kind == Vector) {
6654 CDT = FD->getParamDecl(I)->getType();
6655 break;
6656 }
6657 }
6658 }
6659 }
6660 if (CDT.isNull())
6661 CDT = C.IntTy;
6662 CDT = CDT->getCanonicalTypeUnqualified();
6663 if (CDT->isRecordType() || CDT->isUnionType())
6664 CDT = C.IntTy;
6665 return C.getTypeSize(CDT);
6666}
6667
6668static void
6669emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00006670 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00006671 ArrayRef<ParamAttrTy> ParamAttrs,
6672 OMPDeclareSimdDeclAttr::BranchStateTy State) {
6673 struct ISADataTy {
6674 char ISA;
6675 unsigned VecRegSize;
6676 };
6677 ISADataTy ISAData[] = {
6678 {
6679 'b', 128
6680 }, // SSE
6681 {
6682 'c', 256
6683 }, // AVX
6684 {
6685 'd', 256
6686 }, // AVX2
6687 {
6688 'e', 512
6689 }, // AVX512
6690 };
6691 llvm::SmallVector<char, 2> Masked;
6692 switch (State) {
6693 case OMPDeclareSimdDeclAttr::BS_Undefined:
6694 Masked.push_back('N');
6695 Masked.push_back('M');
6696 break;
6697 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
6698 Masked.push_back('N');
6699 break;
6700 case OMPDeclareSimdDeclAttr::BS_Inbranch:
6701 Masked.push_back('M');
6702 break;
6703 }
6704 for (auto Mask : Masked) {
6705 for (auto &Data : ISAData) {
6706 SmallString<256> Buffer;
6707 llvm::raw_svector_ostream Out(Buffer);
6708 Out << "_ZGV" << Data.ISA << Mask;
6709 if (!VLENVal) {
6710 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
6711 evaluateCDTSize(FD, ParamAttrs));
6712 } else
6713 Out << VLENVal;
6714 for (auto &ParamAttr : ParamAttrs) {
6715 switch (ParamAttr.Kind){
6716 case LinearWithVarStride:
6717 Out << 's' << ParamAttr.StrideOrArg;
6718 break;
6719 case Linear:
6720 Out << 'l';
6721 if (!!ParamAttr.StrideOrArg)
6722 Out << ParamAttr.StrideOrArg;
6723 break;
6724 case Uniform:
6725 Out << 'u';
6726 break;
6727 case Vector:
6728 Out << 'v';
6729 break;
6730 }
6731 if (!!ParamAttr.Alignment)
6732 Out << 'a' << ParamAttr.Alignment;
6733 }
6734 Out << '_' << Fn->getName();
6735 Fn->addFnAttr(Out.str());
6736 }
6737 }
6738}
6739
6740void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
6741 llvm::Function *Fn) {
6742 ASTContext &C = CGM.getContext();
6743 FD = FD->getCanonicalDecl();
6744 // Map params to their positions in function decl.
6745 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
6746 if (isa<CXXMethodDecl>(FD))
6747 ParamPositions.insert({FD, 0});
6748 unsigned ParamPos = ParamPositions.size();
David Majnemer59f77922016-06-24 04:05:48 +00006749 for (auto *P : FD->parameters()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00006750 ParamPositions.insert({P->getCanonicalDecl(), ParamPos});
6751 ++ParamPos;
6752 }
6753 for (auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
6754 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
6755 // Mark uniform parameters.
6756 for (auto *E : Attr->uniforms()) {
6757 E = E->IgnoreParenImpCasts();
6758 unsigned Pos;
6759 if (isa<CXXThisExpr>(E))
6760 Pos = ParamPositions[FD];
6761 else {
6762 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
6763 ->getCanonicalDecl();
6764 Pos = ParamPositions[PVD];
6765 }
6766 ParamAttrs[Pos].Kind = Uniform;
6767 }
6768 // Get alignment info.
6769 auto NI = Attr->alignments_begin();
6770 for (auto *E : Attr->aligneds()) {
6771 E = E->IgnoreParenImpCasts();
6772 unsigned Pos;
6773 QualType ParmTy;
6774 if (isa<CXXThisExpr>(E)) {
6775 Pos = ParamPositions[FD];
6776 ParmTy = E->getType();
6777 } else {
6778 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
6779 ->getCanonicalDecl();
6780 Pos = ParamPositions[PVD];
6781 ParmTy = PVD->getType();
6782 }
6783 ParamAttrs[Pos].Alignment =
6784 (*NI) ? (*NI)->EvaluateKnownConstInt(C)
6785 : llvm::APSInt::getUnsigned(
6786 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
6787 .getQuantity());
6788 ++NI;
6789 }
6790 // Mark linear parameters.
6791 auto SI = Attr->steps_begin();
6792 auto MI = Attr->modifiers_begin();
6793 for (auto *E : Attr->linears()) {
6794 E = E->IgnoreParenImpCasts();
6795 unsigned Pos;
6796 if (isa<CXXThisExpr>(E))
6797 Pos = ParamPositions[FD];
6798 else {
6799 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
6800 ->getCanonicalDecl();
6801 Pos = ParamPositions[PVD];
6802 }
6803 auto &ParamAttr = ParamAttrs[Pos];
6804 ParamAttr.Kind = Linear;
6805 if (*SI) {
6806 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
6807 Expr::SE_AllowSideEffects)) {
6808 if (auto *DRE = cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
6809 if (auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
6810 ParamAttr.Kind = LinearWithVarStride;
6811 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
6812 ParamPositions[StridePVD->getCanonicalDecl()]);
6813 }
6814 }
6815 }
6816 }
6817 ++SI;
6818 ++MI;
6819 }
6820 llvm::APSInt VLENVal;
6821 if (const Expr *VLEN = Attr->getSimdlen())
6822 VLENVal = VLEN->EvaluateKnownConstInt(C);
6823 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
6824 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
6825 CGM.getTriple().getArch() == llvm::Triple::x86_64)
6826 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
6827 }
6828}
Alexey Bataev8b427062016-05-25 12:36:08 +00006829
6830namespace {
6831/// Cleanup action for doacross support.
6832class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
6833public:
6834 static const int DoacrossFinArgs = 2;
6835
6836private:
6837 llvm::Value *RTLFn;
6838 llvm::Value *Args[DoacrossFinArgs];
6839
6840public:
6841 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
6842 : RTLFn(RTLFn) {
6843 assert(CallArgs.size() == DoacrossFinArgs);
6844 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
6845 }
6846 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
6847 if (!CGF.HaveInsertPoint())
6848 return;
6849 CGF.EmitRuntimeCall(RTLFn, Args);
6850 }
6851};
6852} // namespace
6853
6854void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
6855 const OMPLoopDirective &D) {
6856 if (!CGF.HaveInsertPoint())
6857 return;
6858
6859 ASTContext &C = CGM.getContext();
6860 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
6861 RecordDecl *RD;
6862 if (KmpDimTy.isNull()) {
6863 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
6864 // kmp_int64 lo; // lower
6865 // kmp_int64 up; // upper
6866 // kmp_int64 st; // stride
6867 // };
6868 RD = C.buildImplicitRecord("kmp_dim");
6869 RD->startDefinition();
6870 addFieldToRecordDecl(C, RD, Int64Ty);
6871 addFieldToRecordDecl(C, RD, Int64Ty);
6872 addFieldToRecordDecl(C, RD, Int64Ty);
6873 RD->completeDefinition();
6874 KmpDimTy = C.getRecordType(RD);
6875 } else
6876 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
6877
6878 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
6879 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
6880 enum { LowerFD = 0, UpperFD, StrideFD };
6881 // Fill dims with data.
6882 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
6883 // dims.upper = num_iterations;
6884 LValue UpperLVal =
6885 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
6886 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
6887 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
6888 Int64Ty, D.getNumIterations()->getExprLoc());
6889 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
6890 // dims.stride = 1;
6891 LValue StrideLVal =
6892 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
6893 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
6894 StrideLVal);
6895
6896 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
6897 // kmp_int32 num_dims, struct kmp_dim * dims);
6898 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
6899 getThreadID(CGF, D.getLocStart()),
6900 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
6901 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6902 DimsAddr.getPointer(), CGM.VoidPtrTy)};
6903
6904 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
6905 CGF.EmitRuntimeCall(RTLFn, Args);
6906 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
6907 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
6908 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
6909 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
6910 llvm::makeArrayRef(FiniArgs));
6911}
6912
6913void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
6914 const OMPDependClause *C) {
6915 QualType Int64Ty =
6916 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
6917 const Expr *CounterVal = C->getCounterValue();
6918 assert(CounterVal);
6919 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
6920 CounterVal->getType(), Int64Ty,
6921 CounterVal->getExprLoc());
6922 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
6923 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
6924 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
6925 getThreadID(CGF, C->getLocStart()),
6926 CntAddr.getPointer()};
6927 llvm::Value *RTLFn;
6928 if (C->getDependencyKind() == OMPC_DEPEND_source)
6929 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
6930 else {
6931 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
6932 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
6933 }
6934 CGF.EmitRuntimeCall(RTLFn, Args);
6935}
6936