blob: afbeb183e871b52ad9849f163d2b261aae61b5a5 [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 Bataevbe5a8b42017-07-17 13:30:36 +0000646 // Call to void *__kmpc_task_reduction_init(int gtid, int num_data, void
647 // *data);
648 OMPRTL__kmpc_task_reduction_init,
649 // Call to void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
650 // *d);
651 OMPRTL__kmpc_task_reduction_get_th_data,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000652
653 //
654 // Offloading related calls
655 //
656 // Call to int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
657 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
658 // *arg_types);
659 OMPRTL__tgt_target,
Samuel Antaob68e2db2016-03-03 16:20:23 +0000660 // Call to int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
661 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
662 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
663 OMPRTL__tgt_target_teams,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000664 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
665 OMPRTL__tgt_register_lib,
666 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
667 OMPRTL__tgt_unregister_lib,
Samuel Antaodf158d52016-04-27 22:58:19 +0000668 // Call to void __tgt_target_data_begin(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_begin,
671 // Call to void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
672 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
673 OMPRTL__tgt_target_data_end,
Samuel Antao8d2d7302016-05-26 18:30:22 +0000674 // Call to void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
675 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
676 OMPRTL__tgt_target_data_update,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000677};
678
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000679/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
680/// region.
681class CleanupTy final : public EHScopeStack::Cleanup {
682 PrePostActionTy *Action;
683
684public:
685 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
686 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
687 if (!CGF.HaveInsertPoint())
688 return;
689 Action->Exit(CGF);
690 }
691};
692
Hans Wennborg7eb54642015-09-10 17:07:54 +0000693} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000694
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000695void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
696 CodeGenFunction::RunCleanupsScope Scope(CGF);
697 if (PrePostAction) {
698 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
699 Callback(CodeGen, CGF, *PrePostAction);
700 } else {
701 PrePostActionTy Action;
702 Callback(CodeGen, CGF, Action);
703 }
704}
705
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000706/// Check if the combiner is a call to UDR combiner and if it is so return the
707/// UDR decl used for reduction.
708static const OMPDeclareReductionDecl *
709getReductionInit(const Expr *ReductionOp) {
710 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
711 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
712 if (auto *DRE =
713 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
714 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
715 return DRD;
716 return nullptr;
717}
718
719static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
720 const OMPDeclareReductionDecl *DRD,
721 const Expr *InitOp,
722 Address Private, Address Original,
723 QualType Ty) {
724 if (DRD->getInitializer()) {
725 std::pair<llvm::Function *, llvm::Function *> Reduction =
726 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
727 auto *CE = cast<CallExpr>(InitOp);
728 auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
729 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
730 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
731 auto *LHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
732 auto *RHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
733 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
734 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
735 [=]() -> Address { return Private; });
736 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
737 [=]() -> Address { return Original; });
738 (void)PrivateScope.Privatize();
739 RValue Func = RValue::get(Reduction.second);
740 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
741 CGF.EmitIgnoredExpr(InitOp);
742 } else {
743 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
744 auto *GV = new llvm::GlobalVariable(
745 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
746 llvm::GlobalValue::PrivateLinkage, Init, ".init");
747 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
748 RValue InitRVal;
749 switch (CGF.getEvaluationKind(Ty)) {
750 case TEK_Scalar:
751 InitRVal = CGF.EmitLoadOfLValue(LV, SourceLocation());
752 break;
753 case TEK_Complex:
754 InitRVal =
755 RValue::getComplex(CGF.EmitLoadOfComplex(LV, SourceLocation()));
756 break;
757 case TEK_Aggregate:
758 InitRVal = RValue::getAggregate(LV.getAddress());
759 break;
760 }
761 OpaqueValueExpr OVE(SourceLocation(), Ty, VK_RValue);
762 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
763 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
764 /*IsInitializer=*/false);
765 }
766}
767
768/// \brief Emit initialization of arrays of complex types.
769/// \param DestAddr Address of the array.
770/// \param Type Type of array.
771/// \param Init Initial expression of array.
772/// \param SrcAddr Address of the original array.
773static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
774 QualType Type, const Expr *Init,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000775 const OMPDeclareReductionDecl *DRD,
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000776 Address SrcAddr = Address::invalid()) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000777 // Perform element-by-element initialization.
778 QualType ElementTy;
779
780 // Drill down to the base element type on both arrays.
781 auto ArrayTy = Type->getAsArrayTypeUnsafe();
782 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
783 DestAddr =
784 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
785 if (DRD)
786 SrcAddr =
787 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
788
789 llvm::Value *SrcBegin = nullptr;
790 if (DRD)
791 SrcBegin = SrcAddr.getPointer();
792 auto DestBegin = DestAddr.getPointer();
793 // Cast from pointer to array type to pointer to single element.
794 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
795 // The basic structure here is a while-do loop.
796 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
797 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
798 auto IsEmpty =
799 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
800 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
801
802 // Enter the loop body, making that address the current address.
803 auto EntryBB = CGF.Builder.GetInsertBlock();
804 CGF.EmitBlock(BodyBB);
805
806 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
807
808 llvm::PHINode *SrcElementPHI = nullptr;
809 Address SrcElementCurrent = Address::invalid();
810 if (DRD) {
811 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
812 "omp.arraycpy.srcElementPast");
813 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
814 SrcElementCurrent =
815 Address(SrcElementPHI,
816 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
817 }
818 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
819 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
820 DestElementPHI->addIncoming(DestBegin, EntryBB);
821 Address DestElementCurrent =
822 Address(DestElementPHI,
823 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
824
825 // Emit copy.
826 {
827 CodeGenFunction::RunCleanupsScope InitScope(CGF);
828 if (DRD && (DRD->getInitializer() || !Init)) {
829 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
830 SrcElementCurrent, ElementTy);
831 } else
832 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
833 /*IsInitializer=*/false);
834 }
835
836 if (DRD) {
837 // Shift the address forward by one element.
838 auto SrcElementNext = CGF.Builder.CreateConstGEP1_32(
839 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
840 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
841 }
842
843 // Shift the address forward by one element.
844 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
845 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
846 // Check whether we've reached the end.
847 auto Done =
848 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
849 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
850 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
851
852 // Done.
853 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
854}
855
856LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
857 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
858 return CGF.EmitOMPArraySectionExpr(OASE);
859 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(E))
860 return CGF.EmitLValue(ASE);
861 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
862 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
863 CGF.CapturedStmtInfo &&
864 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
865 E->getType(), VK_LValue, E->getExprLoc());
866 // Store the address of the original variable associated with the LHS
867 // implicit variable.
868 return CGF.EmitLValue(&DRE);
869}
870
871LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
872 const Expr *E) {
873 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
874 return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
875 return LValue();
876}
877
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000878void ReductionCodeGen::emitAggregateInitialization(
879 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
880 const OMPDeclareReductionDecl *DRD) {
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000881 // Emit VarDecl with copy init for arrays.
882 // Get the address of the original variable captured in current
883 // captured region.
884 auto *PrivateVD =
885 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000886 EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
887 DRD ? ClausesData[N].ReductionOp : PrivateVD->getInit(),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000888 DRD, SharedLVal.getAddress());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000889}
890
891ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
892 ArrayRef<const Expr *> Privates,
893 ArrayRef<const Expr *> ReductionOps) {
894 ClausesData.reserve(Shareds.size());
895 SharedAddresses.reserve(Shareds.size());
896 Sizes.reserve(Shareds.size());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000897 BaseDecls.reserve(Shareds.size());
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000898 auto IPriv = Privates.begin();
899 auto IRed = ReductionOps.begin();
900 for (const auto *Ref : Shareds) {
901 ClausesData.emplace_back(Ref, *IPriv, *IRed);
902 std::advance(IPriv, 1);
903 std::advance(IRed, 1);
904 }
905}
906
907void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
908 assert(SharedAddresses.size() == N &&
909 "Number of generated lvalues must be exactly N.");
910 SharedAddresses.emplace_back(emitSharedLValue(CGF, ClausesData[N].Ref),
911 emitSharedLValueUB(CGF, ClausesData[N].Ref));
912}
913
914void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
915 auto *PrivateVD =
916 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
917 QualType PrivateType = PrivateVD->getType();
918 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
919 if (!AsArraySection && !PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000920 Sizes.emplace_back(
921 CGF.getTypeSize(
922 SharedAddresses[N].first.getType().getNonReferenceType()),
923 nullptr);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000924 return;
925 }
926 llvm::Value *Size;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000927 llvm::Value *SizeInChars;
928 llvm::Type *ElemType =
929 cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType())
930 ->getElementType();
931 auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000932 if (AsArraySection) {
933 Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
934 SharedAddresses[N].first.getPointer());
935 Size = CGF.Builder.CreateNUWAdd(
936 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000937 SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000938 } else {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000939 SizeInChars = CGF.getTypeSize(
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000940 SharedAddresses[N].first.getType().getNonReferenceType());
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000941 Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000942 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000943 Sizes.emplace_back(SizeInChars, Size);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000944 CodeGenFunction::OpaqueValueMapping OpaqueMap(
945 CGF,
946 cast<OpaqueValueExpr>(
947 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
948 RValue::get(Size));
949 CGF.EmitVariablyModifiedType(PrivateType);
950}
951
952void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
953 llvm::Value *Size) {
954 auto *PrivateVD =
955 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
956 QualType PrivateType = PrivateVD->getType();
957 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
958 if (!AsArraySection && !PrivateType->isVariablyModifiedType()) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000959 assert(!Size && !Sizes[N].second &&
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000960 "Size should be nullptr for non-variably modified redution "
961 "items.");
962 return;
963 }
964 CodeGenFunction::OpaqueValueMapping OpaqueMap(
965 CGF,
966 cast<OpaqueValueExpr>(
967 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
968 RValue::get(Size));
969 CGF.EmitVariablyModifiedType(PrivateType);
970}
971
972void ReductionCodeGen::emitInitialization(
973 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
974 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
975 assert(SharedAddresses.size() > N && "No variable was generated");
976 auto *PrivateVD =
977 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
978 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
979 QualType PrivateType = PrivateVD->getType();
980 PrivateAddr = CGF.Builder.CreateElementBitCast(
981 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
982 QualType SharedType = SharedAddresses[N].first.getType();
983 SharedLVal = CGF.MakeAddrLValue(
984 CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
985 CGF.ConvertTypeForMem(SharedType)),
986 SharedType, SharedAddresses[N].first.getBaseInfo());
987 if (isa<OMPArraySectionExpr>(ClausesData[N].Ref) ||
988 CGF.getContext().getAsArrayType(PrivateVD->getType())) {
Alexey Bataevbe5a8b42017-07-17 13:30:36 +0000989 emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000990 } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
991 emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
992 PrivateAddr, SharedLVal.getAddress(),
993 SharedLVal.getType());
994 } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
995 !CGF.isTrivialInitializer(PrivateVD->getInit())) {
996 CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
997 PrivateVD->getType().getQualifiers(),
998 /*IsInitializer=*/false);
999 }
1000}
1001
1002bool ReductionCodeGen::needCleanups(unsigned N) {
1003 auto *PrivateVD =
1004 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1005 QualType PrivateType = PrivateVD->getType();
1006 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1007 return DTorKind != QualType::DK_none;
1008}
1009
1010void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
1011 Address PrivateAddr) {
1012 auto *PrivateVD =
1013 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
1014 QualType PrivateType = PrivateVD->getType();
1015 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1016 if (needCleanups(N)) {
1017 PrivateAddr = CGF.Builder.CreateElementBitCast(
1018 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1019 CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
1020 }
1021}
1022
1023static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1024 LValue BaseLV) {
1025 BaseTy = BaseTy.getNonReferenceType();
1026 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1027 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1028 if (auto *PtrTy = BaseTy->getAs<PointerType>())
1029 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
1030 else {
1031 BaseLV = CGF.EmitLoadOfReferenceLValue(BaseLV.getAddress(),
1032 BaseTy->castAs<ReferenceType>());
1033 }
1034 BaseTy = BaseTy->getPointeeType();
1035 }
1036 return CGF.MakeAddrLValue(
1037 CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
1038 CGF.ConvertTypeForMem(ElTy)),
1039 BaseLV.getType(), BaseLV.getBaseInfo());
1040}
1041
1042static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1043 llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
1044 llvm::Value *Addr) {
1045 Address Tmp = Address::invalid();
1046 Address TopTmp = Address::invalid();
1047 Address MostTopTmp = Address::invalid();
1048 BaseTy = BaseTy.getNonReferenceType();
1049 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1050 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1051 Tmp = CGF.CreateMemTemp(BaseTy);
1052 if (TopTmp.isValid())
1053 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
1054 else
1055 MostTopTmp = Tmp;
1056 TopTmp = Tmp;
1057 BaseTy = BaseTy->getPointeeType();
1058 }
1059 llvm::Type *Ty = BaseLVType;
1060 if (Tmp.isValid())
1061 Ty = Tmp.getElementType();
1062 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
1063 if (Tmp.isValid()) {
1064 CGF.Builder.CreateStore(Addr, Tmp);
1065 return MostTopTmp;
1066 }
1067 return Address(Addr, BaseLVAlignment);
1068}
1069
1070Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
1071 Address PrivateAddr) {
1072 const DeclRefExpr *DE;
1073 const VarDecl *OrigVD = nullptr;
1074 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(ClausesData[N].Ref)) {
1075 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
1076 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
1077 Base = TempOASE->getBase()->IgnoreParenImpCasts();
1078 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1079 Base = TempASE->getBase()->IgnoreParenImpCasts();
1080 DE = cast<DeclRefExpr>(Base);
1081 OrigVD = cast<VarDecl>(DE->getDecl());
1082 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(ClausesData[N].Ref)) {
1083 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
1084 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1085 Base = TempASE->getBase()->IgnoreParenImpCasts();
1086 DE = cast<DeclRefExpr>(Base);
1087 OrigVD = cast<VarDecl>(DE->getDecl());
1088 }
1089 if (OrigVD) {
1090 BaseDecls.emplace_back(OrigVD);
1091 auto OriginalBaseLValue = CGF.EmitLValue(DE);
1092 LValue BaseLValue =
1093 loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1094 OriginalBaseLValue);
1095 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1096 BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
1097 llvm::Value *Ptr =
1098 CGF.Builder.CreateGEP(PrivateAddr.getPointer(), Adjustment);
1099 return castToBase(CGF, OrigVD->getType(),
1100 SharedAddresses[N].first.getType(),
1101 OriginalBaseLValue.getPointer()->getType(),
1102 OriginalBaseLValue.getAlignment(), Ptr);
1103 }
1104 BaseDecls.emplace_back(
1105 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1106 return PrivateAddr;
1107}
1108
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001109bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
1110 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
1111 return DRD && DRD->getInitializer();
1112}
1113
Alexey Bataev18095712014-10-10 12:19:54 +00001114LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00001115 return CGF.EmitLoadOfPointerLValue(
1116 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1117 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +00001118}
1119
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001120void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001121 if (!CGF.HaveInsertPoint())
1122 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001123 // 1.2.2 OpenMP Language Terminology
1124 // Structured block - An executable statement with a single entry at the
1125 // top and a single exit at the bottom.
1126 // The point of exit cannot be a branch out of the structured block.
1127 // longjmp() and throw() must not violate the entry/exit criteria.
1128 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001129 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001130 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001131}
1132
Alexey Bataev62b63b12015-03-10 07:28:44 +00001133LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1134 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001135 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1136 getThreadIDVariable()->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001137 LValueBaseInfo(AlignmentSource::Decl, false));
Alexey Bataev62b63b12015-03-10 07:28:44 +00001138}
1139
Alexey Bataev9959db52014-05-06 10:08:46 +00001140CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001141 : CGM(CGM), OffloadEntriesInfoManager(CGM) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001142 IdentTy = llvm::StructType::create(
1143 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
1144 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Serge Guelton1d993272017-05-09 19:31:30 +00001145 CGM.Int8PtrTy /* psource */);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001146 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +00001147
1148 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +00001149}
1150
Alexey Bataev91797552015-03-18 04:13:55 +00001151void CGOpenMPRuntime::clear() {
1152 InternalVars.clear();
1153}
1154
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001155static llvm::Function *
1156emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1157 const Expr *CombinerInitializer, const VarDecl *In,
1158 const VarDecl *Out, bool IsCombiner) {
1159 // void .omp_combiner.(Ty *in, Ty *out);
1160 auto &C = CGM.getContext();
1161 QualType PtrTy = C.getPointerType(Ty).withRestrict();
1162 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001163 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001164 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001165 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001166 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001167 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001168 Args.push_back(&OmpInParm);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001169 auto &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001170 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001171 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1172 auto *Fn = llvm::Function::Create(
1173 FnTy, llvm::GlobalValue::InternalLinkage,
1174 IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
1175 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001176 Fn->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001177 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001178 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001179 CodeGenFunction CGF(CGM);
1180 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1181 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
1182 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
1183 CodeGenFunction::OMPPrivateScope Scope(CGF);
1184 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
1185 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
1186 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1187 .getAddress();
1188 });
1189 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
1190 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
1191 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1192 .getAddress();
1193 });
1194 (void)Scope.Privatize();
1195 CGF.EmitIgnoredExpr(CombinerInitializer);
1196 Scope.ForceCleanup();
1197 CGF.FinishFunction();
1198 return Fn;
1199}
1200
1201void CGOpenMPRuntime::emitUserDefinedReduction(
1202 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1203 if (UDRMap.count(D) > 0)
1204 return;
1205 auto &C = CGM.getContext();
1206 if (!In || !Out) {
1207 In = &C.Idents.get("omp_in");
1208 Out = &C.Idents.get("omp_out");
1209 }
1210 llvm::Function *Combiner = emitCombinerOrInitializer(
1211 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
1212 cast<VarDecl>(D->lookup(Out).front()),
1213 /*IsCombiner=*/true);
1214 llvm::Function *Initializer = nullptr;
1215 if (auto *Init = D->getInitializer()) {
1216 if (!Priv || !Orig) {
1217 Priv = &C.Idents.get("omp_priv");
1218 Orig = &C.Idents.get("omp_orig");
1219 }
1220 Initializer = emitCombinerOrInitializer(
1221 CGM, D->getType(), Init, cast<VarDecl>(D->lookup(Orig).front()),
1222 cast<VarDecl>(D->lookup(Priv).front()),
1223 /*IsCombiner=*/false);
1224 }
1225 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
1226 if (CGF) {
1227 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1228 Decls.second.push_back(D);
1229 }
1230}
1231
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001232std::pair<llvm::Function *, llvm::Function *>
1233CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1234 auto I = UDRMap.find(D);
1235 if (I != UDRMap.end())
1236 return I->second;
1237 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1238 return UDRMap.lookup(D);
1239}
1240
John McCall7f416cc2015-09-08 08:05:57 +00001241// Layout information for ident_t.
1242static CharUnits getIdentAlign(CodeGenModule &CGM) {
1243 return CGM.getPointerAlign();
1244}
1245static CharUnits getIdentSize(CodeGenModule &CGM) {
1246 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
1247 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
1248}
Alexey Bataev50b3c952016-02-19 10:38:26 +00001249static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
John McCall7f416cc2015-09-08 08:05:57 +00001250 // All the fields except the last are i32, so this works beautifully.
1251 return unsigned(Field) * CharUnits::fromQuantity(4);
1252}
1253static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001254 IdentFieldIndex Field,
John McCall7f416cc2015-09-08 08:05:57 +00001255 const llvm::Twine &Name = "") {
1256 auto Offset = getOffsetOfIdentField(Field);
1257 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
1258}
1259
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001260static llvm::Value *emitParallelOrTeamsOutlinedFunction(
1261 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1262 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1263 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001264 assert(ThreadIDVar->getType()->isPointerType() &&
1265 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +00001266 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00001267 bool HasCancel = false;
1268 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
1269 HasCancel = OPD->hasCancel();
1270 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
1271 HasCancel = OPSD->hasCancel();
1272 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
1273 HasCancel = OPFD->hasCancel();
1274 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001275 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +00001276 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001277 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +00001278}
1279
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001280llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
1281 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1282 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1283 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1284 return emitParallelOrTeamsOutlinedFunction(
1285 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1286}
1287
1288llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1289 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1290 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1291 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1292 return emitParallelOrTeamsOutlinedFunction(
1293 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1294}
1295
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001296llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
1297 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +00001298 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1299 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1300 bool Tied, unsigned &NumberOfParts) {
1301 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1302 PrePostActionTy &) {
1303 auto *ThreadID = getThreadID(CGF, D.getLocStart());
1304 auto *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
1305 llvm::Value *TaskArgs[] = {
1306 UpLoc, ThreadID,
1307 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1308 TaskTVar->getType()->castAs<PointerType>())
1309 .getPointer()};
1310 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1311 };
1312 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1313 UntiedCodeGen);
1314 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001315 assert(!ThreadIDVar->getType()->isPointerType() &&
1316 "thread id variable must be of type kmp_int32 for tasks");
1317 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
Alexey Bataev7292c292016-04-25 12:22:29 +00001318 auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001319 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +00001320 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1321 InnermostKind,
1322 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +00001323 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev48591dd2016-04-20 04:01:36 +00001324 auto *Res = CGF.GenerateCapturedStmtFunction(*CS);
1325 if (!Tied)
1326 NumberOfParts = Action.getNumberOfParts();
1327 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001328}
1329
Alexey Bataev50b3c952016-02-19 10:38:26 +00001330Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +00001331 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +00001332 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +00001333 if (!Entry) {
1334 if (!DefaultOpenMPPSource) {
1335 // Initialize default location for psource field of ident_t structure of
1336 // all ident_t objects. Format is ";file;function;line;column;;".
1337 // Taken from
1338 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1339 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +00001340 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001341 DefaultOpenMPPSource =
1342 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1343 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001344
John McCall23c9dc62016-11-28 22:18:27 +00001345 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001346 auto fields = builder.beginStruct(IdentTy);
1347 fields.addInt(CGM.Int32Ty, 0);
1348 fields.addInt(CGM.Int32Ty, Flags);
1349 fields.addInt(CGM.Int32Ty, 0);
1350 fields.addInt(CGM.Int32Ty, 0);
1351 fields.add(DefaultOpenMPPSource);
1352 auto DefaultOpenMPLocation =
1353 fields.finishAndCreateGlobal("", Align, /*isConstant*/ true,
1354 llvm::GlobalValue::PrivateLinkage);
1355 DefaultOpenMPLocation->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1356
John McCall7f416cc2015-09-08 08:05:57 +00001357 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +00001358 }
John McCall7f416cc2015-09-08 08:05:57 +00001359 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +00001360}
1361
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001362llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1363 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001364 unsigned Flags) {
1365 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +00001366 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001367 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +00001368 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +00001369 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001370
1371 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1372
John McCall7f416cc2015-09-08 08:05:57 +00001373 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001374 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1375 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +00001376 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
1377
Alexander Musmanc6388682014-12-15 07:07:06 +00001378 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1379 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +00001380 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +00001381 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +00001382 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
1383 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +00001384 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +00001385 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001386 LocValue = AI;
1387
1388 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1389 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001390 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +00001391 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +00001392 }
1393
1394 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +00001395 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +00001396
Alexey Bataevf002aca2014-05-30 05:48:40 +00001397 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
1398 if (OMPDebugLoc == nullptr) {
1399 SmallString<128> Buffer2;
1400 llvm::raw_svector_ostream OS2(Buffer2);
1401 // Build debug location
1402 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1403 OS2 << ";" << PLoc.getFilename() << ";";
1404 if (const FunctionDecl *FD =
1405 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
1406 OS2 << FD->getQualifiedNameAsString();
1407 }
1408 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1409 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1410 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +00001411 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001412 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +00001413 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
1414
John McCall7f416cc2015-09-08 08:05:57 +00001415 // Our callers always pass this to a runtime function, so for
1416 // convenience, go ahead and return a naked pointer.
1417 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001418}
1419
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001420llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1421 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001422 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1423
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001424 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001425 // Check whether we've already cached a load of the thread id in this
1426 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001427 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001428 if (I != OpenMPLocThreadIDMap.end()) {
1429 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001430 if (ThreadID != nullptr)
1431 return ThreadID;
1432 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001433 if (auto *OMPRegionInfo =
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001434 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001435 if (OMPRegionInfo->getThreadIDVariable()) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001436 // Check if this an outlined function with thread id passed as argument.
1437 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001438 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
1439 // If value loaded in entry block, cache it and use it everywhere in
1440 // function.
1441 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1442 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1443 Elem.second.ThreadID = ThreadID;
1444 }
1445 return ThreadID;
Alexey Bataevd6c57552014-07-25 07:55:17 +00001446 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001447 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001448
1449 // This is not an outlined function region - need to call __kmpc_int32
1450 // kmpc_global_thread_num(ident_t *loc).
1451 // Generate thread id value and cache this value for use across the
1452 // function.
1453 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1454 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
1455 ThreadID =
1456 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1457 emitUpdateLocation(CGF, Loc));
1458 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1459 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001460 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +00001461}
1462
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001463void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001464 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001465 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1466 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001467 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1468 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
1469 UDRMap.erase(D);
1470 }
1471 FunctionUDRMap.erase(CGF.CurFn);
1472 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001473}
1474
1475llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001476 if (!IdentTy) {
1477 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001478 return llvm::PointerType::getUnqual(IdentTy);
1479}
1480
1481llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001482 if (!Kmpc_MicroTy) {
1483 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1484 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1485 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1486 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1487 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001488 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1489}
1490
1491llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001492CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001493 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001494 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001495 case OMPRTL__kmpc_fork_call: {
1496 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1497 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001498 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1499 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001500 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001501 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001502 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1503 break;
1504 }
1505 case OMPRTL__kmpc_global_thread_num: {
1506 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001507 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001508 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001509 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001510 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1511 break;
1512 }
Alexey Bataev97720002014-11-11 04:05:39 +00001513 case OMPRTL__kmpc_threadprivate_cached: {
1514 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1515 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1516 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1517 CGM.VoidPtrTy, CGM.SizeTy,
1518 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1519 llvm::FunctionType *FnTy =
1520 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1521 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1522 break;
1523 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001524 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001525 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1526 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001527 llvm::Type *TypeParams[] = {
1528 getIdentTyPointerTy(), CGM.Int32Ty,
1529 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1530 llvm::FunctionType *FnTy =
1531 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1532 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1533 break;
1534 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001535 case OMPRTL__kmpc_critical_with_hint: {
1536 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1537 // kmp_critical_name *crit, uintptr_t hint);
1538 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1539 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1540 CGM.IntPtrTy};
1541 llvm::FunctionType *FnTy =
1542 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1543 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1544 break;
1545 }
Alexey Bataev97720002014-11-11 04:05:39 +00001546 case OMPRTL__kmpc_threadprivate_register: {
1547 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1548 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1549 // typedef void *(*kmpc_ctor)(void *);
1550 auto KmpcCtorTy =
1551 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1552 /*isVarArg*/ false)->getPointerTo();
1553 // typedef void *(*kmpc_cctor)(void *, void *);
1554 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1555 auto KmpcCopyCtorTy =
1556 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1557 /*isVarArg*/ false)->getPointerTo();
1558 // typedef void (*kmpc_dtor)(void *);
1559 auto KmpcDtorTy =
1560 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1561 ->getPointerTo();
1562 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1563 KmpcCopyCtorTy, KmpcDtorTy};
1564 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1565 /*isVarArg*/ false);
1566 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1567 break;
1568 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001569 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001570 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1571 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001572 llvm::Type *TypeParams[] = {
1573 getIdentTyPointerTy(), CGM.Int32Ty,
1574 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1575 llvm::FunctionType *FnTy =
1576 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1577 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1578 break;
1579 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001580 case OMPRTL__kmpc_cancel_barrier: {
1581 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1582 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001583 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1584 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001585 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1586 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001587 break;
1588 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001589 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001590 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001591 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1592 llvm::FunctionType *FnTy =
1593 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1594 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1595 break;
1596 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001597 case OMPRTL__kmpc_for_static_fini: {
1598 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1599 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1600 llvm::FunctionType *FnTy =
1601 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1602 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1603 break;
1604 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001605 case OMPRTL__kmpc_push_num_threads: {
1606 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1607 // kmp_int32 num_threads)
1608 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1609 CGM.Int32Ty};
1610 llvm::FunctionType *FnTy =
1611 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1612 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1613 break;
1614 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001615 case OMPRTL__kmpc_serialized_parallel: {
1616 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1617 // global_tid);
1618 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1619 llvm::FunctionType *FnTy =
1620 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1621 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1622 break;
1623 }
1624 case OMPRTL__kmpc_end_serialized_parallel: {
1625 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1626 // global_tid);
1627 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1628 llvm::FunctionType *FnTy =
1629 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1630 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1631 break;
1632 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001633 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001634 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001635 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1636 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001637 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001638 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1639 break;
1640 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001641 case OMPRTL__kmpc_master: {
1642 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1643 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1644 llvm::FunctionType *FnTy =
1645 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1646 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1647 break;
1648 }
1649 case OMPRTL__kmpc_end_master: {
1650 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1651 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1652 llvm::FunctionType *FnTy =
1653 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1654 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1655 break;
1656 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001657 case OMPRTL__kmpc_omp_taskyield: {
1658 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1659 // int end_part);
1660 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1661 llvm::FunctionType *FnTy =
1662 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1663 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1664 break;
1665 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001666 case OMPRTL__kmpc_single: {
1667 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1668 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1669 llvm::FunctionType *FnTy =
1670 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1671 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1672 break;
1673 }
1674 case OMPRTL__kmpc_end_single: {
1675 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1676 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1677 llvm::FunctionType *FnTy =
1678 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1679 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1680 break;
1681 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001682 case OMPRTL__kmpc_omp_task_alloc: {
1683 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1684 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1685 // kmp_routine_entry_t *task_entry);
1686 assert(KmpRoutineEntryPtrTy != nullptr &&
1687 "Type kmp_routine_entry_t must be created.");
1688 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1689 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1690 // Return void * and then cast to particular kmp_task_t type.
1691 llvm::FunctionType *FnTy =
1692 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1693 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1694 break;
1695 }
1696 case OMPRTL__kmpc_omp_task: {
1697 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1698 // *new_task);
1699 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1700 CGM.VoidPtrTy};
1701 llvm::FunctionType *FnTy =
1702 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1703 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1704 break;
1705 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001706 case OMPRTL__kmpc_copyprivate: {
1707 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001708 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001709 // kmp_int32 didit);
1710 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1711 auto *CpyFnTy =
1712 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001713 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001714 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1715 CGM.Int32Ty};
1716 llvm::FunctionType *FnTy =
1717 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1718 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1719 break;
1720 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001721 case OMPRTL__kmpc_reduce: {
1722 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1723 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1724 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1725 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1726 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1727 /*isVarArg=*/false);
1728 llvm::Type *TypeParams[] = {
1729 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1730 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1731 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1732 llvm::FunctionType *FnTy =
1733 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1734 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1735 break;
1736 }
1737 case OMPRTL__kmpc_reduce_nowait: {
1738 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1739 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1740 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1741 // *lck);
1742 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1743 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1744 /*isVarArg=*/false);
1745 llvm::Type *TypeParams[] = {
1746 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1747 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1748 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1749 llvm::FunctionType *FnTy =
1750 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1751 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1752 break;
1753 }
1754 case OMPRTL__kmpc_end_reduce: {
1755 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1756 // kmp_critical_name *lck);
1757 llvm::Type *TypeParams[] = {
1758 getIdentTyPointerTy(), CGM.Int32Ty,
1759 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1760 llvm::FunctionType *FnTy =
1761 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1762 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1763 break;
1764 }
1765 case OMPRTL__kmpc_end_reduce_nowait: {
1766 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1767 // kmp_critical_name *lck);
1768 llvm::Type *TypeParams[] = {
1769 getIdentTyPointerTy(), CGM.Int32Ty,
1770 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1771 llvm::FunctionType *FnTy =
1772 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1773 RTLFn =
1774 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1775 break;
1776 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001777 case OMPRTL__kmpc_omp_task_begin_if0: {
1778 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1779 // *new_task);
1780 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1781 CGM.VoidPtrTy};
1782 llvm::FunctionType *FnTy =
1783 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1784 RTLFn =
1785 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1786 break;
1787 }
1788 case OMPRTL__kmpc_omp_task_complete_if0: {
1789 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1790 // *new_task);
1791 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1792 CGM.VoidPtrTy};
1793 llvm::FunctionType *FnTy =
1794 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1795 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1796 /*Name=*/"__kmpc_omp_task_complete_if0");
1797 break;
1798 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001799 case OMPRTL__kmpc_ordered: {
1800 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1801 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1802 llvm::FunctionType *FnTy =
1803 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1804 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1805 break;
1806 }
1807 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001808 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001809 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1810 llvm::FunctionType *FnTy =
1811 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1812 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1813 break;
1814 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001815 case OMPRTL__kmpc_omp_taskwait: {
1816 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1817 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1818 llvm::FunctionType *FnTy =
1819 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1820 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1821 break;
1822 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001823 case OMPRTL__kmpc_taskgroup: {
1824 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1825 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1826 llvm::FunctionType *FnTy =
1827 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1828 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1829 break;
1830 }
1831 case OMPRTL__kmpc_end_taskgroup: {
1832 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1833 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1834 llvm::FunctionType *FnTy =
1835 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1836 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1837 break;
1838 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001839 case OMPRTL__kmpc_push_proc_bind: {
1840 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1841 // int proc_bind)
1842 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1843 llvm::FunctionType *FnTy =
1844 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1845 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1846 break;
1847 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001848 case OMPRTL__kmpc_omp_task_with_deps: {
1849 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1850 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1851 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1852 llvm::Type *TypeParams[] = {
1853 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1854 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1855 llvm::FunctionType *FnTy =
1856 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1857 RTLFn =
1858 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1859 break;
1860 }
1861 case OMPRTL__kmpc_omp_wait_deps: {
1862 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1863 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1864 // kmp_depend_info_t *noalias_dep_list);
1865 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1866 CGM.Int32Ty, CGM.VoidPtrTy,
1867 CGM.Int32Ty, CGM.VoidPtrTy};
1868 llvm::FunctionType *FnTy =
1869 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1870 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1871 break;
1872 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001873 case OMPRTL__kmpc_cancellationpoint: {
1874 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1875 // global_tid, kmp_int32 cncl_kind)
1876 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1877 llvm::FunctionType *FnTy =
1878 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1879 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1880 break;
1881 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001882 case OMPRTL__kmpc_cancel: {
1883 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1884 // kmp_int32 cncl_kind)
1885 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1886 llvm::FunctionType *FnTy =
1887 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1888 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1889 break;
1890 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001891 case OMPRTL__kmpc_push_num_teams: {
1892 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1893 // kmp_int32 num_teams, kmp_int32 num_threads)
1894 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1895 CGM.Int32Ty};
1896 llvm::FunctionType *FnTy =
1897 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1898 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1899 break;
1900 }
1901 case OMPRTL__kmpc_fork_teams: {
1902 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1903 // microtask, ...);
1904 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1905 getKmpc_MicroPointerTy()};
1906 llvm::FunctionType *FnTy =
1907 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1908 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1909 break;
1910 }
Alexey Bataev7292c292016-04-25 12:22:29 +00001911 case OMPRTL__kmpc_taskloop: {
1912 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
1913 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
1914 // sched, kmp_uint64 grainsize, void *task_dup);
1915 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1916 CGM.IntTy,
1917 CGM.VoidPtrTy,
1918 CGM.IntTy,
1919 CGM.Int64Ty->getPointerTo(),
1920 CGM.Int64Ty->getPointerTo(),
1921 CGM.Int64Ty,
1922 CGM.IntTy,
1923 CGM.IntTy,
1924 CGM.Int64Ty,
1925 CGM.VoidPtrTy};
1926 llvm::FunctionType *FnTy =
1927 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1928 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
1929 break;
1930 }
Alexey Bataev8b427062016-05-25 12:36:08 +00001931 case OMPRTL__kmpc_doacross_init: {
1932 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
1933 // num_dims, struct kmp_dim *dims);
1934 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1935 CGM.Int32Ty,
1936 CGM.Int32Ty,
1937 CGM.VoidPtrTy};
1938 llvm::FunctionType *FnTy =
1939 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1940 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
1941 break;
1942 }
1943 case OMPRTL__kmpc_doacross_fini: {
1944 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
1945 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1946 llvm::FunctionType *FnTy =
1947 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1948 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
1949 break;
1950 }
1951 case OMPRTL__kmpc_doacross_post: {
1952 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
1953 // *vec);
1954 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1955 CGM.Int64Ty->getPointerTo()};
1956 llvm::FunctionType *FnTy =
1957 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1958 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
1959 break;
1960 }
1961 case OMPRTL__kmpc_doacross_wait: {
1962 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
1963 // *vec);
1964 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1965 CGM.Int64Ty->getPointerTo()};
1966 llvm::FunctionType *FnTy =
1967 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1968 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
1969 break;
1970 }
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00001971 case OMPRTL__kmpc_task_reduction_init: {
1972 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void
1973 // *data);
1974 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy};
1975 llvm::FunctionType *FnTy =
1976 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1977 RTLFn =
1978 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init");
1979 break;
1980 }
1981 case OMPRTL__kmpc_task_reduction_get_th_data: {
1982 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
1983 // *d);
1984 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy};
1985 llvm::FunctionType *FnTy =
1986 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1987 RTLFn = CGM.CreateRuntimeFunction(
1988 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data");
1989 break;
1990 }
Samuel Antaobed3c462015-10-02 16:14:20 +00001991 case OMPRTL__tgt_target: {
1992 // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
1993 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
1994 // *arg_types);
1995 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1996 CGM.VoidPtrTy,
1997 CGM.Int32Ty,
1998 CGM.VoidPtrPtrTy,
1999 CGM.VoidPtrPtrTy,
2000 CGM.SizeTy->getPointerTo(),
2001 CGM.Int32Ty->getPointerTo()};
2002 llvm::FunctionType *FnTy =
2003 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2004 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
2005 break;
2006 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00002007 case OMPRTL__tgt_target_teams: {
2008 // Build int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
2009 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
2010 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
2011 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2012 CGM.VoidPtrTy,
2013 CGM.Int32Ty,
2014 CGM.VoidPtrPtrTy,
2015 CGM.VoidPtrPtrTy,
2016 CGM.SizeTy->getPointerTo(),
2017 CGM.Int32Ty->getPointerTo(),
2018 CGM.Int32Ty,
2019 CGM.Int32Ty};
2020 llvm::FunctionType *FnTy =
2021 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2022 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
2023 break;
2024 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00002025 case OMPRTL__tgt_register_lib: {
2026 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
2027 QualType ParamTy =
2028 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2029 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2030 llvm::FunctionType *FnTy =
2031 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2032 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
2033 break;
2034 }
2035 case OMPRTL__tgt_unregister_lib: {
2036 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
2037 QualType ParamTy =
2038 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
2039 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2040 llvm::FunctionType *FnTy =
2041 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2042 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2043 break;
2044 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002045 case OMPRTL__tgt_target_data_begin: {
2046 // Build void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
2047 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2048 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2049 CGM.Int32Ty,
2050 CGM.VoidPtrPtrTy,
2051 CGM.VoidPtrPtrTy,
2052 CGM.SizeTy->getPointerTo(),
2053 CGM.Int32Ty->getPointerTo()};
2054 llvm::FunctionType *FnTy =
2055 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2056 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2057 break;
2058 }
2059 case OMPRTL__tgt_target_data_end: {
2060 // Build void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
2061 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2062 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2063 CGM.Int32Ty,
2064 CGM.VoidPtrPtrTy,
2065 CGM.VoidPtrPtrTy,
2066 CGM.SizeTy->getPointerTo(),
2067 CGM.Int32Ty->getPointerTo()};
2068 llvm::FunctionType *FnTy =
2069 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2070 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2071 break;
2072 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002073 case OMPRTL__tgt_target_data_update: {
2074 // Build void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
2075 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2076 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2077 CGM.Int32Ty,
2078 CGM.VoidPtrPtrTy,
2079 CGM.VoidPtrPtrTy,
2080 CGM.SizeTy->getPointerTo(),
2081 CGM.Int32Ty->getPointerTo()};
2082 llvm::FunctionType *FnTy =
2083 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2084 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2085 break;
2086 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002087 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002088 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002089 return RTLFn;
2090}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002091
Alexander Musman21212e42015-03-13 10:38:23 +00002092llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2093 bool IVSigned) {
2094 assert((IVSize == 32 || IVSize == 64) &&
2095 "IV size is not compatible with the omp runtime");
2096 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2097 : "__kmpc_for_static_init_4u")
2098 : (IVSigned ? "__kmpc_for_static_init_8"
2099 : "__kmpc_for_static_init_8u");
2100 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2101 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2102 llvm::Type *TypeParams[] = {
2103 getIdentTyPointerTy(), // loc
2104 CGM.Int32Ty, // tid
2105 CGM.Int32Ty, // schedtype
2106 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2107 PtrTy, // p_lower
2108 PtrTy, // p_upper
2109 PtrTy, // p_stride
2110 ITy, // incr
2111 ITy // chunk
2112 };
2113 llvm::FunctionType *FnTy =
2114 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2115 return CGM.CreateRuntimeFunction(FnTy, Name);
2116}
2117
Alexander Musman92bdaab2015-03-12 13:37:50 +00002118llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2119 bool IVSigned) {
2120 assert((IVSize == 32 || IVSize == 64) &&
2121 "IV size is not compatible with the omp runtime");
2122 auto Name =
2123 IVSize == 32
2124 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2125 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
2126 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2127 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2128 CGM.Int32Ty, // tid
2129 CGM.Int32Ty, // schedtype
2130 ITy, // lower
2131 ITy, // upper
2132 ITy, // stride
2133 ITy // chunk
2134 };
2135 llvm::FunctionType *FnTy =
2136 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2137 return CGM.CreateRuntimeFunction(FnTy, Name);
2138}
2139
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002140llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2141 bool IVSigned) {
2142 assert((IVSize == 32 || IVSize == 64) &&
2143 "IV size is not compatible with the omp runtime");
2144 auto Name =
2145 IVSize == 32
2146 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2147 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2148 llvm::Type *TypeParams[] = {
2149 getIdentTyPointerTy(), // loc
2150 CGM.Int32Ty, // tid
2151 };
2152 llvm::FunctionType *FnTy =
2153 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2154 return CGM.CreateRuntimeFunction(FnTy, Name);
2155}
2156
Alexander Musman92bdaab2015-03-12 13:37:50 +00002157llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2158 bool IVSigned) {
2159 assert((IVSize == 32 || IVSize == 64) &&
2160 "IV size is not compatible with the omp runtime");
2161 auto Name =
2162 IVSize == 32
2163 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2164 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
2165 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2166 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2167 llvm::Type *TypeParams[] = {
2168 getIdentTyPointerTy(), // loc
2169 CGM.Int32Ty, // tid
2170 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2171 PtrTy, // p_lower
2172 PtrTy, // p_upper
2173 PtrTy // p_stride
2174 };
2175 llvm::FunctionType *FnTy =
2176 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2177 return CGM.CreateRuntimeFunction(FnTy, Name);
2178}
2179
Alexey Bataev97720002014-11-11 04:05:39 +00002180llvm::Constant *
2181CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002182 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2183 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002184 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002185 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002186 Twine(CGM.getMangledName(VD)) + ".cache.");
2187}
2188
John McCall7f416cc2015-09-08 08:05:57 +00002189Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2190 const VarDecl *VD,
2191 Address VDAddr,
2192 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002193 if (CGM.getLangOpts().OpenMPUseTLS &&
2194 CGM.getContext().getTargetInfo().isTLSSupported())
2195 return VDAddr;
2196
John McCall7f416cc2015-09-08 08:05:57 +00002197 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002198 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002199 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2200 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002201 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2202 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002203 return Address(CGF.EmitRuntimeCall(
2204 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2205 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002206}
2207
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002208void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002209 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002210 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2211 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2212 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002213 auto OMPLoc = emitUpdateLocation(CGF, Loc);
2214 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002215 OMPLoc);
2216 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2217 // to register constructor/destructor for variable.
2218 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00002219 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2220 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002221 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002222 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002223 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002224}
2225
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002226llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002227 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002228 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002229 if (CGM.getLangOpts().OpenMPUseTLS &&
2230 CGM.getContext().getTargetInfo().isTLSSupported())
2231 return nullptr;
2232
Alexey Bataev97720002014-11-11 04:05:39 +00002233 VD = VD->getDefinition(CGM.getContext());
2234 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
2235 ThreadPrivateWithDefinition.insert(VD);
2236 QualType ASTTy = VD->getType();
2237
2238 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
2239 auto Init = VD->getAnyInitializer();
2240 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2241 // Generate function that re-emits the declaration's initializer into the
2242 // threadprivate copy of the variable VD
2243 CodeGenFunction CtorCGF(CGM);
2244 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002245 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
2246 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002247 Args.push_back(&Dst);
2248
John McCallc56a8b32016-03-11 04:30:31 +00002249 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2250 CGM.getContext().VoidPtrTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002251 auto FTy = CGM.getTypes().GetFunctionType(FI);
2252 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002253 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002254 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
2255 Args, SourceLocation());
2256 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002257 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002258 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002259 Address Arg = Address(ArgVal, VDAddr.getAlignment());
2260 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
2261 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002262 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2263 /*IsInitializer=*/true);
2264 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002265 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002266 CGM.getContext().VoidPtrTy, Dst.getLocation());
2267 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2268 CtorCGF.FinishFunction();
2269 Ctor = Fn;
2270 }
2271 if (VD->getType().isDestructedType() != QualType::DK_none) {
2272 // Generate function that emits destructor call for the threadprivate copy
2273 // of the variable VD
2274 CodeGenFunction DtorCGF(CGM);
2275 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002276 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
2277 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002278 Args.push_back(&Dst);
2279
John McCallc56a8b32016-03-11 04:30:31 +00002280 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2281 CGM.getContext().VoidTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002282 auto FTy = CGM.getTypes().GetFunctionType(FI);
2283 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002284 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002285 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002286 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
2287 SourceLocation());
Adrian Prantl1858c662016-04-24 22:22:29 +00002288 // Create a scope with an artificial location for the body of this function.
2289 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002290 auto ArgVal = DtorCGF.EmitLoadOfScalar(
2291 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002292 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2293 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002294 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2295 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2296 DtorCGF.FinishFunction();
2297 Dtor = Fn;
2298 }
2299 // Do not emit init function if it is not required.
2300 if (!Ctor && !Dtor)
2301 return nullptr;
2302
2303 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
2304 auto CopyCtorTy =
2305 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2306 /*isVarArg=*/false)->getPointerTo();
2307 // Copying constructor for the threadprivate variable.
2308 // Must be NULL - reserved by runtime, but currently it requires that this
2309 // parameter is always NULL. Otherwise it fires assertion.
2310 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2311 if (Ctor == nullptr) {
2312 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2313 /*isVarArg=*/false)->getPointerTo();
2314 Ctor = llvm::Constant::getNullValue(CtorTy);
2315 }
2316 if (Dtor == nullptr) {
2317 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2318 /*isVarArg=*/false)->getPointerTo();
2319 Dtor = llvm::Constant::getNullValue(DtorTy);
2320 }
2321 if (!CGF) {
2322 auto InitFunctionTy =
2323 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
2324 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002325 InitFunctionTy, ".__omp_threadprivate_init_.",
2326 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002327 CodeGenFunction InitCGF(CGM);
2328 FunctionArgList ArgList;
2329 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2330 CGM.getTypes().arrangeNullaryFunction(), ArgList,
2331 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002332 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002333 InitCGF.FinishFunction();
2334 return InitFunction;
2335 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002336 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002337 }
2338 return nullptr;
2339}
2340
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002341Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2342 QualType VarType,
2343 StringRef Name) {
2344 llvm::Twine VarName(Name, ".artificial.");
2345 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
2346 llvm::Value *GAddr = getOrCreateInternalVariable(VarLVType, VarName);
2347 llvm::Value *Args[] = {
2348 emitUpdateLocation(CGF, SourceLocation()),
2349 getThreadID(CGF, SourceLocation()),
2350 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2351 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2352 /*IsSigned=*/false),
2353 getOrCreateInternalVariable(CGM.VoidPtrPtrTy, VarName + ".cache.")};
2354 return Address(
2355 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2356 CGF.EmitRuntimeCall(
2357 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2358 VarLVType->getPointerTo(/*AddrSpace=*/0)),
2359 CGM.getPointerAlign());
2360}
2361
Alexey Bataev1d677132015-04-22 13:57:31 +00002362/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
2363/// function. Here is the logic:
2364/// if (Cond) {
2365/// ThenGen();
2366/// } else {
2367/// ElseGen();
2368/// }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002369void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2370 const RegionCodeGenTy &ThenGen,
2371 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002372 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2373
2374 // If the condition constant folds and can be elided, try to avoid emitting
2375 // the condition and the dead arm of the if/else.
2376 bool CondConstant;
2377 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002378 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002379 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002380 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002381 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002382 return;
2383 }
2384
2385 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2386 // emit the conditional branch.
2387 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
2388 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
2389 auto ContBlock = CGF.createBasicBlock("omp_if.end");
2390 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2391
2392 // Emit the 'then' code.
2393 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002394 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002395 CGF.EmitBranch(ContBlock);
2396 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002397 // There is no need to emit line number for unconditional branch.
2398 (void)ApplyDebugLocation::CreateEmpty(CGF);
2399 CGF.EmitBlock(ElseBlock);
2400 ElseGen(CGF);
2401 // There is no need to emit line number for unconditional branch.
2402 (void)ApplyDebugLocation::CreateEmpty(CGF);
2403 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002404 // Emit the continuation block for code after the if.
2405 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002406}
2407
Alexey Bataev1d677132015-04-22 13:57:31 +00002408void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2409 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002410 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002411 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002412 if (!CGF.HaveInsertPoint())
2413 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00002414 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002415 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2416 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002417 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002418 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002419 llvm::Value *Args[] = {
2420 RTLoc,
2421 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002422 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002423 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2424 RealArgs.append(std::begin(Args), std::end(Args));
2425 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2426
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002427 auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002428 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2429 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002430 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2431 PrePostActionTy &) {
2432 auto &RT = CGF.CGM.getOpenMPRuntime();
2433 auto ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00002434 // Build calls:
2435 // __kmpc_serialized_parallel(&Loc, GTid);
2436 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002437 CGF.EmitRuntimeCall(
2438 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002439
Alexey Bataev1d677132015-04-22 13:57:31 +00002440 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002441 auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00002442 Address ZeroAddr =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002443 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
2444 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00002445 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00002446 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2447 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2448 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2449 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev3c595a62017-08-14 15:01:03 +00002450 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002451
Alexey Bataev1d677132015-04-22 13:57:31 +00002452 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002453 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00002454 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002455 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2456 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002457 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002458 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00002459 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002460 else {
2461 RegionCodeGenTy ThenRCG(ThenGen);
2462 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002463 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002464}
2465
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002466// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002467// thread-ID variable (it is passed in a first argument of the outlined function
2468// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2469// regular serial code region, get thread ID by calling kmp_int32
2470// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2471// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002472Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2473 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002474 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002475 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002476 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002477 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002478
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002479 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002480 auto Int32Ty =
2481 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2482 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2483 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002484 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002485
2486 return ThreadIDTemp;
2487}
2488
Alexey Bataev97720002014-11-11 04:05:39 +00002489llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002490CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002491 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002492 SmallString<256> Buffer;
2493 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002494 Out << Name;
2495 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00002496 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
2497 if (Elem.second) {
2498 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002499 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002500 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002501 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002502
David Blaikie13156b62014-11-19 03:06:06 +00002503 return Elem.second = new llvm::GlobalVariable(
2504 CGM.getModule(), Ty, /*IsConstant*/ false,
2505 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2506 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002507}
2508
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002509llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00002510 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002511 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002512}
2513
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002514namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002515/// Common pre(post)-action for different OpenMP constructs.
2516class CommonActionTy final : public PrePostActionTy {
2517 llvm::Value *EnterCallee;
2518 ArrayRef<llvm::Value *> EnterArgs;
2519 llvm::Value *ExitCallee;
2520 ArrayRef<llvm::Value *> ExitArgs;
2521 bool Conditional;
2522 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002523
2524public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002525 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2526 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2527 bool Conditional = false)
2528 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2529 ExitArgs(ExitArgs), Conditional(Conditional) {}
2530 void Enter(CodeGenFunction &CGF) override {
2531 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2532 if (Conditional) {
2533 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2534 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2535 ContBlock = CGF.createBasicBlock("omp_if.end");
2536 // Generate the branch (If-stmt)
2537 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2538 CGF.EmitBlock(ThenBlock);
2539 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002540 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002541 void Done(CodeGenFunction &CGF) {
2542 // Emit the rest of blocks/branches
2543 CGF.EmitBranch(ContBlock);
2544 CGF.EmitBlock(ContBlock, true);
2545 }
2546 void Exit(CodeGenFunction &CGF) override {
2547 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002548 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002549};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002550} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002551
2552void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2553 StringRef CriticalName,
2554 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002555 SourceLocation Loc, const Expr *Hint) {
2556 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002557 // CriticalOpGen();
2558 // __kmpc_end_critical(ident_t *, gtid, Lock);
2559 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002560 if (!CGF.HaveInsertPoint())
2561 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002562 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2563 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002564 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2565 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002566 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002567 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2568 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2569 }
2570 CommonActionTy Action(
2571 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2572 : OMPRTL__kmpc_critical),
2573 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2574 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002575 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002576}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002577
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002578void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002579 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002580 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002581 if (!CGF.HaveInsertPoint())
2582 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002583 // if(__kmpc_master(ident_t *, gtid)) {
2584 // MasterOpGen();
2585 // __kmpc_end_master(ident_t *, gtid);
2586 // }
2587 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002588 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002589 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2590 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2591 /*Conditional=*/true);
2592 MasterOpGen.setAction(Action);
2593 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2594 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002595}
2596
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002597void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2598 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002599 if (!CGF.HaveInsertPoint())
2600 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00002601 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2602 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002603 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00002604 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002605 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002606 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2607 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00002608}
2609
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002610void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2611 const RegionCodeGenTy &TaskgroupOpGen,
2612 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002613 if (!CGF.HaveInsertPoint())
2614 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002615 // __kmpc_taskgroup(ident_t *, gtid);
2616 // TaskgroupOpGen();
2617 // __kmpc_end_taskgroup(ident_t *, gtid);
2618 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002619 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2620 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2621 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2622 Args);
2623 TaskgroupOpGen.setAction(Action);
2624 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002625}
2626
John McCall7f416cc2015-09-08 08:05:57 +00002627/// Given an array of pointers to variables, project the address of a
2628/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002629static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2630 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00002631 // Pull out the pointer to the variable.
2632 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002633 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00002634 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2635
2636 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002637 Addr = CGF.Builder.CreateElementBitCast(
2638 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002639 return Addr;
2640}
2641
Alexey Bataeva63048e2015-03-23 06:18:07 +00002642static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00002643 CodeGenModule &CGM, llvm::Type *ArgsType,
2644 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
2645 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002646 auto &C = CGM.getContext();
2647 // void copy_func(void *LHSArg, void *RHSArg);
2648 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002649 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
2650 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002651 Args.push_back(&LHSArg);
2652 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00002653 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002654 auto *Fn = llvm::Function::Create(
2655 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2656 ".omp.copyprivate.copy_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002657 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002658 CodeGenFunction CGF(CGM);
2659 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00002660 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002661 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00002662 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2663 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2664 ArgsType), CGF.getPointerAlign());
2665 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2666 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2667 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002668 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2669 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2670 // ...
2671 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00002672 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002673 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2674 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2675
2676 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2677 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2678
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002679 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2680 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00002681 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002682 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002683 CGF.FinishFunction();
2684 return Fn;
2685}
2686
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002687void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002688 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00002689 SourceLocation Loc,
2690 ArrayRef<const Expr *> CopyprivateVars,
2691 ArrayRef<const Expr *> SrcExprs,
2692 ArrayRef<const Expr *> DstExprs,
2693 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002694 if (!CGF.HaveInsertPoint())
2695 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002696 assert(CopyprivateVars.size() == SrcExprs.size() &&
2697 CopyprivateVars.size() == DstExprs.size() &&
2698 CopyprivateVars.size() == AssignmentOps.size());
2699 auto &C = CGM.getContext();
2700 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002701 // if(__kmpc_single(ident_t *, gtid)) {
2702 // SingleOpGen();
2703 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002704 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002705 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002706 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2707 // <copy_func>, did_it);
2708
John McCall7f416cc2015-09-08 08:05:57 +00002709 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00002710 if (!CopyprivateVars.empty()) {
2711 // int32 did_it = 0;
2712 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2713 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00002714 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002715 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002716 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002717 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002718 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
2719 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
2720 /*Conditional=*/true);
2721 SingleOpGen.setAction(Action);
2722 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2723 if (DidIt.isValid()) {
2724 // did_it = 1;
2725 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2726 }
2727 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002728 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2729 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00002730 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002731 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2732 auto CopyprivateArrayTy =
2733 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2734 /*IndexTypeQuals=*/0);
2735 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00002736 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00002737 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2738 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002739 Address Elem = CGF.Builder.CreateConstArrayGEP(
2740 CopyprivateList, I, CGF.getPointerSize());
2741 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00002742 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002743 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2744 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002745 }
2746 // Build function that copies private values from single region to all other
2747 // threads in the corresponding parallel region.
2748 auto *CpyFn = emitCopyprivateCopyFunction(
2749 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00002750 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev1189bd02016-01-26 12:20:39 +00002751 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00002752 Address CL =
2753 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2754 CGF.VoidPtrTy);
2755 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002756 llvm::Value *Args[] = {
2757 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2758 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00002759 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00002760 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00002761 CpyFn, // void (*) (void *, void *) <copy_func>
2762 DidItVal // i32 did_it
2763 };
2764 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2765 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002766}
2767
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002768void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2769 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00002770 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002771 if (!CGF.HaveInsertPoint())
2772 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002773 // __kmpc_ordered(ident_t *, gtid);
2774 // OrderedOpGen();
2775 // __kmpc_end_ordered(ident_t *, gtid);
2776 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00002777 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002778 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002779 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
2780 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2781 Args);
2782 OrderedOpGen.setAction(Action);
2783 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2784 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002785 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002786 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002787}
2788
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002789void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002790 OpenMPDirectiveKind Kind, bool EmitChecks,
2791 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002792 if (!CGF.HaveInsertPoint())
2793 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002794 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002795 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002796 unsigned Flags;
2797 if (Kind == OMPD_for)
2798 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2799 else if (Kind == OMPD_sections)
2800 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2801 else if (Kind == OMPD_single)
2802 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2803 else if (Kind == OMPD_barrier)
2804 Flags = OMP_IDENT_BARRIER_EXPL;
2805 else
2806 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002807 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2808 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002809 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2810 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002811 if (auto *OMPRegionInfo =
2812 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00002813 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002814 auto *Result = CGF.EmitRuntimeCall(
2815 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002816 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002817 // if (__kmpc_cancel_barrier()) {
2818 // exit from construct;
2819 // }
2820 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2821 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2822 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2823 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2824 CGF.EmitBlock(ExitBB);
2825 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002826 auto CancelDestination =
2827 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002828 CGF.EmitBranchThroughCleanup(CancelDestination);
2829 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2830 }
2831 return;
2832 }
2833 }
2834 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002835}
2836
Alexander Musmanc6388682014-12-15 07:07:06 +00002837/// \brief Map the OpenMP loop schedule to the runtime enumeration.
2838static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002839 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002840 switch (ScheduleKind) {
2841 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002842 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2843 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00002844 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002845 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002846 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002847 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002848 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002849 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2850 case OMPC_SCHEDULE_auto:
2851 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00002852 case OMPC_SCHEDULE_unknown:
2853 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002854 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00002855 }
2856 llvm_unreachable("Unexpected runtime schedule");
2857}
2858
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002859/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
2860static OpenMPSchedType
2861getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2862 // only static is allowed for dist_schedule
2863 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
2864}
2865
Alexander Musmanc6388682014-12-15 07:07:06 +00002866bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2867 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002868 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00002869 return Schedule == OMP_sch_static;
2870}
2871
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002872bool CGOpenMPRuntime::isStaticNonchunked(
2873 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2874 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2875 return Schedule == OMP_dist_sch_static;
2876}
2877
2878
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002879bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002880 auto Schedule =
2881 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002882 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2883 return Schedule != OMP_sch_static;
2884}
2885
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002886static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
2887 OpenMPScheduleClauseModifier M1,
2888 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00002889 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002890 switch (M1) {
2891 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002892 Modifier = OMP_sch_modifier_monotonic;
2893 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002894 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002895 Modifier = OMP_sch_modifier_nonmonotonic;
2896 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002897 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002898 if (Schedule == OMP_sch_static_chunked)
2899 Schedule = OMP_sch_static_balanced_chunked;
2900 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002901 case OMPC_SCHEDULE_MODIFIER_last:
2902 case OMPC_SCHEDULE_MODIFIER_unknown:
2903 break;
2904 }
2905 switch (M2) {
2906 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002907 Modifier = OMP_sch_modifier_monotonic;
2908 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002909 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002910 Modifier = OMP_sch_modifier_nonmonotonic;
2911 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002912 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002913 if (Schedule == OMP_sch_static_chunked)
2914 Schedule = OMP_sch_static_balanced_chunked;
2915 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002916 case OMPC_SCHEDULE_MODIFIER_last:
2917 case OMPC_SCHEDULE_MODIFIER_unknown:
2918 break;
2919 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00002920 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002921}
2922
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002923void CGOpenMPRuntime::emitForDispatchInit(
2924 CodeGenFunction &CGF, SourceLocation Loc,
2925 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
2926 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002927 if (!CGF.HaveInsertPoint())
2928 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002929 OpenMPSchedType Schedule = getRuntimeSchedule(
2930 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00002931 assert(Ordered ||
2932 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00002933 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
2934 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00002935 // Call __kmpc_dispatch_init(
2936 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2937 // kmp_int[32|64] lower, kmp_int[32|64] upper,
2938 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002939
John McCall7f416cc2015-09-08 08:05:57 +00002940 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002941 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
2942 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00002943 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002944 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2945 CGF.Builder.getInt32(addMonoNonMonoModifier(
2946 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002947 DispatchValues.LB, // Lower
2948 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002949 CGF.Builder.getIntN(IVSize, 1), // Stride
2950 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00002951 };
2952 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2953}
2954
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002955static void emitForStaticInitCall(
2956 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
2957 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
2958 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
2959 unsigned IVSize, bool Ordered, Address IL, Address LB, Address UB,
2960 Address ST, llvm::Value *Chunk) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002961 if (!CGF.HaveInsertPoint())
2962 return;
2963
2964 assert(!Ordered);
2965 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
Alexey Bataev6cff6242016-05-30 13:05:14 +00002966 Schedule == OMP_sch_static_balanced_chunked ||
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002967 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
2968 Schedule == OMP_dist_sch_static ||
2969 Schedule == OMP_dist_sch_static_chunked);
2970
2971 // Call __kmpc_for_static_init(
2972 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2973 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2974 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2975 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
2976 if (Chunk == nullptr) {
2977 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
2978 Schedule == OMP_dist_sch_static) &&
2979 "expected static non-chunked schedule");
2980 // If the Chunk was not specified in the clause - use default value 1.
2981 Chunk = CGF.Builder.getIntN(IVSize, 1);
2982 } else {
2983 assert((Schedule == OMP_sch_static_chunked ||
Alexey Bataev6cff6242016-05-30 13:05:14 +00002984 Schedule == OMP_sch_static_balanced_chunked ||
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002985 Schedule == OMP_ord_static_chunked ||
2986 Schedule == OMP_dist_sch_static_chunked) &&
2987 "expected static chunked schedule");
2988 }
2989 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002990 UpdateLocation, ThreadId, CGF.Builder.getInt32(addMonoNonMonoModifier(
2991 Schedule, M1, M2)), // Schedule type
2992 IL.getPointer(), // &isLastIter
2993 LB.getPointer(), // &LB
2994 UB.getPointer(), // &UB
2995 ST.getPointer(), // &Stride
2996 CGF.Builder.getIntN(IVSize, 1), // Incr
2997 Chunk // Chunk
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002998 };
2999 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
3000}
3001
John McCall7f416cc2015-09-08 08:05:57 +00003002void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
3003 SourceLocation Loc,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003004 const OpenMPScheduleTy &ScheduleKind,
John McCall7f416cc2015-09-08 08:05:57 +00003005 unsigned IVSize, bool IVSigned,
3006 bool Ordered, Address IL, Address LB,
3007 Address UB, Address ST,
3008 llvm::Value *Chunk) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003009 OpenMPSchedType ScheduleNum =
3010 getRuntimeSchedule(ScheduleKind.Schedule, Chunk != nullptr, Ordered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003011 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
3012 auto *ThreadId = getThreadID(CGF, Loc);
3013 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003014 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3015 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, IVSize,
3016 Ordered, IL, LB, UB, ST, Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003017}
John McCall7f416cc2015-09-08 08:05:57 +00003018
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003019void CGOpenMPRuntime::emitDistributeStaticInit(
3020 CodeGenFunction &CGF, SourceLocation Loc,
3021 OpenMPDistScheduleClauseKind SchedKind, unsigned IVSize, bool IVSigned,
3022 bool Ordered, Address IL, Address LB, Address UB, Address ST,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00003023 llvm::Value *Chunk) {
3024 OpenMPSchedType ScheduleNum = getRuntimeSchedule(SchedKind, Chunk != nullptr);
3025 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
3026 auto *ThreadId = getThreadID(CGF, Loc);
3027 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00003028 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
3029 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
3030 OMPC_SCHEDULE_MODIFIER_unknown, IVSize, Ordered, IL, LB,
3031 UB, ST, Chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00003032}
3033
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003034void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
3035 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003036 if (!CGF.HaveInsertPoint())
3037 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00003038 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003039 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003040 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
3041 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00003042}
3043
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00003044void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
3045 SourceLocation Loc,
3046 unsigned IVSize,
3047 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003048 if (!CGF.HaveInsertPoint())
3049 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003050 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00003051 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00003052 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
3053}
3054
Alexander Musman92bdaab2015-03-12 13:37:50 +00003055llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
3056 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00003057 bool IVSigned, Address IL,
3058 Address LB, Address UB,
3059 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00003060 // Call __kmpc_dispatch_next(
3061 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3062 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3063 // kmp_int[32|64] *p_stride);
3064 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003065 emitUpdateLocation(CGF, Loc),
3066 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003067 IL.getPointer(), // &isLastIter
3068 LB.getPointer(), // &Lower
3069 UB.getPointer(), // &Upper
3070 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003071 };
3072 llvm::Value *Call =
3073 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3074 return CGF.EmitScalarConversion(
3075 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003076 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003077}
3078
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003079void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3080 llvm::Value *NumThreads,
3081 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003082 if (!CGF.HaveInsertPoint())
3083 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003084 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3085 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003086 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003087 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003088 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3089 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003090}
3091
Alexey Bataev7f210c62015-06-18 13:40:03 +00003092void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3093 OpenMPProcBindClauseKind ProcBind,
3094 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003095 if (!CGF.HaveInsertPoint())
3096 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003097 // Constants for proc bind value accepted by the runtime.
3098 enum ProcBindTy {
3099 ProcBindFalse = 0,
3100 ProcBindTrue,
3101 ProcBindMaster,
3102 ProcBindClose,
3103 ProcBindSpread,
3104 ProcBindIntel,
3105 ProcBindDefault
3106 } RuntimeProcBind;
3107 switch (ProcBind) {
3108 case OMPC_PROC_BIND_master:
3109 RuntimeProcBind = ProcBindMaster;
3110 break;
3111 case OMPC_PROC_BIND_close:
3112 RuntimeProcBind = ProcBindClose;
3113 break;
3114 case OMPC_PROC_BIND_spread:
3115 RuntimeProcBind = ProcBindSpread;
3116 break;
3117 case OMPC_PROC_BIND_unknown:
3118 llvm_unreachable("Unsupported proc_bind value.");
3119 }
3120 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3121 llvm::Value *Args[] = {
3122 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3123 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3124 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3125}
3126
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003127void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3128 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003129 if (!CGF.HaveInsertPoint())
3130 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003131 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003132 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3133 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003134}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003135
Alexey Bataev62b63b12015-03-10 07:28:44 +00003136namespace {
3137/// \brief Indexes of fields for type kmp_task_t.
3138enum KmpTaskTFields {
3139 /// \brief List of shared variables.
3140 KmpTaskTShareds,
3141 /// \brief Task routine.
3142 KmpTaskTRoutine,
3143 /// \brief Partition id for the untied tasks.
3144 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003145 /// Function with call of destructors for private variables.
3146 Data1,
3147 /// Task priority.
3148 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003149 /// (Taskloops only) Lower bound.
3150 KmpTaskTLowerBound,
3151 /// (Taskloops only) Upper bound.
3152 KmpTaskTUpperBound,
3153 /// (Taskloops only) Stride.
3154 KmpTaskTStride,
3155 /// (Taskloops only) Is last iteration flag.
3156 KmpTaskTLastIter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003157 /// (Taskloops only) Reduction data.
3158 KmpTaskTReductions,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003159};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003160} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003161
Samuel Antaoee8fb302016-01-06 13:42:12 +00003162bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
3163 // FIXME: Add other entries type when they become supported.
3164 return OffloadEntriesTargetRegion.empty();
3165}
3166
3167/// \brief Initialize target region entry.
3168void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3169 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3170 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003171 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003172 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3173 "only required for the device "
3174 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003175 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003176 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
3177 /*Flags=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003178 ++OffloadingEntriesNum;
3179}
3180
3181void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3182 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3183 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003184 llvm::Constant *Addr, llvm::Constant *ID,
3185 int32_t Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003186 // If we are emitting code for a target, the entry is already initialized,
3187 // only has to be registered.
3188 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003189 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00003190 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003191 auto &Entry =
3192 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003193 assert(Entry.isValid() && "Entry not initialized!");
3194 Entry.setAddress(Addr);
3195 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003196 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003197 return;
3198 } else {
Samuel Antaof83efdb2017-01-05 16:02:49 +00003199 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003200 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003201 }
3202}
3203
3204bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003205 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3206 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003207 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3208 if (PerDevice == OffloadEntriesTargetRegion.end())
3209 return false;
3210 auto PerFile = PerDevice->second.find(FileID);
3211 if (PerFile == PerDevice->second.end())
3212 return false;
3213 auto PerParentName = PerFile->second.find(ParentName);
3214 if (PerParentName == PerFile->second.end())
3215 return false;
3216 auto PerLine = PerParentName->second.find(LineNum);
3217 if (PerLine == PerParentName->second.end())
3218 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003219 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003220 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003221 return false;
3222 return true;
3223}
3224
3225void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3226 const OffloadTargetRegionEntryInfoActTy &Action) {
3227 // Scan all target region entries and perform the provided action.
3228 for (auto &D : OffloadEntriesTargetRegion)
3229 for (auto &F : D.second)
3230 for (auto &P : F.second)
3231 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003232 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003233}
3234
3235/// \brief Create a Ctor/Dtor-like function whose body is emitted through
3236/// \a Codegen. This is used to emit the two functions that register and
3237/// unregister the descriptor of the current compilation unit.
3238static llvm::Function *
3239createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
3240 const RegionCodeGenTy &Codegen) {
3241 auto &C = CGM.getContext();
3242 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003243 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003244 Args.push_back(&DummyPtr);
3245
3246 CodeGenFunction CGF(CGM);
John McCallc56a8b32016-03-11 04:30:31 +00003247 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003248 auto FTy = CGM.getTypes().GetFunctionType(FI);
3249 auto *Fn =
3250 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
3251 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
3252 Codegen(CGF);
3253 CGF.FinishFunction();
3254 return Fn;
3255}
3256
3257llvm::Function *
3258CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
3259
3260 // If we don't have entries or if we are emitting code for the device, we
3261 // don't need to do anything.
3262 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3263 return nullptr;
3264
3265 auto &M = CGM.getModule();
3266 auto &C = CGM.getContext();
3267
3268 // Get list of devices we care about
3269 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
3270
3271 // We should be creating an offloading descriptor only if there are devices
3272 // specified.
3273 assert(!Devices.empty() && "No OpenMP offloading devices??");
3274
3275 // Create the external variables that will point to the begin and end of the
3276 // host entries section. These will be defined by the linker.
3277 auto *OffloadEntryTy =
3278 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
3279 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
3280 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003281 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003282 ".omp_offloading.entries_begin");
3283 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
3284 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003285 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003286 ".omp_offloading.entries_end");
3287
3288 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003289 auto *DeviceImageTy = cast<llvm::StructType>(
3290 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003291 ConstantInitBuilder DeviceImagesBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003292 auto DeviceImagesEntries = DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003293
3294 for (unsigned i = 0; i < Devices.size(); ++i) {
3295 StringRef T = Devices[i].getTriple();
3296 auto *ImgBegin = new llvm::GlobalVariable(
3297 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003298 /*Initializer=*/nullptr,
3299 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003300 auto *ImgEnd = new llvm::GlobalVariable(
3301 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003302 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003303
John McCall6c9f1fdb2016-11-19 08:17:24 +00003304 auto Dev = DeviceImagesEntries.beginStruct(DeviceImageTy);
3305 Dev.add(ImgBegin);
3306 Dev.add(ImgEnd);
3307 Dev.add(HostEntriesBegin);
3308 Dev.add(HostEntriesEnd);
John McCallf1788632016-11-28 22:18:30 +00003309 Dev.finishAndAddTo(DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003310 }
3311
3312 // Create device images global array.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003313 llvm::GlobalVariable *DeviceImages =
3314 DeviceImagesEntries.finishAndCreateGlobal(".omp_offloading.device_images",
3315 CGM.getPointerAlign(),
3316 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003317 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003318
3319 // This is a Zero array to be used in the creation of the constant expressions
3320 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3321 llvm::Constant::getNullValue(CGM.Int32Ty)};
3322
3323 // Create the target region descriptor.
3324 auto *BinaryDescriptorTy = cast<llvm::StructType>(
3325 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003326 ConstantInitBuilder DescBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003327 auto DescInit = DescBuilder.beginStruct(BinaryDescriptorTy);
3328 DescInit.addInt(CGM.Int32Ty, Devices.size());
3329 DescInit.add(llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3330 DeviceImages,
3331 Index));
3332 DescInit.add(HostEntriesBegin);
3333 DescInit.add(HostEntriesEnd);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003334
John McCall6c9f1fdb2016-11-19 08:17:24 +00003335 auto *Desc = DescInit.finishAndCreateGlobal(".omp_offloading.descriptor",
3336 CGM.getPointerAlign(),
3337 /*isConstant=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003338
3339 // Emit code to register or unregister the descriptor at execution
3340 // startup or closing, respectively.
3341
3342 // Create a variable to drive the registration and unregistration of the
3343 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3344 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
3345 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00003346 IdentInfo, C.CharTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003347
3348 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003349 CGM, ".omp_offloading.descriptor_unreg",
3350 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00003351 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3352 Desc);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003353 });
3354 auto *RegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003355 CGM, ".omp_offloading.descriptor_reg",
3356 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00003357 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib),
3358 Desc);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003359 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3360 });
George Rokos29d0f002017-05-27 03:03:13 +00003361 if (CGM.supportsCOMDAT()) {
3362 // It is sufficient to call registration function only once, so create a
3363 // COMDAT group for registration/unregistration functions and associated
3364 // data. That would reduce startup time and code size. Registration
3365 // function serves as a COMDAT group key.
3366 auto ComdatKey = M.getOrInsertComdat(RegFn->getName());
3367 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3368 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3369 RegFn->setComdat(ComdatKey);
3370 UnRegFn->setComdat(ComdatKey);
3371 DeviceImages->setComdat(ComdatKey);
3372 Desc->setComdat(ComdatKey);
3373 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003374 return RegFn;
3375}
3376
Samuel Antao2de62b02016-02-13 23:35:10 +00003377void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003378 llvm::Constant *Addr, uint64_t Size,
3379 int32_t Flags) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003380 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003381 auto *TgtOffloadEntryType = cast<llvm::StructType>(
3382 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
3383 llvm::LLVMContext &C = CGM.getModule().getContext();
3384 llvm::Module &M = CGM.getModule();
3385
3386 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00003387 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003388
3389 // Create constant string with the name.
3390 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3391
3392 llvm::GlobalVariable *Str =
3393 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
3394 llvm::GlobalValue::InternalLinkage, StrPtrInit,
3395 ".omp_offloading.entry_name");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003396 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003397 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
3398
John McCall6c9f1fdb2016-11-19 08:17:24 +00003399 // We can't have any padding between symbols, so we need to have 1-byte
3400 // alignment.
3401 auto Align = CharUnits::fromQuantity(1);
3402
Samuel Antaoee8fb302016-01-06 13:42:12 +00003403 // Create the entry struct.
John McCall23c9dc62016-11-28 22:18:27 +00003404 ConstantInitBuilder EntryBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003405 auto EntryInit = EntryBuilder.beginStruct(TgtOffloadEntryType);
3406 EntryInit.add(AddrPtr);
3407 EntryInit.add(StrPtr);
3408 EntryInit.addInt(CGM.SizeTy, Size);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003409 EntryInit.addInt(CGM.Int32Ty, Flags);
3410 EntryInit.addInt(CGM.Int32Ty, 0);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003411 llvm::GlobalVariable *Entry =
3412 EntryInit.finishAndCreateGlobal(".omp_offloading.entry",
3413 Align,
3414 /*constant*/ true,
3415 llvm::GlobalValue::ExternalLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003416
3417 // The entry has to be created in the section the linker expects it to be.
3418 Entry->setSection(".omp_offloading.entries");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003419}
3420
3421void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3422 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003423 // can easily figure out what to emit. The produced metadata looks like
3424 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003425 //
3426 // !omp_offload.info = !{!1, ...}
3427 //
3428 // Right now we only generate metadata for function that contain target
3429 // regions.
3430
3431 // If we do not have entries, we dont need to do anything.
3432 if (OffloadEntriesInfoManager.empty())
3433 return;
3434
3435 llvm::Module &M = CGM.getModule();
3436 llvm::LLVMContext &C = M.getContext();
3437 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
3438 OrderedEntries(OffloadEntriesInfoManager.size());
3439
3440 // Create the offloading info metadata node.
3441 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
3442
Simon Pilgrim2c518802017-03-30 14:13:19 +00003443 // Auxiliary methods to create metadata values and strings.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003444 auto getMDInt = [&](unsigned v) {
3445 return llvm::ConstantAsMetadata::get(
3446 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
3447 };
3448
3449 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
3450
3451 // Create function that emits metadata for each target region entry;
3452 auto &&TargetRegionMetadataEmitter = [&](
3453 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003454 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3455 llvm::SmallVector<llvm::Metadata *, 32> Ops;
3456 // Generate metadata for target regions. Each entry of this metadata
3457 // contains:
3458 // - Entry 0 -> Kind of this type of metadata (0).
3459 // - Entry 1 -> Device ID of the file where the entry was identified.
3460 // - Entry 2 -> File ID of the file where the entry was identified.
3461 // - Entry 3 -> Mangled name of the function where the entry was identified.
3462 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00003463 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003464 // The first element of the metadata node is the kind.
3465 Ops.push_back(getMDInt(E.getKind()));
3466 Ops.push_back(getMDInt(DeviceID));
3467 Ops.push_back(getMDInt(FileID));
3468 Ops.push_back(getMDString(ParentName));
3469 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003470 Ops.push_back(getMDInt(E.getOrder()));
3471
3472 // Save this entry in the right position of the ordered entries array.
3473 OrderedEntries[E.getOrder()] = &E;
3474
3475 // Add metadata to the named metadata node.
3476 MD->addOperand(llvm::MDNode::get(C, Ops));
3477 };
3478
3479 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3480 TargetRegionMetadataEmitter);
3481
3482 for (auto *E : OrderedEntries) {
3483 assert(E && "All ordered entries must exist!");
3484 if (auto *CE =
3485 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3486 E)) {
3487 assert(CE->getID() && CE->getAddress() &&
3488 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00003489 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003490 } else
3491 llvm_unreachable("Unsupported entry kind.");
3492 }
3493}
3494
3495/// \brief Loads all the offload entries information from the host IR
3496/// metadata.
3497void CGOpenMPRuntime::loadOffloadInfoMetadata() {
3498 // If we are in target mode, load the metadata from the host IR. This code has
3499 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
3500
3501 if (!CGM.getLangOpts().OpenMPIsDevice)
3502 return;
3503
3504 if (CGM.getLangOpts().OMPHostIRFile.empty())
3505 return;
3506
3507 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
3508 if (Buf.getError())
3509 return;
3510
3511 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00003512 auto ME = expectedToErrorOrAndEmitErrors(
3513 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003514
3515 if (ME.getError())
3516 return;
3517
3518 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
3519 if (!MD)
3520 return;
3521
3522 for (auto I : MD->operands()) {
3523 llvm::MDNode *MN = cast<llvm::MDNode>(I);
3524
3525 auto getMDInt = [&](unsigned Idx) {
3526 llvm::ConstantAsMetadata *V =
3527 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
3528 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
3529 };
3530
3531 auto getMDString = [&](unsigned Idx) {
3532 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
3533 return V->getString();
3534 };
3535
3536 switch (getMDInt(0)) {
3537 default:
3538 llvm_unreachable("Unexpected metadata!");
3539 break;
3540 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3541 OFFLOAD_ENTRY_INFO_TARGET_REGION:
3542 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
3543 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
3544 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00003545 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003546 break;
3547 }
3548 }
3549}
3550
Alexey Bataev62b63b12015-03-10 07:28:44 +00003551void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
3552 if (!KmpRoutineEntryPtrTy) {
3553 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
3554 auto &C = CGM.getContext();
3555 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
3556 FunctionProtoType::ExtProtoInfo EPI;
3557 KmpRoutineEntryPtrQTy = C.getPointerType(
3558 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
3559 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
3560 }
3561}
3562
Alexey Bataevc71a4092015-09-11 10:29:41 +00003563static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
3564 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003565 auto *Field = FieldDecl::Create(
3566 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
3567 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
3568 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
3569 Field->setAccess(AS_public);
3570 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003571 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003572}
3573
Samuel Antaoee8fb302016-01-06 13:42:12 +00003574QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
3575
3576 // Make sure the type of the entry is already created. This is the type we
3577 // have to create:
3578 // struct __tgt_offload_entry{
3579 // void *addr; // Pointer to the offload entry info.
3580 // // (function or global)
3581 // char *name; // Name of the function or global.
3582 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00003583 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
3584 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003585 // };
3586 if (TgtOffloadEntryQTy.isNull()) {
3587 ASTContext &C = CGM.getContext();
3588 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
3589 RD->startDefinition();
3590 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3591 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
3592 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00003593 addFieldToRecordDecl(
3594 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3595 addFieldToRecordDecl(
3596 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003597 RD->completeDefinition();
3598 TgtOffloadEntryQTy = C.getRecordType(RD);
3599 }
3600 return TgtOffloadEntryQTy;
3601}
3602
3603QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
3604 // These are the types we need to build:
3605 // struct __tgt_device_image{
3606 // void *ImageStart; // Pointer to the target code start.
3607 // void *ImageEnd; // Pointer to the target code end.
3608 // // We also add the host entries to the device image, as it may be useful
3609 // // for the target runtime to have access to that information.
3610 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
3611 // // the entries.
3612 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3613 // // entries (non inclusive).
3614 // };
3615 if (TgtDeviceImageQTy.isNull()) {
3616 ASTContext &C = CGM.getContext();
3617 auto *RD = C.buildImplicitRecord("__tgt_device_image");
3618 RD->startDefinition();
3619 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3620 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3621 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3622 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3623 RD->completeDefinition();
3624 TgtDeviceImageQTy = C.getRecordType(RD);
3625 }
3626 return TgtDeviceImageQTy;
3627}
3628
3629QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
3630 // struct __tgt_bin_desc{
3631 // int32_t NumDevices; // Number of devices supported.
3632 // __tgt_device_image *DeviceImages; // Arrays of device images
3633 // // (one per device).
3634 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
3635 // // entries.
3636 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3637 // // entries (non inclusive).
3638 // };
3639 if (TgtBinaryDescriptorQTy.isNull()) {
3640 ASTContext &C = CGM.getContext();
3641 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
3642 RD->startDefinition();
3643 addFieldToRecordDecl(
3644 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3645 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
3646 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3647 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3648 RD->completeDefinition();
3649 TgtBinaryDescriptorQTy = C.getRecordType(RD);
3650 }
3651 return TgtBinaryDescriptorQTy;
3652}
3653
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003654namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00003655struct PrivateHelpersTy {
3656 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
3657 const VarDecl *PrivateElemInit)
3658 : Original(Original), PrivateCopy(PrivateCopy),
3659 PrivateElemInit(PrivateElemInit) {}
3660 const VarDecl *Original;
3661 const VarDecl *PrivateCopy;
3662 const VarDecl *PrivateElemInit;
3663};
3664typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00003665} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003666
Alexey Bataev9e034042015-05-05 04:05:12 +00003667static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00003668createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003669 if (!Privates.empty()) {
3670 auto &C = CGM.getContext();
3671 // Build struct .kmp_privates_t. {
3672 // /* private vars */
3673 // };
3674 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
3675 RD->startDefinition();
3676 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00003677 auto *VD = Pair.second.Original;
3678 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003679 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00003680 auto *FD = addFieldToRecordDecl(C, RD, Type);
3681 if (VD->hasAttrs()) {
3682 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
3683 E(VD->getAttrs().end());
3684 I != E; ++I)
3685 FD->addAttr(*I);
3686 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003687 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003688 RD->completeDefinition();
3689 return RD;
3690 }
3691 return nullptr;
3692}
3693
Alexey Bataev9e034042015-05-05 04:05:12 +00003694static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00003695createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
3696 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003697 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003698 auto &C = CGM.getContext();
3699 // Build struct kmp_task_t {
3700 // void * shareds;
3701 // kmp_routine_entry_t routine;
3702 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00003703 // kmp_cmplrdata_t data1;
3704 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00003705 // For taskloops additional fields:
3706 // kmp_uint64 lb;
3707 // kmp_uint64 ub;
3708 // kmp_int64 st;
3709 // kmp_int32 liter;
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003710 // void * reductions;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003711 // };
Alexey Bataevad537bb2016-05-30 09:06:50 +00003712 auto *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
3713 UD->startDefinition();
3714 addFieldToRecordDecl(C, UD, KmpInt32Ty);
3715 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
3716 UD->completeDefinition();
3717 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003718 auto *RD = C.buildImplicitRecord("kmp_task_t");
3719 RD->startDefinition();
3720 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3721 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
3722 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00003723 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3724 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003725 if (isOpenMPTaskLoopDirective(Kind)) {
3726 QualType KmpUInt64Ty =
3727 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3728 QualType KmpInt64Ty =
3729 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3730 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3731 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3732 addFieldToRecordDecl(C, RD, KmpInt64Ty);
3733 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003734 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003735 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003736 RD->completeDefinition();
3737 return RD;
3738}
3739
3740static RecordDecl *
3741createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003742 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003743 auto &C = CGM.getContext();
3744 // Build struct kmp_task_t_with_privates {
3745 // kmp_task_t task_data;
3746 // .kmp_privates_t. privates;
3747 // };
3748 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
3749 RD->startDefinition();
3750 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003751 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
3752 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
3753 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003754 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003755 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003756}
3757
3758/// \brief Emit a proxy function which accepts kmp_task_t as the second
3759/// argument.
3760/// \code
3761/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003762/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00003763/// For taskloops:
3764/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003765/// tt->reductions, tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003766/// return 0;
3767/// }
3768/// \endcode
3769static llvm::Value *
3770emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00003771 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
3772 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003773 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003774 QualType SharedsPtrTy, llvm::Value *TaskFunction,
3775 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003776 auto &C = CGM.getContext();
3777 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003778 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3779 ImplicitParamDecl::Other);
3780 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3781 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3782 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003783 Args.push_back(&GtidArg);
3784 Args.push_back(&TaskTypeArg);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003785 auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003786 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003787 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
3788 auto *TaskEntry =
3789 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
3790 ".omp_task_entry.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003791 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003792 CodeGenFunction CGF(CGM);
3793 CGF.disableDebugInfo();
3794 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
3795
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003796 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00003797 // tt,
3798 // For taskloops:
3799 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3800 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003801 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00003802 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003803 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3804 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3805 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003806 auto *KmpTaskTWithPrivatesQTyRD =
3807 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003808 LValue Base =
3809 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003810 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3811 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3812 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003813 auto *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003814
3815 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3816 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003817 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003818 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003819 CGF.ConvertTypeForMem(SharedsPtrTy));
3820
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003821 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3822 llvm::Value *PrivatesParam;
3823 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3824 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3825 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003826 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003827 } else
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003828 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003829
Alexey Bataev7292c292016-04-25 12:22:29 +00003830 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
3831 TaskPrivatesMap,
3832 CGF.Builder
3833 .CreatePointerBitCastOrAddrSpaceCast(
3834 TDBase.getAddress(), CGF.VoidPtrTy)
3835 .getPointer()};
3836 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
3837 std::end(CommonArgs));
3838 if (isOpenMPTaskLoopDirective(Kind)) {
3839 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
3840 auto LBLVal = CGF.EmitLValueForField(Base, *LBFI);
3841 auto *LBParam = CGF.EmitLoadOfLValue(LBLVal, Loc).getScalarVal();
3842 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
3843 auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
3844 auto *UBParam = CGF.EmitLoadOfLValue(UBLVal, Loc).getScalarVal();
3845 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
3846 auto StLVal = CGF.EmitLValueForField(Base, *StFI);
3847 auto *StParam = CGF.EmitLoadOfLValue(StLVal, Loc).getScalarVal();
3848 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3849 auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
3850 auto *LIParam = CGF.EmitLoadOfLValue(LILVal, Loc).getScalarVal();
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003851 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
3852 auto RLVal = CGF.EmitLValueForField(Base, *RFI);
3853 auto *RParam = CGF.EmitLoadOfLValue(RLVal, Loc).getScalarVal();
Alexey Bataev7292c292016-04-25 12:22:29 +00003854 CallArgs.push_back(LBParam);
3855 CallArgs.push_back(UBParam);
3856 CallArgs.push_back(StParam);
3857 CallArgs.push_back(LIParam);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00003858 CallArgs.push_back(RParam);
Alexey Bataev7292c292016-04-25 12:22:29 +00003859 }
3860 CallArgs.push_back(SharedsParam);
3861
Alexey Bataev3c595a62017-08-14 15:01:03 +00003862 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
3863 CallArgs);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003864 CGF.EmitStoreThroughLValue(
3865 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00003866 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00003867 CGF.FinishFunction();
3868 return TaskEntry;
3869}
3870
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003871static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
3872 SourceLocation Loc,
3873 QualType KmpInt32Ty,
3874 QualType KmpTaskTWithPrivatesPtrQTy,
3875 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003876 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003877 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003878 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3879 ImplicitParamDecl::Other);
3880 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3881 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3882 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003883 Args.push_back(&GtidArg);
3884 Args.push_back(&TaskTypeArg);
3885 FunctionType::ExtInfo Info;
3886 auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003887 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003888 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
3889 auto *DestructorFn =
3890 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
3891 ".omp_task_destructor.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003892 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
3893 DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003894 CodeGenFunction CGF(CGM);
3895 CGF.disableDebugInfo();
3896 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
3897 Args);
3898
Alexey Bataev31300ed2016-02-04 11:27:03 +00003899 LValue Base = CGF.EmitLoadOfPointerLValue(
3900 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3901 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003902 auto *KmpTaskTWithPrivatesQTyRD =
3903 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3904 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003905 Base = CGF.EmitLValueForField(Base, *FI);
3906 for (auto *Field :
3907 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
3908 if (auto DtorKind = Field->getType().isDestructedType()) {
3909 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
3910 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
3911 }
3912 }
3913 CGF.FinishFunction();
3914 return DestructorFn;
3915}
3916
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003917/// \brief Emit a privates mapping function for correct handling of private and
3918/// firstprivate variables.
3919/// \code
3920/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
3921/// **noalias priv1,..., <tyn> **noalias privn) {
3922/// *priv1 = &.privates.priv1;
3923/// ...;
3924/// *privn = &.privates.privn;
3925/// }
3926/// \endcode
3927static llvm::Value *
3928emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00003929 ArrayRef<const Expr *> PrivateVars,
3930 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00003931 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003932 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003933 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003934 auto &C = CGM.getContext();
3935 FunctionArgList Args;
3936 ImplicitParamDecl TaskPrivatesArg(
3937 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003938 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
3939 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003940 Args.push_back(&TaskPrivatesArg);
3941 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
3942 unsigned Counter = 1;
3943 for (auto *E: PrivateVars) {
3944 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003945 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3946 C.getPointerType(C.getPointerType(E->getType()))
3947 .withConst()
3948 .withRestrict(),
3949 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003950 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3951 PrivateVarsPos[VD] = Counter;
3952 ++Counter;
3953 }
3954 for (auto *E : FirstprivateVars) {
3955 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003956 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3957 C.getPointerType(C.getPointerType(E->getType()))
3958 .withConst()
3959 .withRestrict(),
3960 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003961 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3962 PrivateVarsPos[VD] = Counter;
3963 ++Counter;
3964 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003965 for (auto *E: LastprivateVars) {
3966 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003967 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3968 C.getPointerType(C.getPointerType(E->getType()))
3969 .withConst()
3970 .withRestrict(),
3971 ImplicitParamDecl::Other));
Alexey Bataevf93095a2016-05-05 08:46:22 +00003972 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3973 PrivateVarsPos[VD] = Counter;
3974 ++Counter;
3975 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003976 auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003977 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003978 auto *TaskPrivatesMapTy =
3979 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
3980 auto *TaskPrivatesMap = llvm::Function::Create(
3981 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
3982 ".omp_task_privates_map.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003983 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
3984 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00003985 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00003986 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00003987 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003988 CodeGenFunction CGF(CGM);
3989 CGF.disableDebugInfo();
3990 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
3991 TaskPrivatesMapFnInfo, Args);
3992
3993 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003994 LValue Base = CGF.EmitLoadOfPointerLValue(
3995 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
3996 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003997 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
3998 Counter = 0;
3999 for (auto *Field : PrivatesQTyRD->fields()) {
4000 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
4001 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00004002 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00004003 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
4004 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00004005 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004006 ++Counter;
4007 }
4008 CGF.FinishFunction();
4009 return TaskPrivatesMap;
4010}
4011
Alexey Bataev9e034042015-05-05 04:05:12 +00004012static int array_pod_sort_comparator(const PrivateDataTy *P1,
4013 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004014 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
4015}
4016
Alexey Bataevf93095a2016-05-05 08:46:22 +00004017/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00004018static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00004019 const OMPExecutableDirective &D,
4020 Address KmpTaskSharedsPtr, LValue TDBase,
4021 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4022 QualType SharedsTy, QualType SharedsPtrTy,
4023 const OMPTaskDataTy &Data,
4024 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
4025 auto &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004026 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4027 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
4028 LValue SrcBase;
4029 if (!Data.FirstprivateVars.empty()) {
4030 SrcBase = CGF.MakeAddrLValue(
4031 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4032 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
4033 SharedsTy);
4034 }
4035 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
4036 cast<CapturedStmt>(*D.getAssociatedStmt()));
4037 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
4038 for (auto &&Pair : Privates) {
4039 auto *VD = Pair.second.PrivateCopy;
4040 auto *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00004041 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
4042 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004043 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004044 if (auto *Elem = Pair.second.PrivateElemInit) {
4045 auto *OriginalVD = Pair.second.Original;
4046 auto *SharedField = CapturesInfo.lookup(OriginalVD);
4047 auto SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
4048 SharedRefLValue = CGF.MakeAddrLValue(
4049 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004050 SharedRefLValue.getType(),
4051 LValueBaseInfo(AlignmentSource::Decl,
4052 SharedRefLValue.getBaseInfo().getMayAlias()));
Alexey Bataevf93095a2016-05-05 08:46:22 +00004053 QualType Type = OriginalVD->getType();
4054 if (Type->isArrayType()) {
4055 // Initialize firstprivate array.
4056 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
4057 // Perform simple memcpy.
4058 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
4059 SharedRefLValue.getAddress(), Type);
4060 } else {
4061 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00004062 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00004063 CGF.EmitOMPAggregateAssign(
4064 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
4065 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
4066 Address SrcElement) {
4067 // Clean up any temporaries needed by the initialization.
4068 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4069 InitScope.addPrivate(
4070 Elem, [SrcElement]() -> Address { return SrcElement; });
4071 (void)InitScope.Privatize();
4072 // Emit initialization for single element.
4073 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4074 CGF, &CapturesInfo);
4075 CGF.EmitAnyExprToMem(Init, DestElement,
4076 Init->getType().getQualifiers(),
4077 /*IsInitializer=*/false);
4078 });
4079 }
4080 } else {
4081 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4082 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4083 return SharedRefLValue.getAddress();
4084 });
4085 (void)InitScope.Privatize();
4086 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4087 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4088 /*capturedByInit=*/false);
4089 }
4090 } else
4091 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
4092 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004093 ++FI;
4094 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004095}
4096
4097/// Check if duplication function is required for taskloops.
4098static bool checkInitIsRequired(CodeGenFunction &CGF,
4099 ArrayRef<PrivateDataTy> Privates) {
4100 bool InitRequired = false;
4101 for (auto &&Pair : Privates) {
4102 auto *VD = Pair.second.PrivateCopy;
4103 auto *Init = VD->getAnyInitializer();
4104 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4105 !CGF.isTrivialInitializer(Init));
4106 }
4107 return InitRequired;
4108}
4109
4110
4111/// Emit task_dup function (for initialization of
4112/// private/firstprivate/lastprivate vars and last_iter flag)
4113/// \code
4114/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4115/// lastpriv) {
4116/// // setup lastprivate flag
4117/// task_dst->last = lastpriv;
4118/// // could be constructor calls here...
4119/// }
4120/// \endcode
4121static llvm::Value *
4122emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4123 const OMPExecutableDirective &D,
4124 QualType KmpTaskTWithPrivatesPtrQTy,
4125 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4126 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4127 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4128 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
4129 auto &C = CGM.getContext();
4130 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004131 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4132 KmpTaskTWithPrivatesPtrQTy,
4133 ImplicitParamDecl::Other);
4134 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4135 KmpTaskTWithPrivatesPtrQTy,
4136 ImplicitParamDecl::Other);
4137 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4138 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004139 Args.push_back(&DstArg);
4140 Args.push_back(&SrcArg);
4141 Args.push_back(&LastprivArg);
4142 auto &TaskDupFnInfo =
4143 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
4144 auto *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
4145 auto *TaskDup =
4146 llvm::Function::Create(TaskDupTy, llvm::GlobalValue::InternalLinkage,
4147 ".omp_task_dup.", &CGM.getModule());
4148 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskDup, TaskDupFnInfo);
4149 CodeGenFunction CGF(CGM);
4150 CGF.disableDebugInfo();
4151 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args);
4152
4153 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4154 CGF.GetAddrOfLocalVar(&DstArg),
4155 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4156 // task_dst->liter = lastpriv;
4157 if (WithLastIter) {
4158 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4159 LValue Base = CGF.EmitLValueForField(
4160 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4161 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4162 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4163 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4164 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4165 }
4166
4167 // Emit initial values for private copies (if any).
4168 assert(!Privates.empty());
4169 Address KmpTaskSharedsPtr = Address::invalid();
4170 if (!Data.FirstprivateVars.empty()) {
4171 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4172 CGF.GetAddrOfLocalVar(&SrcArg),
4173 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4174 LValue Base = CGF.EmitLValueForField(
4175 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4176 KmpTaskSharedsPtr = Address(
4177 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4178 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4179 KmpTaskTShareds)),
4180 Loc),
4181 CGF.getNaturalTypeAlignment(SharedsTy));
4182 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004183 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4184 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004185 CGF.FinishFunction();
4186 return TaskDup;
4187}
4188
Alexey Bataev8a831592016-05-10 10:36:51 +00004189/// Checks if destructor function is required to be generated.
4190/// \return true if cleanups are required, false otherwise.
4191static bool
4192checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4193 bool NeedsCleanup = false;
4194 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4195 auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4196 for (auto *FD : PrivateRD->fields()) {
4197 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4198 if (NeedsCleanup)
4199 break;
4200 }
4201 return NeedsCleanup;
4202}
4203
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004204CGOpenMPRuntime::TaskResultTy
4205CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4206 const OMPExecutableDirective &D,
4207 llvm::Value *TaskFunction, QualType SharedsTy,
4208 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004209 auto &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004210 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004211 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004212 auto I = Data.PrivateCopies.begin();
4213 for (auto *E : Data.PrivateVars) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004214 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4215 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004216 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004217 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4218 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004219 ++I;
4220 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004221 I = Data.FirstprivateCopies.begin();
4222 auto IElemInitRef = Data.FirstprivateInits.begin();
4223 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev9e034042015-05-05 04:05:12 +00004224 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4225 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004226 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004227 PrivateHelpersTy(
4228 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4229 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
Richard Trieucc3949d2016-02-18 22:34:54 +00004230 ++I;
4231 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004232 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004233 I = Data.LastprivateCopies.begin();
4234 for (auto *E : Data.LastprivateVars) {
4235 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4236 Privates.push_back(std::make_pair(
4237 C.getDeclAlign(VD),
4238 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4239 /*PrivateElemInit=*/nullptr)));
4240 ++I;
4241 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004242 llvm::array_pod_sort(Privates.begin(), Privates.end(),
4243 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004244 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
4245 // Build type kmp_routine_entry_t (if not built yet).
4246 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004247 // Build type kmp_task_t (if not built yet).
4248 if (KmpTaskTQTy.isNull()) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004249 KmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4250 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004251 }
4252 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004253 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004254 auto *KmpTaskTWithPrivatesQTyRD =
4255 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
4256 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
4257 QualType KmpTaskTWithPrivatesPtrQTy =
4258 C.getPointerType(KmpTaskTWithPrivatesQTy);
4259 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4260 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004261 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004262 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4263
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004264 // Emit initial values for private copies (if any).
4265 llvm::Value *TaskPrivatesMap = nullptr;
4266 auto *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00004267 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004268 if (!Privates.empty()) {
4269 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004270 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4271 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4272 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004273 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4274 TaskPrivatesMap, TaskPrivatesMapTy);
4275 } else {
4276 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4277 cast<llvm::PointerType>(TaskPrivatesMapTy));
4278 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004279 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4280 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004281 auto *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004282 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4283 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4284 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004285
4286 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4287 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4288 // kmp_routine_entry_t *task_entry);
4289 // Task flags. Format is taken from
4290 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4291 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004292 enum {
4293 TiedFlag = 0x1,
4294 FinalFlag = 0x2,
4295 DestructorsFlag = 0x8,
4296 PriorityFlag = 0x20
4297 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004298 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004299 bool NeedsCleanup = false;
4300 if (!Privates.empty()) {
4301 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4302 if (NeedsCleanup)
4303 Flags = Flags | DestructorsFlag;
4304 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004305 if (Data.Priority.getInt())
4306 Flags = Flags | PriorityFlag;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004307 auto *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004308 Data.Final.getPointer()
4309 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00004310 CGF.Builder.getInt32(FinalFlag),
4311 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004312 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004313 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00004314 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004315 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4316 getThreadID(CGF, Loc), TaskFlags,
4317 KmpTaskTWithPrivatesTySize, SharedsSize,
4318 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4319 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00004320 auto *NewTask = CGF.EmitRuntimeCall(
4321 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004322 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4323 NewTask, KmpTaskTWithPrivatesPtrTy);
4324 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4325 KmpTaskTWithPrivatesQTy);
4326 LValue TDBase =
4327 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004328 // Fill the data in the resulting kmp_task_t record.
4329 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00004330 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004331 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00004332 KmpTaskSharedsPtr =
4333 Address(CGF.EmitLoadOfScalar(
4334 CGF.EmitLValueForField(
4335 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4336 KmpTaskTShareds)),
4337 Loc),
4338 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004339 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004340 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004341 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00004342 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004343 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004344 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4345 SharedsTy, SharedsPtrTy, Data, Privates,
4346 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004347 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4348 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4349 Result.TaskDupFn = emitTaskDupFunction(
4350 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4351 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4352 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004353 }
4354 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00004355 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4356 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00004357 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00004358 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
4359 auto *KmpCmplrdataUD = (*FI)->getType()->getAsUnionType()->getDecl();
4360 if (NeedsCleanup) {
4361 llvm::Value *DestructorFn = emitDestructorsFunction(
4362 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4363 KmpTaskTWithPrivatesQTy);
4364 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4365 LValue DestructorsLV = CGF.EmitLValueForField(
4366 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4367 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4368 DestructorFn, KmpRoutineEntryPtrTy),
4369 DestructorsLV);
4370 }
4371 // Set priority.
4372 if (Data.Priority.getInt()) {
4373 LValue Data2LV = CGF.EmitLValueForField(
4374 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
4375 LValue PriorityLV = CGF.EmitLValueForField(
4376 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
4377 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
4378 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004379 Result.NewTask = NewTask;
4380 Result.TaskEntry = TaskEntry;
4381 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
4382 Result.TDBase = TDBase;
4383 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
4384 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00004385}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004386
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004387void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
4388 const OMPExecutableDirective &D,
4389 llvm::Value *TaskFunction,
4390 QualType SharedsTy, Address Shareds,
4391 const Expr *IfCond,
4392 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004393 if (!CGF.HaveInsertPoint())
4394 return;
4395
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004396 TaskResultTy Result =
4397 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4398 llvm::Value *NewTask = Result.NewTask;
4399 llvm::Value *TaskEntry = Result.TaskEntry;
4400 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
4401 LValue TDBase = Result.TDBase;
4402 RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
Alexey Bataev7292c292016-04-25 12:22:29 +00004403 auto &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004404 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00004405 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004406 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00004407 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004408 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00004409 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004410 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
4411 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004412 QualType FlagsTy =
4413 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004414 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
4415 if (KmpDependInfoTy.isNull()) {
4416 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
4417 KmpDependInfoRD->startDefinition();
4418 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
4419 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
4420 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
4421 KmpDependInfoRD->completeDefinition();
4422 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004423 } else
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004424 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
John McCall7f416cc2015-09-08 08:05:57 +00004425 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004426 // Define type kmp_depend_info[<Dependences.size()>];
4427 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00004428 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004429 ArrayType::Normal, /*IndexTypeQuals=*/0);
4430 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00004431 DependenciesArray =
4432 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
John McCall7f416cc2015-09-08 08:05:57 +00004433 for (unsigned i = 0; i < NumDependencies; ++i) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004434 const Expr *E = Data.Dependences[i].second;
John McCall7f416cc2015-09-08 08:05:57 +00004435 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004436 llvm::Value *Size;
4437 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004438 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
4439 LValue UpAddrLVal =
4440 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
4441 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00004442 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004443 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00004444 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004445 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
4446 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004447 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00004448 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00004449 auto Base = CGF.MakeAddrLValue(
4450 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004451 KmpDependInfoTy);
4452 // deps[i].base_addr = &<Dependences[i].second>;
4453 auto BaseAddrLVal = CGF.EmitLValueForField(
4454 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00004455 CGF.EmitStoreOfScalar(
4456 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
4457 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004458 // deps[i].len = sizeof(<Dependences[i].second>);
4459 auto LenLVal = CGF.EmitLValueForField(
4460 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
4461 CGF.EmitStoreOfScalar(Size, LenLVal);
4462 // deps[i].flags = <Dependences[i].first>;
4463 RTLDependenceKindTy DepKind;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004464 switch (Data.Dependences[i].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004465 case OMPC_DEPEND_in:
4466 DepKind = DepIn;
4467 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00004468 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004469 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004470 case OMPC_DEPEND_inout:
4471 DepKind = DepInOut;
4472 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00004473 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004474 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004475 case OMPC_DEPEND_unknown:
4476 llvm_unreachable("Unknown task dependence type");
4477 }
4478 auto FlagsLVal = CGF.EmitLValueForField(
4479 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
4480 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
4481 FlagsLVal);
4482 }
John McCall7f416cc2015-09-08 08:05:57 +00004483 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4484 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004485 CGF.VoidPtrTy);
4486 }
4487
Alexey Bataev62b63b12015-03-10 07:28:44 +00004488 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4489 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004490 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
4491 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
4492 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
4493 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00004494 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004495 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00004496 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
4497 llvm::Value *DepTaskArgs[7];
4498 if (NumDependencies) {
4499 DepTaskArgs[0] = UpLoc;
4500 DepTaskArgs[1] = ThreadID;
4501 DepTaskArgs[2] = NewTask;
4502 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
4503 DepTaskArgs[4] = DependenciesArray.getPointer();
4504 DepTaskArgs[5] = CGF.Builder.getInt32(0);
4505 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4506 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00004507 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
4508 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004509 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004510 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004511 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4512 auto PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
4513 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
4514 }
John McCall7f416cc2015-09-08 08:05:57 +00004515 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004516 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00004517 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00004518 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004519 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00004520 TaskArgs);
4521 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00004522 // Check if parent region is untied and build return for untied task;
4523 if (auto *Region =
4524 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4525 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00004526 };
John McCall7f416cc2015-09-08 08:05:57 +00004527
4528 llvm::Value *DepWaitTaskArgs[6];
4529 if (NumDependencies) {
4530 DepWaitTaskArgs[0] = UpLoc;
4531 DepWaitTaskArgs[1] = ThreadID;
4532 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
4533 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
4534 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
4535 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4536 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004537 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
Alexey Bataev3c595a62017-08-14 15:01:03 +00004538 NumDependencies, &DepWaitTaskArgs,
4539 Loc](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004540 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004541 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
4542 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
4543 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
4544 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
4545 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00004546 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004547 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004548 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004549 // Call proxy_task_entry(gtid, new_task);
Alexey Bataev3c595a62017-08-14 15:01:03 +00004550 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy,
4551 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004552 Action.Enter(CGF);
4553 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
Alexey Bataev3c595a62017-08-14 15:01:03 +00004554 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry,
Alexey Bataev2c7eee52017-08-04 19:10:54 +00004555 OutlinedFnArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004556 };
4557
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004558 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
4559 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004560 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
4561 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004562 RegionCodeGenTy RCG(CodeGen);
4563 CommonActionTy Action(
4564 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
4565 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
4566 RCG.setAction(Action);
4567 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004568 };
John McCall7f416cc2015-09-08 08:05:57 +00004569
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004570 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00004571 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004572 else {
4573 RegionCodeGenTy ThenRCG(ThenCodeGen);
4574 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00004575 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004576}
4577
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004578void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
4579 const OMPLoopDirective &D,
4580 llvm::Value *TaskFunction,
4581 QualType SharedsTy, Address Shareds,
4582 const Expr *IfCond,
4583 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004584 if (!CGF.HaveInsertPoint())
4585 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004586 TaskResultTy Result =
4587 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004588 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4589 // libcall.
4590 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
4591 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
4592 // sched, kmp_uint64 grainsize, void *task_dup);
4593 llvm::Value *ThreadID = getThreadID(CGF, Loc);
4594 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
4595 llvm::Value *IfVal;
4596 if (IfCond) {
4597 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
4598 /*isSigned=*/true);
4599 } else
4600 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
4601
4602 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004603 Result.TDBase,
4604 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004605 auto *LBVar =
4606 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
4607 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
4608 /*IsInitializer=*/true);
4609 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004610 Result.TDBase,
4611 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004612 auto *UBVar =
4613 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
4614 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
4615 /*IsInitializer=*/true);
4616 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004617 Result.TDBase,
4618 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataev7292c292016-04-25 12:22:29 +00004619 auto *StVar =
4620 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
4621 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
4622 /*IsInitializer=*/true);
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00004623 // Store reductions address.
4624 LValue RedLVal = CGF.EmitLValueForField(
4625 Result.TDBase,
4626 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions));
4627 if (Data.Reductions)
4628 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal);
4629 else {
4630 CGF.EmitNullInitialization(RedLVal.getAddress(),
4631 CGF.getContext().VoidPtrTy);
4632 }
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004633 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00004634 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00004635 UpLoc,
4636 ThreadID,
4637 Result.NewTask,
4638 IfVal,
4639 LBLVal.getPointer(),
4640 UBLVal.getPointer(),
4641 CGF.EmitLoadOfScalar(StLVal, SourceLocation()),
4642 llvm::ConstantInt::getNullValue(
4643 CGF.IntTy), // Always 0 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004644 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004645 CGF.IntTy, Data.Schedule.getPointer()
4646 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004647 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004648 Data.Schedule.getPointer()
4649 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004650 /*isSigned=*/false)
4651 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00004652 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4653 Result.TaskDupFn, CGF.VoidPtrTy)
4654 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00004655 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
4656}
4657
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004658/// \brief Emit reduction operation for each element of array (required for
4659/// array sections) LHS op = RHS.
4660/// \param Type Type of array.
4661/// \param LHSVar Variable on the left side of the reduction operation
4662/// (references element of array in original variable).
4663/// \param RHSVar Variable on the right side of the reduction operation
4664/// (references element of array in original variable).
4665/// \param RedOpGen Generator of reduction operation with use of LHSVar and
4666/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00004667static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004668 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
4669 const VarDecl *RHSVar,
4670 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
4671 const Expr *, const Expr *)> &RedOpGen,
4672 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
4673 const Expr *UpExpr = nullptr) {
4674 // Perform element-by-element initialization.
4675 QualType ElementTy;
4676 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
4677 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
4678
4679 // Drill down to the base element type on both arrays.
4680 auto ArrayTy = Type->getAsArrayTypeUnsafe();
4681 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
4682
4683 auto RHSBegin = RHSAddr.getPointer();
4684 auto LHSBegin = LHSAddr.getPointer();
4685 // Cast from pointer to array type to pointer to single element.
4686 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
4687 // The basic structure here is a while-do loop.
4688 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
4689 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
4690 auto IsEmpty =
4691 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
4692 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
4693
4694 // Enter the loop body, making that address the current address.
4695 auto EntryBB = CGF.Builder.GetInsertBlock();
4696 CGF.EmitBlock(BodyBB);
4697
4698 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
4699
4700 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
4701 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
4702 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
4703 Address RHSElementCurrent =
4704 Address(RHSElementPHI,
4705 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4706
4707 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
4708 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
4709 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
4710 Address LHSElementCurrent =
4711 Address(LHSElementPHI,
4712 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4713
4714 // Emit copy.
4715 CodeGenFunction::OMPPrivateScope Scope(CGF);
4716 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
4717 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
4718 Scope.Privatize();
4719 RedOpGen(CGF, XExpr, EExpr, UpExpr);
4720 Scope.ForceCleanup();
4721
4722 // Shift the address forward by one element.
4723 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
4724 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
4725 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
4726 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
4727 // Check whether we've reached the end.
4728 auto Done =
4729 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
4730 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
4731 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
4732 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
4733
4734 // Done.
4735 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
4736}
4737
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004738/// Emit reduction combiner. If the combiner is a simple expression emit it as
4739/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
4740/// UDR combiner function.
4741static void emitReductionCombiner(CodeGenFunction &CGF,
4742 const Expr *ReductionOp) {
4743 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
4744 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
4745 if (auto *DRE =
4746 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
4747 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
4748 std::pair<llvm::Function *, llvm::Function *> Reduction =
4749 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
4750 RValue Func = RValue::get(Reduction.first);
4751 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
4752 CGF.EmitIgnoredExpr(ReductionOp);
4753 return;
4754 }
4755 CGF.EmitIgnoredExpr(ReductionOp);
4756}
4757
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004758llvm::Value *CGOpenMPRuntime::emitReductionFunction(
4759 CodeGenModule &CGM, llvm::Type *ArgsType, ArrayRef<const Expr *> Privates,
4760 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4761 ArrayRef<const Expr *> ReductionOps) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004762 auto &C = CGM.getContext();
4763
4764 // void reduction_func(void *LHSArg, void *RHSArg);
4765 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004766 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
4767 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004768 Args.push_back(&LHSArg);
4769 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00004770 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004771 auto *Fn = llvm::Function::Create(
4772 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
4773 ".omp.reduction.reduction_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004774 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004775 CodeGenFunction CGF(CGM);
4776 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
4777
4778 // Dst = (void*[n])(LHSArg);
4779 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00004780 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4781 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
4782 ArgsType), CGF.getPointerAlign());
4783 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4784 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
4785 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004786
4787 // ...
4788 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
4789 // ...
4790 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004791 auto IPriv = Privates.begin();
4792 unsigned Idx = 0;
4793 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004794 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
4795 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004796 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004797 });
4798 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
4799 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004800 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004801 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004802 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004803 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004804 // Get array size and emit VLA type.
4805 ++Idx;
4806 Address Elem =
4807 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
4808 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004809 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
4810 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004811 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00004812 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004813 CGF.EmitVariablyModifiedType(PrivTy);
4814 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004815 }
4816 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004817 IPriv = Privates.begin();
4818 auto ILHS = LHSExprs.begin();
4819 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004820 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004821 if ((*IPriv)->getType()->isArrayType()) {
4822 // Emit reduction for array section.
4823 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4824 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004825 EmitOMPAggregateReduction(
4826 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4827 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4828 emitReductionCombiner(CGF, E);
4829 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004830 } else
4831 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004832 emitReductionCombiner(CGF, E);
Richard Trieucc3949d2016-02-18 22:34:54 +00004833 ++IPriv;
4834 ++ILHS;
4835 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004836 }
4837 Scope.ForceCleanup();
4838 CGF.FinishFunction();
4839 return Fn;
4840}
4841
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004842void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
4843 const Expr *ReductionOp,
4844 const Expr *PrivateRef,
4845 const DeclRefExpr *LHS,
4846 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004847 if (PrivateRef->getType()->isArrayType()) {
4848 // Emit reduction for array section.
4849 auto *LHSVar = cast<VarDecl>(LHS->getDecl());
4850 auto *RHSVar = cast<VarDecl>(RHS->getDecl());
4851 EmitOMPAggregateReduction(
4852 CGF, PrivateRef->getType(), LHSVar, RHSVar,
4853 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4854 emitReductionCombiner(CGF, ReductionOp);
4855 });
4856 } else
4857 // Emit reduction for array subscript or single variable.
4858 emitReductionCombiner(CGF, ReductionOp);
4859}
4860
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004861void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004862 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004863 ArrayRef<const Expr *> LHSExprs,
4864 ArrayRef<const Expr *> RHSExprs,
4865 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004866 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004867 if (!CGF.HaveInsertPoint())
4868 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004869
4870 bool WithNowait = Options.WithNowait;
4871 bool SimpleReduction = Options.SimpleReduction;
4872
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004873 // Next code should be emitted for reduction:
4874 //
4875 // static kmp_critical_name lock = { 0 };
4876 //
4877 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
4878 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
4879 // ...
4880 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
4881 // *(Type<n>-1*)rhs[<n>-1]);
4882 // }
4883 //
4884 // ...
4885 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
4886 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4887 // RedList, reduce_func, &<lock>)) {
4888 // case 1:
4889 // ...
4890 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4891 // ...
4892 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4893 // break;
4894 // case 2:
4895 // ...
4896 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4897 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00004898 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004899 // break;
4900 // default:;
4901 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004902 //
4903 // if SimpleReduction is true, only the next code is generated:
4904 // ...
4905 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4906 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004907
4908 auto &C = CGM.getContext();
4909
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004910 if (SimpleReduction) {
4911 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004912 auto IPriv = Privates.begin();
4913 auto ILHS = LHSExprs.begin();
4914 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004915 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004916 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4917 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00004918 ++IPriv;
4919 ++ILHS;
4920 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004921 }
4922 return;
4923 }
4924
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004925 // 1. Build a list of reduction variables.
4926 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004927 auto Size = RHSExprs.size();
4928 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00004929 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004930 // Reserve place for array size.
4931 ++Size;
4932 }
4933 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004934 QualType ReductionArrayTy =
4935 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4936 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00004937 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004938 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004939 auto IPriv = Privates.begin();
4940 unsigned Idx = 0;
4941 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004942 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004943 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00004944 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004945 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004946 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4947 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004948 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004949 // Store array size.
4950 ++Idx;
4951 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
4952 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00004953 llvm::Value *Size = CGF.Builder.CreateIntCast(
4954 CGF.getVLASize(
4955 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4956 .first,
4957 CGF.SizeTy, /*isSigned=*/false);
4958 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4959 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004960 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004961 }
4962
4963 // 2. Emit reduce_func().
4964 auto *ReductionFn = emitReductionFunction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004965 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
4966 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004967
4968 // 3. Create static kmp_critical_name lock = { 0 };
4969 auto *Lock = getCriticalRegionLock(".reduction");
4970
4971 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4972 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00004973 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004974 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004975 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
Samuel Antao4c8035b2016-12-12 18:00:20 +00004976 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4977 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004978 llvm::Value *Args[] = {
4979 IdentTLoc, // ident_t *<loc>
4980 ThreadId, // i32 <gtid>
4981 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
4982 ReductionArrayTySize, // size_type sizeof(RedList)
4983 RL, // void *RedList
4984 ReductionFn, // void (*) (void *, void *) <reduce_func>
4985 Lock // kmp_critical_name *&<lock>
4986 };
4987 auto Res = CGF.EmitRuntimeCall(
4988 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
4989 : OMPRTL__kmpc_reduce),
4990 Args);
4991
4992 // 5. Build switch(res)
4993 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
4994 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
4995
4996 // 6. Build case 1:
4997 // ...
4998 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4999 // ...
5000 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5001 // break;
5002 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
5003 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
5004 CGF.EmitBlock(Case1BB);
5005
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005006 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
5007 llvm::Value *EndArgs[] = {
5008 IdentTLoc, // ident_t *<loc>
5009 ThreadId, // i32 <gtid>
5010 Lock // kmp_critical_name *&<lock>
5011 };
5012 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5013 CodeGenFunction &CGF, PrePostActionTy &Action) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005014 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005015 auto IPriv = Privates.begin();
5016 auto ILHS = LHSExprs.begin();
5017 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005018 for (auto *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00005019 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
5020 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00005021 ++IPriv;
5022 ++ILHS;
5023 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005024 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005025 };
5026 RegionCodeGenTy RCG(CodeGen);
5027 CommonActionTy Action(
5028 nullptr, llvm::None,
5029 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
5030 : OMPRTL__kmpc_end_reduce),
5031 EndArgs);
5032 RCG.setAction(Action);
5033 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005034
5035 CGF.EmitBranch(DefaultBB);
5036
5037 // 7. Build case 2:
5038 // ...
5039 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
5040 // ...
5041 // break;
5042 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
5043 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
5044 CGF.EmitBlock(Case2BB);
5045
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005046 auto &&AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs, &ReductionOps](
5047 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005048 auto ILHS = LHSExprs.begin();
5049 auto IRHS = RHSExprs.begin();
5050 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005051 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005052 const Expr *XExpr = nullptr;
5053 const Expr *EExpr = nullptr;
5054 const Expr *UpExpr = nullptr;
5055 BinaryOperatorKind BO = BO_Comma;
5056 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
5057 if (BO->getOpcode() == BO_Assign) {
5058 XExpr = BO->getLHS();
5059 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005060 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005061 }
5062 // Try to emit update expression as a simple atomic.
5063 auto *RHSExpr = UpExpr;
5064 if (RHSExpr) {
5065 // Analyze RHS part of the whole expression.
5066 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
5067 RHSExpr->IgnoreParenImpCasts())) {
5068 // If this is a conditional operator, analyze its condition for
5069 // min/max reduction operator.
5070 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00005071 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005072 if (auto *BORHS =
5073 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
5074 EExpr = BORHS->getRHS();
5075 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00005076 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005077 }
5078 if (XExpr) {
5079 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005080 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005081 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5082 const Expr *EExpr, const Expr *UpExpr) {
5083 LValue X = CGF.EmitLValue(XExpr);
5084 RValue E;
5085 if (EExpr)
5086 E = CGF.EmitAnyExpr(EExpr);
5087 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005088 X, E, BO, /*IsXLHSInRHSPart=*/true,
5089 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005090 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005091 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5092 PrivateScope.addPrivate(
5093 VD, [&CGF, VD, XRValue, Loc]() -> Address {
5094 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5095 CGF.emitOMPSimpleStore(
5096 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5097 VD->getType().getNonReferenceType(), Loc);
5098 return LHSTemp;
5099 });
5100 (void)PrivateScope.Privatize();
5101 return CGF.EmitAnyExpr(UpExpr);
5102 });
5103 };
5104 if ((*IPriv)->getType()->isArrayType()) {
5105 // Emit atomic reduction for array section.
5106 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5107 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5108 AtomicRedGen, XExpr, EExpr, UpExpr);
5109 } else
5110 // Emit atomic reduction for array subscript or single variable.
5111 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
5112 } else {
5113 // Emit as a critical region.
5114 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
5115 const Expr *, const Expr *) {
5116 auto &RT = CGF.CGM.getOpenMPRuntime();
5117 RT.emitCriticalRegion(
5118 CGF, ".atomic_reduction",
5119 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5120 Action.Enter(CGF);
5121 emitReductionCombiner(CGF, E);
5122 },
5123 Loc);
5124 };
5125 if ((*IPriv)->getType()->isArrayType()) {
5126 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5127 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5128 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5129 CritRedGen);
5130 } else
5131 CritRedGen(CGF, nullptr, nullptr, nullptr);
5132 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005133 ++ILHS;
5134 ++IRHS;
5135 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005136 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005137 };
5138 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5139 if (!WithNowait) {
5140 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5141 llvm::Value *EndArgs[] = {
5142 IdentTLoc, // ident_t *<loc>
5143 ThreadId, // i32 <gtid>
5144 Lock // kmp_critical_name *&<lock>
5145 };
5146 CommonActionTy Action(nullptr, llvm::None,
5147 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5148 EndArgs);
5149 AtomicRCG.setAction(Action);
5150 AtomicRCG(CGF);
5151 } else
5152 AtomicRCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005153
5154 CGF.EmitBranch(DefaultBB);
5155 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5156}
5157
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00005158/// Generates unique name for artificial threadprivate variables.
5159/// Format is: <Prefix> "." <Loc_raw_encoding> "_" <N>
5160static std::string generateUniqueName(StringRef Prefix, SourceLocation Loc,
5161 unsigned N) {
5162 SmallString<256> Buffer;
5163 llvm::raw_svector_ostream Out(Buffer);
5164 Out << Prefix << "." << Loc.getRawEncoding() << "_" << N;
5165 return Out.str();
5166}
5167
5168/// Emits reduction initializer function:
5169/// \code
5170/// void @.red_init(void* %arg) {
5171/// %0 = bitcast void* %arg to <type>*
5172/// store <type> <init>, <type>* %0
5173/// ret void
5174/// }
5175/// \endcode
5176static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM,
5177 SourceLocation Loc,
5178 ReductionCodeGen &RCG, unsigned N) {
5179 auto &C = CGM.getContext();
5180 FunctionArgList Args;
5181 ImplicitParamDecl Param(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5182 Args.emplace_back(&Param);
5183 auto &FnInfo =
5184 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5185 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5186 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5187 ".red_init.", &CGM.getModule());
5188 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5189 CodeGenFunction CGF(CGM);
5190 CGF.disableDebugInfo();
5191 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5192 Address PrivateAddr = CGF.EmitLoadOfPointer(
5193 CGF.GetAddrOfLocalVar(&Param),
5194 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5195 llvm::Value *Size = nullptr;
5196 // If the size of the reduction item is non-constant, load it from global
5197 // threadprivate variable.
5198 if (RCG.getSizes(N).second) {
5199 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5200 CGF, CGM.getContext().getSizeType(),
5201 generateUniqueName("reduction_size", Loc, N));
5202 Size =
5203 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5204 CGM.getContext().getSizeType(), SourceLocation());
5205 }
5206 RCG.emitAggregateType(CGF, N, Size);
5207 LValue SharedLVal;
5208 // If initializer uses initializer from declare reduction construct, emit a
5209 // pointer to the address of the original reduction item (reuired by reduction
5210 // initializer)
5211 if (RCG.usesReductionInitializer(N)) {
5212 Address SharedAddr =
5213 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5214 CGF, CGM.getContext().VoidPtrTy,
5215 generateUniqueName("reduction", Loc, N));
5216 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy);
5217 } else {
5218 SharedLVal = CGF.MakeNaturalAlignAddrLValue(
5219 llvm::ConstantPointerNull::get(CGM.VoidPtrTy),
5220 CGM.getContext().VoidPtrTy);
5221 }
5222 // Emit the initializer:
5223 // %0 = bitcast void* %arg to <type>*
5224 // store <type> <init>, <type>* %0
5225 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal,
5226 [](CodeGenFunction &) { return false; });
5227 CGF.FinishFunction();
5228 return Fn;
5229}
5230
5231/// Emits reduction combiner function:
5232/// \code
5233/// void @.red_comb(void* %arg0, void* %arg1) {
5234/// %lhs = bitcast void* %arg0 to <type>*
5235/// %rhs = bitcast void* %arg1 to <type>*
5236/// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs)
5237/// store <type> %2, <type>* %lhs
5238/// ret void
5239/// }
5240/// \endcode
5241static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM,
5242 SourceLocation Loc,
5243 ReductionCodeGen &RCG, unsigned N,
5244 const Expr *ReductionOp,
5245 const Expr *LHS, const Expr *RHS,
5246 const Expr *PrivateRef) {
5247 auto &C = CGM.getContext();
5248 auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl());
5249 auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl());
5250 FunctionArgList Args;
5251 ImplicitParamDecl ParamInOut(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5252 ImplicitParamDecl ParamIn(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5253 Args.emplace_back(&ParamInOut);
5254 Args.emplace_back(&ParamIn);
5255 auto &FnInfo =
5256 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5257 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5258 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5259 ".red_comb.", &CGM.getModule());
5260 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5261 CodeGenFunction CGF(CGM);
5262 CGF.disableDebugInfo();
5263 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5264 llvm::Value *Size = nullptr;
5265 // If the size of the reduction item is non-constant, load it from global
5266 // threadprivate variable.
5267 if (RCG.getSizes(N).second) {
5268 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5269 CGF, CGM.getContext().getSizeType(),
5270 generateUniqueName("reduction_size", Loc, N));
5271 Size =
5272 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5273 CGM.getContext().getSizeType(), SourceLocation());
5274 }
5275 RCG.emitAggregateType(CGF, N, Size);
5276 // Remap lhs and rhs variables to the addresses of the function arguments.
5277 // %lhs = bitcast void* %arg0 to <type>*
5278 // %rhs = bitcast void* %arg1 to <type>*
5279 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5280 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() -> Address {
5281 // Pull out the pointer to the variable.
5282 Address PtrAddr = CGF.EmitLoadOfPointer(
5283 CGF.GetAddrOfLocalVar(&ParamInOut),
5284 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5285 return CGF.Builder.CreateElementBitCast(
5286 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType()));
5287 });
5288 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() -> Address {
5289 // Pull out the pointer to the variable.
5290 Address PtrAddr = CGF.EmitLoadOfPointer(
5291 CGF.GetAddrOfLocalVar(&ParamIn),
5292 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5293 return CGF.Builder.CreateElementBitCast(
5294 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType()));
5295 });
5296 PrivateScope.Privatize();
5297 // Emit the combiner body:
5298 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs)
5299 // store <type> %2, <type>* %lhs
5300 CGM.getOpenMPRuntime().emitSingleReductionCombiner(
5301 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS),
5302 cast<DeclRefExpr>(RHS));
5303 CGF.FinishFunction();
5304 return Fn;
5305}
5306
5307/// Emits reduction finalizer function:
5308/// \code
5309/// void @.red_fini(void* %arg) {
5310/// %0 = bitcast void* %arg to <type>*
5311/// <destroy>(<type>* %0)
5312/// ret void
5313/// }
5314/// \endcode
5315static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM,
5316 SourceLocation Loc,
5317 ReductionCodeGen &RCG, unsigned N) {
5318 if (!RCG.needCleanups(N))
5319 return nullptr;
5320 auto &C = CGM.getContext();
5321 FunctionArgList Args;
5322 ImplicitParamDecl Param(C, C.VoidPtrTy, ImplicitParamDecl::Other);
5323 Args.emplace_back(&Param);
5324 auto &FnInfo =
5325 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
5326 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
5327 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
5328 ".red_fini.", &CGM.getModule());
5329 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
5330 CodeGenFunction CGF(CGM);
5331 CGF.disableDebugInfo();
5332 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
5333 Address PrivateAddr = CGF.EmitLoadOfPointer(
5334 CGF.GetAddrOfLocalVar(&Param),
5335 C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
5336 llvm::Value *Size = nullptr;
5337 // If the size of the reduction item is non-constant, load it from global
5338 // threadprivate variable.
5339 if (RCG.getSizes(N).second) {
5340 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate(
5341 CGF, CGM.getContext().getSizeType(),
5342 generateUniqueName("reduction_size", Loc, N));
5343 Size =
5344 CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false,
5345 CGM.getContext().getSizeType(), SourceLocation());
5346 }
5347 RCG.emitAggregateType(CGF, N, Size);
5348 // Emit the finalizer body:
5349 // <destroy>(<type>* %0)
5350 RCG.emitCleanups(CGF, N, PrivateAddr);
5351 CGF.FinishFunction();
5352 return Fn;
5353}
5354
5355llvm::Value *CGOpenMPRuntime::emitTaskReductionInit(
5356 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs,
5357 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) {
5358 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty())
5359 return nullptr;
5360
5361 // Build typedef struct:
5362 // kmp_task_red_input {
5363 // void *reduce_shar; // shared reduction item
5364 // size_t reduce_size; // size of data item
5365 // void *reduce_init; // data initialization routine
5366 // void *reduce_fini; // data finalization routine
5367 // void *reduce_comb; // data combiner routine
5368 // kmp_task_red_flags_t flags; // flags for additional info from compiler
5369 // } kmp_task_red_input_t;
5370 ASTContext &C = CGM.getContext();
5371 auto *RD = C.buildImplicitRecord("kmp_task_red_input_t");
5372 RD->startDefinition();
5373 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5374 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType());
5375 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5376 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5377 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy);
5378 const FieldDecl *FlagsFD = addFieldToRecordDecl(
5379 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false));
5380 RD->completeDefinition();
5381 QualType RDType = C.getRecordType(RD);
5382 unsigned Size = Data.ReductionVars.size();
5383 llvm::APInt ArraySize(/*numBits=*/64, Size);
5384 QualType ArrayRDType = C.getConstantArrayType(
5385 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0);
5386 // kmp_task_red_input_t .rd_input.[Size];
5387 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input.");
5388 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies,
5389 Data.ReductionOps);
5390 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) {
5391 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt];
5392 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0),
5393 llvm::ConstantInt::get(CGM.SizeTy, Cnt)};
5394 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP(
5395 TaskRedInput.getPointer(), Idxs,
5396 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc,
5397 ".rd_input.gep.");
5398 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType);
5399 // ElemLVal.reduce_shar = &Shareds[Cnt];
5400 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD);
5401 RCG.emitSharedLValue(CGF, Cnt);
5402 llvm::Value *CastedShared =
5403 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer());
5404 CGF.EmitStoreOfScalar(CastedShared, SharedLVal);
5405 RCG.emitAggregateType(CGF, Cnt);
5406 llvm::Value *SizeValInChars;
5407 llvm::Value *SizeVal;
5408 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt);
5409 // We use delayed creation/initialization for VLAs, array sections and
5410 // custom reduction initializations. It is required because runtime does not
5411 // provide the way to pass the sizes of VLAs/array sections to
5412 // initializer/combiner/finalizer functions and does not pass the pointer to
5413 // original reduction item to the initializer. Instead threadprivate global
5414 // variables are used to store these values and use them in the functions.
5415 bool DelayedCreation = !!SizeVal;
5416 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy,
5417 /*isSigned=*/false);
5418 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD);
5419 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal);
5420 // ElemLVal.reduce_init = init;
5421 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD);
5422 llvm::Value *InitAddr =
5423 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt));
5424 CGF.EmitStoreOfScalar(InitAddr, InitLVal);
5425 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt);
5426 // ElemLVal.reduce_fini = fini;
5427 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD);
5428 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt);
5429 llvm::Value *FiniAddr = Fini
5430 ? CGF.EmitCastToVoidPtr(Fini)
5431 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy);
5432 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal);
5433 // ElemLVal.reduce_comb = comb;
5434 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD);
5435 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction(
5436 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt],
5437 RHSExprs[Cnt], Data.ReductionCopies[Cnt]));
5438 CGF.EmitStoreOfScalar(CombAddr, CombLVal);
5439 // ElemLVal.flags = 0;
5440 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD);
5441 if (DelayedCreation) {
5442 CGF.EmitStoreOfScalar(
5443 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true),
5444 FlagsLVal);
5445 } else
5446 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType());
5447 }
5448 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void
5449 // *data);
5450 llvm::Value *Args[] = {
5451 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5452 /*isSigned=*/true),
5453 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true),
5454 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(),
5455 CGM.VoidPtrTy)};
5456 return CGF.EmitRuntimeCall(
5457 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args);
5458}
5459
5460void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF,
5461 SourceLocation Loc,
5462 ReductionCodeGen &RCG,
5463 unsigned N) {
5464 auto Sizes = RCG.getSizes(N);
5465 // Emit threadprivate global variable if the type is non-constant
5466 // (Sizes.second = nullptr).
5467 if (Sizes.second) {
5468 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy,
5469 /*isSigned=*/false);
5470 Address SizeAddr = getAddrOfArtificialThreadPrivate(
5471 CGF, CGM.getContext().getSizeType(),
5472 generateUniqueName("reduction_size", Loc, N));
5473 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false);
5474 }
5475 // Store address of the original reduction item if custom initializer is used.
5476 if (RCG.usesReductionInitializer(N)) {
5477 Address SharedAddr = getAddrOfArtificialThreadPrivate(
5478 CGF, CGM.getContext().VoidPtrTy,
5479 generateUniqueName("reduction", Loc, N));
5480 CGF.Builder.CreateStore(
5481 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5482 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy),
5483 SharedAddr, /*IsVolatile=*/false);
5484 }
5485}
5486
5487Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF,
5488 SourceLocation Loc,
5489 llvm::Value *ReductionsPtr,
5490 LValue SharedLVal) {
5491 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void
5492 // *d);
5493 llvm::Value *Args[] = {
5494 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy,
5495 /*isSigned=*/true),
5496 ReductionsPtr,
5497 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(),
5498 CGM.VoidPtrTy)};
5499 return Address(
5500 CGF.EmitRuntimeCall(
5501 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args),
5502 SharedLVal.getAlignment());
5503}
5504
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005505void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
5506 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005507 if (!CGF.HaveInsertPoint())
5508 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005509 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
5510 // global_tid);
5511 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
5512 // Ignore return result until untied tasks are supported.
5513 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005514 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5515 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005516}
5517
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005518void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005519 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005520 const RegionCodeGenTy &CodeGen,
5521 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005522 if (!CGF.HaveInsertPoint())
5523 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005524 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005525 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00005526}
5527
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005528namespace {
5529enum RTCancelKind {
5530 CancelNoreq = 0,
5531 CancelParallel = 1,
5532 CancelLoop = 2,
5533 CancelSections = 3,
5534 CancelTaskgroup = 4
5535};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00005536} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005537
5538static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
5539 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00005540 if (CancelRegion == OMPD_parallel)
5541 CancelKind = CancelParallel;
5542 else if (CancelRegion == OMPD_for)
5543 CancelKind = CancelLoop;
5544 else if (CancelRegion == OMPD_sections)
5545 CancelKind = CancelSections;
5546 else {
5547 assert(CancelRegion == OMPD_taskgroup);
5548 CancelKind = CancelTaskgroup;
5549 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005550 return CancelKind;
5551}
5552
5553void CGOpenMPRuntime::emitCancellationPointCall(
5554 CodeGenFunction &CGF, SourceLocation Loc,
5555 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005556 if (!CGF.HaveInsertPoint())
5557 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005558 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
5559 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005560 if (auto *OMPRegionInfo =
5561 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00005562 // For 'cancellation point taskgroup', the task region info may not have a
5563 // cancel. This may instead happen in another adjacent task.
5564 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005565 llvm::Value *Args[] = {
5566 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
5567 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005568 // Ignore return result until untied tasks are supported.
5569 auto *Result = CGF.EmitRuntimeCall(
5570 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
5571 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005572 // exit from construct;
5573 // }
5574 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5575 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5576 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5577 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5578 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005579 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005580 auto CancelDest =
5581 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005582 CGF.EmitBranchThroughCleanup(CancelDest);
5583 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5584 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005585 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005586}
5587
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005588void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00005589 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005590 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005591 if (!CGF.HaveInsertPoint())
5592 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005593 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
5594 // kmp_int32 cncl_kind);
5595 if (auto *OMPRegionInfo =
5596 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005597 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
5598 PrePostActionTy &) {
5599 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00005600 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005601 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00005602 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
5603 // Ignore return result until untied tasks are supported.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005604 auto *Result = CGF.EmitRuntimeCall(
5605 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00005606 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00005607 // exit from construct;
5608 // }
5609 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5610 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5611 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5612 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5613 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00005614 // exit from construct;
5615 auto CancelDest =
5616 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
5617 CGF.EmitBranchThroughCleanup(CancelDest);
5618 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5619 };
5620 if (IfCond)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005621 emitOMPIfClause(CGF, IfCond, ThenGen,
5622 [](CodeGenFunction &, PrePostActionTy &) {});
5623 else {
5624 RegionCodeGenTy ThenRCG(ThenGen);
5625 ThenRCG(CGF);
5626 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005627 }
5628}
Samuel Antaobed3c462015-10-02 16:14:20 +00005629
Samuel Antaoee8fb302016-01-06 13:42:12 +00005630/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00005631/// consists of the file and device IDs as well as line number associated with
5632/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005633static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
5634 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005635 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005636
5637 auto &SM = C.getSourceManager();
5638
5639 // The loc should be always valid and have a file ID (the user cannot use
5640 // #pragma directives in macros)
5641
5642 assert(Loc.isValid() && "Source location is expected to be always valid.");
5643 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
5644
5645 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
5646 assert(PLoc.isValid() && "Source location is expected to be always valid.");
5647
5648 llvm::sys::fs::UniqueID ID;
5649 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
5650 llvm_unreachable("Source file with target region no longer exists!");
5651
5652 DeviceID = ID.getDevice();
5653 FileID = ID.getFile();
5654 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00005655}
5656
5657void CGOpenMPRuntime::emitTargetOutlinedFunction(
5658 const OMPExecutableDirective &D, StringRef ParentName,
5659 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005660 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005661 assert(!ParentName.empty() && "Invalid target region parent name!");
5662
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005663 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
5664 IsOffloadEntry, CodeGen);
5665}
5666
5667void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
5668 const OMPExecutableDirective &D, StringRef ParentName,
5669 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
5670 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00005671 // Create a unique name for the entry function using the source location
5672 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00005673 //
Samuel Antao2de62b02016-02-13 23:35:10 +00005674 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00005675 //
5676 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00005677 // mangled name of the function that encloses the target region and BB is the
5678 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005679
5680 unsigned DeviceID;
5681 unsigned FileID;
5682 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005683 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005684 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005685 SmallString<64> EntryFnName;
5686 {
5687 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00005688 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
5689 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005690 }
5691
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005692 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5693
Samuel Antaobed3c462015-10-02 16:14:20 +00005694 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005695 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00005696 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005697
Samuel Antao6d004262016-06-16 18:39:34 +00005698 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005699
5700 // If this target outline function is not an offload entry, we don't need to
5701 // register it.
5702 if (!IsOffloadEntry)
5703 return;
5704
5705 // The target region ID is used by the runtime library to identify the current
5706 // target region, so it only has to be unique and not necessarily point to
5707 // anything. It could be the pointer to the outlined function that implements
5708 // the target region, but we aren't using that so that the compiler doesn't
5709 // need to keep that, and could therefore inline the host function if proven
5710 // worthwhile during optimization. In the other hand, if emitting code for the
5711 // device, the ID has to be the function address so that it can retrieved from
5712 // the offloading entry and launched by the runtime library. We also mark the
5713 // outlined function to have external linkage in case we are emitting code for
5714 // the device, because these functions will be entry points to the device.
5715
5716 if (CGM.getLangOpts().OpenMPIsDevice) {
5717 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
5718 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
5719 } else
5720 OutlinedFnID = new llvm::GlobalVariable(
5721 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
5722 llvm::GlobalValue::PrivateLinkage,
5723 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
5724
5725 // Register the information for the entry associated with this target region.
5726 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00005727 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
5728 /*Flags=*/0);
Samuel Antaobed3c462015-10-02 16:14:20 +00005729}
5730
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005731/// discard all CompoundStmts intervening between two constructs
5732static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
5733 while (auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
5734 Body = CS->body_front();
5735
5736 return Body;
5737}
5738
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005739/// Emit the number of teams for a target directive. Inspect the num_teams
5740/// clause associated with a teams construct combined or closely nested
5741/// with the target directive.
5742///
5743/// Emit a team of size one for directives such as 'target parallel' that
5744/// have no associated teams construct.
5745///
5746/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00005747static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005748emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
5749 CodeGenFunction &CGF,
5750 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005751
5752 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
5753 "teams directive expected to be "
5754 "emitted only for the host!");
5755
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005756 auto &Bld = CGF.Builder;
5757
5758 // If the target directive is combined with a teams directive:
5759 // Return the value in the num_teams clause, if any.
5760 // Otherwise, return 0 to denote the runtime default.
5761 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
5762 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
5763 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
5764 auto NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
5765 /*IgnoreResultAssign*/ true);
5766 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5767 /*IsSigned=*/true);
5768 }
5769
5770 // The default value is 0.
5771 return Bld.getInt32(0);
5772 }
5773
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005774 // If the target directive is combined with a parallel directive but not a
5775 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005776 if (isOpenMPParallelDirective(D.getDirectiveKind()))
5777 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005778
5779 // If the current target region has a teams region enclosed, we need to get
5780 // the number of teams to pass to the runtime function call. This is done
5781 // by generating the expression in a inlined region. This is required because
5782 // the expression is captured in the enclosing target environment when the
5783 // teams directive is not combined with target.
5784
5785 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5786
5787 // FIXME: Accommodate other combined directives with teams when they become
5788 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005789 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
5790 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005791 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
5792 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5793 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5794 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005795 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5796 /*IsSigned=*/true);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005797 }
5798
5799 // If we have an enclosed teams directive but no num_teams clause we use
5800 // the default value 0.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005801 return Bld.getInt32(0);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005802 }
5803
5804 // No teams associated with the directive.
5805 return nullptr;
5806}
5807
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005808/// Emit the number of threads for a target directive. Inspect the
5809/// thread_limit clause associated with a teams construct combined or closely
5810/// nested with the target directive.
5811///
5812/// Emit the num_threads clause for directives such as 'target parallel' that
5813/// have no associated teams construct.
5814///
5815/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00005816static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005817emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
5818 CodeGenFunction &CGF,
5819 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005820
5821 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
5822 "teams directive expected to be "
5823 "emitted only for the host!");
5824
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005825 auto &Bld = CGF.Builder;
5826
5827 //
5828 // If the target directive is combined with a teams directive:
5829 // Return the value in the thread_limit clause, if any.
5830 //
5831 // If the target directive is combined with a parallel directive:
5832 // Return the value in the num_threads clause, if any.
5833 //
5834 // If both clauses are set, select the minimum of the two.
5835 //
5836 // If neither teams or parallel combined directives set the number of threads
5837 // in a team, return 0 to denote the runtime default.
5838 //
5839 // If this is not a teams directive return nullptr.
5840
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005841 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
5842 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005843 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
5844 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005845 llvm::Value *ThreadLimitVal = nullptr;
5846
5847 if (const auto *ThreadLimitClause =
5848 D.getSingleClause<OMPThreadLimitClause>()) {
5849 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
5850 auto ThreadLimit = CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
5851 /*IgnoreResultAssign*/ true);
5852 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5853 /*IsSigned=*/true);
5854 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005855
5856 if (const auto *NumThreadsClause =
5857 D.getSingleClause<OMPNumThreadsClause>()) {
5858 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
5859 llvm::Value *NumThreads =
5860 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
5861 /*IgnoreResultAssign*/ true);
5862 NumThreadsVal =
5863 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
5864 }
5865
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005866 // Select the lesser of thread_limit and num_threads.
5867 if (NumThreadsVal)
5868 ThreadLimitVal = ThreadLimitVal
5869 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
5870 ThreadLimitVal),
5871 NumThreadsVal, ThreadLimitVal)
5872 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00005873
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005874 // Set default value passed to the runtime if either teams or a target
5875 // parallel type directive is found but no clause is specified.
5876 if (!ThreadLimitVal)
5877 ThreadLimitVal = DefaultThreadLimitVal;
5878
5879 return ThreadLimitVal;
5880 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00005881
Samuel Antaob68e2db2016-03-03 16:20:23 +00005882 // If the current target region has a teams region enclosed, we need to get
5883 // the thread limit to pass to the runtime function call. This is done
5884 // by generating the expression in a inlined region. This is required because
5885 // the expression is captured in the enclosing target environment when the
5886 // teams directive is not combined with target.
5887
5888 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5889
5890 // FIXME: Accommodate other combined directives with teams when they become
5891 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005892 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
5893 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005894 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
5895 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5896 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5897 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
5898 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5899 /*IsSigned=*/true);
5900 }
5901
5902 // If we have an enclosed teams directive but no thread_limit clause we use
5903 // the default value 0.
5904 return CGF.Builder.getInt32(0);
5905 }
5906
5907 // No teams associated with the directive.
5908 return nullptr;
5909}
5910
Samuel Antao86ace552016-04-27 22:40:57 +00005911namespace {
5912// \brief Utility to handle information from clauses associated with a given
5913// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
5914// It provides a convenient interface to obtain the information and generate
5915// code for that information.
5916class MappableExprsHandler {
5917public:
5918 /// \brief Values for bit flags used to specify the mapping type for
5919 /// offloading.
5920 enum OpenMPOffloadMappingFlags {
Samuel Antao86ace552016-04-27 22:40:57 +00005921 /// \brief Allocate memory on the device and move data from host to device.
5922 OMP_MAP_TO = 0x01,
5923 /// \brief Allocate memory on the device and move data from device to host.
5924 OMP_MAP_FROM = 0x02,
5925 /// \brief Always perform the requested mapping action on the element, even
5926 /// if it was already mapped before.
5927 OMP_MAP_ALWAYS = 0x04,
Samuel Antao86ace552016-04-27 22:40:57 +00005928 /// \brief Delete the element from the device environment, ignoring the
5929 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00005930 OMP_MAP_DELETE = 0x08,
5931 /// \brief The element being mapped is a pointer, therefore the pointee
5932 /// should be mapped as well.
5933 OMP_MAP_IS_PTR = 0x10,
5934 /// \brief This flags signals that an argument is the first one relating to
5935 /// a map/private clause expression. For some cases a single
5936 /// map/privatization results in multiple arguments passed to the runtime
5937 /// library.
5938 OMP_MAP_FIRST_REF = 0x20,
Samuel Antaocc10b852016-07-28 14:23:26 +00005939 /// \brief Signal that the runtime library has to return the device pointer
5940 /// in the current position for the data being mapped.
5941 OMP_MAP_RETURN_PTR = 0x40,
Samuel Antaod486f842016-05-26 16:53:38 +00005942 /// \brief This flag signals that the reference being passed is a pointer to
5943 /// private data.
5944 OMP_MAP_PRIVATE_PTR = 0x80,
Samuel Antao86ace552016-04-27 22:40:57 +00005945 /// \brief Pass the element to the device by value.
Samuel Antao6782e942016-05-26 16:48:10 +00005946 OMP_MAP_PRIVATE_VAL = 0x100,
Samuel Antao86ace552016-04-27 22:40:57 +00005947 };
5948
Samuel Antaocc10b852016-07-28 14:23:26 +00005949 /// Class that associates information with a base pointer to be passed to the
5950 /// runtime library.
5951 class BasePointerInfo {
5952 /// The base pointer.
5953 llvm::Value *Ptr = nullptr;
5954 /// The base declaration that refers to this device pointer, or null if
5955 /// there is none.
5956 const ValueDecl *DevPtrDecl = nullptr;
5957
5958 public:
5959 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
5960 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
5961 llvm::Value *operator*() const { return Ptr; }
5962 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
5963 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
5964 };
5965
5966 typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00005967 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
5968 typedef SmallVector<unsigned, 16> MapFlagsArrayTy;
5969
5970private:
5971 /// \brief Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00005972 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00005973
5974 /// \brief Function the directive is being generated for.
5975 CodeGenFunction &CGF;
5976
Samuel Antaod486f842016-05-26 16:53:38 +00005977 /// \brief Set of all first private variables in the current directive.
5978 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
5979
Samuel Antao6890b092016-07-28 14:25:09 +00005980 /// Map between device pointer declarations and their expression components.
5981 /// The key value for declarations in 'this' is null.
5982 llvm::DenseMap<
5983 const ValueDecl *,
5984 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
5985 DevPointersMap;
5986
Samuel Antao86ace552016-04-27 22:40:57 +00005987 llvm::Value *getExprTypeSize(const Expr *E) const {
5988 auto ExprTy = E->getType().getCanonicalType();
5989
5990 // Reference types are ignored for mapping purposes.
5991 if (auto *RefTy = ExprTy->getAs<ReferenceType>())
5992 ExprTy = RefTy->getPointeeType().getCanonicalType();
5993
5994 // Given that an array section is considered a built-in type, we need to
5995 // do the calculation based on the length of the section instead of relying
5996 // on CGF.getTypeSize(E->getType()).
5997 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
5998 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
5999 OAE->getBase()->IgnoreParenImpCasts())
6000 .getCanonicalType();
6001
6002 // If there is no length associated with the expression, that means we
6003 // are using the whole length of the base.
6004 if (!OAE->getLength() && OAE->getColonLoc().isValid())
6005 return CGF.getTypeSize(BaseTy);
6006
6007 llvm::Value *ElemSize;
6008 if (auto *PTy = BaseTy->getAs<PointerType>())
6009 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
6010 else {
6011 auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
6012 assert(ATy && "Expecting array type if not a pointer type.");
6013 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
6014 }
6015
6016 // If we don't have a length at this point, that is because we have an
6017 // array section with a single element.
6018 if (!OAE->getLength())
6019 return ElemSize;
6020
6021 auto *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
6022 LengthVal =
6023 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
6024 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
6025 }
6026 return CGF.getTypeSize(ExprTy);
6027 }
6028
6029 /// \brief Return the corresponding bits for a given map clause modifier. Add
6030 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00006031 /// map as the first one of a series of maps that relate to the same map
6032 /// expression.
Samuel Antao86ace552016-04-27 22:40:57 +00006033 unsigned getMapTypeBits(OpenMPMapClauseKind MapType,
6034 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
Samuel Antao6782e942016-05-26 16:48:10 +00006035 bool AddIsFirstFlag) const {
Samuel Antao86ace552016-04-27 22:40:57 +00006036 unsigned Bits = 0u;
6037 switch (MapType) {
6038 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00006039 case OMPC_MAP_release:
6040 // alloc and release is the default behavior in the runtime library, i.e.
6041 // if we don't pass any bits alloc/release that is what the runtime is
6042 // going to do. Therefore, we don't need to signal anything for these two
6043 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00006044 break;
6045 case OMPC_MAP_to:
6046 Bits = OMP_MAP_TO;
6047 break;
6048 case OMPC_MAP_from:
6049 Bits = OMP_MAP_FROM;
6050 break;
6051 case OMPC_MAP_tofrom:
6052 Bits = OMP_MAP_TO | OMP_MAP_FROM;
6053 break;
6054 case OMPC_MAP_delete:
6055 Bits = OMP_MAP_DELETE;
6056 break;
Samuel Antao86ace552016-04-27 22:40:57 +00006057 default:
6058 llvm_unreachable("Unexpected map type!");
6059 break;
6060 }
6061 if (AddPtrFlag)
Samuel Antao6782e942016-05-26 16:48:10 +00006062 Bits |= OMP_MAP_IS_PTR;
6063 if (AddIsFirstFlag)
6064 Bits |= OMP_MAP_FIRST_REF;
Samuel Antao86ace552016-04-27 22:40:57 +00006065 if (MapTypeModifier == OMPC_MAP_always)
6066 Bits |= OMP_MAP_ALWAYS;
6067 return Bits;
6068 }
6069
6070 /// \brief Return true if the provided expression is a final array section. A
6071 /// final array section, is one whose length can't be proved to be one.
6072 bool isFinalArraySectionExpression(const Expr *E) const {
6073 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
6074
6075 // It is not an array section and therefore not a unity-size one.
6076 if (!OASE)
6077 return false;
6078
6079 // An array section with no colon always refer to a single element.
6080 if (OASE->getColonLoc().isInvalid())
6081 return false;
6082
6083 auto *Length = OASE->getLength();
6084
6085 // If we don't have a length we have to check if the array has size 1
6086 // for this dimension. Also, we should always expect a length if the
6087 // base type is pointer.
6088 if (!Length) {
6089 auto BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
6090 OASE->getBase()->IgnoreParenImpCasts())
6091 .getCanonicalType();
6092 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
6093 return ATy->getSize().getSExtValue() != 1;
6094 // If we don't have a constant dimension length, we have to consider
6095 // the current section as having any size, so it is not necessarily
6096 // unitary. If it happen to be unity size, that's user fault.
6097 return true;
6098 }
6099
6100 // Check if the length evaluates to 1.
6101 llvm::APSInt ConstLength;
6102 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
6103 return true; // Can have more that size 1.
6104
6105 return ConstLength.getSExtValue() != 1;
6106 }
6107
6108 /// \brief Generate the base pointers, section pointers, sizes and map type
6109 /// bits for the provided map type, map modifier, and expression components.
6110 /// \a IsFirstComponent should be set to true if the provided set of
6111 /// components is the first associated with a capture.
6112 void generateInfoForComponentList(
6113 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6114 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00006115 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006116 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
6117 bool IsFirstComponentList) const {
6118
6119 // The following summarizes what has to be generated for each map and the
6120 // types bellow. The generated information is expressed in this order:
6121 // base pointer, section pointer, size, flags
6122 // (to add to the ones that come from the map type and modifier).
6123 //
6124 // double d;
6125 // int i[100];
6126 // float *p;
6127 //
6128 // struct S1 {
6129 // int i;
6130 // float f[50];
6131 // }
6132 // struct S2 {
6133 // int i;
6134 // float f[50];
6135 // S1 s;
6136 // double *p;
6137 // struct S2 *ps;
6138 // }
6139 // S2 s;
6140 // S2 *ps;
6141 //
6142 // map(d)
6143 // &d, &d, sizeof(double), noflags
6144 //
6145 // map(i)
6146 // &i, &i, 100*sizeof(int), noflags
6147 //
6148 // map(i[1:23])
6149 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
6150 //
6151 // map(p)
6152 // &p, &p, sizeof(float*), noflags
6153 //
6154 // map(p[1:24])
6155 // p, &p[1], 24*sizeof(float), noflags
6156 //
6157 // map(s)
6158 // &s, &s, sizeof(S2), noflags
6159 //
6160 // map(s.i)
6161 // &s, &(s.i), sizeof(int), noflags
6162 //
6163 // map(s.s.f)
6164 // &s, &(s.i.f), 50*sizeof(int), noflags
6165 //
6166 // map(s.p)
6167 // &s, &(s.p), sizeof(double*), noflags
6168 //
6169 // map(s.p[:22], s.a s.b)
6170 // &s, &(s.p), sizeof(double*), noflags
6171 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag + extra_flag
6172 //
6173 // map(s.ps)
6174 // &s, &(s.ps), sizeof(S2*), noflags
6175 //
6176 // map(s.ps->s.i)
6177 // &s, &(s.ps), sizeof(S2*), noflags
6178 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag + extra_flag
6179 //
6180 // map(s.ps->ps)
6181 // &s, &(s.ps), sizeof(S2*), noflags
6182 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
6183 //
6184 // map(s.ps->ps->ps)
6185 // &s, &(s.ps), sizeof(S2*), noflags
6186 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
6187 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6188 //
6189 // map(s.ps->ps->s.f[:22])
6190 // &s, &(s.ps), sizeof(S2*), noflags
6191 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
6192 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag + extra_flag
6193 //
6194 // map(ps)
6195 // &ps, &ps, sizeof(S2*), noflags
6196 //
6197 // map(ps->i)
6198 // ps, &(ps->i), sizeof(int), noflags
6199 //
6200 // map(ps->s.f)
6201 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
6202 //
6203 // map(ps->p)
6204 // ps, &(ps->p), sizeof(double*), noflags
6205 //
6206 // map(ps->p[:22])
6207 // ps, &(ps->p), sizeof(double*), noflags
6208 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag + extra_flag
6209 //
6210 // map(ps->ps)
6211 // ps, &(ps->ps), sizeof(S2*), noflags
6212 //
6213 // map(ps->ps->s.i)
6214 // ps, &(ps->ps), sizeof(S2*), noflags
6215 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag + extra_flag
6216 //
6217 // map(ps->ps->ps)
6218 // ps, &(ps->ps), sizeof(S2*), noflags
6219 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6220 //
6221 // map(ps->ps->ps->ps)
6222 // ps, &(ps->ps), sizeof(S2*), noflags
6223 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6224 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6225 //
6226 // map(ps->ps->ps->s.f[:22])
6227 // ps, &(ps->ps), sizeof(S2*), noflags
6228 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
6229 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag +
6230 // extra_flag
6231
6232 // Track if the map information being generated is the first for a capture.
6233 bool IsCaptureFirstInfo = IsFirstComponentList;
6234
6235 // Scan the components from the base to the complete expression.
6236 auto CI = Components.rbegin();
6237 auto CE = Components.rend();
6238 auto I = CI;
6239
6240 // Track if the map information being generated is the first for a list of
6241 // components.
6242 bool IsExpressionFirstInfo = true;
6243 llvm::Value *BP = nullptr;
6244
6245 if (auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
6246 // The base is the 'this' pointer. The content of the pointer is going
6247 // to be the base of the field being mapped.
6248 BP = CGF.EmitScalarExpr(ME->getBase());
6249 } else {
6250 // The base is the reference to the variable.
6251 // BP = &Var.
6252 BP = CGF.EmitLValue(cast<DeclRefExpr>(I->getAssociatedExpression()))
6253 .getPointer();
6254
6255 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00006256 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00006257 // reference. References are ignored for mapping purposes.
6258 QualType Ty =
6259 I->getAssociatedDeclaration()->getType().getNonReferenceType();
6260 if (Ty->isAnyPointerType() && std::next(I) != CE) {
6261 auto PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
Samuel Antao86ace552016-04-27 22:40:57 +00006262 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
Samuel Antao403ffd42016-07-27 22:49:49 +00006263 Ty->castAs<PointerType>())
Samuel Antao86ace552016-04-27 22:40:57 +00006264 .getPointer();
6265
6266 // We do not need to generate individual map information for the
6267 // pointer, it can be associated with the combined storage.
6268 ++I;
6269 }
6270 }
6271
6272 for (; I != CE; ++I) {
6273 auto Next = std::next(I);
6274
6275 // We need to generate the addresses and sizes if this is the last
6276 // component, if the component is a pointer or if it is an array section
6277 // whose length can't be proved to be one. If this is a pointer, it
6278 // becomes the base address for the following components.
6279
6280 // A final array section, is one whose length can't be proved to be one.
6281 bool IsFinalArraySection =
6282 isFinalArraySectionExpression(I->getAssociatedExpression());
6283
6284 // Get information on whether the element is a pointer. Have to do a
6285 // special treatment for array sections given that they are built-in
6286 // types.
6287 const auto *OASE =
6288 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
6289 bool IsPointer =
6290 (OASE &&
6291 OMPArraySectionExpr::getBaseOriginalType(OASE)
6292 .getCanonicalType()
6293 ->isAnyPointerType()) ||
6294 I->getAssociatedExpression()->getType()->isAnyPointerType();
6295
6296 if (Next == CE || IsPointer || IsFinalArraySection) {
6297
6298 // If this is not the last component, we expect the pointer to be
6299 // associated with an array expression or member expression.
6300 assert((Next == CE ||
6301 isa<MemberExpr>(Next->getAssociatedExpression()) ||
6302 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
6303 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
6304 "Unexpected expression");
6305
Samuel Antao86ace552016-04-27 22:40:57 +00006306 auto *LB = CGF.EmitLValue(I->getAssociatedExpression()).getPointer();
6307 auto *Size = getExprTypeSize(I->getAssociatedExpression());
6308
Samuel Antao03a3cec2016-07-27 22:52:16 +00006309 // If we have a member expression and the current component is a
6310 // reference, we have to map the reference too. Whenever we have a
6311 // reference, the section that reference refers to is going to be a
6312 // load instruction from the storage assigned to the reference.
6313 if (isa<MemberExpr>(I->getAssociatedExpression()) &&
6314 I->getAssociatedDeclaration()->getType()->isReferenceType()) {
6315 auto *LI = cast<llvm::LoadInst>(LB);
6316 auto *RefAddr = LI->getPointerOperand();
6317
6318 BasePointers.push_back(BP);
6319 Pointers.push_back(RefAddr);
6320 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
6321 Types.push_back(getMapTypeBits(
6322 /*MapType*/ OMPC_MAP_alloc, /*MapTypeModifier=*/OMPC_MAP_unknown,
6323 !IsExpressionFirstInfo, IsCaptureFirstInfo));
6324 IsExpressionFirstInfo = false;
6325 IsCaptureFirstInfo = false;
6326 // The reference will be the next base address.
6327 BP = RefAddr;
6328 }
6329
6330 BasePointers.push_back(BP);
Samuel Antao86ace552016-04-27 22:40:57 +00006331 Pointers.push_back(LB);
6332 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00006333
Samuel Antao6782e942016-05-26 16:48:10 +00006334 // We need to add a pointer flag for each map that comes from the
6335 // same expression except for the first one. We also need to signal
6336 // this map is the first one that relates with the current capture
6337 // (there is a set of entries for each capture).
Samuel Antao86ace552016-04-27 22:40:57 +00006338 Types.push_back(getMapTypeBits(MapType, MapTypeModifier,
6339 !IsExpressionFirstInfo,
Samuel Antao6782e942016-05-26 16:48:10 +00006340 IsCaptureFirstInfo));
Samuel Antao86ace552016-04-27 22:40:57 +00006341
6342 // If we have a final array section, we are done with this expression.
6343 if (IsFinalArraySection)
6344 break;
6345
6346 // The pointer becomes the base for the next element.
6347 if (Next != CE)
6348 BP = LB;
6349
6350 IsExpressionFirstInfo = false;
6351 IsCaptureFirstInfo = false;
6352 continue;
6353 }
6354 }
6355 }
6356
Samuel Antaod486f842016-05-26 16:53:38 +00006357 /// \brief Return the adjusted map modifiers if the declaration a capture
6358 /// refers to appears in a first-private clause. This is expected to be used
6359 /// only with directives that start with 'target'.
6360 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
6361 unsigned CurrentModifiers) {
6362 assert(Cap.capturesVariable() && "Expected capture by reference only!");
6363
6364 // A first private variable captured by reference will use only the
6365 // 'private ptr' and 'map to' flag. Return the right flags if the captured
6366 // declaration is known as first-private in this handler.
6367 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
6368 return MappableExprsHandler::OMP_MAP_PRIVATE_PTR |
6369 MappableExprsHandler::OMP_MAP_TO;
6370
6371 // We didn't modify anything.
6372 return CurrentModifiers;
6373 }
6374
Samuel Antao86ace552016-04-27 22:40:57 +00006375public:
6376 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
Samuel Antao44bcdb32016-07-28 15:31:29 +00006377 : CurDir(Dir), CGF(CGF) {
Samuel Antaod486f842016-05-26 16:53:38 +00006378 // Extract firstprivate clause information.
6379 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
6380 for (const auto *D : C->varlists())
6381 FirstPrivateDecls.insert(
6382 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
Samuel Antao6890b092016-07-28 14:25:09 +00006383 // Extract device pointer clause information.
6384 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
6385 for (auto L : C->component_lists())
6386 DevPointersMap[L.first].push_back(L.second);
Samuel Antaod486f842016-05-26 16:53:38 +00006387 }
Samuel Antao86ace552016-04-27 22:40:57 +00006388
6389 /// \brief Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00006390 /// types for the extracted mappable expressions. Also, for each item that
6391 /// relates with a device pointer, a pair of the relevant declaration and
6392 /// index where it occurs is appended to the device pointers info array.
6393 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006394 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
6395 MapFlagsArrayTy &Types) const {
6396 BasePointers.clear();
6397 Pointers.clear();
6398 Sizes.clear();
6399 Types.clear();
6400
6401 struct MapInfo {
Samuel Antaocc10b852016-07-28 14:23:26 +00006402 /// Kind that defines how a device pointer has to be returned.
6403 enum ReturnPointerKind {
6404 // Don't have to return any pointer.
6405 RPK_None,
6406 // Pointer is the base of the declaration.
6407 RPK_Base,
6408 // Pointer is a member of the base declaration - 'this'
6409 RPK_Member,
6410 // Pointer is a reference and a member of the base declaration - 'this'
6411 RPK_MemberReference,
6412 };
Samuel Antao86ace552016-04-27 22:40:57 +00006413 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
Hans Wennborgbc1b58d2016-07-30 00:41:37 +00006414 OpenMPMapClauseKind MapType;
6415 OpenMPMapClauseKind MapTypeModifier;
6416 ReturnPointerKind ReturnDevicePointer;
6417
6418 MapInfo()
6419 : MapType(OMPC_MAP_unknown), MapTypeModifier(OMPC_MAP_unknown),
6420 ReturnDevicePointer(RPK_None) {}
Samuel Antaocc10b852016-07-28 14:23:26 +00006421 MapInfo(
6422 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
6423 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
6424 ReturnPointerKind ReturnDevicePointer)
6425 : Components(Components), MapType(MapType),
6426 MapTypeModifier(MapTypeModifier),
6427 ReturnDevicePointer(ReturnDevicePointer) {}
Samuel Antao86ace552016-04-27 22:40:57 +00006428 };
6429
6430 // We have to process the component lists that relate with the same
6431 // declaration in a single chunk so that we can generate the map flags
6432 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00006433 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00006434
6435 // Helper function to fill the information map for the different supported
6436 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00006437 auto &&InfoGen = [&Info](
6438 const ValueDecl *D,
6439 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
6440 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006441 MapInfo::ReturnPointerKind ReturnDevicePointer) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006442 const ValueDecl *VD =
6443 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
6444 Info[VD].push_back({L, MapType, MapModifier, ReturnDevicePointer});
6445 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00006446
Paul Robinson78fb1322016-08-01 22:12:46 +00006447 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006448 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00006449 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006450 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
6451 MapInfo::RPK_None);
Paul Robinson15c84002016-07-29 20:46:16 +00006452 for (auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00006453 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006454 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
6455 MapInfo::RPK_None);
Paul Robinson15c84002016-07-29 20:46:16 +00006456 for (auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00006457 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006458 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
6459 MapInfo::RPK_None);
Samuel Antao86ace552016-04-27 22:40:57 +00006460
Samuel Antaocc10b852016-07-28 14:23:26 +00006461 // Look at the use_device_ptr clause information and mark the existing map
6462 // entries as such. If there is no map information for an entry in the
6463 // use_device_ptr list, we create one with map type 'alloc' and zero size
6464 // section. It is the user fault if that was not mapped before.
Paul Robinson78fb1322016-08-01 22:12:46 +00006465 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006466 for (auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
Samuel Antaocc10b852016-07-28 14:23:26 +00006467 for (auto L : C->component_lists()) {
6468 assert(!L.second.empty() && "Not expecting empty list of components!");
6469 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
6470 VD = cast<ValueDecl>(VD->getCanonicalDecl());
6471 auto *IE = L.second.back().getAssociatedExpression();
6472 // If the first component is a member expression, we have to look into
6473 // 'this', which maps to null in the map of map information. Otherwise
6474 // look directly for the information.
6475 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
6476
6477 // We potentially have map information for this declaration already.
6478 // Look for the first set of components that refer to it.
6479 if (It != Info.end()) {
6480 auto CI = std::find_if(
6481 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
6482 return MI.Components.back().getAssociatedDeclaration() == VD;
6483 });
6484 // If we found a map entry, signal that the pointer has to be returned
6485 // and move on to the next declaration.
6486 if (CI != It->second.end()) {
6487 CI->ReturnDevicePointer = isa<MemberExpr>(IE)
6488 ? (VD->getType()->isReferenceType()
6489 ? MapInfo::RPK_MemberReference
6490 : MapInfo::RPK_Member)
6491 : MapInfo::RPK_Base;
6492 continue;
6493 }
6494 }
6495
6496 // We didn't find any match in our map information - generate a zero
6497 // size array section.
Paul Robinson78fb1322016-08-01 22:12:46 +00006498 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Samuel Antaocc10b852016-07-28 14:23:26 +00006499 llvm::Value *Ptr =
Paul Robinson15c84002016-07-29 20:46:16 +00006500 this->CGF
6501 .EmitLoadOfLValue(this->CGF.EmitLValue(IE), SourceLocation())
Samuel Antaocc10b852016-07-28 14:23:26 +00006502 .getScalarVal();
6503 BasePointers.push_back({Ptr, VD});
6504 Pointers.push_back(Ptr);
Paul Robinson15c84002016-07-29 20:46:16 +00006505 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
Samuel Antaocc10b852016-07-28 14:23:26 +00006506 Types.push_back(OMP_MAP_RETURN_PTR | OMP_MAP_FIRST_REF);
6507 }
6508
Samuel Antao86ace552016-04-27 22:40:57 +00006509 for (auto &M : Info) {
6510 // We need to know when we generate information for the first component
6511 // associated with a capture, because the mapping flags depend on it.
6512 bool IsFirstComponentList = true;
6513 for (MapInfo &L : M.second) {
6514 assert(!L.Components.empty() &&
6515 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00006516
6517 // Remember the current base pointer index.
6518 unsigned CurrentBasePointersIdx = BasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00006519 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Paul Robinson15c84002016-07-29 20:46:16 +00006520 this->generateInfoForComponentList(L.MapType, L.MapTypeModifier,
6521 L.Components, BasePointers, Pointers,
6522 Sizes, Types, IsFirstComponentList);
Samuel Antaocc10b852016-07-28 14:23:26 +00006523
6524 // If this entry relates with a device pointer, set the relevant
6525 // declaration and add the 'return pointer' flag.
6526 if (IsFirstComponentList &&
6527 L.ReturnDevicePointer != MapInfo::RPK_None) {
6528 // If the pointer is not the base of the map, we need to skip the
6529 // base. If it is a reference in a member field, we also need to skip
6530 // the map of the reference.
6531 if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
6532 ++CurrentBasePointersIdx;
6533 if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
6534 ++CurrentBasePointersIdx;
6535 }
6536 assert(BasePointers.size() > CurrentBasePointersIdx &&
6537 "Unexpected number of mapped base pointers.");
6538
6539 auto *RelevantVD = L.Components.back().getAssociatedDeclaration();
6540 assert(RelevantVD &&
6541 "No relevant declaration related with device pointer??");
6542
6543 BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
6544 Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PTR;
6545 }
Samuel Antao86ace552016-04-27 22:40:57 +00006546 IsFirstComponentList = false;
6547 }
6548 }
6549 }
6550
6551 /// \brief Generate the base pointers, section pointers, sizes and map types
6552 /// associated to a given capture.
6553 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00006554 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006555 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006556 MapValuesArrayTy &Pointers,
6557 MapValuesArrayTy &Sizes,
6558 MapFlagsArrayTy &Types) const {
6559 assert(!Cap->capturesVariableArrayType() &&
6560 "Not expecting to generate map info for a variable array type!");
6561
6562 BasePointers.clear();
6563 Pointers.clear();
6564 Sizes.clear();
6565 Types.clear();
6566
Samuel Antao6890b092016-07-28 14:25:09 +00006567 // We need to know when we generating information for the first component
6568 // associated with a capture, because the mapping flags depend on it.
6569 bool IsFirstComponentList = true;
6570
Samuel Antao86ace552016-04-27 22:40:57 +00006571 const ValueDecl *VD =
6572 Cap->capturesThis()
6573 ? nullptr
6574 : cast<ValueDecl>(Cap->getCapturedVar()->getCanonicalDecl());
6575
Samuel Antao6890b092016-07-28 14:25:09 +00006576 // If this declaration appears in a is_device_ptr clause we just have to
6577 // pass the pointer by value. If it is a reference to a declaration, we just
6578 // pass its value, otherwise, if it is a member expression, we need to map
6579 // 'to' the field.
6580 if (!VD) {
6581 auto It = DevPointersMap.find(VD);
6582 if (It != DevPointersMap.end()) {
6583 for (auto L : It->second) {
6584 generateInfoForComponentList(
6585 /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
6586 BasePointers, Pointers, Sizes, Types, IsFirstComponentList);
6587 IsFirstComponentList = false;
6588 }
6589 return;
6590 }
6591 } else if (DevPointersMap.count(VD)) {
6592 BasePointers.push_back({Arg, VD});
6593 Pointers.push_back(Arg);
6594 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
6595 Types.push_back(OMP_MAP_PRIVATE_VAL | OMP_MAP_FIRST_REF);
6596 return;
6597 }
6598
Paul Robinson78fb1322016-08-01 22:12:46 +00006599 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006600 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao86ace552016-04-27 22:40:57 +00006601 for (auto L : C->decl_component_lists(VD)) {
6602 assert(L.first == VD &&
6603 "We got information for the wrong declaration??");
6604 assert(!L.second.empty() &&
6605 "Not expecting declaration with no component lists.");
6606 generateInfoForComponentList(C->getMapType(), C->getMapTypeModifier(),
6607 L.second, BasePointers, Pointers, Sizes,
6608 Types, IsFirstComponentList);
6609 IsFirstComponentList = false;
6610 }
6611
6612 return;
6613 }
Samuel Antaod486f842016-05-26 16:53:38 +00006614
6615 /// \brief Generate the default map information for a given capture \a CI,
6616 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00006617 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
6618 const FieldDecl &RI, llvm::Value *CV,
6619 MapBaseValuesArrayTy &CurBasePointers,
6620 MapValuesArrayTy &CurPointers,
6621 MapValuesArrayTy &CurSizes,
6622 MapFlagsArrayTy &CurMapTypes) {
Samuel Antaod486f842016-05-26 16:53:38 +00006623
6624 // Do the default mapping.
6625 if (CI.capturesThis()) {
6626 CurBasePointers.push_back(CV);
6627 CurPointers.push_back(CV);
6628 const PointerType *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
6629 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
6630 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00006631 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00006632 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00006633 CurBasePointers.push_back(CV);
6634 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00006635 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00006636 // We have to signal to the runtime captures passed by value that are
6637 // not pointers.
Samuel Antaocc10b852016-07-28 14:23:26 +00006638 CurMapTypes.push_back(OMP_MAP_PRIVATE_VAL);
Samuel Antaod486f842016-05-26 16:53:38 +00006639 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
6640 } else {
6641 // Pointers are implicitly mapped with a zero size and no flags
6642 // (other than first map that is added for all implicit maps).
6643 CurMapTypes.push_back(0u);
Samuel Antaod486f842016-05-26 16:53:38 +00006644 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
6645 }
6646 } else {
6647 assert(CI.capturesVariable() && "Expected captured reference.");
6648 CurBasePointers.push_back(CV);
6649 CurPointers.push_back(CV);
6650
6651 const ReferenceType *PtrTy =
6652 cast<ReferenceType>(RI.getType().getTypePtr());
6653 QualType ElementType = PtrTy->getPointeeType();
6654 CurSizes.push_back(CGF.getTypeSize(ElementType));
6655 // The default map type for a scalar/complex type is 'to' because by
6656 // default the value doesn't have to be retrieved. For an aggregate
6657 // type, the default is 'tofrom'.
6658 CurMapTypes.push_back(ElementType->isAggregateType()
Samuel Antaocc10b852016-07-28 14:23:26 +00006659 ? (OMP_MAP_TO | OMP_MAP_FROM)
6660 : OMP_MAP_TO);
Samuel Antaod486f842016-05-26 16:53:38 +00006661
6662 // If we have a capture by reference we may need to add the private
6663 // pointer flag if the base declaration shows in some first-private
6664 // clause.
6665 CurMapTypes.back() =
6666 adjustMapModifiersForPrivateClauses(CI, CurMapTypes.back());
6667 }
6668 // Every default map produces a single argument, so, it is always the
6669 // first one.
Samuel Antaocc10b852016-07-28 14:23:26 +00006670 CurMapTypes.back() |= OMP_MAP_FIRST_REF;
Samuel Antaod486f842016-05-26 16:53:38 +00006671 }
Samuel Antao86ace552016-04-27 22:40:57 +00006672};
Samuel Antaodf158d52016-04-27 22:58:19 +00006673
6674enum OpenMPOffloadingReservedDeviceIDs {
6675 /// \brief Device ID if the device was not defined, runtime should get it
6676 /// from environment variables in the spec.
6677 OMP_DEVICEID_UNDEF = -1,
6678};
6679} // anonymous namespace
6680
6681/// \brief Emit the arrays used to pass the captures and map information to the
6682/// offloading runtime library. If there is no map or capture information,
6683/// return nullptr by reference.
6684static void
Samuel Antaocc10b852016-07-28 14:23:26 +00006685emitOffloadingArrays(CodeGenFunction &CGF,
6686 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00006687 MappableExprsHandler::MapValuesArrayTy &Pointers,
6688 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00006689 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
6690 CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006691 auto &CGM = CGF.CGM;
6692 auto &Ctx = CGF.getContext();
6693
Samuel Antaocc10b852016-07-28 14:23:26 +00006694 // Reset the array information.
6695 Info.clearArrayInfo();
6696 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00006697
Samuel Antaocc10b852016-07-28 14:23:26 +00006698 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006699 // Detect if we have any capture size requiring runtime evaluation of the
6700 // size so that a constant array could be eventually used.
6701 bool hasRuntimeEvaluationCaptureSize = false;
6702 for (auto *S : Sizes)
6703 if (!isa<llvm::Constant>(S)) {
6704 hasRuntimeEvaluationCaptureSize = true;
6705 break;
6706 }
6707
Samuel Antaocc10b852016-07-28 14:23:26 +00006708 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00006709 QualType PointerArrayType =
6710 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
6711 /*IndexTypeQuals=*/0);
6712
Samuel Antaocc10b852016-07-28 14:23:26 +00006713 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006714 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00006715 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006716 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
6717
6718 // If we don't have any VLA types or other types that require runtime
6719 // evaluation, we can use a constant array for the map sizes, otherwise we
6720 // need to fill up the arrays as we do for the pointers.
6721 if (hasRuntimeEvaluationCaptureSize) {
6722 QualType SizeArrayType = Ctx.getConstantArrayType(
6723 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
6724 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00006725 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006726 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
6727 } else {
6728 // We expect all the sizes to be constant, so we collect them to create
6729 // a constant array.
6730 SmallVector<llvm::Constant *, 16> ConstSizes;
6731 for (auto S : Sizes)
6732 ConstSizes.push_back(cast<llvm::Constant>(S));
6733
6734 auto *SizesArrayInit = llvm::ConstantArray::get(
6735 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
6736 auto *SizesArrayGbl = new llvm::GlobalVariable(
6737 CGM.getModule(), SizesArrayInit->getType(),
6738 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
6739 SizesArrayInit, ".offload_sizes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00006740 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00006741 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00006742 }
6743
6744 // The map types are always constant so we don't need to generate code to
6745 // fill arrays. Instead, we create an array constant.
6746 llvm::Constant *MapTypesArrayInit =
6747 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
6748 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
6749 CGM.getModule(), MapTypesArrayInit->getType(),
6750 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
6751 MapTypesArrayInit, ".offload_maptypes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00006752 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00006753 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00006754
Samuel Antaocc10b852016-07-28 14:23:26 +00006755 for (unsigned i = 0; i < Info.NumberOfPtrs; ++i) {
6756 llvm::Value *BPVal = *BasePointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00006757 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006758 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6759 Info.BasePointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00006760 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6761 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00006762 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
6763 CGF.Builder.CreateStore(BPVal, BPAddr);
6764
Samuel Antaocc10b852016-07-28 14:23:26 +00006765 if (Info.requiresDevicePointerInfo())
6766 if (auto *DevVD = BasePointers[i].getDevicePtrDecl())
6767 Info.CaptureDeviceAddrMap.insert(std::make_pair(DevVD, BPAddr));
6768
Samuel Antaodf158d52016-04-27 22:58:19 +00006769 llvm::Value *PVal = Pointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00006770 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006771 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6772 Info.PointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00006773 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6774 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00006775 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
6776 CGF.Builder.CreateStore(PVal, PAddr);
6777
6778 if (hasRuntimeEvaluationCaptureSize) {
6779 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006780 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
6781 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006782 /*Idx0=*/0,
6783 /*Idx1=*/i);
6784 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
6785 CGF.Builder.CreateStore(
6786 CGF.Builder.CreateIntCast(Sizes[i], CGM.SizeTy, /*isSigned=*/true),
6787 SAddr);
6788 }
6789 }
6790 }
6791}
6792/// \brief Emit the arguments to be passed to the runtime library based on the
6793/// arrays of pointers, sizes and map types.
6794static void emitOffloadingArraysArgument(
6795 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
6796 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006797 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006798 auto &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00006799 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006800 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006801 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6802 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006803 /*Idx0=*/0, /*Idx1=*/0);
6804 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006805 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6806 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006807 /*Idx0=*/0,
6808 /*Idx1=*/0);
6809 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006810 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006811 /*Idx0=*/0, /*Idx1=*/0);
6812 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006813 llvm::ArrayType::get(CGM.Int32Ty, Info.NumberOfPtrs),
6814 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006815 /*Idx0=*/0,
6816 /*Idx1=*/0);
6817 } else {
6818 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
6819 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
6820 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
6821 MapTypesArrayArg =
6822 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo());
6823 }
Samuel Antao86ace552016-04-27 22:40:57 +00006824}
6825
Samuel Antaobed3c462015-10-02 16:14:20 +00006826void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
6827 const OMPExecutableDirective &D,
6828 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00006829 llvm::Value *OutlinedFnID,
Samuel Antaobed3c462015-10-02 16:14:20 +00006830 const Expr *IfCond, const Expr *Device,
6831 ArrayRef<llvm::Value *> CapturedVars) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006832 if (!CGF.HaveInsertPoint())
6833 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00006834
Samuel Antaoee8fb302016-01-06 13:42:12 +00006835 assert(OutlinedFn && "Invalid outlined function!");
6836
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006837 auto &Ctx = CGF.getContext();
6838
Samuel Antao86ace552016-04-27 22:40:57 +00006839 // Fill up the arrays with all the captured variables.
6840 MappableExprsHandler::MapValuesArrayTy KernelArgs;
Samuel Antaocc10b852016-07-28 14:23:26 +00006841 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00006842 MappableExprsHandler::MapValuesArrayTy Pointers;
6843 MappableExprsHandler::MapValuesArrayTy Sizes;
6844 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobed3c462015-10-02 16:14:20 +00006845
Samuel Antaocc10b852016-07-28 14:23:26 +00006846 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00006847 MappableExprsHandler::MapValuesArrayTy CurPointers;
6848 MappableExprsHandler::MapValuesArrayTy CurSizes;
6849 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
6850
Samuel Antaod486f842016-05-26 16:53:38 +00006851 // Get mappable expression information.
6852 MappableExprsHandler MEHandler(D, CGF);
Samuel Antaobed3c462015-10-02 16:14:20 +00006853
6854 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
6855 auto RI = CS.getCapturedRecordDecl()->field_begin();
Samuel Antaobed3c462015-10-02 16:14:20 +00006856 auto CV = CapturedVars.begin();
6857 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
6858 CE = CS.capture_end();
6859 CI != CE; ++CI, ++RI, ++CV) {
6860 StringRef Name;
6861 QualType Ty;
Samuel Antaobed3c462015-10-02 16:14:20 +00006862
Samuel Antao86ace552016-04-27 22:40:57 +00006863 CurBasePointers.clear();
6864 CurPointers.clear();
6865 CurSizes.clear();
6866 CurMapTypes.clear();
6867
6868 // VLA sizes are passed to the outlined region by copy and do not have map
6869 // information associated.
Samuel Antaobed3c462015-10-02 16:14:20 +00006870 if (CI->capturesVariableArrayType()) {
Samuel Antao86ace552016-04-27 22:40:57 +00006871 CurBasePointers.push_back(*CV);
6872 CurPointers.push_back(*CV);
6873 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006874 // Copy to the device as an argument. No need to retrieve it.
Samuel Antao6782e942016-05-26 16:48:10 +00006875 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_PRIVATE_VAL |
6876 MappableExprsHandler::OMP_MAP_FIRST_REF);
Samuel Antaobed3c462015-10-02 16:14:20 +00006877 } else {
Samuel Antao86ace552016-04-27 22:40:57 +00006878 // If we have any information in the map clause, we use it, otherwise we
6879 // just do a default mapping.
Samuel Antao6890b092016-07-28 14:25:09 +00006880 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006881 CurSizes, CurMapTypes);
Samuel Antaod486f842016-05-26 16:53:38 +00006882 if (CurBasePointers.empty())
6883 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
6884 CurPointers, CurSizes, CurMapTypes);
Samuel Antaobed3c462015-10-02 16:14:20 +00006885 }
Samuel Antao86ace552016-04-27 22:40:57 +00006886 // We expect to have at least an element of information for this capture.
6887 assert(!CurBasePointers.empty() && "Non-existing map pointer for capture!");
6888 assert(CurBasePointers.size() == CurPointers.size() &&
6889 CurBasePointers.size() == CurSizes.size() &&
6890 CurBasePointers.size() == CurMapTypes.size() &&
6891 "Inconsistent map information sizes!");
Samuel Antaobed3c462015-10-02 16:14:20 +00006892
Samuel Antao86ace552016-04-27 22:40:57 +00006893 // The kernel args are always the first elements of the base pointers
6894 // associated with a capture.
Samuel Antaocc10b852016-07-28 14:23:26 +00006895 KernelArgs.push_back(*CurBasePointers.front());
Samuel Antao86ace552016-04-27 22:40:57 +00006896 // We need to append the results of this capture to what we already have.
6897 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
6898 Pointers.append(CurPointers.begin(), CurPointers.end());
6899 Sizes.append(CurSizes.begin(), CurSizes.end());
6900 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
Samuel Antaobed3c462015-10-02 16:14:20 +00006901 }
6902
6903 // Keep track on whether the host function has to be executed.
6904 auto OffloadErrorQType =
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006905 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006906 auto OffloadError = CGF.MakeAddrLValue(
6907 CGF.CreateMemTemp(OffloadErrorQType, ".run_host_version"),
6908 OffloadErrorQType);
6909 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty),
6910 OffloadError);
6911
6912 // Fill up the pointer arrays and transfer execution to the device.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00006913 auto &&ThenGen = [&BasePointers, &Pointers, &Sizes, &MapTypes, Device,
6914 OutlinedFnID, OffloadError,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006915 &D](CodeGenFunction &CGF, PrePostActionTy &) {
6916 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antaodf158d52016-04-27 22:58:19 +00006917 // Emit the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00006918 TargetDataInfo Info;
6919 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
6920 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
6921 Info.PointersArray, Info.SizesArray,
6922 Info.MapTypesArray, Info);
Samuel Antaobed3c462015-10-02 16:14:20 +00006923
6924 // On top of the arrays that were filled up, the target offloading call
6925 // takes as arguments the device id as well as the host pointer. The host
6926 // pointer is used by the runtime library to identify the current target
6927 // region, so it only has to be unique and not necessarily point to
6928 // anything. It could be the pointer to the outlined function that
6929 // implements the target region, but we aren't using that so that the
6930 // compiler doesn't need to keep that, and could therefore inline the host
6931 // function if proven worthwhile during optimization.
6932
Samuel Antaoee8fb302016-01-06 13:42:12 +00006933 // From this point on, we need to have an ID of the target region defined.
6934 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00006935
6936 // Emit device ID if any.
6937 llvm::Value *DeviceID;
6938 if (Device)
6939 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006940 CGF.Int32Ty, /*isSigned=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006941 else
6942 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6943
Samuel Antaodf158d52016-04-27 22:58:19 +00006944 // Emit the number of elements in the offloading arrays.
6945 llvm::Value *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6946
Samuel Antaob68e2db2016-03-03 16:20:23 +00006947 // Return value of the runtime offloading call.
6948 llvm::Value *Return;
6949
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006950 auto *NumTeams = emitNumTeamsForTargetDirective(RT, CGF, D);
6951 auto *NumThreads = emitNumThreadsForTargetDirective(RT, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006952
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006953 // The target region is an outlined function launched by the runtime
6954 // via calls __tgt_target() or __tgt_target_teams().
6955 //
6956 // __tgt_target() launches a target region with one team and one thread,
6957 // executing a serial region. This master thread may in turn launch
6958 // more threads within its team upon encountering a parallel region,
6959 // however, no additional teams can be launched on the device.
6960 //
6961 // __tgt_target_teams() launches a target region with one or more teams,
6962 // each with one or more threads. This call is required for target
6963 // constructs such as:
6964 // 'target teams'
6965 // 'target' / 'teams'
6966 // 'target teams distribute parallel for'
6967 // 'target parallel'
6968 // and so on.
6969 //
6970 // Note that on the host and CPU targets, the runtime implementation of
6971 // these calls simply call the outlined function without forking threads.
6972 // The outlined functions themselves have runtime calls to
6973 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
6974 // the compiler in emitTeamsCall() and emitParallelCall().
6975 //
6976 // In contrast, on the NVPTX target, the implementation of
6977 // __tgt_target_teams() launches a GPU kernel with the requested number
6978 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006979 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006980 // If we have NumTeams defined this means that we have an enclosed teams
6981 // region. Therefore we also expect to have NumThreads defined. These two
6982 // values should be defined in the presence of a teams directive,
6983 // regardless of having any clauses associated. If the user is using teams
6984 // but no clauses, these two values will be the default that should be
6985 // passed to the runtime library - a 32-bit integer with the value zero.
6986 assert(NumThreads && "Thread limit expression should be available along "
6987 "with number of teams.");
Samuel Antaob68e2db2016-03-03 16:20:23 +00006988 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00006989 DeviceID, OutlinedFnID,
6990 PointerNum, Info.BasePointersArray,
6991 Info.PointersArray, Info.SizesArray,
6992 Info.MapTypesArray, NumTeams,
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006993 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00006994 Return = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006995 RT.createRuntimeFunction(OMPRTL__tgt_target_teams), OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006996 } else {
6997 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00006998 DeviceID, OutlinedFnID,
6999 PointerNum, Info.BasePointersArray,
7000 Info.PointersArray, Info.SizesArray,
7001 Info.MapTypesArray};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007002 Return = CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target),
Samuel Antaob68e2db2016-03-03 16:20:23 +00007003 OffloadingArgs);
7004 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007005
7006 CGF.EmitStoreOfScalar(Return, OffloadError);
7007 };
7008
Samuel Antaoee8fb302016-01-06 13:42:12 +00007009 // Notify that the host version must be executed.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007010 auto &&ElseGen = [OffloadError](CodeGenFunction &CGF, PrePostActionTy &) {
7011 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/-1u),
Samuel Antaoee8fb302016-01-06 13:42:12 +00007012 OffloadError);
7013 };
7014
7015 // If we have a target function ID it means that we need to support
7016 // offloading, otherwise, just execute on the host. We need to execute on host
7017 // regardless of the conditional in the if clause if, e.g., the user do not
7018 // specify target triples.
7019 if (OutlinedFnID) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007020 if (IfCond)
Samuel Antaoee8fb302016-01-06 13:42:12 +00007021 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007022 else {
7023 RegionCodeGenTy ThenRCG(ThenGen);
7024 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007025 }
7026 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00007027 RegionCodeGenTy ElseRCG(ElseGen);
7028 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00007029 }
Samuel Antaobed3c462015-10-02 16:14:20 +00007030
7031 // Check the error code and execute the host version if required.
7032 auto OffloadFailedBlock = CGF.createBasicBlock("omp_offload.failed");
7033 auto OffloadContBlock = CGF.createBasicBlock("omp_offload.cont");
7034 auto OffloadErrorVal = CGF.EmitLoadOfScalar(OffloadError, SourceLocation());
7035 auto Failed = CGF.Builder.CreateIsNotNull(OffloadErrorVal);
7036 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
7037
7038 CGF.EmitBlock(OffloadFailedBlock);
Alexey Bataev3c595a62017-08-14 15:01:03 +00007039 emitOutlinedFunctionCall(CGF, D.getLocStart(), OutlinedFn, KernelArgs);
Samuel Antaobed3c462015-10-02 16:14:20 +00007040 CGF.EmitBranch(OffloadContBlock);
7041
7042 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00007043}
Samuel Antaoee8fb302016-01-06 13:42:12 +00007044
7045void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
7046 StringRef ParentName) {
7047 if (!S)
7048 return;
7049
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007050 // Codegen OMP target directives that offload compute to the device.
7051 bool requiresDeviceCodegen =
7052 isa<OMPExecutableDirective>(S) &&
7053 isOpenMPTargetExecutionDirective(
7054 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00007055
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007056 if (requiresDeviceCodegen) {
7057 auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007058 unsigned DeviceID;
7059 unsigned FileID;
7060 unsigned Line;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007061 getTargetEntryUniqueInfo(CGM.getContext(), E.getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00007062 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007063
7064 // Is this a target region that should not be emitted as an entry point? If
7065 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00007066 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
7067 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00007068 return;
7069
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007070 switch (S->getStmtClass()) {
7071 case Stmt::OMPTargetDirectiveClass:
7072 CodeGenFunction::EmitOMPTargetDeviceFunction(
7073 CGM, ParentName, cast<OMPTargetDirective>(*S));
7074 break;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00007075 case Stmt::OMPTargetParallelDirectiveClass:
7076 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
7077 CGM, ParentName, cast<OMPTargetParallelDirective>(*S));
7078 break;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00007079 case Stmt::OMPTargetTeamsDirectiveClass:
7080 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
7081 CGM, ParentName, cast<OMPTargetTeamsDirective>(*S));
7082 break;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00007083 default:
7084 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
7085 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00007086 return;
7087 }
7088
7089 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
Samuel Antaoe49645c2016-05-08 06:43:56 +00007090 if (!E->hasAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00007091 return;
7092
7093 scanForTargetRegionsFunctions(
7094 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
7095 ParentName);
7096 return;
7097 }
7098
7099 // If this is a lambda function, look into its body.
7100 if (auto *L = dyn_cast<LambdaExpr>(S))
7101 S = L->getBody();
7102
7103 // Keep looking for target regions recursively.
7104 for (auto *II : S->children())
7105 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00007106}
7107
7108bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
7109 auto &FD = *cast<FunctionDecl>(GD.getDecl());
7110
7111 // If emitting code for the host, we do not process FD here. Instead we do
7112 // the normal code generation.
7113 if (!CGM.getLangOpts().OpenMPIsDevice)
7114 return false;
7115
7116 // Try to detect target regions in the function.
7117 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
7118
Samuel Antao4b75b872016-12-12 19:26:31 +00007119 // We should not emit any function other that the ones created during the
Samuel Antaoee8fb302016-01-06 13:42:12 +00007120 // scanning. Therefore, we signal that this function is completely dealt
7121 // with.
7122 return true;
7123}
7124
7125bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
7126 if (!CGM.getLangOpts().OpenMPIsDevice)
7127 return false;
7128
7129 // Check if there are Ctors/Dtors in this declaration and look for target
7130 // regions in it. We use the complete variant to produce the kernel name
7131 // mangling.
7132 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
7133 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
7134 for (auto *Ctor : RD->ctors()) {
7135 StringRef ParentName =
7136 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
7137 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
7138 }
7139 auto *Dtor = RD->getDestructor();
7140 if (Dtor) {
7141 StringRef ParentName =
7142 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
7143 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
7144 }
7145 }
7146
Gheorghe-Teodor Bercea47633db2017-06-13 15:35:27 +00007147 // If we are in target mode, we do not emit any global (declare target is not
Samuel Antaoee8fb302016-01-06 13:42:12 +00007148 // implemented yet). Therefore we signal that GD was processed in this case.
7149 return true;
7150}
7151
7152bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
7153 auto *VD = GD.getDecl();
7154 if (isa<FunctionDecl>(VD))
7155 return emitTargetFunctions(GD);
7156
7157 return emitTargetGlobalVariable(GD);
7158}
7159
7160llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
7161 // If we have offloading in the current module, we need to emit the entries
7162 // now and register the offloading descriptor.
7163 createOffloadEntriesAndInfoMetadata();
7164
7165 // Create and register the offloading binary descriptors. This is the main
7166 // entity that captures all the information about offloading in the current
7167 // compilation unit.
7168 return createOffloadingBinaryDescriptorRegistration();
7169}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007170
7171void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
7172 const OMPExecutableDirective &D,
7173 SourceLocation Loc,
7174 llvm::Value *OutlinedFn,
7175 ArrayRef<llvm::Value *> CapturedVars) {
7176 if (!CGF.HaveInsertPoint())
7177 return;
7178
7179 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7180 CodeGenFunction::RunCleanupsScope Scope(CGF);
7181
7182 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
7183 llvm::Value *Args[] = {
7184 RTLoc,
7185 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
7186 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
7187 llvm::SmallVector<llvm::Value *, 16> RealArgs;
7188 RealArgs.append(std::begin(Args), std::end(Args));
7189 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
7190
7191 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
7192 CGF.EmitRuntimeCall(RTLFn, RealArgs);
7193}
7194
7195void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00007196 const Expr *NumTeams,
7197 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007198 SourceLocation Loc) {
7199 if (!CGF.HaveInsertPoint())
7200 return;
7201
7202 auto *RTLoc = emitUpdateLocation(CGF, Loc);
7203
Carlo Bertollic6872252016-04-04 15:55:02 +00007204 llvm::Value *NumTeamsVal =
7205 (NumTeams)
7206 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
7207 CGF.CGM.Int32Ty, /* isSigned = */ true)
7208 : CGF.Builder.getInt32(0);
7209
7210 llvm::Value *ThreadLimitVal =
7211 (ThreadLimit)
7212 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
7213 CGF.CGM.Int32Ty, /* isSigned = */ true)
7214 : CGF.Builder.getInt32(0);
7215
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007216 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00007217 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
7218 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00007219 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
7220 PushNumTeamsArgs);
7221}
Samuel Antaodf158d52016-04-27 22:58:19 +00007222
Samuel Antaocc10b852016-07-28 14:23:26 +00007223void CGOpenMPRuntime::emitTargetDataCalls(
7224 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7225 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007226 if (!CGF.HaveInsertPoint())
7227 return;
7228
Samuel Antaocc10b852016-07-28 14:23:26 +00007229 // Action used to replace the default codegen action and turn privatization
7230 // off.
7231 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00007232
7233 // Generate the code for the opening of the data environment. Capture all the
7234 // arguments of the runtime call by reference because they are used in the
7235 // closing of the region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007236 auto &&BeginThenGen = [&D, Device, &Info, &CodeGen](CodeGenFunction &CGF,
7237 PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00007238 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00007239 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00007240 MappableExprsHandler::MapValuesArrayTy Pointers;
7241 MappableExprsHandler::MapValuesArrayTy Sizes;
7242 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7243
7244 // Get map clause information.
7245 MappableExprsHandler MCHandler(D, CGF);
7246 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00007247
7248 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00007249 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007250
7251 llvm::Value *BasePointersArrayArg = nullptr;
7252 llvm::Value *PointersArrayArg = nullptr;
7253 llvm::Value *SizesArrayArg = nullptr;
7254 llvm::Value *MapTypesArrayArg = nullptr;
7255 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007256 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007257
7258 // Emit device ID if any.
7259 llvm::Value *DeviceID = nullptr;
7260 if (Device)
7261 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7262 CGF.Int32Ty, /*isSigned=*/true);
7263 else
7264 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
7265
7266 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007267 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007268
7269 llvm::Value *OffloadingArgs[] = {
7270 DeviceID, PointerNum, BasePointersArrayArg,
7271 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
7272 auto &RT = CGF.CGM.getOpenMPRuntime();
7273 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_begin),
7274 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00007275
7276 // If device pointer privatization is required, emit the body of the region
7277 // here. It will have to be duplicated: with and without privatization.
7278 if (!Info.CaptureDeviceAddrMap.empty())
7279 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007280 };
7281
7282 // Generate code for the closing of the data region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007283 auto &&EndThenGen = [Device, &Info](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007284 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00007285
7286 llvm::Value *BasePointersArrayArg = nullptr;
7287 llvm::Value *PointersArrayArg = nullptr;
7288 llvm::Value *SizesArrayArg = nullptr;
7289 llvm::Value *MapTypesArrayArg = nullptr;
7290 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00007291 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00007292
7293 // Emit device ID if any.
7294 llvm::Value *DeviceID = nullptr;
7295 if (Device)
7296 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7297 CGF.Int32Ty, /*isSigned=*/true);
7298 else
7299 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
7300
7301 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00007302 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00007303
7304 llvm::Value *OffloadingArgs[] = {
7305 DeviceID, PointerNum, BasePointersArrayArg,
7306 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
7307 auto &RT = CGF.CGM.getOpenMPRuntime();
7308 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_end),
7309 OffloadingArgs);
7310 };
7311
Samuel Antaocc10b852016-07-28 14:23:26 +00007312 // If we need device pointer privatization, we need to emit the body of the
7313 // region with no privatization in the 'else' branch of the conditional.
7314 // Otherwise, we don't have to do anything.
7315 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
7316 PrePostActionTy &) {
7317 if (!Info.CaptureDeviceAddrMap.empty()) {
7318 CodeGen.setAction(NoPrivAction);
7319 CodeGen(CGF);
7320 }
7321 };
7322
7323 // We don't have to do anything to close the region if the if clause evaluates
7324 // to false.
7325 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00007326
7327 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007328 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007329 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007330 RegionCodeGenTy RCG(BeginThenGen);
7331 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007332 }
7333
Samuel Antaocc10b852016-07-28 14:23:26 +00007334 // If we don't require privatization of device pointers, we emit the body in
7335 // between the runtime calls. This avoids duplicating the body code.
7336 if (Info.CaptureDeviceAddrMap.empty()) {
7337 CodeGen.setAction(NoPrivAction);
7338 CodeGen(CGF);
7339 }
Samuel Antaodf158d52016-04-27 22:58:19 +00007340
7341 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00007342 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00007343 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00007344 RegionCodeGenTy RCG(EndThenGen);
7345 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00007346 }
7347}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007348
Samuel Antao8d2d7302016-05-26 18:30:22 +00007349void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00007350 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
7351 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007352 if (!CGF.HaveInsertPoint())
7353 return;
7354
Samuel Antao8dd66282016-04-27 23:14:30 +00007355 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00007356 isa<OMPTargetExitDataDirective>(D) ||
7357 isa<OMPTargetUpdateDirective>(D)) &&
7358 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00007359
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007360 // Generate the code for the opening of the data environment.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00007361 auto &&ThenGen = [&D, Device](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007362 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00007363 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007364 MappableExprsHandler::MapValuesArrayTy Pointers;
7365 MappableExprsHandler::MapValuesArrayTy Sizes;
7366 MappableExprsHandler::MapFlagsArrayTy MapTypes;
7367
7368 // Get map clause information.
Samuel Antao8d2d7302016-05-26 18:30:22 +00007369 MappableExprsHandler MEHandler(D, CGF);
7370 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007371
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007372 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00007373 TargetDataInfo Info;
7374 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
7375 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
7376 Info.PointersArray, Info.SizesArray,
7377 Info.MapTypesArray, Info);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007378
7379 // Emit device ID if any.
7380 llvm::Value *DeviceID = nullptr;
7381 if (Device)
7382 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
7383 CGF.Int32Ty, /*isSigned=*/true);
7384 else
7385 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
7386
7387 // Emit the number of elements in the offloading arrays.
7388 auto *PointerNum = CGF.Builder.getInt32(BasePointers.size());
7389
7390 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00007391 DeviceID, PointerNum, Info.BasePointersArray,
7392 Info.PointersArray, Info.SizesArray, Info.MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00007393
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007394 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antao8d2d7302016-05-26 18:30:22 +00007395 // Select the right runtime function call for each expected standalone
7396 // directive.
7397 OpenMPRTLFunction RTLFn;
7398 switch (D.getDirectiveKind()) {
7399 default:
7400 llvm_unreachable("Unexpected standalone target data directive.");
7401 break;
7402 case OMPD_target_enter_data:
7403 RTLFn = OMPRTL__tgt_target_data_begin;
7404 break;
7405 case OMPD_target_exit_data:
7406 RTLFn = OMPRTL__tgt_target_data_end;
7407 break;
7408 case OMPD_target_update:
7409 RTLFn = OMPRTL__tgt_target_data_update;
7410 break;
7411 }
7412 CGF.EmitRuntimeCall(RT.createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00007413 };
7414
7415 // In the event we get an if clause, we don't have to take any action on the
7416 // else side.
7417 auto &&ElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
7418
7419 if (IfCond) {
7420 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
7421 } else {
7422 RegionCodeGenTy ThenGenRCG(ThenGen);
7423 ThenGenRCG(CGF);
7424 }
7425}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007426
7427namespace {
7428 /// Kind of parameter in a function with 'declare simd' directive.
7429 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
7430 /// Attribute set of the parameter.
7431 struct ParamAttrTy {
7432 ParamKindTy Kind = Vector;
7433 llvm::APSInt StrideOrArg;
7434 llvm::APSInt Alignment;
7435 };
7436} // namespace
7437
7438static unsigned evaluateCDTSize(const FunctionDecl *FD,
7439 ArrayRef<ParamAttrTy> ParamAttrs) {
7440 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
7441 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
7442 // of that clause. The VLEN value must be power of 2.
7443 // In other case the notion of the function`s "characteristic data type" (CDT)
7444 // is used to compute the vector length.
7445 // CDT is defined in the following order:
7446 // a) For non-void function, the CDT is the return type.
7447 // b) If the function has any non-uniform, non-linear parameters, then the
7448 // CDT is the type of the first such parameter.
7449 // c) If the CDT determined by a) or b) above is struct, union, or class
7450 // type which is pass-by-value (except for the type that maps to the
7451 // built-in complex data type), the characteristic data type is int.
7452 // d) If none of the above three cases is applicable, the CDT is int.
7453 // The VLEN is then determined based on the CDT and the size of vector
7454 // register of that ISA for which current vector version is generated. The
7455 // VLEN is computed using the formula below:
7456 // VLEN = sizeof(vector_register) / sizeof(CDT),
7457 // where vector register size specified in section 3.2.1 Registers and the
7458 // Stack Frame of original AMD64 ABI document.
7459 QualType RetType = FD->getReturnType();
7460 if (RetType.isNull())
7461 return 0;
7462 ASTContext &C = FD->getASTContext();
7463 QualType CDT;
7464 if (!RetType.isNull() && !RetType->isVoidType())
7465 CDT = RetType;
7466 else {
7467 unsigned Offset = 0;
7468 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
7469 if (ParamAttrs[Offset].Kind == Vector)
7470 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
7471 ++Offset;
7472 }
7473 if (CDT.isNull()) {
7474 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
7475 if (ParamAttrs[I + Offset].Kind == Vector) {
7476 CDT = FD->getParamDecl(I)->getType();
7477 break;
7478 }
7479 }
7480 }
7481 }
7482 if (CDT.isNull())
7483 CDT = C.IntTy;
7484 CDT = CDT->getCanonicalTypeUnqualified();
7485 if (CDT->isRecordType() || CDT->isUnionType())
7486 CDT = C.IntTy;
7487 return C.getTypeSize(CDT);
7488}
7489
7490static void
7491emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00007492 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007493 ArrayRef<ParamAttrTy> ParamAttrs,
7494 OMPDeclareSimdDeclAttr::BranchStateTy State) {
7495 struct ISADataTy {
7496 char ISA;
7497 unsigned VecRegSize;
7498 };
7499 ISADataTy ISAData[] = {
7500 {
7501 'b', 128
7502 }, // SSE
7503 {
7504 'c', 256
7505 }, // AVX
7506 {
7507 'd', 256
7508 }, // AVX2
7509 {
7510 'e', 512
7511 }, // AVX512
7512 };
7513 llvm::SmallVector<char, 2> Masked;
7514 switch (State) {
7515 case OMPDeclareSimdDeclAttr::BS_Undefined:
7516 Masked.push_back('N');
7517 Masked.push_back('M');
7518 break;
7519 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
7520 Masked.push_back('N');
7521 break;
7522 case OMPDeclareSimdDeclAttr::BS_Inbranch:
7523 Masked.push_back('M');
7524 break;
7525 }
7526 for (auto Mask : Masked) {
7527 for (auto &Data : ISAData) {
7528 SmallString<256> Buffer;
7529 llvm::raw_svector_ostream Out(Buffer);
7530 Out << "_ZGV" << Data.ISA << Mask;
7531 if (!VLENVal) {
7532 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
7533 evaluateCDTSize(FD, ParamAttrs));
7534 } else
7535 Out << VLENVal;
7536 for (auto &ParamAttr : ParamAttrs) {
7537 switch (ParamAttr.Kind){
7538 case LinearWithVarStride:
7539 Out << 's' << ParamAttr.StrideOrArg;
7540 break;
7541 case Linear:
7542 Out << 'l';
7543 if (!!ParamAttr.StrideOrArg)
7544 Out << ParamAttr.StrideOrArg;
7545 break;
7546 case Uniform:
7547 Out << 'u';
7548 break;
7549 case Vector:
7550 Out << 'v';
7551 break;
7552 }
7553 if (!!ParamAttr.Alignment)
7554 Out << 'a' << ParamAttr.Alignment;
7555 }
7556 Out << '_' << Fn->getName();
7557 Fn->addFnAttr(Out.str());
7558 }
7559 }
7560}
7561
7562void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
7563 llvm::Function *Fn) {
7564 ASTContext &C = CGM.getContext();
7565 FD = FD->getCanonicalDecl();
7566 // Map params to their positions in function decl.
7567 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
7568 if (isa<CXXMethodDecl>(FD))
7569 ParamPositions.insert({FD, 0});
7570 unsigned ParamPos = ParamPositions.size();
David Majnemer59f77922016-06-24 04:05:48 +00007571 for (auto *P : FD->parameters()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007572 ParamPositions.insert({P->getCanonicalDecl(), ParamPos});
7573 ++ParamPos;
7574 }
7575 for (auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
7576 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
7577 // Mark uniform parameters.
7578 for (auto *E : Attr->uniforms()) {
7579 E = E->IgnoreParenImpCasts();
7580 unsigned Pos;
7581 if (isa<CXXThisExpr>(E))
7582 Pos = ParamPositions[FD];
7583 else {
7584 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7585 ->getCanonicalDecl();
7586 Pos = ParamPositions[PVD];
7587 }
7588 ParamAttrs[Pos].Kind = Uniform;
7589 }
7590 // Get alignment info.
7591 auto NI = Attr->alignments_begin();
7592 for (auto *E : Attr->aligneds()) {
7593 E = E->IgnoreParenImpCasts();
7594 unsigned Pos;
7595 QualType ParmTy;
7596 if (isa<CXXThisExpr>(E)) {
7597 Pos = ParamPositions[FD];
7598 ParmTy = E->getType();
7599 } else {
7600 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7601 ->getCanonicalDecl();
7602 Pos = ParamPositions[PVD];
7603 ParmTy = PVD->getType();
7604 }
7605 ParamAttrs[Pos].Alignment =
7606 (*NI) ? (*NI)->EvaluateKnownConstInt(C)
7607 : llvm::APSInt::getUnsigned(
7608 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
7609 .getQuantity());
7610 ++NI;
7611 }
7612 // Mark linear parameters.
7613 auto SI = Attr->steps_begin();
7614 auto MI = Attr->modifiers_begin();
7615 for (auto *E : Attr->linears()) {
7616 E = E->IgnoreParenImpCasts();
7617 unsigned Pos;
7618 if (isa<CXXThisExpr>(E))
7619 Pos = ParamPositions[FD];
7620 else {
7621 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7622 ->getCanonicalDecl();
7623 Pos = ParamPositions[PVD];
7624 }
7625 auto &ParamAttr = ParamAttrs[Pos];
7626 ParamAttr.Kind = Linear;
7627 if (*SI) {
7628 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
7629 Expr::SE_AllowSideEffects)) {
7630 if (auto *DRE = cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
7631 if (auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
7632 ParamAttr.Kind = LinearWithVarStride;
7633 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
7634 ParamPositions[StridePVD->getCanonicalDecl()]);
7635 }
7636 }
7637 }
7638 }
7639 ++SI;
7640 ++MI;
7641 }
7642 llvm::APSInt VLENVal;
7643 if (const Expr *VLEN = Attr->getSimdlen())
7644 VLENVal = VLEN->EvaluateKnownConstInt(C);
7645 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
7646 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
7647 CGM.getTriple().getArch() == llvm::Triple::x86_64)
7648 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
7649 }
7650}
Alexey Bataev8b427062016-05-25 12:36:08 +00007651
7652namespace {
7653/// Cleanup action for doacross support.
7654class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
7655public:
7656 static const int DoacrossFinArgs = 2;
7657
7658private:
7659 llvm::Value *RTLFn;
7660 llvm::Value *Args[DoacrossFinArgs];
7661
7662public:
7663 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
7664 : RTLFn(RTLFn) {
7665 assert(CallArgs.size() == DoacrossFinArgs);
7666 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
7667 }
7668 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
7669 if (!CGF.HaveInsertPoint())
7670 return;
7671 CGF.EmitRuntimeCall(RTLFn, Args);
7672 }
7673};
7674} // namespace
7675
7676void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
7677 const OMPLoopDirective &D) {
7678 if (!CGF.HaveInsertPoint())
7679 return;
7680
7681 ASTContext &C = CGM.getContext();
7682 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
7683 RecordDecl *RD;
7684 if (KmpDimTy.isNull()) {
7685 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
7686 // kmp_int64 lo; // lower
7687 // kmp_int64 up; // upper
7688 // kmp_int64 st; // stride
7689 // };
7690 RD = C.buildImplicitRecord("kmp_dim");
7691 RD->startDefinition();
7692 addFieldToRecordDecl(C, RD, Int64Ty);
7693 addFieldToRecordDecl(C, RD, Int64Ty);
7694 addFieldToRecordDecl(C, RD, Int64Ty);
7695 RD->completeDefinition();
7696 KmpDimTy = C.getRecordType(RD);
7697 } else
7698 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
7699
7700 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
7701 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
7702 enum { LowerFD = 0, UpperFD, StrideFD };
7703 // Fill dims with data.
7704 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
7705 // dims.upper = num_iterations;
7706 LValue UpperLVal =
7707 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
7708 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
7709 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
7710 Int64Ty, D.getNumIterations()->getExprLoc());
7711 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
7712 // dims.stride = 1;
7713 LValue StrideLVal =
7714 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
7715 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
7716 StrideLVal);
7717
7718 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
7719 // kmp_int32 num_dims, struct kmp_dim * dims);
7720 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
7721 getThreadID(CGF, D.getLocStart()),
7722 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
7723 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7724 DimsAddr.getPointer(), CGM.VoidPtrTy)};
7725
7726 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
7727 CGF.EmitRuntimeCall(RTLFn, Args);
7728 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
7729 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
7730 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
7731 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
7732 llvm::makeArrayRef(FiniArgs));
7733}
7734
7735void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
7736 const OMPDependClause *C) {
7737 QualType Int64Ty =
7738 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
7739 const Expr *CounterVal = C->getCounterValue();
7740 assert(CounterVal);
7741 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
7742 CounterVal->getType(), Int64Ty,
7743 CounterVal->getExprLoc());
7744 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
7745 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
7746 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
7747 getThreadID(CGF, C->getLocStart()),
7748 CntAddr.getPointer()};
7749 llvm::Value *RTLFn;
7750 if (C->getDependencyKind() == OMPC_DEPEND_source)
7751 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
7752 else {
7753 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
7754 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
7755 }
7756 CGF.EmitRuntimeCall(RTLFn, Args);
7757}
7758
Alexey Bataev3c595a62017-08-14 15:01:03 +00007759void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, llvm::Value *Callee,
7760 ArrayRef<llvm::Value *> Args,
7761 SourceLocation Loc) const {
7762 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
7763
7764 if (auto *Fn = dyn_cast<llvm::Function>(Callee)) {
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007765 if (Fn->doesNotThrow()) {
Alexey Bataev3c595a62017-08-14 15:01:03 +00007766 CGF.EmitNounwindRuntimeCall(Fn, Args);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007767 return;
7768 }
7769 }
Alexey Bataev3c595a62017-08-14 15:01:03 +00007770 CGF.EmitRuntimeCall(Callee, Args);
7771}
7772
7773void CGOpenMPRuntime::emitOutlinedFunctionCall(
7774 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn,
7775 ArrayRef<llvm::Value *> Args) const {
7776 assert(Loc.isValid() && "Outlined function call location must be valid.");
7777 emitCall(CGF, OutlinedFn, Args, Loc);
Alexey Bataev2c7eee52017-08-04 19:10:54 +00007778}
Alexey Bataev3b8d5582017-08-08 18:04:06 +00007779
7780Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF,
7781 const VarDecl *NativeParam,
7782 const VarDecl *TargetParam) const {
7783 return CGF.GetAddrOfLocalVar(NativeParam);
7784}