blob: 76f44670612754a391a7ea17ab7958fbd6a802dc [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===----- CGOpenMPRuntime.cpp - Interface to OpenMP Runtimes -------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides a class for OpenMP runtime code generation.
11//
12//===----------------------------------------------------------------------===//
13
Samuel Antaoee8fb302016-01-06 13:42:12 +000014#include "CGCXXABI.h"
15#include "CGCleanup.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000016#include "CGOpenMPRuntime.h"
17#include "CodeGenFunction.h"
John McCall5ad74072017-03-02 20:04:19 +000018#include "clang/CodeGen/ConstantInitBuilder.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000019#include "clang/AST/Decl.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000020#include "clang/AST/StmtOpenMP.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000021#include "llvm/ADT/ArrayRef.h"
Teresa Johnsonffc4e242016-11-11 05:35:12 +000022#include "llvm/Bitcode/BitcodeReader.h"
Alexey Bataevd74d0602014-10-13 06:02:40 +000023#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000024#include "llvm/IR/DerivedTypes.h"
25#include "llvm/IR/GlobalValue.h"
26#include "llvm/IR/Value.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000027#include "llvm/Support/Format.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000028#include "llvm/Support/raw_ostream.h"
Alexey Bataev23b69422014-06-18 07:08:49 +000029#include <cassert>
Alexey Bataev9959db52014-05-06 10:08:46 +000030
31using namespace clang;
32using namespace CodeGen;
33
Benjamin Kramerc52193f2014-10-10 13:57:57 +000034namespace {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000035/// \brief Base class for handling code generation inside OpenMP regions.
Alexey Bataev18095712014-10-10 12:19:54 +000036class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
37public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000038 /// \brief Kinds of OpenMP regions used in codegen.
39 enum CGOpenMPRegionKind {
40 /// \brief Region with outlined function for standalone 'parallel'
41 /// directive.
42 ParallelOutlinedRegion,
43 /// \brief Region with outlined function for standalone 'task' directive.
44 TaskOutlinedRegion,
45 /// \brief Region for constructs that do not require function outlining,
46 /// like 'for', 'sections', 'atomic' etc. directives.
47 InlinedRegion,
Samuel Antaobed3c462015-10-02 16:14:20 +000048 /// \brief Region with outlined function for standalone 'target' directive.
49 TargetRegion,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000050 };
Alexey Bataev18095712014-10-10 12:19:54 +000051
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000052 CGOpenMPRegionInfo(const CapturedStmt &CS,
53 const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000054 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
55 bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000056 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
Alexey Bataev25e5b442015-09-15 12:52:43 +000057 CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000058
59 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000060 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
61 bool HasCancel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +000062 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
Alexey Bataev25e5b442015-09-15 12:52:43 +000063 Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000064
65 /// \brief Get a variable or parameter for storing global thread id
Alexey Bataev18095712014-10-10 12:19:54 +000066 /// inside OpenMP construct.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000067 virtual const VarDecl *getThreadIDVariable() const = 0;
Alexey Bataev18095712014-10-10 12:19:54 +000068
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000069 /// \brief Emit the captured statement body.
Hans Wennborg7eb54642015-09-10 17:07:54 +000070 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000071
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000072 /// \brief Get an LValue for the current ThreadID variable.
Alexey Bataev62b63b12015-03-10 07:28:44 +000073 /// \return LValue for thread id variable. This LValue always has type int32*.
74 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
Alexey Bataev18095712014-10-10 12:19:54 +000075
Alexey Bataev48591dd2016-04-20 04:01:36 +000076 virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {}
77
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000078 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000079
Alexey Bataev81c7ea02015-07-03 09:56:58 +000080 OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
81
Alexey Bataev25e5b442015-09-15 12:52:43 +000082 bool hasCancel() const { return HasCancel; }
83
Alexey Bataev18095712014-10-10 12:19:54 +000084 static bool classof(const CGCapturedStmtInfo *Info) {
85 return Info->getKind() == CR_OpenMP;
86 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000087
Alexey Bataev48591dd2016-04-20 04:01:36 +000088 ~CGOpenMPRegionInfo() override = default;
89
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000090protected:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000091 CGOpenMPRegionKind RegionKind;
Hans Wennborg45c74392016-01-12 20:54:36 +000092 RegionCodeGenTy CodeGen;
Alexey Bataev81c7ea02015-07-03 09:56:58 +000093 OpenMPDirectiveKind Kind;
Alexey Bataev25e5b442015-09-15 12:52:43 +000094 bool HasCancel;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000095};
Alexey Bataev18095712014-10-10 12:19:54 +000096
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000097/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +000098class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000099public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000100 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000101 const RegionCodeGenTy &CodeGen,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000102 OpenMPDirectiveKind Kind, bool HasCancel,
103 StringRef HelperName)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000104 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
105 HasCancel),
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000106 ThreadIDVar(ThreadIDVar), HelperName(HelperName) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000107 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
108 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000109
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000110 /// \brief Get a variable or parameter for storing global thread id
111 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000112 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000113
Alexey Bataev18095712014-10-10 12:19:54 +0000114 /// \brief Get the name of the capture helper.
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000115 StringRef getHelperName() const override { return HelperName; }
Alexey Bataev18095712014-10-10 12:19:54 +0000116
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000117 static bool classof(const CGCapturedStmtInfo *Info) {
118 return CGOpenMPRegionInfo::classof(Info) &&
119 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
120 ParallelOutlinedRegion;
121 }
122
Alexey Bataev18095712014-10-10 12:19:54 +0000123private:
124 /// \brief A variable or parameter storing global thread id for OpenMP
125 /// constructs.
126 const VarDecl *ThreadIDVar;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000127 StringRef HelperName;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000128};
129
Alexey Bataev62b63b12015-03-10 07:28:44 +0000130/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000131class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000132public:
Alexey Bataev48591dd2016-04-20 04:01:36 +0000133 class UntiedTaskActionTy final : public PrePostActionTy {
134 bool Untied;
135 const VarDecl *PartIDVar;
136 const RegionCodeGenTy UntiedCodeGen;
137 llvm::SwitchInst *UntiedSwitch = nullptr;
138
139 public:
140 UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
141 const RegionCodeGenTy &UntiedCodeGen)
142 : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
143 void Enter(CodeGenFunction &CGF) override {
144 if (Untied) {
145 // Emit task switching point.
146 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
147 CGF.GetAddrOfLocalVar(PartIDVar),
148 PartIDVar->getType()->castAs<PointerType>());
149 auto *Res = CGF.EmitLoadOfScalar(PartIdLVal, SourceLocation());
150 auto *DoneBB = CGF.createBasicBlock(".untied.done.");
151 UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
152 CGF.EmitBlock(DoneBB);
153 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
154 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
155 UntiedSwitch->addCase(CGF.Builder.getInt32(0),
156 CGF.Builder.GetInsertBlock());
157 emitUntiedSwitch(CGF);
158 }
159 }
160 void emitUntiedSwitch(CodeGenFunction &CGF) const {
161 if (Untied) {
162 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
163 CGF.GetAddrOfLocalVar(PartIDVar),
164 PartIDVar->getType()->castAs<PointerType>());
165 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
166 PartIdLVal);
167 UntiedCodeGen(CGF);
168 CodeGenFunction::JumpDest CurPoint =
169 CGF.getJumpDestInCurrentScope(".untied.next.");
170 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
171 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
172 UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
173 CGF.Builder.GetInsertBlock());
174 CGF.EmitBranchThroughCleanup(CurPoint);
175 CGF.EmitBlock(CurPoint.getBlock());
176 }
177 }
178 unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
179 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000180 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000181 const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000182 const RegionCodeGenTy &CodeGen,
Alexey Bataev48591dd2016-04-20 04:01:36 +0000183 OpenMPDirectiveKind Kind, bool HasCancel,
184 const UntiedTaskActionTy &Action)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000185 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
Alexey Bataev48591dd2016-04-20 04:01:36 +0000186 ThreadIDVar(ThreadIDVar), Action(Action) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000187 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
188 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000189
Alexey Bataev62b63b12015-03-10 07:28:44 +0000190 /// \brief Get a variable or parameter for storing global thread id
191 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000192 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000193
194 /// \brief Get an LValue for the current ThreadID variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000195 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000196
Alexey Bataev62b63b12015-03-10 07:28:44 +0000197 /// \brief Get the name of the capture helper.
198 StringRef getHelperName() const override { return ".omp_outlined."; }
199
Alexey Bataev48591dd2016-04-20 04:01:36 +0000200 void emitUntiedSwitch(CodeGenFunction &CGF) override {
201 Action.emitUntiedSwitch(CGF);
202 }
203
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000204 static bool classof(const CGCapturedStmtInfo *Info) {
205 return CGOpenMPRegionInfo::classof(Info) &&
206 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
207 TaskOutlinedRegion;
208 }
209
Alexey Bataev62b63b12015-03-10 07:28:44 +0000210private:
211 /// \brief A variable or parameter storing global thread id for OpenMP
212 /// constructs.
213 const VarDecl *ThreadIDVar;
Alexey Bataev48591dd2016-04-20 04:01:36 +0000214 /// Action for emitting code for untied tasks.
215 const UntiedTaskActionTy &Action;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000216};
217
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000218/// \brief API for inlined captured statement code generation in OpenMP
219/// constructs.
220class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
221public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000222 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000223 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000224 OpenMPDirectiveKind Kind, bool HasCancel)
225 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
226 OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000227 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000228
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000229 // \brief Retrieve the value of the context parameter.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000230 llvm::Value *getContextValue() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000231 if (OuterRegionInfo)
232 return OuterRegionInfo->getContextValue();
233 llvm_unreachable("No context value for inlined OpenMP region");
234 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000235
Hans Wennborg7eb54642015-09-10 17:07:54 +0000236 void setContextValue(llvm::Value *V) override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000237 if (OuterRegionInfo) {
238 OuterRegionInfo->setContextValue(V);
239 return;
240 }
241 llvm_unreachable("No context value for inlined OpenMP region");
242 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000243
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000244 /// \brief Lookup the captured field decl for a variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000245 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000246 if (OuterRegionInfo)
247 return OuterRegionInfo->lookup(VD);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000248 // If there is no outer outlined region,no need to lookup in a list of
249 // captured variables, we can use the original one.
250 return nullptr;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000251 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000252
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000253 FieldDecl *getThisFieldDecl() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000254 if (OuterRegionInfo)
255 return OuterRegionInfo->getThisFieldDecl();
256 return nullptr;
257 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000258
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000259 /// \brief Get a variable or parameter for storing global thread id
260 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000261 const VarDecl *getThreadIDVariable() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000262 if (OuterRegionInfo)
263 return OuterRegionInfo->getThreadIDVariable();
264 return nullptr;
265 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000266
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000267 /// \brief Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000268 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000269 if (auto *OuterRegionInfo = getOldCSI())
270 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000271 llvm_unreachable("No helper name for inlined OpenMP construct");
272 }
273
Alexey Bataev48591dd2016-04-20 04:01:36 +0000274 void emitUntiedSwitch(CodeGenFunction &CGF) override {
275 if (OuterRegionInfo)
276 OuterRegionInfo->emitUntiedSwitch(CGF);
277 }
278
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000279 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
280
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000281 static bool classof(const CGCapturedStmtInfo *Info) {
282 return CGOpenMPRegionInfo::classof(Info) &&
283 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
284 }
285
Alexey Bataev48591dd2016-04-20 04:01:36 +0000286 ~CGOpenMPInlinedRegionInfo() override = default;
287
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000288private:
289 /// \brief CodeGen info about outer OpenMP region.
290 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
291 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000292};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000293
Samuel Antaobed3c462015-10-02 16:14:20 +0000294/// \brief API for captured statement code generation in OpenMP target
295/// constructs. For this captures, implicit parameters are used instead of the
Samuel Antaoee8fb302016-01-06 13:42:12 +0000296/// captured fields. The name of the target region has to be unique in a given
297/// application so it is provided by the client, because only the client has
298/// the information to generate that.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000299class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
Samuel Antaobed3c462015-10-02 16:14:20 +0000300public:
301 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000302 const RegionCodeGenTy &CodeGen, StringRef HelperName)
Samuel Antaobed3c462015-10-02 16:14:20 +0000303 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000304 /*HasCancel=*/false),
305 HelperName(HelperName) {}
Samuel Antaobed3c462015-10-02 16:14:20 +0000306
307 /// \brief This is unused for target regions because each starts executing
308 /// with a single thread.
309 const VarDecl *getThreadIDVariable() const override { return nullptr; }
310
311 /// \brief Get the name of the capture helper.
Samuel Antaoee8fb302016-01-06 13:42:12 +0000312 StringRef getHelperName() const override { return HelperName; }
Samuel Antaobed3c462015-10-02 16:14:20 +0000313
314 static bool classof(const CGCapturedStmtInfo *Info) {
315 return CGOpenMPRegionInfo::classof(Info) &&
316 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
317 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000318
319private:
320 StringRef HelperName;
Samuel Antaobed3c462015-10-02 16:14:20 +0000321};
322
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000323static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000324 llvm_unreachable("No codegen for expressions");
325}
326/// \brief API for generation of expressions captured in a innermost OpenMP
327/// region.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000328class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000329public:
330 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
331 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
332 OMPD_unknown,
333 /*HasCancel=*/false),
334 PrivScope(CGF) {
335 // Make sure the globals captured in the provided statement are local by
336 // using the privatization logic. We assume the same variable is not
337 // captured more than once.
338 for (auto &C : CS.captures()) {
339 if (!C.capturesVariable() && !C.capturesVariableByCopy())
340 continue;
341
342 const VarDecl *VD = C.getCapturedVar();
343 if (VD->isLocalVarDeclOrParm())
344 continue;
345
346 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
347 /*RefersToEnclosingVariableOrCapture=*/false,
348 VD->getType().getNonReferenceType(), VK_LValue,
349 SourceLocation());
350 PrivScope.addPrivate(VD, [&CGF, &DRE]() -> Address {
351 return CGF.EmitLValue(&DRE).getAddress();
352 });
353 }
354 (void)PrivScope.Privatize();
355 }
356
357 /// \brief Lookup the captured field decl for a variable.
358 const FieldDecl *lookup(const VarDecl *VD) const override {
359 if (auto *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
360 return FD;
361 return nullptr;
362 }
363
364 /// \brief Emit the captured statement body.
365 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
366 llvm_unreachable("No body for expressions");
367 }
368
369 /// \brief Get a variable or parameter for storing global thread id
370 /// inside OpenMP construct.
371 const VarDecl *getThreadIDVariable() const override {
372 llvm_unreachable("No thread id for expressions");
373 }
374
375 /// \brief Get the name of the capture helper.
376 StringRef getHelperName() const override {
377 llvm_unreachable("No helper name for expressions");
378 }
379
380 static bool classof(const CGCapturedStmtInfo *Info) { return false; }
381
382private:
383 /// Private scope to capture global variables.
384 CodeGenFunction::OMPPrivateScope PrivScope;
385};
386
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000387/// \brief RAII for emitting code of OpenMP constructs.
388class InlinedOpenMPRegionRAII {
389 CodeGenFunction &CGF;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000390 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
391 FieldDecl *LambdaThisCaptureField = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000392
393public:
394 /// \brief Constructs region for combined constructs.
395 /// \param CodeGen Code generation sequence for combined directives. Includes
396 /// a list of functions used for code generation of implicitly inlined
397 /// regions.
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000398 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000399 OpenMPDirectiveKind Kind, bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000400 : CGF(CGF) {
401 // Start emission for the construct.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000402 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
403 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000404 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
405 LambdaThisCaptureField = CGF.LambdaThisCaptureField;
406 CGF.LambdaThisCaptureField = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000407 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000408
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000409 ~InlinedOpenMPRegionRAII() {
410 // Restore original CapturedStmtInfo only if we're done with code emission.
411 auto *OldCSI =
412 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
413 delete CGF.CapturedStmtInfo;
414 CGF.CapturedStmtInfo = OldCSI;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000415 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
416 CGF.LambdaThisCaptureField = LambdaThisCaptureField;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000417 }
418};
419
Alexey Bataev50b3c952016-02-19 10:38:26 +0000420/// \brief Values for bit flags used in the ident_t to describe the fields.
421/// All enumeric elements are named and described in accordance with the code
422/// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
423enum OpenMPLocationFlags {
424 /// \brief Use trampoline for internal microtask.
425 OMP_IDENT_IMD = 0x01,
426 /// \brief Use c-style ident structure.
427 OMP_IDENT_KMPC = 0x02,
428 /// \brief Atomic reduction option for kmpc_reduce.
429 OMP_ATOMIC_REDUCE = 0x10,
430 /// \brief Explicit 'barrier' directive.
431 OMP_IDENT_BARRIER_EXPL = 0x20,
432 /// \brief Implicit barrier in code.
433 OMP_IDENT_BARRIER_IMPL = 0x40,
434 /// \brief Implicit barrier in 'for' directive.
435 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
436 /// \brief Implicit barrier in 'sections' directive.
437 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
438 /// \brief Implicit barrier in 'single' directive.
439 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140
440};
441
442/// \brief Describes ident structure that describes a source location.
443/// All descriptions are taken from
444/// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
445/// Original structure:
446/// typedef struct ident {
447/// kmp_int32 reserved_1; /**< might be used in Fortran;
448/// see above */
449/// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
450/// KMP_IDENT_KMPC identifies this union
451/// member */
452/// kmp_int32 reserved_2; /**< not really used in Fortran any more;
453/// see above */
454///#if USE_ITT_BUILD
455/// /* but currently used for storing
456/// region-specific ITT */
457/// /* contextual information. */
458///#endif /* USE_ITT_BUILD */
459/// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
460/// C++ */
461/// char const *psource; /**< String describing the source location.
462/// The string is composed of semi-colon separated
463// fields which describe the source file,
464/// the function and a pair of line numbers that
465/// delimit the construct.
466/// */
467/// } ident_t;
468enum IdentFieldIndex {
469 /// \brief might be used in Fortran
470 IdentField_Reserved_1,
471 /// \brief OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
472 IdentField_Flags,
473 /// \brief Not really used in Fortran any more
474 IdentField_Reserved_2,
475 /// \brief Source[4] in Fortran, do not use for C++
476 IdentField_Reserved_3,
477 /// \brief String describing the source location. The string is composed of
478 /// semi-colon separated fields which describe the source file, the function
479 /// and a pair of line numbers that delimit the construct.
480 IdentField_PSource
481};
482
483/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
484/// the enum sched_type in kmp.h).
485enum OpenMPSchedType {
486 /// \brief Lower bound for default (unordered) versions.
487 OMP_sch_lower = 32,
488 OMP_sch_static_chunked = 33,
489 OMP_sch_static = 34,
490 OMP_sch_dynamic_chunked = 35,
491 OMP_sch_guided_chunked = 36,
492 OMP_sch_runtime = 37,
493 OMP_sch_auto = 38,
Alexey Bataev6cff6242016-05-30 13:05:14 +0000494 /// static with chunk adjustment (e.g., simd)
Samuel Antao4c8035b2016-12-12 18:00:20 +0000495 OMP_sch_static_balanced_chunked = 45,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000496 /// \brief Lower bound for 'ordered' versions.
497 OMP_ord_lower = 64,
498 OMP_ord_static_chunked = 65,
499 OMP_ord_static = 66,
500 OMP_ord_dynamic_chunked = 67,
501 OMP_ord_guided_chunked = 68,
502 OMP_ord_runtime = 69,
503 OMP_ord_auto = 70,
504 OMP_sch_default = OMP_sch_static,
Carlo Bertollifc35ad22016-03-07 16:04:49 +0000505 /// \brief dist_schedule types
506 OMP_dist_sch_static_chunked = 91,
507 OMP_dist_sch_static = 92,
Alexey Bataev9ebd7422016-05-10 09:57:36 +0000508 /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
509 /// Set if the monotonic schedule modifier was present.
510 OMP_sch_modifier_monotonic = (1 << 29),
511 /// Set if the nonmonotonic schedule modifier was present.
512 OMP_sch_modifier_nonmonotonic = (1 << 30),
Alexey Bataev50b3c952016-02-19 10:38:26 +0000513};
514
515enum OpenMPRTLFunction {
516 /// \brief Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
517 /// kmpc_micro microtask, ...);
518 OMPRTL__kmpc_fork_call,
519 /// \brief Call to void *__kmpc_threadprivate_cached(ident_t *loc,
520 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
521 OMPRTL__kmpc_threadprivate_cached,
522 /// \brief Call to void __kmpc_threadprivate_register( ident_t *,
523 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
524 OMPRTL__kmpc_threadprivate_register,
525 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
526 OMPRTL__kmpc_global_thread_num,
527 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
528 // kmp_critical_name *crit);
529 OMPRTL__kmpc_critical,
530 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
531 // global_tid, kmp_critical_name *crit, uintptr_t hint);
532 OMPRTL__kmpc_critical_with_hint,
533 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
534 // kmp_critical_name *crit);
535 OMPRTL__kmpc_end_critical,
536 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
537 // global_tid);
538 OMPRTL__kmpc_cancel_barrier,
539 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
540 OMPRTL__kmpc_barrier,
541 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
542 OMPRTL__kmpc_for_static_fini,
543 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
544 // global_tid);
545 OMPRTL__kmpc_serialized_parallel,
546 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
547 // global_tid);
548 OMPRTL__kmpc_end_serialized_parallel,
549 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
550 // kmp_int32 num_threads);
551 OMPRTL__kmpc_push_num_threads,
552 // Call to void __kmpc_flush(ident_t *loc);
553 OMPRTL__kmpc_flush,
554 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
555 OMPRTL__kmpc_master,
556 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
557 OMPRTL__kmpc_end_master,
558 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
559 // int end_part);
560 OMPRTL__kmpc_omp_taskyield,
561 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
562 OMPRTL__kmpc_single,
563 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
564 OMPRTL__kmpc_end_single,
565 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
566 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
567 // kmp_routine_entry_t *task_entry);
568 OMPRTL__kmpc_omp_task_alloc,
569 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
570 // new_task);
571 OMPRTL__kmpc_omp_task,
572 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
573 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
574 // kmp_int32 didit);
575 OMPRTL__kmpc_copyprivate,
576 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
577 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
578 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
579 OMPRTL__kmpc_reduce,
580 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
581 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
582 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
583 // *lck);
584 OMPRTL__kmpc_reduce_nowait,
585 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
586 // kmp_critical_name *lck);
587 OMPRTL__kmpc_end_reduce,
588 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
589 // kmp_critical_name *lck);
590 OMPRTL__kmpc_end_reduce_nowait,
591 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
592 // kmp_task_t * new_task);
593 OMPRTL__kmpc_omp_task_begin_if0,
594 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
595 // kmp_task_t * new_task);
596 OMPRTL__kmpc_omp_task_complete_if0,
597 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
598 OMPRTL__kmpc_ordered,
599 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
600 OMPRTL__kmpc_end_ordered,
601 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
602 // global_tid);
603 OMPRTL__kmpc_omp_taskwait,
604 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
605 OMPRTL__kmpc_taskgroup,
606 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
607 OMPRTL__kmpc_end_taskgroup,
608 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
609 // int proc_bind);
610 OMPRTL__kmpc_push_proc_bind,
611 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
612 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
613 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
614 OMPRTL__kmpc_omp_task_with_deps,
615 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
616 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
617 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
618 OMPRTL__kmpc_omp_wait_deps,
619 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
620 // global_tid, kmp_int32 cncl_kind);
621 OMPRTL__kmpc_cancellationpoint,
622 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
623 // kmp_int32 cncl_kind);
624 OMPRTL__kmpc_cancel,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000625 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
626 // kmp_int32 num_teams, kmp_int32 thread_limit);
627 OMPRTL__kmpc_push_num_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000628 // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
629 // microtask, ...);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000630 OMPRTL__kmpc_fork_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000631 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
632 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
633 // sched, kmp_uint64 grainsize, void *task_dup);
634 OMPRTL__kmpc_taskloop,
Alexey Bataev8b427062016-05-25 12:36:08 +0000635 // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
636 // num_dims, struct kmp_dim *dims);
637 OMPRTL__kmpc_doacross_init,
638 // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
639 OMPRTL__kmpc_doacross_fini,
640 // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
641 // *vec);
642 OMPRTL__kmpc_doacross_post,
643 // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
644 // *vec);
645 OMPRTL__kmpc_doacross_wait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000646
647 //
648 // Offloading related calls
649 //
650 // Call to int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
651 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
652 // *arg_types);
653 OMPRTL__tgt_target,
Samuel Antaob68e2db2016-03-03 16:20:23 +0000654 // Call to int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
655 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
656 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
657 OMPRTL__tgt_target_teams,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000658 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
659 OMPRTL__tgt_register_lib,
660 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
661 OMPRTL__tgt_unregister_lib,
Samuel Antaodf158d52016-04-27 22:58:19 +0000662 // Call to void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
663 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
664 OMPRTL__tgt_target_data_begin,
665 // Call to void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
666 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
667 OMPRTL__tgt_target_data_end,
Samuel Antao8d2d7302016-05-26 18:30:22 +0000668 // Call to void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
669 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
670 OMPRTL__tgt_target_data_update,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000671};
672
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000673/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
674/// region.
675class CleanupTy final : public EHScopeStack::Cleanup {
676 PrePostActionTy *Action;
677
678public:
679 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
680 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
681 if (!CGF.HaveInsertPoint())
682 return;
683 Action->Exit(CGF);
684 }
685};
686
Hans Wennborg7eb54642015-09-10 17:07:54 +0000687} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000688
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000689void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
690 CodeGenFunction::RunCleanupsScope Scope(CGF);
691 if (PrePostAction) {
692 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
693 Callback(CodeGen, CGF, *PrePostAction);
694 } else {
695 PrePostActionTy Action;
696 Callback(CodeGen, CGF, Action);
697 }
698}
699
Alexey Bataev5c40bec2017-07-13 13:36:14 +0000700/// Check if the combiner is a call to UDR combiner and if it is so return the
701/// UDR decl used for reduction.
702static const OMPDeclareReductionDecl *
703getReductionInit(const Expr *ReductionOp) {
704 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
705 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
706 if (auto *DRE =
707 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
708 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
709 return DRD;
710 return nullptr;
711}
712
713static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
714 const OMPDeclareReductionDecl *DRD,
715 const Expr *InitOp,
716 Address Private, Address Original,
717 QualType Ty) {
718 if (DRD->getInitializer()) {
719 std::pair<llvm::Function *, llvm::Function *> Reduction =
720 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
721 auto *CE = cast<CallExpr>(InitOp);
722 auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
723 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
724 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
725 auto *LHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
726 auto *RHSDRE = cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
727 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
728 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
729 [=]() -> Address { return Private; });
730 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
731 [=]() -> Address { return Original; });
732 (void)PrivateScope.Privatize();
733 RValue Func = RValue::get(Reduction.second);
734 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
735 CGF.EmitIgnoredExpr(InitOp);
736 } else {
737 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
738 auto *GV = new llvm::GlobalVariable(
739 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
740 llvm::GlobalValue::PrivateLinkage, Init, ".init");
741 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
742 RValue InitRVal;
743 switch (CGF.getEvaluationKind(Ty)) {
744 case TEK_Scalar:
745 InitRVal = CGF.EmitLoadOfLValue(LV, SourceLocation());
746 break;
747 case TEK_Complex:
748 InitRVal =
749 RValue::getComplex(CGF.EmitLoadOfComplex(LV, SourceLocation()));
750 break;
751 case TEK_Aggregate:
752 InitRVal = RValue::getAggregate(LV.getAddress());
753 break;
754 }
755 OpaqueValueExpr OVE(SourceLocation(), Ty, VK_RValue);
756 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
757 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
758 /*IsInitializer=*/false);
759 }
760}
761
762/// \brief Emit initialization of arrays of complex types.
763/// \param DestAddr Address of the array.
764/// \param Type Type of array.
765/// \param Init Initial expression of array.
766/// \param SrcAddr Address of the original array.
767static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
768 QualType Type, const Expr *Init,
769 Address SrcAddr = Address::invalid()) {
770 auto *DRD = getReductionInit(Init);
771 // Perform element-by-element initialization.
772 QualType ElementTy;
773
774 // Drill down to the base element type on both arrays.
775 auto ArrayTy = Type->getAsArrayTypeUnsafe();
776 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
777 DestAddr =
778 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
779 if (DRD)
780 SrcAddr =
781 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
782
783 llvm::Value *SrcBegin = nullptr;
784 if (DRD)
785 SrcBegin = SrcAddr.getPointer();
786 auto DestBegin = DestAddr.getPointer();
787 // Cast from pointer to array type to pointer to single element.
788 auto DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements);
789 // The basic structure here is a while-do loop.
790 auto BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
791 auto DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
792 auto IsEmpty =
793 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
794 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
795
796 // Enter the loop body, making that address the current address.
797 auto EntryBB = CGF.Builder.GetInsertBlock();
798 CGF.EmitBlock(BodyBB);
799
800 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
801
802 llvm::PHINode *SrcElementPHI = nullptr;
803 Address SrcElementCurrent = Address::invalid();
804 if (DRD) {
805 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
806 "omp.arraycpy.srcElementPast");
807 SrcElementPHI->addIncoming(SrcBegin, EntryBB);
808 SrcElementCurrent =
809 Address(SrcElementPHI,
810 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
811 }
812 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
813 DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
814 DestElementPHI->addIncoming(DestBegin, EntryBB);
815 Address DestElementCurrent =
816 Address(DestElementPHI,
817 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
818
819 // Emit copy.
820 {
821 CodeGenFunction::RunCleanupsScope InitScope(CGF);
822 if (DRD && (DRD->getInitializer() || !Init)) {
823 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
824 SrcElementCurrent, ElementTy);
825 } else
826 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
827 /*IsInitializer=*/false);
828 }
829
830 if (DRD) {
831 // Shift the address forward by one element.
832 auto SrcElementNext = CGF.Builder.CreateConstGEP1_32(
833 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
834 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
835 }
836
837 // Shift the address forward by one element.
838 auto DestElementNext = CGF.Builder.CreateConstGEP1_32(
839 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
840 // Check whether we've reached the end.
841 auto Done =
842 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
843 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
844 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
845
846 // Done.
847 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
848}
849
850LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
851 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
852 return CGF.EmitOMPArraySectionExpr(OASE);
853 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(E))
854 return CGF.EmitLValue(ASE);
855 auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
856 DeclRefExpr DRE(const_cast<VarDecl *>(OrigVD),
857 CGF.CapturedStmtInfo &&
858 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr,
859 E->getType(), VK_LValue, E->getExprLoc());
860 // Store the address of the original variable associated with the LHS
861 // implicit variable.
862 return CGF.EmitLValue(&DRE);
863}
864
865LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
866 const Expr *E) {
867 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
868 return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
869 return LValue();
870}
871
872void ReductionCodeGen::emitAggregateInitialization(CodeGenFunction &CGF,
873 unsigned N,
874 Address PrivateAddr,
875 LValue SharedLVal) {
876 // Emit VarDecl with copy init for arrays.
877 // Get the address of the original variable captured in current
878 // captured region.
879 auto *PrivateVD =
880 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
881 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
882 EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
883 DRD ? ClausesData[N].ReductionOp : PrivateVD->getInit(),
884 SharedLVal.getAddress());
885}
886
887ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
888 ArrayRef<const Expr *> Privates,
889 ArrayRef<const Expr *> ReductionOps) {
890 ClausesData.reserve(Shareds.size());
891 SharedAddresses.reserve(Shareds.size());
892 Sizes.reserve(Shareds.size());
893 auto IPriv = Privates.begin();
894 auto IRed = ReductionOps.begin();
895 for (const auto *Ref : Shareds) {
896 ClausesData.emplace_back(Ref, *IPriv, *IRed);
897 std::advance(IPriv, 1);
898 std::advance(IRed, 1);
899 }
900}
901
902void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) {
903 assert(SharedAddresses.size() == N &&
904 "Number of generated lvalues must be exactly N.");
905 SharedAddresses.emplace_back(emitSharedLValue(CGF, ClausesData[N].Ref),
906 emitSharedLValueUB(CGF, ClausesData[N].Ref));
907}
908
909void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
910 auto *PrivateVD =
911 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
912 QualType PrivateType = PrivateVD->getType();
913 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
914 if (!AsArraySection && !PrivateType->isVariablyModifiedType()) {
915 Sizes.emplace_back(nullptr);
916 return;
917 }
918 llvm::Value *Size;
919 if (AsArraySection) {
920 Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(),
921 SharedAddresses[N].first.getPointer());
922 Size = CGF.Builder.CreateNUWAdd(
923 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
924 } else {
925 Size = CGF.getTypeSize(
926 SharedAddresses[N].first.getType().getNonReferenceType());
927 }
928 Sizes.emplace_back(Size);
929 CodeGenFunction::OpaqueValueMapping OpaqueMap(
930 CGF,
931 cast<OpaqueValueExpr>(
932 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
933 RValue::get(Size));
934 CGF.EmitVariablyModifiedType(PrivateType);
935}
936
937void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
938 llvm::Value *Size) {
939 auto *PrivateVD =
940 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
941 QualType PrivateType = PrivateVD->getType();
942 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
943 if (!AsArraySection && !PrivateType->isVariablyModifiedType()) {
944 assert(!Size && !Sizes[N] &&
945 "Size should be nullptr for non-variably modified redution "
946 "items.");
947 return;
948 }
949 CodeGenFunction::OpaqueValueMapping OpaqueMap(
950 CGF,
951 cast<OpaqueValueExpr>(
952 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
953 RValue::get(Size));
954 CGF.EmitVariablyModifiedType(PrivateType);
955}
956
957void ReductionCodeGen::emitInitialization(
958 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
959 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
960 assert(SharedAddresses.size() > N && "No variable was generated");
961 auto *PrivateVD =
962 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
963 auto *DRD = getReductionInit(ClausesData[N].ReductionOp);
964 QualType PrivateType = PrivateVD->getType();
965 PrivateAddr = CGF.Builder.CreateElementBitCast(
966 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
967 QualType SharedType = SharedAddresses[N].first.getType();
968 SharedLVal = CGF.MakeAddrLValue(
969 CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(),
970 CGF.ConvertTypeForMem(SharedType)),
971 SharedType, SharedAddresses[N].first.getBaseInfo());
972 if (isa<OMPArraySectionExpr>(ClausesData[N].Ref) ||
973 CGF.getContext().getAsArrayType(PrivateVD->getType())) {
974 emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal);
975 } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) {
976 emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
977 PrivateAddr, SharedLVal.getAddress(),
978 SharedLVal.getType());
979 } else if (!DefaultInit(CGF) && PrivateVD->hasInit() &&
980 !CGF.isTrivialInitializer(PrivateVD->getInit())) {
981 CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
982 PrivateVD->getType().getQualifiers(),
983 /*IsInitializer=*/false);
984 }
985}
986
987bool ReductionCodeGen::needCleanups(unsigned N) {
988 auto *PrivateVD =
989 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
990 QualType PrivateType = PrivateVD->getType();
991 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
992 return DTorKind != QualType::DK_none;
993}
994
995void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
996 Address PrivateAddr) {
997 auto *PrivateVD =
998 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
999 QualType PrivateType = PrivateVD->getType();
1000 QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
1001 if (needCleanups(N)) {
1002 PrivateAddr = CGF.Builder.CreateElementBitCast(
1003 PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
1004 CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
1005 }
1006}
1007
1008static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1009 LValue BaseLV) {
1010 BaseTy = BaseTy.getNonReferenceType();
1011 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1012 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1013 if (auto *PtrTy = BaseTy->getAs<PointerType>())
1014 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy);
1015 else {
1016 BaseLV = CGF.EmitLoadOfReferenceLValue(BaseLV.getAddress(),
1017 BaseTy->castAs<ReferenceType>());
1018 }
1019 BaseTy = BaseTy->getPointeeType();
1020 }
1021 return CGF.MakeAddrLValue(
1022 CGF.Builder.CreateElementBitCast(BaseLV.getAddress(),
1023 CGF.ConvertTypeForMem(ElTy)),
1024 BaseLV.getType(), BaseLV.getBaseInfo());
1025}
1026
1027static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
1028 llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
1029 llvm::Value *Addr) {
1030 Address Tmp = Address::invalid();
1031 Address TopTmp = Address::invalid();
1032 Address MostTopTmp = Address::invalid();
1033 BaseTy = BaseTy.getNonReferenceType();
1034 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) &&
1035 !CGF.getContext().hasSameType(BaseTy, ElTy)) {
1036 Tmp = CGF.CreateMemTemp(BaseTy);
1037 if (TopTmp.isValid())
1038 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
1039 else
1040 MostTopTmp = Tmp;
1041 TopTmp = Tmp;
1042 BaseTy = BaseTy->getPointeeType();
1043 }
1044 llvm::Type *Ty = BaseLVType;
1045 if (Tmp.isValid())
1046 Ty = Tmp.getElementType();
1047 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
1048 if (Tmp.isValid()) {
1049 CGF.Builder.CreateStore(Addr, Tmp);
1050 return MostTopTmp;
1051 }
1052 return Address(Addr, BaseLVAlignment);
1053}
1054
1055Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
1056 Address PrivateAddr) {
1057 const DeclRefExpr *DE;
1058 const VarDecl *OrigVD = nullptr;
1059 if (auto *OASE = dyn_cast<OMPArraySectionExpr>(ClausesData[N].Ref)) {
1060 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
1061 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
1062 Base = TempOASE->getBase()->IgnoreParenImpCasts();
1063 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1064 Base = TempASE->getBase()->IgnoreParenImpCasts();
1065 DE = cast<DeclRefExpr>(Base);
1066 OrigVD = cast<VarDecl>(DE->getDecl());
1067 } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(ClausesData[N].Ref)) {
1068 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
1069 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1070 Base = TempASE->getBase()->IgnoreParenImpCasts();
1071 DE = cast<DeclRefExpr>(Base);
1072 OrigVD = cast<VarDecl>(DE->getDecl());
1073 }
1074 if (OrigVD) {
1075 BaseDecls.emplace_back(OrigVD);
1076 auto OriginalBaseLValue = CGF.EmitLValue(DE);
1077 LValue BaseLValue =
1078 loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1079 OriginalBaseLValue);
1080 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1081 BaseLValue.getPointer(), SharedAddresses[N].first.getPointer());
1082 llvm::Value *Ptr =
1083 CGF.Builder.CreateGEP(PrivateAddr.getPointer(), Adjustment);
1084 return castToBase(CGF, OrigVD->getType(),
1085 SharedAddresses[N].first.getType(),
1086 OriginalBaseLValue.getPointer()->getType(),
1087 OriginalBaseLValue.getAlignment(), Ptr);
1088 }
1089 BaseDecls.emplace_back(
1090 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1091 return PrivateAddr;
1092}
1093
Alexey Bataev18095712014-10-10 12:19:54 +00001094LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00001095 return CGF.EmitLoadOfPointerLValue(
1096 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1097 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +00001098}
1099
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001100void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001101 if (!CGF.HaveInsertPoint())
1102 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001103 // 1.2.2 OpenMP Language Terminology
1104 // Structured block - An executable statement with a single entry at the
1105 // top and a single exit at the bottom.
1106 // The point of exit cannot be a branch out of the structured block.
1107 // longjmp() and throw() must not violate the entry/exit criteria.
1108 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001109 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001110 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001111}
1112
Alexey Bataev62b63b12015-03-10 07:28:44 +00001113LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1114 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001115 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1116 getThreadIDVariable()->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001117 LValueBaseInfo(AlignmentSource::Decl, false));
Alexey Bataev62b63b12015-03-10 07:28:44 +00001118}
1119
Alexey Bataev9959db52014-05-06 10:08:46 +00001120CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001121 : CGM(CGM), OffloadEntriesInfoManager(CGM) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001122 IdentTy = llvm::StructType::create(
1123 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
1124 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Serge Guelton1d993272017-05-09 19:31:30 +00001125 CGM.Int8PtrTy /* psource */);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001126 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +00001127
1128 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +00001129}
1130
Alexey Bataev91797552015-03-18 04:13:55 +00001131void CGOpenMPRuntime::clear() {
1132 InternalVars.clear();
1133}
1134
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001135static llvm::Function *
1136emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1137 const Expr *CombinerInitializer, const VarDecl *In,
1138 const VarDecl *Out, bool IsCombiner) {
1139 // void .omp_combiner.(Ty *in, Ty *out);
1140 auto &C = CGM.getContext();
1141 QualType PtrTy = C.getPointerType(Ty).withRestrict();
1142 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001143 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001144 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001145 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00001146 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001147 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001148 Args.push_back(&OmpInParm);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001149 auto &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00001150 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001151 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1152 auto *Fn = llvm::Function::Create(
1153 FnTy, llvm::GlobalValue::InternalLinkage,
1154 IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
1155 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00001156 Fn->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00001157 Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001158 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001159 CodeGenFunction CGF(CGM);
1160 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1161 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
1162 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
1163 CodeGenFunction::OMPPrivateScope Scope(CGF);
1164 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
1165 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
1166 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1167 .getAddress();
1168 });
1169 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
1170 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
1171 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1172 .getAddress();
1173 });
1174 (void)Scope.Privatize();
1175 CGF.EmitIgnoredExpr(CombinerInitializer);
1176 Scope.ForceCleanup();
1177 CGF.FinishFunction();
1178 return Fn;
1179}
1180
1181void CGOpenMPRuntime::emitUserDefinedReduction(
1182 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1183 if (UDRMap.count(D) > 0)
1184 return;
1185 auto &C = CGM.getContext();
1186 if (!In || !Out) {
1187 In = &C.Idents.get("omp_in");
1188 Out = &C.Idents.get("omp_out");
1189 }
1190 llvm::Function *Combiner = emitCombinerOrInitializer(
1191 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
1192 cast<VarDecl>(D->lookup(Out).front()),
1193 /*IsCombiner=*/true);
1194 llvm::Function *Initializer = nullptr;
1195 if (auto *Init = D->getInitializer()) {
1196 if (!Priv || !Orig) {
1197 Priv = &C.Idents.get("omp_priv");
1198 Orig = &C.Idents.get("omp_orig");
1199 }
1200 Initializer = emitCombinerOrInitializer(
1201 CGM, D->getType(), Init, cast<VarDecl>(D->lookup(Orig).front()),
1202 cast<VarDecl>(D->lookup(Priv).front()),
1203 /*IsCombiner=*/false);
1204 }
1205 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
1206 if (CGF) {
1207 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1208 Decls.second.push_back(D);
1209 }
1210}
1211
Alexey Bataeva839ddd2016-03-17 10:19:46 +00001212std::pair<llvm::Function *, llvm::Function *>
1213CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1214 auto I = UDRMap.find(D);
1215 if (I != UDRMap.end())
1216 return I->second;
1217 emitUserDefinedReduction(/*CGF=*/nullptr, D);
1218 return UDRMap.lookup(D);
1219}
1220
John McCall7f416cc2015-09-08 08:05:57 +00001221// Layout information for ident_t.
1222static CharUnits getIdentAlign(CodeGenModule &CGM) {
1223 return CGM.getPointerAlign();
1224}
1225static CharUnits getIdentSize(CodeGenModule &CGM) {
1226 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
1227 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
1228}
Alexey Bataev50b3c952016-02-19 10:38:26 +00001229static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
John McCall7f416cc2015-09-08 08:05:57 +00001230 // All the fields except the last are i32, so this works beautifully.
1231 return unsigned(Field) * CharUnits::fromQuantity(4);
1232}
1233static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001234 IdentFieldIndex Field,
John McCall7f416cc2015-09-08 08:05:57 +00001235 const llvm::Twine &Name = "") {
1236 auto Offset = getOffsetOfIdentField(Field);
1237 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
1238}
1239
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001240static llvm::Value *emitParallelOrTeamsOutlinedFunction(
1241 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1242 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1243 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001244 assert(ThreadIDVar->getType()->isPointerType() &&
1245 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +00001246 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +00001247 bool HasCancel = false;
1248 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
1249 HasCancel = OPD->hasCancel();
1250 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
1251 HasCancel = OPSD->hasCancel();
1252 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
1253 HasCancel = OPFD->hasCancel();
1254 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001255 HasCancel, OutlinedHelperName);
Alexey Bataevd157d472015-06-24 03:35:38 +00001256 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001257 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +00001258}
1259
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00001260llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction(
1261 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1262 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1263 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1264 return emitParallelOrTeamsOutlinedFunction(
1265 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1266}
1267
1268llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1269 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1270 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1271 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1272 return emitParallelOrTeamsOutlinedFunction(
1273 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1274}
1275
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001276llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
1277 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +00001278 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1279 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1280 bool Tied, unsigned &NumberOfParts) {
1281 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1282 PrePostActionTy &) {
1283 auto *ThreadID = getThreadID(CGF, D.getLocStart());
1284 auto *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
1285 llvm::Value *TaskArgs[] = {
1286 UpLoc, ThreadID,
1287 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1288 TaskTVar->getType()->castAs<PointerType>())
1289 .getPointer()};
1290 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
1291 };
1292 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1293 UntiedCodeGen);
1294 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001295 assert(!ThreadIDVar->getType()->isPointerType() &&
1296 "thread id variable must be of type kmp_int32 for tasks");
1297 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
Alexey Bataev7292c292016-04-25 12:22:29 +00001298 auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +00001299 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +00001300 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1301 InnermostKind,
1302 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +00001303 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev48591dd2016-04-20 04:01:36 +00001304 auto *Res = CGF.GenerateCapturedStmtFunction(*CS);
1305 if (!Tied)
1306 NumberOfParts = Action.getNumberOfParts();
1307 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +00001308}
1309
Alexey Bataev50b3c952016-02-19 10:38:26 +00001310Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +00001311 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +00001312 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +00001313 if (!Entry) {
1314 if (!DefaultOpenMPPSource) {
1315 // Initialize default location for psource field of ident_t structure of
1316 // all ident_t objects. Format is ";file;function;line;column;;".
1317 // Taken from
1318 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
1319 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +00001320 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001321 DefaultOpenMPPSource =
1322 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
1323 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001324
John McCall23c9dc62016-11-28 22:18:27 +00001325 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00001326 auto fields = builder.beginStruct(IdentTy);
1327 fields.addInt(CGM.Int32Ty, 0);
1328 fields.addInt(CGM.Int32Ty, Flags);
1329 fields.addInt(CGM.Int32Ty, 0);
1330 fields.addInt(CGM.Int32Ty, 0);
1331 fields.add(DefaultOpenMPPSource);
1332 auto DefaultOpenMPLocation =
1333 fields.finishAndCreateGlobal("", Align, /*isConstant*/ true,
1334 llvm::GlobalValue::PrivateLinkage);
1335 DefaultOpenMPLocation->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1336
John McCall7f416cc2015-09-08 08:05:57 +00001337 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +00001338 }
John McCall7f416cc2015-09-08 08:05:57 +00001339 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +00001340}
1341
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001342llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1343 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +00001344 unsigned Flags) {
1345 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +00001346 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +00001347 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +00001348 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +00001349 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001350
1351 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1352
John McCall7f416cc2015-09-08 08:05:57 +00001353 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001354 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1355 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +00001356 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
1357
Alexander Musmanc6388682014-12-15 07:07:06 +00001358 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
1359 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +00001360 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +00001361 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +00001362 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
1363 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +00001364 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +00001365 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001366 LocValue = AI;
1367
1368 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1369 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001370 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +00001371 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +00001372 }
1373
1374 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +00001375 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +00001376
Alexey Bataevf002aca2014-05-30 05:48:40 +00001377 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
1378 if (OMPDebugLoc == nullptr) {
1379 SmallString<128> Buffer2;
1380 llvm::raw_svector_ostream OS2(Buffer2);
1381 // Build debug location
1382 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1383 OS2 << ";" << PLoc.getFilename() << ";";
1384 if (const FunctionDecl *FD =
1385 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
1386 OS2 << FD->getQualifiedNameAsString();
1387 }
1388 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1389 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
1390 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +00001391 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001392 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +00001393 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
1394
John McCall7f416cc2015-09-08 08:05:57 +00001395 // Our callers always pass this to a runtime function, so for
1396 // convenience, go ahead and return a naked pointer.
1397 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +00001398}
1399
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001400llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1401 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001402 assert(CGF.CurFn && "No function in current CodeGenFunction.");
1403
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001404 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +00001405 // Check whether we've already cached a load of the thread id in this
1406 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001407 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +00001408 if (I != OpenMPLocThreadIDMap.end()) {
1409 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +00001410 if (ThreadID != nullptr)
1411 return ThreadID;
1412 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001413 if (auto *OMPRegionInfo =
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001414 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001415 if (OMPRegionInfo->getThreadIDVariable()) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001416 // Check if this an outlined function with thread id passed as argument.
1417 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001418 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
1419 // If value loaded in entry block, cache it and use it everywhere in
1420 // function.
1421 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1422 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1423 Elem.second.ThreadID = ThreadID;
1424 }
1425 return ThreadID;
Alexey Bataevd6c57552014-07-25 07:55:17 +00001426 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001427 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001428
1429 // This is not an outlined function region - need to call __kmpc_int32
1430 // kmpc_global_thread_num(ident_t *loc).
1431 // Generate thread id value and cache this value for use across the
1432 // function.
1433 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1434 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
1435 ThreadID =
1436 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1437 emitUpdateLocation(CGF, Loc));
1438 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1439 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001440 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +00001441}
1442
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001443void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001444 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001445 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1446 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001447 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1448 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
1449 UDRMap.erase(D);
1450 }
1451 FunctionUDRMap.erase(CGF.CurFn);
1452 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001453}
1454
1455llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001456 if (!IdentTy) {
1457 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001458 return llvm::PointerType::getUnqual(IdentTy);
1459}
1460
1461llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001462 if (!Kmpc_MicroTy) {
1463 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1464 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1465 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1466 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1467 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001468 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1469}
1470
1471llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001472CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001473 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001474 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001475 case OMPRTL__kmpc_fork_call: {
1476 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1477 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001478 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1479 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001480 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001481 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001482 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1483 break;
1484 }
1485 case OMPRTL__kmpc_global_thread_num: {
1486 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001487 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001488 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001489 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001490 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1491 break;
1492 }
Alexey Bataev97720002014-11-11 04:05:39 +00001493 case OMPRTL__kmpc_threadprivate_cached: {
1494 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1495 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1496 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1497 CGM.VoidPtrTy, CGM.SizeTy,
1498 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1499 llvm::FunctionType *FnTy =
1500 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1501 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1502 break;
1503 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001504 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001505 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1506 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001507 llvm::Type *TypeParams[] = {
1508 getIdentTyPointerTy(), CGM.Int32Ty,
1509 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1510 llvm::FunctionType *FnTy =
1511 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1512 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1513 break;
1514 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001515 case OMPRTL__kmpc_critical_with_hint: {
1516 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1517 // kmp_critical_name *crit, uintptr_t hint);
1518 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1519 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1520 CGM.IntPtrTy};
1521 llvm::FunctionType *FnTy =
1522 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1523 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1524 break;
1525 }
Alexey Bataev97720002014-11-11 04:05:39 +00001526 case OMPRTL__kmpc_threadprivate_register: {
1527 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1528 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1529 // typedef void *(*kmpc_ctor)(void *);
1530 auto KmpcCtorTy =
1531 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1532 /*isVarArg*/ false)->getPointerTo();
1533 // typedef void *(*kmpc_cctor)(void *, void *);
1534 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1535 auto KmpcCopyCtorTy =
1536 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1537 /*isVarArg*/ false)->getPointerTo();
1538 // typedef void (*kmpc_dtor)(void *);
1539 auto KmpcDtorTy =
1540 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1541 ->getPointerTo();
1542 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1543 KmpcCopyCtorTy, KmpcDtorTy};
1544 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1545 /*isVarArg*/ false);
1546 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1547 break;
1548 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001549 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001550 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1551 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001552 llvm::Type *TypeParams[] = {
1553 getIdentTyPointerTy(), CGM.Int32Ty,
1554 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1555 llvm::FunctionType *FnTy =
1556 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1557 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1558 break;
1559 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001560 case OMPRTL__kmpc_cancel_barrier: {
1561 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1562 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001563 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1564 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001565 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1566 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001567 break;
1568 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001569 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001570 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001571 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1572 llvm::FunctionType *FnTy =
1573 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1574 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1575 break;
1576 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001577 case OMPRTL__kmpc_for_static_fini: {
1578 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1579 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1580 llvm::FunctionType *FnTy =
1581 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1582 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1583 break;
1584 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001585 case OMPRTL__kmpc_push_num_threads: {
1586 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1587 // kmp_int32 num_threads)
1588 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1589 CGM.Int32Ty};
1590 llvm::FunctionType *FnTy =
1591 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1592 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1593 break;
1594 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001595 case OMPRTL__kmpc_serialized_parallel: {
1596 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1597 // global_tid);
1598 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1599 llvm::FunctionType *FnTy =
1600 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1601 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1602 break;
1603 }
1604 case OMPRTL__kmpc_end_serialized_parallel: {
1605 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1606 // global_tid);
1607 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1608 llvm::FunctionType *FnTy =
1609 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1610 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1611 break;
1612 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001613 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001614 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001615 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1616 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001617 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001618 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1619 break;
1620 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001621 case OMPRTL__kmpc_master: {
1622 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1623 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1624 llvm::FunctionType *FnTy =
1625 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1626 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1627 break;
1628 }
1629 case OMPRTL__kmpc_end_master: {
1630 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1631 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1632 llvm::FunctionType *FnTy =
1633 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1634 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1635 break;
1636 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001637 case OMPRTL__kmpc_omp_taskyield: {
1638 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1639 // int end_part);
1640 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1641 llvm::FunctionType *FnTy =
1642 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1643 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1644 break;
1645 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001646 case OMPRTL__kmpc_single: {
1647 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1648 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1649 llvm::FunctionType *FnTy =
1650 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1651 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1652 break;
1653 }
1654 case OMPRTL__kmpc_end_single: {
1655 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1656 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1657 llvm::FunctionType *FnTy =
1658 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1659 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1660 break;
1661 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001662 case OMPRTL__kmpc_omp_task_alloc: {
1663 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1664 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1665 // kmp_routine_entry_t *task_entry);
1666 assert(KmpRoutineEntryPtrTy != nullptr &&
1667 "Type kmp_routine_entry_t must be created.");
1668 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1669 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1670 // Return void * and then cast to particular kmp_task_t type.
1671 llvm::FunctionType *FnTy =
1672 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1673 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1674 break;
1675 }
1676 case OMPRTL__kmpc_omp_task: {
1677 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1678 // *new_task);
1679 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1680 CGM.VoidPtrTy};
1681 llvm::FunctionType *FnTy =
1682 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1683 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1684 break;
1685 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001686 case OMPRTL__kmpc_copyprivate: {
1687 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001688 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001689 // kmp_int32 didit);
1690 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1691 auto *CpyFnTy =
1692 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001693 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001694 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1695 CGM.Int32Ty};
1696 llvm::FunctionType *FnTy =
1697 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1698 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1699 break;
1700 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001701 case OMPRTL__kmpc_reduce: {
1702 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1703 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1704 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1705 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1706 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1707 /*isVarArg=*/false);
1708 llvm::Type *TypeParams[] = {
1709 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1710 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1711 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1712 llvm::FunctionType *FnTy =
1713 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1714 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1715 break;
1716 }
1717 case OMPRTL__kmpc_reduce_nowait: {
1718 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1719 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1720 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1721 // *lck);
1722 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1723 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1724 /*isVarArg=*/false);
1725 llvm::Type *TypeParams[] = {
1726 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1727 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1728 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1729 llvm::FunctionType *FnTy =
1730 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1731 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1732 break;
1733 }
1734 case OMPRTL__kmpc_end_reduce: {
1735 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1736 // kmp_critical_name *lck);
1737 llvm::Type *TypeParams[] = {
1738 getIdentTyPointerTy(), CGM.Int32Ty,
1739 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1740 llvm::FunctionType *FnTy =
1741 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1742 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1743 break;
1744 }
1745 case OMPRTL__kmpc_end_reduce_nowait: {
1746 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1747 // kmp_critical_name *lck);
1748 llvm::Type *TypeParams[] = {
1749 getIdentTyPointerTy(), CGM.Int32Ty,
1750 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1751 llvm::FunctionType *FnTy =
1752 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1753 RTLFn =
1754 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1755 break;
1756 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001757 case OMPRTL__kmpc_omp_task_begin_if0: {
1758 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1759 // *new_task);
1760 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1761 CGM.VoidPtrTy};
1762 llvm::FunctionType *FnTy =
1763 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1764 RTLFn =
1765 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1766 break;
1767 }
1768 case OMPRTL__kmpc_omp_task_complete_if0: {
1769 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1770 // *new_task);
1771 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1772 CGM.VoidPtrTy};
1773 llvm::FunctionType *FnTy =
1774 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1775 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1776 /*Name=*/"__kmpc_omp_task_complete_if0");
1777 break;
1778 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001779 case OMPRTL__kmpc_ordered: {
1780 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1781 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1782 llvm::FunctionType *FnTy =
1783 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1784 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1785 break;
1786 }
1787 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001788 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001789 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1790 llvm::FunctionType *FnTy =
1791 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1792 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1793 break;
1794 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001795 case OMPRTL__kmpc_omp_taskwait: {
1796 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1797 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1798 llvm::FunctionType *FnTy =
1799 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1800 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1801 break;
1802 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001803 case OMPRTL__kmpc_taskgroup: {
1804 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1805 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1806 llvm::FunctionType *FnTy =
1807 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1808 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1809 break;
1810 }
1811 case OMPRTL__kmpc_end_taskgroup: {
1812 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1813 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1814 llvm::FunctionType *FnTy =
1815 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1816 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1817 break;
1818 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001819 case OMPRTL__kmpc_push_proc_bind: {
1820 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1821 // int proc_bind)
1822 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1823 llvm::FunctionType *FnTy =
1824 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1825 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1826 break;
1827 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001828 case OMPRTL__kmpc_omp_task_with_deps: {
1829 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1830 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1831 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1832 llvm::Type *TypeParams[] = {
1833 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1834 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1835 llvm::FunctionType *FnTy =
1836 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1837 RTLFn =
1838 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1839 break;
1840 }
1841 case OMPRTL__kmpc_omp_wait_deps: {
1842 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1843 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1844 // kmp_depend_info_t *noalias_dep_list);
1845 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1846 CGM.Int32Ty, CGM.VoidPtrTy,
1847 CGM.Int32Ty, CGM.VoidPtrTy};
1848 llvm::FunctionType *FnTy =
1849 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1850 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1851 break;
1852 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001853 case OMPRTL__kmpc_cancellationpoint: {
1854 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1855 // global_tid, kmp_int32 cncl_kind)
1856 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1857 llvm::FunctionType *FnTy =
1858 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1859 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1860 break;
1861 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001862 case OMPRTL__kmpc_cancel: {
1863 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1864 // kmp_int32 cncl_kind)
1865 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1866 llvm::FunctionType *FnTy =
1867 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1868 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1869 break;
1870 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001871 case OMPRTL__kmpc_push_num_teams: {
1872 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1873 // kmp_int32 num_teams, kmp_int32 num_threads)
1874 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1875 CGM.Int32Ty};
1876 llvm::FunctionType *FnTy =
1877 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1878 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1879 break;
1880 }
1881 case OMPRTL__kmpc_fork_teams: {
1882 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1883 // microtask, ...);
1884 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1885 getKmpc_MicroPointerTy()};
1886 llvm::FunctionType *FnTy =
1887 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1888 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1889 break;
1890 }
Alexey Bataev7292c292016-04-25 12:22:29 +00001891 case OMPRTL__kmpc_taskloop: {
1892 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
1893 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
1894 // sched, kmp_uint64 grainsize, void *task_dup);
1895 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1896 CGM.IntTy,
1897 CGM.VoidPtrTy,
1898 CGM.IntTy,
1899 CGM.Int64Ty->getPointerTo(),
1900 CGM.Int64Ty->getPointerTo(),
1901 CGM.Int64Ty,
1902 CGM.IntTy,
1903 CGM.IntTy,
1904 CGM.Int64Ty,
1905 CGM.VoidPtrTy};
1906 llvm::FunctionType *FnTy =
1907 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1908 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
1909 break;
1910 }
Alexey Bataev8b427062016-05-25 12:36:08 +00001911 case OMPRTL__kmpc_doacross_init: {
1912 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
1913 // num_dims, struct kmp_dim *dims);
1914 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1915 CGM.Int32Ty,
1916 CGM.Int32Ty,
1917 CGM.VoidPtrTy};
1918 llvm::FunctionType *FnTy =
1919 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1920 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
1921 break;
1922 }
1923 case OMPRTL__kmpc_doacross_fini: {
1924 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
1925 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1926 llvm::FunctionType *FnTy =
1927 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1928 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
1929 break;
1930 }
1931 case OMPRTL__kmpc_doacross_post: {
1932 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
1933 // *vec);
1934 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1935 CGM.Int64Ty->getPointerTo()};
1936 llvm::FunctionType *FnTy =
1937 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1938 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
1939 break;
1940 }
1941 case OMPRTL__kmpc_doacross_wait: {
1942 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
1943 // *vec);
1944 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1945 CGM.Int64Ty->getPointerTo()};
1946 llvm::FunctionType *FnTy =
1947 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1948 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
1949 break;
1950 }
Samuel Antaobed3c462015-10-02 16:14:20 +00001951 case OMPRTL__tgt_target: {
1952 // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
1953 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
1954 // *arg_types);
1955 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1956 CGM.VoidPtrTy,
1957 CGM.Int32Ty,
1958 CGM.VoidPtrPtrTy,
1959 CGM.VoidPtrPtrTy,
1960 CGM.SizeTy->getPointerTo(),
1961 CGM.Int32Ty->getPointerTo()};
1962 llvm::FunctionType *FnTy =
1963 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1964 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
1965 break;
1966 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00001967 case OMPRTL__tgt_target_teams: {
1968 // Build int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
1969 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
1970 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
1971 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1972 CGM.VoidPtrTy,
1973 CGM.Int32Ty,
1974 CGM.VoidPtrPtrTy,
1975 CGM.VoidPtrPtrTy,
1976 CGM.SizeTy->getPointerTo(),
1977 CGM.Int32Ty->getPointerTo(),
1978 CGM.Int32Ty,
1979 CGM.Int32Ty};
1980 llvm::FunctionType *FnTy =
1981 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1982 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
1983 break;
1984 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00001985 case OMPRTL__tgt_register_lib: {
1986 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
1987 QualType ParamTy =
1988 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1989 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1990 llvm::FunctionType *FnTy =
1991 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1992 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
1993 break;
1994 }
1995 case OMPRTL__tgt_unregister_lib: {
1996 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
1997 QualType ParamTy =
1998 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1999 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
2000 llvm::FunctionType *FnTy =
2001 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2002 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
2003 break;
2004 }
Samuel Antaodf158d52016-04-27 22:58:19 +00002005 case OMPRTL__tgt_target_data_begin: {
2006 // Build void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
2007 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2008 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2009 CGM.Int32Ty,
2010 CGM.VoidPtrPtrTy,
2011 CGM.VoidPtrPtrTy,
2012 CGM.SizeTy->getPointerTo(),
2013 CGM.Int32Ty->getPointerTo()};
2014 llvm::FunctionType *FnTy =
2015 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2016 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
2017 break;
2018 }
2019 case OMPRTL__tgt_target_data_end: {
2020 // Build void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
2021 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2022 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2023 CGM.Int32Ty,
2024 CGM.VoidPtrPtrTy,
2025 CGM.VoidPtrPtrTy,
2026 CGM.SizeTy->getPointerTo(),
2027 CGM.Int32Ty->getPointerTo()};
2028 llvm::FunctionType *FnTy =
2029 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2030 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
2031 break;
2032 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00002033 case OMPRTL__tgt_target_data_update: {
2034 // Build void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
2035 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
2036 llvm::Type *TypeParams[] = {CGM.Int32Ty,
2037 CGM.Int32Ty,
2038 CGM.VoidPtrPtrTy,
2039 CGM.VoidPtrPtrTy,
2040 CGM.SizeTy->getPointerTo(),
2041 CGM.Int32Ty->getPointerTo()};
2042 llvm::FunctionType *FnTy =
2043 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2044 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
2045 break;
2046 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002047 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00002048 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00002049 return RTLFn;
2050}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002051
Alexander Musman21212e42015-03-13 10:38:23 +00002052llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
2053 bool IVSigned) {
2054 assert((IVSize == 32 || IVSize == 64) &&
2055 "IV size is not compatible with the omp runtime");
2056 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
2057 : "__kmpc_for_static_init_4u")
2058 : (IVSigned ? "__kmpc_for_static_init_8"
2059 : "__kmpc_for_static_init_8u");
2060 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2061 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2062 llvm::Type *TypeParams[] = {
2063 getIdentTyPointerTy(), // loc
2064 CGM.Int32Ty, // tid
2065 CGM.Int32Ty, // schedtype
2066 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2067 PtrTy, // p_lower
2068 PtrTy, // p_upper
2069 PtrTy, // p_stride
2070 ITy, // incr
2071 ITy // chunk
2072 };
2073 llvm::FunctionType *FnTy =
2074 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2075 return CGM.CreateRuntimeFunction(FnTy, Name);
2076}
2077
Alexander Musman92bdaab2015-03-12 13:37:50 +00002078llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
2079 bool IVSigned) {
2080 assert((IVSize == 32 || IVSize == 64) &&
2081 "IV size is not compatible with the omp runtime");
2082 auto Name =
2083 IVSize == 32
2084 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
2085 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
2086 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2087 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
2088 CGM.Int32Ty, // tid
2089 CGM.Int32Ty, // schedtype
2090 ITy, // lower
2091 ITy, // upper
2092 ITy, // stride
2093 ITy // chunk
2094 };
2095 llvm::FunctionType *FnTy =
2096 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
2097 return CGM.CreateRuntimeFunction(FnTy, Name);
2098}
2099
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002100llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
2101 bool IVSigned) {
2102 assert((IVSize == 32 || IVSize == 64) &&
2103 "IV size is not compatible with the omp runtime");
2104 auto Name =
2105 IVSize == 32
2106 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
2107 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
2108 llvm::Type *TypeParams[] = {
2109 getIdentTyPointerTy(), // loc
2110 CGM.Int32Ty, // tid
2111 };
2112 llvm::FunctionType *FnTy =
2113 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
2114 return CGM.CreateRuntimeFunction(FnTy, Name);
2115}
2116
Alexander Musman92bdaab2015-03-12 13:37:50 +00002117llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
2118 bool IVSigned) {
2119 assert((IVSize == 32 || IVSize == 64) &&
2120 "IV size is not compatible with the omp runtime");
2121 auto Name =
2122 IVSize == 32
2123 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
2124 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
2125 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
2126 auto PtrTy = llvm::PointerType::getUnqual(ITy);
2127 llvm::Type *TypeParams[] = {
2128 getIdentTyPointerTy(), // loc
2129 CGM.Int32Ty, // tid
2130 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
2131 PtrTy, // p_lower
2132 PtrTy, // p_upper
2133 PtrTy // p_stride
2134 };
2135 llvm::FunctionType *FnTy =
2136 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
2137 return CGM.CreateRuntimeFunction(FnTy, Name);
2138}
2139
Alexey Bataev97720002014-11-11 04:05:39 +00002140llvm::Constant *
2141CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002142 assert(!CGM.getLangOpts().OpenMPUseTLS ||
2143 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00002144 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002145 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002146 Twine(CGM.getMangledName(VD)) + ".cache.");
2147}
2148
John McCall7f416cc2015-09-08 08:05:57 +00002149Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
2150 const VarDecl *VD,
2151 Address VDAddr,
2152 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002153 if (CGM.getLangOpts().OpenMPUseTLS &&
2154 CGM.getContext().getTargetInfo().isTLSSupported())
2155 return VDAddr;
2156
John McCall7f416cc2015-09-08 08:05:57 +00002157 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002158 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002159 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2160 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002161 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
2162 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00002163 return Address(CGF.EmitRuntimeCall(
2164 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
2165 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00002166}
2167
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002168void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00002169 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00002170 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
2171 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
2172 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002173 auto OMPLoc = emitUpdateLocation(CGF, Loc);
2174 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00002175 OMPLoc);
2176 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
2177 // to register constructor/destructor for variable.
2178 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00002179 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
2180 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00002181 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00002182 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002183 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002184}
2185
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002186llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00002187 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00002188 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00002189 if (CGM.getLangOpts().OpenMPUseTLS &&
2190 CGM.getContext().getTargetInfo().isTLSSupported())
2191 return nullptr;
2192
Alexey Bataev97720002014-11-11 04:05:39 +00002193 VD = VD->getDefinition(CGM.getContext());
2194 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
2195 ThreadPrivateWithDefinition.insert(VD);
2196 QualType ASTTy = VD->getType();
2197
2198 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
2199 auto Init = VD->getAnyInitializer();
2200 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
2201 // Generate function that re-emits the declaration's initializer into the
2202 // threadprivate copy of the variable VD
2203 CodeGenFunction CtorCGF(CGM);
2204 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002205 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
2206 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002207 Args.push_back(&Dst);
2208
John McCallc56a8b32016-03-11 04:30:31 +00002209 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2210 CGM.getContext().VoidPtrTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002211 auto FTy = CGM.getTypes().GetFunctionType(FI);
2212 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002213 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002214 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
2215 Args, SourceLocation());
2216 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002217 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002218 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00002219 Address Arg = Address(ArgVal, VDAddr.getAlignment());
2220 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
2221 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00002222 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
2223 /*IsInitializer=*/true);
2224 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00002225 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00002226 CGM.getContext().VoidPtrTy, Dst.getLocation());
2227 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
2228 CtorCGF.FinishFunction();
2229 Ctor = Fn;
2230 }
2231 if (VD->getType().isDestructedType() != QualType::DK_none) {
2232 // Generate function that emits destructor call for the threadprivate copy
2233 // of the variable VD
2234 CodeGenFunction DtorCGF(CGM);
2235 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002236 ImplicitParamDecl Dst(CGM.getContext(), CGM.getContext().VoidPtrTy,
2237 ImplicitParamDecl::Other);
Alexey Bataev97720002014-11-11 04:05:39 +00002238 Args.push_back(&Dst);
2239
John McCallc56a8b32016-03-11 04:30:31 +00002240 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
2241 CGM.getContext().VoidTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00002242 auto FTy = CGM.getTypes().GetFunctionType(FI);
2243 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002244 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00002245 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002246 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
2247 SourceLocation());
Adrian Prantl1858c662016-04-24 22:22:29 +00002248 // Create a scope with an artificial location for the body of this function.
2249 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00002250 auto ArgVal = DtorCGF.EmitLoadOfScalar(
2251 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00002252 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
2253 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002254 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
2255 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
2256 DtorCGF.FinishFunction();
2257 Dtor = Fn;
2258 }
2259 // Do not emit init function if it is not required.
2260 if (!Ctor && !Dtor)
2261 return nullptr;
2262
2263 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
2264 auto CopyCtorTy =
2265 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
2266 /*isVarArg=*/false)->getPointerTo();
2267 // Copying constructor for the threadprivate variable.
2268 // Must be NULL - reserved by runtime, but currently it requires that this
2269 // parameter is always NULL. Otherwise it fires assertion.
2270 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
2271 if (Ctor == nullptr) {
2272 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
2273 /*isVarArg=*/false)->getPointerTo();
2274 Ctor = llvm::Constant::getNullValue(CtorTy);
2275 }
2276 if (Dtor == nullptr) {
2277 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
2278 /*isVarArg=*/false)->getPointerTo();
2279 Dtor = llvm::Constant::getNullValue(DtorTy);
2280 }
2281 if (!CGF) {
2282 auto InitFunctionTy =
2283 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
2284 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00002285 InitFunctionTy, ".__omp_threadprivate_init_.",
2286 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00002287 CodeGenFunction InitCGF(CGM);
2288 FunctionArgList ArgList;
2289 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
2290 CGM.getTypes().arrangeNullaryFunction(), ArgList,
2291 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002292 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002293 InitCGF.FinishFunction();
2294 return InitFunction;
2295 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002296 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00002297 }
2298 return nullptr;
2299}
2300
Alexey Bataev1d677132015-04-22 13:57:31 +00002301/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
2302/// function. Here is the logic:
2303/// if (Cond) {
2304/// ThenGen();
2305/// } else {
2306/// ElseGen();
2307/// }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00002308void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
2309 const RegionCodeGenTy &ThenGen,
2310 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00002311 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2312
2313 // If the condition constant folds and can be elided, try to avoid emitting
2314 // the condition and the dead arm of the if/else.
2315 bool CondConstant;
2316 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002317 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00002318 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002319 else
Alexey Bataev1d677132015-04-22 13:57:31 +00002320 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002321 return;
2322 }
2323
2324 // Otherwise, the condition did not fold, or we couldn't elide it. Just
2325 // emit the conditional branch.
2326 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
2327 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
2328 auto ContBlock = CGF.createBasicBlock("omp_if.end");
2329 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2330
2331 // Emit the 'then' code.
2332 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002333 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00002334 CGF.EmitBranch(ContBlock);
2335 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002336 // There is no need to emit line number for unconditional branch.
2337 (void)ApplyDebugLocation::CreateEmpty(CGF);
2338 CGF.EmitBlock(ElseBlock);
2339 ElseGen(CGF);
2340 // There is no need to emit line number for unconditional branch.
2341 (void)ApplyDebugLocation::CreateEmpty(CGF);
2342 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00002343 // Emit the continuation block for code after the if.
2344 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002345}
2346
Alexey Bataev1d677132015-04-22 13:57:31 +00002347void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2348 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00002349 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00002350 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002351 if (!CGF.HaveInsertPoint())
2352 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00002353 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002354 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
2355 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00002356 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002357 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002358 llvm::Value *Args[] = {
2359 RTLoc,
2360 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002361 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00002362 llvm::SmallVector<llvm::Value *, 16> RealArgs;
2363 RealArgs.append(std::begin(Args), std::end(Args));
2364 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2365
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002366 auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002367 CGF.EmitRuntimeCall(RTLFn, RealArgs);
2368 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002369 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
2370 PrePostActionTy &) {
2371 auto &RT = CGF.CGM.getOpenMPRuntime();
2372 auto ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00002373 // Build calls:
2374 // __kmpc_serialized_parallel(&Loc, GTid);
2375 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002376 CGF.EmitRuntimeCall(
2377 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002378
Alexey Bataev1d677132015-04-22 13:57:31 +00002379 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002380 auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00002381 Address ZeroAddr =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002382 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
2383 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00002384 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00002385 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2386 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2387 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
2388 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev1d677132015-04-22 13:57:31 +00002389 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002390
Alexey Bataev1d677132015-04-22 13:57:31 +00002391 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002392 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00002393 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002394 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
2395 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00002396 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002397 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00002398 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002399 else {
2400 RegionCodeGenTy ThenRCG(ThenGen);
2401 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00002402 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00002403}
2404
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00002405// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00002406// thread-ID variable (it is passed in a first argument of the outlined function
2407// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2408// regular serial code region, get thread ID by calling kmp_int32
2409// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2410// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002411Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2412 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002413 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002414 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002415 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002416 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002417
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002418 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002419 auto Int32Ty =
2420 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2421 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2422 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002423 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002424
2425 return ThreadIDTemp;
2426}
2427
Alexey Bataev97720002014-11-11 04:05:39 +00002428llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002429CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002430 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002431 SmallString<256> Buffer;
2432 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002433 Out << Name;
2434 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00002435 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
2436 if (Elem.second) {
2437 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002438 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002439 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002440 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002441
David Blaikie13156b62014-11-19 03:06:06 +00002442 return Elem.second = new llvm::GlobalVariable(
2443 CGM.getModule(), Ty, /*IsConstant*/ false,
2444 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2445 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002446}
2447
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002448llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00002449 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002450 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002451}
2452
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002453namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002454/// Common pre(post)-action for different OpenMP constructs.
2455class CommonActionTy final : public PrePostActionTy {
2456 llvm::Value *EnterCallee;
2457 ArrayRef<llvm::Value *> EnterArgs;
2458 llvm::Value *ExitCallee;
2459 ArrayRef<llvm::Value *> ExitArgs;
2460 bool Conditional;
2461 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002462
2463public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002464 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2465 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2466 bool Conditional = false)
2467 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2468 ExitArgs(ExitArgs), Conditional(Conditional) {}
2469 void Enter(CodeGenFunction &CGF) override {
2470 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2471 if (Conditional) {
2472 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2473 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2474 ContBlock = CGF.createBasicBlock("omp_if.end");
2475 // Generate the branch (If-stmt)
2476 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2477 CGF.EmitBlock(ThenBlock);
2478 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002479 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002480 void Done(CodeGenFunction &CGF) {
2481 // Emit the rest of blocks/branches
2482 CGF.EmitBranch(ContBlock);
2483 CGF.EmitBlock(ContBlock, true);
2484 }
2485 void Exit(CodeGenFunction &CGF) override {
2486 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002487 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002488};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002489} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002490
2491void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2492 StringRef CriticalName,
2493 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002494 SourceLocation Loc, const Expr *Hint) {
2495 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002496 // CriticalOpGen();
2497 // __kmpc_end_critical(ident_t *, gtid, Lock);
2498 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002499 if (!CGF.HaveInsertPoint())
2500 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002501 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2502 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002503 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2504 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002505 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002506 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2507 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2508 }
2509 CommonActionTy Action(
2510 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2511 : OMPRTL__kmpc_critical),
2512 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2513 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002514 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002515}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002516
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002517void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002518 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002519 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002520 if (!CGF.HaveInsertPoint())
2521 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002522 // if(__kmpc_master(ident_t *, gtid)) {
2523 // MasterOpGen();
2524 // __kmpc_end_master(ident_t *, gtid);
2525 // }
2526 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002527 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002528 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2529 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2530 /*Conditional=*/true);
2531 MasterOpGen.setAction(Action);
2532 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2533 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002534}
2535
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002536void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2537 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002538 if (!CGF.HaveInsertPoint())
2539 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00002540 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2541 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002542 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00002543 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002544 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002545 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2546 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00002547}
2548
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002549void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2550 const RegionCodeGenTy &TaskgroupOpGen,
2551 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002552 if (!CGF.HaveInsertPoint())
2553 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002554 // __kmpc_taskgroup(ident_t *, gtid);
2555 // TaskgroupOpGen();
2556 // __kmpc_end_taskgroup(ident_t *, gtid);
2557 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002558 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2559 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2560 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2561 Args);
2562 TaskgroupOpGen.setAction(Action);
2563 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002564}
2565
John McCall7f416cc2015-09-08 08:05:57 +00002566/// Given an array of pointers to variables, project the address of a
2567/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002568static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2569 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00002570 // Pull out the pointer to the variable.
2571 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002572 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00002573 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2574
2575 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002576 Addr = CGF.Builder.CreateElementBitCast(
2577 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002578 return Addr;
2579}
2580
Alexey Bataeva63048e2015-03-23 06:18:07 +00002581static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00002582 CodeGenModule &CGM, llvm::Type *ArgsType,
2583 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
2584 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002585 auto &C = CGM.getContext();
2586 // void copy_func(void *LHSArg, void *RHSArg);
2587 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002588 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
2589 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002590 Args.push_back(&LHSArg);
2591 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00002592 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002593 auto *Fn = llvm::Function::Create(
2594 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2595 ".omp.copyprivate.copy_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002596 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002597 CodeGenFunction CGF(CGM);
2598 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00002599 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002600 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00002601 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2602 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2603 ArgsType), CGF.getPointerAlign());
2604 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2605 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2606 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002607 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2608 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2609 // ...
2610 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00002611 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002612 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2613 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2614
2615 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2616 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2617
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002618 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2619 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00002620 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002621 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002622 CGF.FinishFunction();
2623 return Fn;
2624}
2625
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002626void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002627 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00002628 SourceLocation Loc,
2629 ArrayRef<const Expr *> CopyprivateVars,
2630 ArrayRef<const Expr *> SrcExprs,
2631 ArrayRef<const Expr *> DstExprs,
2632 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002633 if (!CGF.HaveInsertPoint())
2634 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002635 assert(CopyprivateVars.size() == SrcExprs.size() &&
2636 CopyprivateVars.size() == DstExprs.size() &&
2637 CopyprivateVars.size() == AssignmentOps.size());
2638 auto &C = CGM.getContext();
2639 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002640 // if(__kmpc_single(ident_t *, gtid)) {
2641 // SingleOpGen();
2642 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002643 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002644 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002645 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2646 // <copy_func>, did_it);
2647
John McCall7f416cc2015-09-08 08:05:57 +00002648 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00002649 if (!CopyprivateVars.empty()) {
2650 // int32 did_it = 0;
2651 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2652 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00002653 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002654 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002655 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002656 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002657 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
2658 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
2659 /*Conditional=*/true);
2660 SingleOpGen.setAction(Action);
2661 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2662 if (DidIt.isValid()) {
2663 // did_it = 1;
2664 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2665 }
2666 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002667 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2668 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00002669 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002670 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2671 auto CopyprivateArrayTy =
2672 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2673 /*IndexTypeQuals=*/0);
2674 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00002675 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00002676 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2677 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002678 Address Elem = CGF.Builder.CreateConstArrayGEP(
2679 CopyprivateList, I, CGF.getPointerSize());
2680 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00002681 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002682 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2683 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002684 }
2685 // Build function that copies private values from single region to all other
2686 // threads in the corresponding parallel region.
2687 auto *CpyFn = emitCopyprivateCopyFunction(
2688 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00002689 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev1189bd02016-01-26 12:20:39 +00002690 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00002691 Address CL =
2692 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2693 CGF.VoidPtrTy);
2694 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002695 llvm::Value *Args[] = {
2696 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2697 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00002698 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00002699 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00002700 CpyFn, // void (*) (void *, void *) <copy_func>
2701 DidItVal // i32 did_it
2702 };
2703 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2704 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002705}
2706
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002707void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2708 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00002709 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002710 if (!CGF.HaveInsertPoint())
2711 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002712 // __kmpc_ordered(ident_t *, gtid);
2713 // OrderedOpGen();
2714 // __kmpc_end_ordered(ident_t *, gtid);
2715 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00002716 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002717 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002718 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
2719 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2720 Args);
2721 OrderedOpGen.setAction(Action);
2722 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2723 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002724 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002725 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002726}
2727
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002728void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002729 OpenMPDirectiveKind Kind, bool EmitChecks,
2730 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002731 if (!CGF.HaveInsertPoint())
2732 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002733 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002734 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002735 unsigned Flags;
2736 if (Kind == OMPD_for)
2737 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2738 else if (Kind == OMPD_sections)
2739 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2740 else if (Kind == OMPD_single)
2741 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2742 else if (Kind == OMPD_barrier)
2743 Flags = OMP_IDENT_BARRIER_EXPL;
2744 else
2745 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002746 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2747 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002748 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2749 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002750 if (auto *OMPRegionInfo =
2751 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00002752 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002753 auto *Result = CGF.EmitRuntimeCall(
2754 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002755 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002756 // if (__kmpc_cancel_barrier()) {
2757 // exit from construct;
2758 // }
2759 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2760 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2761 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2762 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2763 CGF.EmitBlock(ExitBB);
2764 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002765 auto CancelDestination =
2766 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002767 CGF.EmitBranchThroughCleanup(CancelDestination);
2768 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2769 }
2770 return;
2771 }
2772 }
2773 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002774}
2775
Alexander Musmanc6388682014-12-15 07:07:06 +00002776/// \brief Map the OpenMP loop schedule to the runtime enumeration.
2777static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002778 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002779 switch (ScheduleKind) {
2780 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002781 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2782 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00002783 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002784 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002785 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002786 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002787 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002788 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2789 case OMPC_SCHEDULE_auto:
2790 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00002791 case OMPC_SCHEDULE_unknown:
2792 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002793 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00002794 }
2795 llvm_unreachable("Unexpected runtime schedule");
2796}
2797
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002798/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
2799static OpenMPSchedType
2800getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2801 // only static is allowed for dist_schedule
2802 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
2803}
2804
Alexander Musmanc6388682014-12-15 07:07:06 +00002805bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2806 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002807 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00002808 return Schedule == OMP_sch_static;
2809}
2810
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002811bool CGOpenMPRuntime::isStaticNonchunked(
2812 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2813 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2814 return Schedule == OMP_dist_sch_static;
2815}
2816
2817
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002818bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002819 auto Schedule =
2820 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002821 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2822 return Schedule != OMP_sch_static;
2823}
2824
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002825static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
2826 OpenMPScheduleClauseModifier M1,
2827 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00002828 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002829 switch (M1) {
2830 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002831 Modifier = OMP_sch_modifier_monotonic;
2832 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002833 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002834 Modifier = OMP_sch_modifier_nonmonotonic;
2835 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002836 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002837 if (Schedule == OMP_sch_static_chunked)
2838 Schedule = OMP_sch_static_balanced_chunked;
2839 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002840 case OMPC_SCHEDULE_MODIFIER_last:
2841 case OMPC_SCHEDULE_MODIFIER_unknown:
2842 break;
2843 }
2844 switch (M2) {
2845 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002846 Modifier = OMP_sch_modifier_monotonic;
2847 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002848 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002849 Modifier = OMP_sch_modifier_nonmonotonic;
2850 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002851 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002852 if (Schedule == OMP_sch_static_chunked)
2853 Schedule = OMP_sch_static_balanced_chunked;
2854 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002855 case OMPC_SCHEDULE_MODIFIER_last:
2856 case OMPC_SCHEDULE_MODIFIER_unknown:
2857 break;
2858 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00002859 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002860}
2861
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002862void CGOpenMPRuntime::emitForDispatchInit(
2863 CodeGenFunction &CGF, SourceLocation Loc,
2864 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
2865 bool Ordered, const DispatchRTInput &DispatchValues) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002866 if (!CGF.HaveInsertPoint())
2867 return;
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002868 OpenMPSchedType Schedule = getRuntimeSchedule(
2869 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00002870 assert(Ordered ||
2871 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00002872 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
2873 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00002874 // Call __kmpc_dispatch_init(
2875 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2876 // kmp_int[32|64] lower, kmp_int[32|64] upper,
2877 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002878
John McCall7f416cc2015-09-08 08:05:57 +00002879 // If the Chunk was not specified in the clause - use default value 1.
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002880 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk
2881 : CGF.Builder.getIntN(IVSize, 1);
John McCall7f416cc2015-09-08 08:05:57 +00002882 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002883 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2884 CGF.Builder.getInt32(addMonoNonMonoModifier(
2885 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
Carlo Bertollib0ff0a62017-04-25 17:52:12 +00002886 DispatchValues.LB, // Lower
2887 DispatchValues.UB, // Upper
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002888 CGF.Builder.getIntN(IVSize, 1), // Stride
2889 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00002890 };
2891 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2892}
2893
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002894static void emitForStaticInitCall(
2895 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
2896 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
2897 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
2898 unsigned IVSize, bool Ordered, Address IL, Address LB, Address UB,
2899 Address ST, llvm::Value *Chunk) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002900 if (!CGF.HaveInsertPoint())
2901 return;
2902
2903 assert(!Ordered);
2904 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
Alexey Bataev6cff6242016-05-30 13:05:14 +00002905 Schedule == OMP_sch_static_balanced_chunked ||
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002906 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
2907 Schedule == OMP_dist_sch_static ||
2908 Schedule == OMP_dist_sch_static_chunked);
2909
2910 // Call __kmpc_for_static_init(
2911 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2912 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2913 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2914 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
2915 if (Chunk == nullptr) {
2916 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
2917 Schedule == OMP_dist_sch_static) &&
2918 "expected static non-chunked schedule");
2919 // If the Chunk was not specified in the clause - use default value 1.
2920 Chunk = CGF.Builder.getIntN(IVSize, 1);
2921 } else {
2922 assert((Schedule == OMP_sch_static_chunked ||
Alexey Bataev6cff6242016-05-30 13:05:14 +00002923 Schedule == OMP_sch_static_balanced_chunked ||
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002924 Schedule == OMP_ord_static_chunked ||
2925 Schedule == OMP_dist_sch_static_chunked) &&
2926 "expected static chunked schedule");
2927 }
2928 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002929 UpdateLocation, ThreadId, CGF.Builder.getInt32(addMonoNonMonoModifier(
2930 Schedule, M1, M2)), // Schedule type
2931 IL.getPointer(), // &isLastIter
2932 LB.getPointer(), // &LB
2933 UB.getPointer(), // &UB
2934 ST.getPointer(), // &Stride
2935 CGF.Builder.getIntN(IVSize, 1), // Incr
2936 Chunk // Chunk
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002937 };
2938 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
2939}
2940
John McCall7f416cc2015-09-08 08:05:57 +00002941void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
2942 SourceLocation Loc,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002943 const OpenMPScheduleTy &ScheduleKind,
John McCall7f416cc2015-09-08 08:05:57 +00002944 unsigned IVSize, bool IVSigned,
2945 bool Ordered, Address IL, Address LB,
2946 Address UB, Address ST,
2947 llvm::Value *Chunk) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002948 OpenMPSchedType ScheduleNum =
2949 getRuntimeSchedule(ScheduleKind.Schedule, Chunk != nullptr, Ordered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002950 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2951 auto *ThreadId = getThreadID(CGF, Loc);
2952 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002953 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
2954 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, IVSize,
2955 Ordered, IL, LB, UB, ST, Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002956}
John McCall7f416cc2015-09-08 08:05:57 +00002957
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002958void CGOpenMPRuntime::emitDistributeStaticInit(
2959 CodeGenFunction &CGF, SourceLocation Loc,
2960 OpenMPDistScheduleClauseKind SchedKind, unsigned IVSize, bool IVSigned,
2961 bool Ordered, Address IL, Address LB, Address UB, Address ST,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002962 llvm::Value *Chunk) {
2963 OpenMPSchedType ScheduleNum = getRuntimeSchedule(SchedKind, Chunk != nullptr);
2964 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2965 auto *ThreadId = getThreadID(CGF, Loc);
2966 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002967 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
2968 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
2969 OMPC_SCHEDULE_MODIFIER_unknown, IVSize, Ordered, IL, LB,
2970 UB, ST, Chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002971}
2972
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002973void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
2974 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002975 if (!CGF.HaveInsertPoint())
2976 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00002977 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002978 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002979 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
2980 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00002981}
2982
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002983void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
2984 SourceLocation Loc,
2985 unsigned IVSize,
2986 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002987 if (!CGF.HaveInsertPoint())
2988 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002989 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002990 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002991 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
2992}
2993
Alexander Musman92bdaab2015-03-12 13:37:50 +00002994llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
2995 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00002996 bool IVSigned, Address IL,
2997 Address LB, Address UB,
2998 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00002999 // Call __kmpc_dispatch_next(
3000 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
3001 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
3002 // kmp_int[32|64] *p_stride);
3003 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00003004 emitUpdateLocation(CGF, Loc),
3005 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00003006 IL.getPointer(), // &isLastIter
3007 LB.getPointer(), // &Lower
3008 UB.getPointer(), // &Upper
3009 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00003010 };
3011 llvm::Value *Call =
3012 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
3013 return CGF.EmitScalarConversion(
3014 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003015 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00003016}
3017
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003018void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
3019 llvm::Value *NumThreads,
3020 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003021 if (!CGF.HaveInsertPoint())
3022 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00003023 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
3024 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003025 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00003026 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003027 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
3028 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00003029}
3030
Alexey Bataev7f210c62015-06-18 13:40:03 +00003031void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
3032 OpenMPProcBindClauseKind ProcBind,
3033 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003034 if (!CGF.HaveInsertPoint())
3035 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00003036 // Constants for proc bind value accepted by the runtime.
3037 enum ProcBindTy {
3038 ProcBindFalse = 0,
3039 ProcBindTrue,
3040 ProcBindMaster,
3041 ProcBindClose,
3042 ProcBindSpread,
3043 ProcBindIntel,
3044 ProcBindDefault
3045 } RuntimeProcBind;
3046 switch (ProcBind) {
3047 case OMPC_PROC_BIND_master:
3048 RuntimeProcBind = ProcBindMaster;
3049 break;
3050 case OMPC_PROC_BIND_close:
3051 RuntimeProcBind = ProcBindClose;
3052 break;
3053 case OMPC_PROC_BIND_spread:
3054 RuntimeProcBind = ProcBindSpread;
3055 break;
3056 case OMPC_PROC_BIND_unknown:
3057 llvm_unreachable("Unsupported proc_bind value.");
3058 }
3059 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
3060 llvm::Value *Args[] = {
3061 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
3062 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
3063 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
3064}
3065
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003066void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
3067 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00003068 if (!CGF.HaveInsertPoint())
3069 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00003070 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003071 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
3072 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00003073}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00003074
Alexey Bataev62b63b12015-03-10 07:28:44 +00003075namespace {
3076/// \brief Indexes of fields for type kmp_task_t.
3077enum KmpTaskTFields {
3078 /// \brief List of shared variables.
3079 KmpTaskTShareds,
3080 /// \brief Task routine.
3081 KmpTaskTRoutine,
3082 /// \brief Partition id for the untied tasks.
3083 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00003084 /// Function with call of destructors for private variables.
3085 Data1,
3086 /// Task priority.
3087 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00003088 /// (Taskloops only) Lower bound.
3089 KmpTaskTLowerBound,
3090 /// (Taskloops only) Upper bound.
3091 KmpTaskTUpperBound,
3092 /// (Taskloops only) Stride.
3093 KmpTaskTStride,
3094 /// (Taskloops only) Is last iteration flag.
3095 KmpTaskTLastIter,
Alexey Bataev62b63b12015-03-10 07:28:44 +00003096};
Hans Wennborg7eb54642015-09-10 17:07:54 +00003097} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00003098
Samuel Antaoee8fb302016-01-06 13:42:12 +00003099bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
3100 // FIXME: Add other entries type when they become supported.
3101 return OffloadEntriesTargetRegion.empty();
3102}
3103
3104/// \brief Initialize target region entry.
3105void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3106 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3107 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00003108 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003109 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3110 "only required for the device "
3111 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003112 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00003113 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
3114 /*Flags=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003115 ++OffloadingEntriesNum;
3116}
3117
3118void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3119 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
3120 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003121 llvm::Constant *Addr, llvm::Constant *ID,
3122 int32_t Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003123 // If we are emitting code for a target, the entry is already initialized,
3124 // only has to be registered.
3125 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003126 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00003127 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00003128 auto &Entry =
3129 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00003130 assert(Entry.isValid() && "Entry not initialized!");
3131 Entry.setAddress(Addr);
3132 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003133 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003134 return;
3135 } else {
Samuel Antaof83efdb2017-01-05 16:02:49 +00003136 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00003137 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003138 }
3139}
3140
3141bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00003142 unsigned DeviceID, unsigned FileID, StringRef ParentName,
3143 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003144 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3145 if (PerDevice == OffloadEntriesTargetRegion.end())
3146 return false;
3147 auto PerFile = PerDevice->second.find(FileID);
3148 if (PerFile == PerDevice->second.end())
3149 return false;
3150 auto PerParentName = PerFile->second.find(ParentName);
3151 if (PerParentName == PerFile->second.end())
3152 return false;
3153 auto PerLine = PerParentName->second.find(LineNum);
3154 if (PerLine == PerParentName->second.end())
3155 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00003156 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00003157 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00003158 return false;
3159 return true;
3160}
3161
3162void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3163 const OffloadTargetRegionEntryInfoActTy &Action) {
3164 // Scan all target region entries and perform the provided action.
3165 for (auto &D : OffloadEntriesTargetRegion)
3166 for (auto &F : D.second)
3167 for (auto &P : F.second)
3168 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00003169 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003170}
3171
3172/// \brief Create a Ctor/Dtor-like function whose body is emitted through
3173/// \a Codegen. This is used to emit the two functions that register and
3174/// unregister the descriptor of the current compilation unit.
3175static llvm::Function *
3176createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
3177 const RegionCodeGenTy &Codegen) {
3178 auto &C = CGM.getContext();
3179 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003180 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003181 Args.push_back(&DummyPtr);
3182
3183 CodeGenFunction CGF(CGM);
John McCallc56a8b32016-03-11 04:30:31 +00003184 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003185 auto FTy = CGM.getTypes().GetFunctionType(FI);
3186 auto *Fn =
3187 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
3188 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
3189 Codegen(CGF);
3190 CGF.FinishFunction();
3191 return Fn;
3192}
3193
3194llvm::Function *
3195CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
3196
3197 // If we don't have entries or if we are emitting code for the device, we
3198 // don't need to do anything.
3199 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
3200 return nullptr;
3201
3202 auto &M = CGM.getModule();
3203 auto &C = CGM.getContext();
3204
3205 // Get list of devices we care about
3206 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
3207
3208 // We should be creating an offloading descriptor only if there are devices
3209 // specified.
3210 assert(!Devices.empty() && "No OpenMP offloading devices??");
3211
3212 // Create the external variables that will point to the begin and end of the
3213 // host entries section. These will be defined by the linker.
3214 auto *OffloadEntryTy =
3215 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
3216 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
3217 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003218 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003219 ".omp_offloading.entries_begin");
3220 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
3221 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003222 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003223 ".omp_offloading.entries_end");
3224
3225 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00003226 auto *DeviceImageTy = cast<llvm::StructType>(
3227 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003228 ConstantInitBuilder DeviceImagesBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003229 auto DeviceImagesEntries = DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003230
3231 for (unsigned i = 0; i < Devices.size(); ++i) {
3232 StringRef T = Devices[i].getTriple();
3233 auto *ImgBegin = new llvm::GlobalVariable(
3234 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003235 /*Initializer=*/nullptr,
3236 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003237 auto *ImgEnd = new llvm::GlobalVariable(
3238 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00003239 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003240
John McCall6c9f1fdb2016-11-19 08:17:24 +00003241 auto Dev = DeviceImagesEntries.beginStruct(DeviceImageTy);
3242 Dev.add(ImgBegin);
3243 Dev.add(ImgEnd);
3244 Dev.add(HostEntriesBegin);
3245 Dev.add(HostEntriesEnd);
John McCallf1788632016-11-28 22:18:30 +00003246 Dev.finishAndAddTo(DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003247 }
3248
3249 // Create device images global array.
John McCall6c9f1fdb2016-11-19 08:17:24 +00003250 llvm::GlobalVariable *DeviceImages =
3251 DeviceImagesEntries.finishAndCreateGlobal(".omp_offloading.device_images",
3252 CGM.getPointerAlign(),
3253 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003254 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003255
3256 // This is a Zero array to be used in the creation of the constant expressions
3257 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
3258 llvm::Constant::getNullValue(CGM.Int32Ty)};
3259
3260 // Create the target region descriptor.
3261 auto *BinaryDescriptorTy = cast<llvm::StructType>(
3262 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00003263 ConstantInitBuilder DescBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003264 auto DescInit = DescBuilder.beginStruct(BinaryDescriptorTy);
3265 DescInit.addInt(CGM.Int32Ty, Devices.size());
3266 DescInit.add(llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
3267 DeviceImages,
3268 Index));
3269 DescInit.add(HostEntriesBegin);
3270 DescInit.add(HostEntriesEnd);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003271
John McCall6c9f1fdb2016-11-19 08:17:24 +00003272 auto *Desc = DescInit.finishAndCreateGlobal(".omp_offloading.descriptor",
3273 CGM.getPointerAlign(),
3274 /*isConstant=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003275
3276 // Emit code to register or unregister the descriptor at execution
3277 // startup or closing, respectively.
3278
3279 // Create a variable to drive the registration and unregistration of the
3280 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
3281 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
3282 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
Alexey Bataev56223232017-06-09 13:40:18 +00003283 IdentInfo, C.CharTy, ImplicitParamDecl::Other);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003284
3285 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003286 CGM, ".omp_offloading.descriptor_unreg",
3287 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003288 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
3289 Desc);
3290 });
3291 auto *RegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003292 CGM, ".omp_offloading.descriptor_reg",
3293 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00003294 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_register_lib),
3295 Desc);
3296 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
3297 });
George Rokos29d0f002017-05-27 03:03:13 +00003298 if (CGM.supportsCOMDAT()) {
3299 // It is sufficient to call registration function only once, so create a
3300 // COMDAT group for registration/unregistration functions and associated
3301 // data. That would reduce startup time and code size. Registration
3302 // function serves as a COMDAT group key.
3303 auto ComdatKey = M.getOrInsertComdat(RegFn->getName());
3304 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3305 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility);
3306 RegFn->setComdat(ComdatKey);
3307 UnRegFn->setComdat(ComdatKey);
3308 DeviceImages->setComdat(ComdatKey);
3309 Desc->setComdat(ComdatKey);
3310 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00003311 return RegFn;
3312}
3313
Samuel Antao2de62b02016-02-13 23:35:10 +00003314void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
Samuel Antaof83efdb2017-01-05 16:02:49 +00003315 llvm::Constant *Addr, uint64_t Size,
3316 int32_t Flags) {
Samuel Antao2de62b02016-02-13 23:35:10 +00003317 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00003318 auto *TgtOffloadEntryType = cast<llvm::StructType>(
3319 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
3320 llvm::LLVMContext &C = CGM.getModule().getContext();
3321 llvm::Module &M = CGM.getModule();
3322
3323 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00003324 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003325
3326 // Create constant string with the name.
3327 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3328
3329 llvm::GlobalVariable *Str =
3330 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
3331 llvm::GlobalValue::InternalLinkage, StrPtrInit,
3332 ".omp_offloading.entry_name");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003333 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003334 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
3335
John McCall6c9f1fdb2016-11-19 08:17:24 +00003336 // We can't have any padding between symbols, so we need to have 1-byte
3337 // alignment.
3338 auto Align = CharUnits::fromQuantity(1);
3339
Samuel Antaoee8fb302016-01-06 13:42:12 +00003340 // Create the entry struct.
John McCall23c9dc62016-11-28 22:18:27 +00003341 ConstantInitBuilder EntryBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003342 auto EntryInit = EntryBuilder.beginStruct(TgtOffloadEntryType);
3343 EntryInit.add(AddrPtr);
3344 EntryInit.add(StrPtr);
3345 EntryInit.addInt(CGM.SizeTy, Size);
Samuel Antaof83efdb2017-01-05 16:02:49 +00003346 EntryInit.addInt(CGM.Int32Ty, Flags);
3347 EntryInit.addInt(CGM.Int32Ty, 0);
John McCall6c9f1fdb2016-11-19 08:17:24 +00003348 llvm::GlobalVariable *Entry =
3349 EntryInit.finishAndCreateGlobal(".omp_offloading.entry",
3350 Align,
3351 /*constant*/ true,
3352 llvm::GlobalValue::ExternalLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003353
3354 // The entry has to be created in the section the linker expects it to be.
3355 Entry->setSection(".omp_offloading.entries");
Samuel Antaoee8fb302016-01-06 13:42:12 +00003356}
3357
3358void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3359 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00003360 // can easily figure out what to emit. The produced metadata looks like
3361 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00003362 //
3363 // !omp_offload.info = !{!1, ...}
3364 //
3365 // Right now we only generate metadata for function that contain target
3366 // regions.
3367
3368 // If we do not have entries, we dont need to do anything.
3369 if (OffloadEntriesInfoManager.empty())
3370 return;
3371
3372 llvm::Module &M = CGM.getModule();
3373 llvm::LLVMContext &C = M.getContext();
3374 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
3375 OrderedEntries(OffloadEntriesInfoManager.size());
3376
3377 // Create the offloading info metadata node.
3378 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
3379
Simon Pilgrim2c518802017-03-30 14:13:19 +00003380 // Auxiliary methods to create metadata values and strings.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003381 auto getMDInt = [&](unsigned v) {
3382 return llvm::ConstantAsMetadata::get(
3383 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
3384 };
3385
3386 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
3387
3388 // Create function that emits metadata for each target region entry;
3389 auto &&TargetRegionMetadataEmitter = [&](
3390 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00003391 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3392 llvm::SmallVector<llvm::Metadata *, 32> Ops;
3393 // Generate metadata for target regions. Each entry of this metadata
3394 // contains:
3395 // - Entry 0 -> Kind of this type of metadata (0).
3396 // - Entry 1 -> Device ID of the file where the entry was identified.
3397 // - Entry 2 -> File ID of the file where the entry was identified.
3398 // - Entry 3 -> Mangled name of the function where the entry was identified.
3399 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00003400 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003401 // The first element of the metadata node is the kind.
3402 Ops.push_back(getMDInt(E.getKind()));
3403 Ops.push_back(getMDInt(DeviceID));
3404 Ops.push_back(getMDInt(FileID));
3405 Ops.push_back(getMDString(ParentName));
3406 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003407 Ops.push_back(getMDInt(E.getOrder()));
3408
3409 // Save this entry in the right position of the ordered entries array.
3410 OrderedEntries[E.getOrder()] = &E;
3411
3412 // Add metadata to the named metadata node.
3413 MD->addOperand(llvm::MDNode::get(C, Ops));
3414 };
3415
3416 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3417 TargetRegionMetadataEmitter);
3418
3419 for (auto *E : OrderedEntries) {
3420 assert(E && "All ordered entries must exist!");
3421 if (auto *CE =
3422 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3423 E)) {
3424 assert(CE->getID() && CE->getAddress() &&
3425 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00003426 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003427 } else
3428 llvm_unreachable("Unsupported entry kind.");
3429 }
3430}
3431
3432/// \brief Loads all the offload entries information from the host IR
3433/// metadata.
3434void CGOpenMPRuntime::loadOffloadInfoMetadata() {
3435 // If we are in target mode, load the metadata from the host IR. This code has
3436 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
3437
3438 if (!CGM.getLangOpts().OpenMPIsDevice)
3439 return;
3440
3441 if (CGM.getLangOpts().OMPHostIRFile.empty())
3442 return;
3443
3444 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
3445 if (Buf.getError())
3446 return;
3447
3448 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00003449 auto ME = expectedToErrorOrAndEmitErrors(
3450 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003451
3452 if (ME.getError())
3453 return;
3454
3455 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
3456 if (!MD)
3457 return;
3458
3459 for (auto I : MD->operands()) {
3460 llvm::MDNode *MN = cast<llvm::MDNode>(I);
3461
3462 auto getMDInt = [&](unsigned Idx) {
3463 llvm::ConstantAsMetadata *V =
3464 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
3465 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
3466 };
3467
3468 auto getMDString = [&](unsigned Idx) {
3469 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
3470 return V->getString();
3471 };
3472
3473 switch (getMDInt(0)) {
3474 default:
3475 llvm_unreachable("Unexpected metadata!");
3476 break;
3477 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3478 OFFLOAD_ENTRY_INFO_TARGET_REGION:
3479 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
3480 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
3481 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00003482 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003483 break;
3484 }
3485 }
3486}
3487
Alexey Bataev62b63b12015-03-10 07:28:44 +00003488void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
3489 if (!KmpRoutineEntryPtrTy) {
3490 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
3491 auto &C = CGM.getContext();
3492 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
3493 FunctionProtoType::ExtProtoInfo EPI;
3494 KmpRoutineEntryPtrQTy = C.getPointerType(
3495 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
3496 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
3497 }
3498}
3499
Alexey Bataevc71a4092015-09-11 10:29:41 +00003500static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
3501 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003502 auto *Field = FieldDecl::Create(
3503 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
3504 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
3505 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
3506 Field->setAccess(AS_public);
3507 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003508 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003509}
3510
Samuel Antaoee8fb302016-01-06 13:42:12 +00003511QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
3512
3513 // Make sure the type of the entry is already created. This is the type we
3514 // have to create:
3515 // struct __tgt_offload_entry{
3516 // void *addr; // Pointer to the offload entry info.
3517 // // (function or global)
3518 // char *name; // Name of the function or global.
3519 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00003520 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
3521 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003522 // };
3523 if (TgtOffloadEntryQTy.isNull()) {
3524 ASTContext &C = CGM.getContext();
3525 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
3526 RD->startDefinition();
3527 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3528 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
3529 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00003530 addFieldToRecordDecl(
3531 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3532 addFieldToRecordDecl(
3533 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003534 RD->completeDefinition();
3535 TgtOffloadEntryQTy = C.getRecordType(RD);
3536 }
3537 return TgtOffloadEntryQTy;
3538}
3539
3540QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
3541 // These are the types we need to build:
3542 // struct __tgt_device_image{
3543 // void *ImageStart; // Pointer to the target code start.
3544 // void *ImageEnd; // Pointer to the target code end.
3545 // // We also add the host entries to the device image, as it may be useful
3546 // // for the target runtime to have access to that information.
3547 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
3548 // // the entries.
3549 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3550 // // entries (non inclusive).
3551 // };
3552 if (TgtDeviceImageQTy.isNull()) {
3553 ASTContext &C = CGM.getContext();
3554 auto *RD = C.buildImplicitRecord("__tgt_device_image");
3555 RD->startDefinition();
3556 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3557 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3558 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3559 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3560 RD->completeDefinition();
3561 TgtDeviceImageQTy = C.getRecordType(RD);
3562 }
3563 return TgtDeviceImageQTy;
3564}
3565
3566QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
3567 // struct __tgt_bin_desc{
3568 // int32_t NumDevices; // Number of devices supported.
3569 // __tgt_device_image *DeviceImages; // Arrays of device images
3570 // // (one per device).
3571 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
3572 // // entries.
3573 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3574 // // entries (non inclusive).
3575 // };
3576 if (TgtBinaryDescriptorQTy.isNull()) {
3577 ASTContext &C = CGM.getContext();
3578 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
3579 RD->startDefinition();
3580 addFieldToRecordDecl(
3581 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3582 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
3583 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3584 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3585 RD->completeDefinition();
3586 TgtBinaryDescriptorQTy = C.getRecordType(RD);
3587 }
3588 return TgtBinaryDescriptorQTy;
3589}
3590
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003591namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00003592struct PrivateHelpersTy {
3593 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
3594 const VarDecl *PrivateElemInit)
3595 : Original(Original), PrivateCopy(PrivateCopy),
3596 PrivateElemInit(PrivateElemInit) {}
3597 const VarDecl *Original;
3598 const VarDecl *PrivateCopy;
3599 const VarDecl *PrivateElemInit;
3600};
3601typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00003602} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003603
Alexey Bataev9e034042015-05-05 04:05:12 +00003604static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00003605createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003606 if (!Privates.empty()) {
3607 auto &C = CGM.getContext();
3608 // Build struct .kmp_privates_t. {
3609 // /* private vars */
3610 // };
3611 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
3612 RD->startDefinition();
3613 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00003614 auto *VD = Pair.second.Original;
3615 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003616 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00003617 auto *FD = addFieldToRecordDecl(C, RD, Type);
3618 if (VD->hasAttrs()) {
3619 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
3620 E(VD->getAttrs().end());
3621 I != E; ++I)
3622 FD->addAttr(*I);
3623 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003624 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003625 RD->completeDefinition();
3626 return RD;
3627 }
3628 return nullptr;
3629}
3630
Alexey Bataev9e034042015-05-05 04:05:12 +00003631static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00003632createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
3633 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003634 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003635 auto &C = CGM.getContext();
3636 // Build struct kmp_task_t {
3637 // void * shareds;
3638 // kmp_routine_entry_t routine;
3639 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00003640 // kmp_cmplrdata_t data1;
3641 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00003642 // For taskloops additional fields:
3643 // kmp_uint64 lb;
3644 // kmp_uint64 ub;
3645 // kmp_int64 st;
3646 // kmp_int32 liter;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003647 // };
Alexey Bataevad537bb2016-05-30 09:06:50 +00003648 auto *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
3649 UD->startDefinition();
3650 addFieldToRecordDecl(C, UD, KmpInt32Ty);
3651 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
3652 UD->completeDefinition();
3653 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003654 auto *RD = C.buildImplicitRecord("kmp_task_t");
3655 RD->startDefinition();
3656 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3657 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
3658 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00003659 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3660 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003661 if (isOpenMPTaskLoopDirective(Kind)) {
3662 QualType KmpUInt64Ty =
3663 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3664 QualType KmpInt64Ty =
3665 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3666 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3667 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3668 addFieldToRecordDecl(C, RD, KmpInt64Ty);
3669 addFieldToRecordDecl(C, RD, KmpInt32Ty);
3670 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003671 RD->completeDefinition();
3672 return RD;
3673}
3674
3675static RecordDecl *
3676createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003677 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003678 auto &C = CGM.getContext();
3679 // Build struct kmp_task_t_with_privates {
3680 // kmp_task_t task_data;
3681 // .kmp_privates_t. privates;
3682 // };
3683 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
3684 RD->startDefinition();
3685 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003686 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
3687 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
3688 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003689 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003690 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003691}
3692
3693/// \brief Emit a proxy function which accepts kmp_task_t as the second
3694/// argument.
3695/// \code
3696/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003697/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00003698/// For taskloops:
3699/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003700/// tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003701/// return 0;
3702/// }
3703/// \endcode
3704static llvm::Value *
3705emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00003706 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
3707 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003708 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003709 QualType SharedsPtrTy, llvm::Value *TaskFunction,
3710 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003711 auto &C = CGM.getContext();
3712 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003713 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3714 ImplicitParamDecl::Other);
3715 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3716 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3717 ImplicitParamDecl::Other);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003718 Args.push_back(&GtidArg);
3719 Args.push_back(&TaskTypeArg);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003720 auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003721 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003722 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
3723 auto *TaskEntry =
3724 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
3725 ".omp_task_entry.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003726 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003727 CodeGenFunction CGF(CGM);
3728 CGF.disableDebugInfo();
3729 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
3730
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003731 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00003732 // tt,
3733 // For taskloops:
3734 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3735 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003736 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00003737 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003738 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3739 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3740 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003741 auto *KmpTaskTWithPrivatesQTyRD =
3742 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003743 LValue Base =
3744 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003745 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3746 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3747 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003748 auto *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003749
3750 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3751 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003752 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003753 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003754 CGF.ConvertTypeForMem(SharedsPtrTy));
3755
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003756 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3757 llvm::Value *PrivatesParam;
3758 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3759 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3760 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003761 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003762 } else
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003763 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003764
Alexey Bataev7292c292016-04-25 12:22:29 +00003765 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
3766 TaskPrivatesMap,
3767 CGF.Builder
3768 .CreatePointerBitCastOrAddrSpaceCast(
3769 TDBase.getAddress(), CGF.VoidPtrTy)
3770 .getPointer()};
3771 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
3772 std::end(CommonArgs));
3773 if (isOpenMPTaskLoopDirective(Kind)) {
3774 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
3775 auto LBLVal = CGF.EmitLValueForField(Base, *LBFI);
3776 auto *LBParam = CGF.EmitLoadOfLValue(LBLVal, Loc).getScalarVal();
3777 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
3778 auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
3779 auto *UBParam = CGF.EmitLoadOfLValue(UBLVal, Loc).getScalarVal();
3780 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
3781 auto StLVal = CGF.EmitLValueForField(Base, *StFI);
3782 auto *StParam = CGF.EmitLoadOfLValue(StLVal, Loc).getScalarVal();
3783 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3784 auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
3785 auto *LIParam = CGF.EmitLoadOfLValue(LILVal, Loc).getScalarVal();
3786 CallArgs.push_back(LBParam);
3787 CallArgs.push_back(UBParam);
3788 CallArgs.push_back(StParam);
3789 CallArgs.push_back(LIParam);
3790 }
3791 CallArgs.push_back(SharedsParam);
3792
Alexey Bataev62b63b12015-03-10 07:28:44 +00003793 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
3794 CGF.EmitStoreThroughLValue(
3795 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00003796 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00003797 CGF.FinishFunction();
3798 return TaskEntry;
3799}
3800
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003801static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
3802 SourceLocation Loc,
3803 QualType KmpInt32Ty,
3804 QualType KmpTaskTWithPrivatesPtrQTy,
3805 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003806 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003807 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003808 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3809 ImplicitParamDecl::Other);
3810 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3811 KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3812 ImplicitParamDecl::Other);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003813 Args.push_back(&GtidArg);
3814 Args.push_back(&TaskTypeArg);
3815 FunctionType::ExtInfo Info;
3816 auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003817 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003818 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
3819 auto *DestructorFn =
3820 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
3821 ".omp_task_destructor.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003822 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
3823 DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003824 CodeGenFunction CGF(CGM);
3825 CGF.disableDebugInfo();
3826 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
3827 Args);
3828
Alexey Bataev31300ed2016-02-04 11:27:03 +00003829 LValue Base = CGF.EmitLoadOfPointerLValue(
3830 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3831 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003832 auto *KmpTaskTWithPrivatesQTyRD =
3833 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3834 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003835 Base = CGF.EmitLValueForField(Base, *FI);
3836 for (auto *Field :
3837 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
3838 if (auto DtorKind = Field->getType().isDestructedType()) {
3839 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
3840 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
3841 }
3842 }
3843 CGF.FinishFunction();
3844 return DestructorFn;
3845}
3846
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003847/// \brief Emit a privates mapping function for correct handling of private and
3848/// firstprivate variables.
3849/// \code
3850/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
3851/// **noalias priv1,..., <tyn> **noalias privn) {
3852/// *priv1 = &.privates.priv1;
3853/// ...;
3854/// *privn = &.privates.privn;
3855/// }
3856/// \endcode
3857static llvm::Value *
3858emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00003859 ArrayRef<const Expr *> PrivateVars,
3860 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00003861 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003862 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003863 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003864 auto &C = CGM.getContext();
3865 FunctionArgList Args;
3866 ImplicitParamDecl TaskPrivatesArg(
3867 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
Alexey Bataev56223232017-06-09 13:40:18 +00003868 C.getPointerType(PrivatesQTy).withConst().withRestrict(),
3869 ImplicitParamDecl::Other);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003870 Args.push_back(&TaskPrivatesArg);
3871 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
3872 unsigned Counter = 1;
3873 for (auto *E: PrivateVars) {
3874 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003875 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3876 C.getPointerType(C.getPointerType(E->getType()))
3877 .withConst()
3878 .withRestrict(),
3879 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003880 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3881 PrivateVarsPos[VD] = Counter;
3882 ++Counter;
3883 }
3884 for (auto *E : FirstprivateVars) {
3885 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003886 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3887 C.getPointerType(C.getPointerType(E->getType()))
3888 .withConst()
3889 .withRestrict(),
3890 ImplicitParamDecl::Other));
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003891 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3892 PrivateVarsPos[VD] = Counter;
3893 ++Counter;
3894 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003895 for (auto *E: LastprivateVars) {
3896 Args.push_back(ImplicitParamDecl::Create(
Alexey Bataev56223232017-06-09 13:40:18 +00003897 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3898 C.getPointerType(C.getPointerType(E->getType()))
3899 .withConst()
3900 .withRestrict(),
3901 ImplicitParamDecl::Other));
Alexey Bataevf93095a2016-05-05 08:46:22 +00003902 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3903 PrivateVarsPos[VD] = Counter;
3904 ++Counter;
3905 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003906 auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003907 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003908 auto *TaskPrivatesMapTy =
3909 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
3910 auto *TaskPrivatesMap = llvm::Function::Create(
3911 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
3912 ".omp_task_privates_map.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003913 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
3914 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00003915 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Mehdi Amini6aa9e9b2017-05-29 05:38:20 +00003916 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00003917 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003918 CodeGenFunction CGF(CGM);
3919 CGF.disableDebugInfo();
3920 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
3921 TaskPrivatesMapFnInfo, Args);
3922
3923 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003924 LValue Base = CGF.EmitLoadOfPointerLValue(
3925 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
3926 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003927 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
3928 Counter = 0;
3929 for (auto *Field : PrivatesQTyRD->fields()) {
3930 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
3931 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00003932 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00003933 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
3934 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00003935 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003936 ++Counter;
3937 }
3938 CGF.FinishFunction();
3939 return TaskPrivatesMap;
3940}
3941
Alexey Bataev9e034042015-05-05 04:05:12 +00003942static int array_pod_sort_comparator(const PrivateDataTy *P1,
3943 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003944 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
3945}
3946
Alexey Bataevf93095a2016-05-05 08:46:22 +00003947/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00003948static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00003949 const OMPExecutableDirective &D,
3950 Address KmpTaskSharedsPtr, LValue TDBase,
3951 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
3952 QualType SharedsTy, QualType SharedsPtrTy,
3953 const OMPTaskDataTy &Data,
3954 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
3955 auto &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00003956 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3957 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
3958 LValue SrcBase;
3959 if (!Data.FirstprivateVars.empty()) {
3960 SrcBase = CGF.MakeAddrLValue(
3961 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3962 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
3963 SharedsTy);
3964 }
3965 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
3966 cast<CapturedStmt>(*D.getAssociatedStmt()));
3967 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
3968 for (auto &&Pair : Privates) {
3969 auto *VD = Pair.second.PrivateCopy;
3970 auto *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00003971 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
3972 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00003973 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003974 if (auto *Elem = Pair.second.PrivateElemInit) {
3975 auto *OriginalVD = Pair.second.Original;
3976 auto *SharedField = CapturesInfo.lookup(OriginalVD);
3977 auto SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
3978 SharedRefLValue = CGF.MakeAddrLValue(
3979 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003980 SharedRefLValue.getType(),
3981 LValueBaseInfo(AlignmentSource::Decl,
3982 SharedRefLValue.getBaseInfo().getMayAlias()));
Alexey Bataevf93095a2016-05-05 08:46:22 +00003983 QualType Type = OriginalVD->getType();
3984 if (Type->isArrayType()) {
3985 // Initialize firstprivate array.
3986 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
3987 // Perform simple memcpy.
3988 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
3989 SharedRefLValue.getAddress(), Type);
3990 } else {
3991 // Initialize firstprivate array using element-by-element
Simon Pilgrim2c518802017-03-30 14:13:19 +00003992 // initialization.
Alexey Bataevf93095a2016-05-05 08:46:22 +00003993 CGF.EmitOMPAggregateAssign(
3994 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
3995 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
3996 Address SrcElement) {
3997 // Clean up any temporaries needed by the initialization.
3998 CodeGenFunction::OMPPrivateScope InitScope(CGF);
3999 InitScope.addPrivate(
4000 Elem, [SrcElement]() -> Address { return SrcElement; });
4001 (void)InitScope.Privatize();
4002 // Emit initialization for single element.
4003 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
4004 CGF, &CapturesInfo);
4005 CGF.EmitAnyExprToMem(Init, DestElement,
4006 Init->getType().getQualifiers(),
4007 /*IsInitializer=*/false);
4008 });
4009 }
4010 } else {
4011 CodeGenFunction::OMPPrivateScope InitScope(CGF);
4012 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
4013 return SharedRefLValue.getAddress();
4014 });
4015 (void)InitScope.Privatize();
4016 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
4017 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
4018 /*capturedByInit=*/false);
4019 }
4020 } else
4021 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
4022 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004023 ++FI;
4024 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004025}
4026
4027/// Check if duplication function is required for taskloops.
4028static bool checkInitIsRequired(CodeGenFunction &CGF,
4029 ArrayRef<PrivateDataTy> Privates) {
4030 bool InitRequired = false;
4031 for (auto &&Pair : Privates) {
4032 auto *VD = Pair.second.PrivateCopy;
4033 auto *Init = VD->getAnyInitializer();
4034 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
4035 !CGF.isTrivialInitializer(Init));
4036 }
4037 return InitRequired;
4038}
4039
4040
4041/// Emit task_dup function (for initialization of
4042/// private/firstprivate/lastprivate vars and last_iter flag)
4043/// \code
4044/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
4045/// lastpriv) {
4046/// // setup lastprivate flag
4047/// task_dst->last = lastpriv;
4048/// // could be constructor calls here...
4049/// }
4050/// \endcode
4051static llvm::Value *
4052emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
4053 const OMPExecutableDirective &D,
4054 QualType KmpTaskTWithPrivatesPtrQTy,
4055 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4056 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
4057 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
4058 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
4059 auto &C = CGM.getContext();
4060 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004061 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4062 KmpTaskTWithPrivatesPtrQTy,
4063 ImplicitParamDecl::Other);
4064 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
4065 KmpTaskTWithPrivatesPtrQTy,
4066 ImplicitParamDecl::Other);
4067 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
4068 ImplicitParamDecl::Other);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004069 Args.push_back(&DstArg);
4070 Args.push_back(&SrcArg);
4071 Args.push_back(&LastprivArg);
4072 auto &TaskDupFnInfo =
4073 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
4074 auto *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
4075 auto *TaskDup =
4076 llvm::Function::Create(TaskDupTy, llvm::GlobalValue::InternalLinkage,
4077 ".omp_task_dup.", &CGM.getModule());
4078 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskDup, TaskDupFnInfo);
4079 CodeGenFunction CGF(CGM);
4080 CGF.disableDebugInfo();
4081 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args);
4082
4083 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4084 CGF.GetAddrOfLocalVar(&DstArg),
4085 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4086 // task_dst->liter = lastpriv;
4087 if (WithLastIter) {
4088 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4089 LValue Base = CGF.EmitLValueForField(
4090 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4091 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4092 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4093 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4094 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4095 }
4096
4097 // Emit initial values for private copies (if any).
4098 assert(!Privates.empty());
4099 Address KmpTaskSharedsPtr = Address::invalid();
4100 if (!Data.FirstprivateVars.empty()) {
4101 LValue TDBase = CGF.EmitLoadOfPointerLValue(
4102 CGF.GetAddrOfLocalVar(&SrcArg),
4103 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4104 LValue Base = CGF.EmitLValueForField(
4105 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4106 KmpTaskSharedsPtr = Address(
4107 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4108 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4109 KmpTaskTShareds)),
4110 Loc),
4111 CGF.getNaturalTypeAlignment(SharedsTy));
4112 }
Alexey Bataev8a831592016-05-10 10:36:51 +00004113 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4114 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004115 CGF.FinishFunction();
4116 return TaskDup;
4117}
4118
Alexey Bataev8a831592016-05-10 10:36:51 +00004119/// Checks if destructor function is required to be generated.
4120/// \return true if cleanups are required, false otherwise.
4121static bool
4122checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
4123 bool NeedsCleanup = false;
4124 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4125 auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
4126 for (auto *FD : PrivateRD->fields()) {
4127 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
4128 if (NeedsCleanup)
4129 break;
4130 }
4131 return NeedsCleanup;
4132}
4133
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004134CGOpenMPRuntime::TaskResultTy
4135CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4136 const OMPExecutableDirective &D,
4137 llvm::Value *TaskFunction, QualType SharedsTy,
4138 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004139 auto &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00004140 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004141 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004142 auto I = Data.PrivateCopies.begin();
4143 for (auto *E : Data.PrivateVars) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004144 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4145 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004146 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004147 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4148 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004149 ++I;
4150 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004151 I = Data.FirstprivateCopies.begin();
4152 auto IElemInitRef = Data.FirstprivateInits.begin();
4153 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev9e034042015-05-05 04:05:12 +00004154 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4155 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00004156 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00004157 PrivateHelpersTy(
4158 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4159 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
Richard Trieucc3949d2016-02-18 22:34:54 +00004160 ++I;
4161 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00004162 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00004163 I = Data.LastprivateCopies.begin();
4164 for (auto *E : Data.LastprivateVars) {
4165 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4166 Privates.push_back(std::make_pair(
4167 C.getDeclAlign(VD),
4168 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4169 /*PrivateElemInit=*/nullptr)));
4170 ++I;
4171 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004172 llvm::array_pod_sort(Privates.begin(), Privates.end(),
4173 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004174 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
4175 // Build type kmp_routine_entry_t (if not built yet).
4176 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004177 // Build type kmp_task_t (if not built yet).
4178 if (KmpTaskTQTy.isNull()) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004179 KmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4180 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004181 }
4182 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004183 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004184 auto *KmpTaskTWithPrivatesQTyRD =
4185 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
4186 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
4187 QualType KmpTaskTWithPrivatesPtrQTy =
4188 C.getPointerType(KmpTaskTWithPrivatesQTy);
4189 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4190 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004191 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004192 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4193
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004194 // Emit initial values for private copies (if any).
4195 llvm::Value *TaskPrivatesMap = nullptr;
4196 auto *TaskPrivatesMapTy =
Reid Klecknere258c442017-03-16 18:55:46 +00004197 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004198 if (!Privates.empty()) {
4199 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00004200 TaskPrivatesMap = emitTaskPrivateMappingFunction(
4201 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
4202 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00004203 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4204 TaskPrivatesMap, TaskPrivatesMapTy);
4205 } else {
4206 TaskPrivatesMap = llvm::ConstantPointerNull::get(
4207 cast<llvm::PointerType>(TaskPrivatesMapTy));
4208 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004209 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4210 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004211 auto *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00004212 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4213 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4214 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004215
4216 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4217 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4218 // kmp_routine_entry_t *task_entry);
4219 // Task flags. Format is taken from
4220 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
4221 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004222 enum {
4223 TiedFlag = 0x1,
4224 FinalFlag = 0x2,
4225 DestructorsFlag = 0x8,
4226 PriorityFlag = 0x20
4227 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004228 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00004229 bool NeedsCleanup = false;
4230 if (!Privates.empty()) {
4231 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
4232 if (NeedsCleanup)
4233 Flags = Flags | DestructorsFlag;
4234 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00004235 if (Data.Priority.getInt())
4236 Flags = Flags | PriorityFlag;
Alexey Bataev62b63b12015-03-10 07:28:44 +00004237 auto *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004238 Data.Final.getPointer()
4239 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00004240 CGF.Builder.getInt32(FinalFlag),
4241 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004242 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00004243 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00004244 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004245 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
4246 getThreadID(CGF, Loc), TaskFlags,
4247 KmpTaskTWithPrivatesTySize, SharedsSize,
4248 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4249 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00004250 auto *NewTask = CGF.EmitRuntimeCall(
4251 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004252 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4253 NewTask, KmpTaskTWithPrivatesPtrTy);
4254 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4255 KmpTaskTWithPrivatesQTy);
4256 LValue TDBase =
4257 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00004258 // Fill the data in the resulting kmp_task_t record.
4259 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00004260 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004261 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00004262 KmpTaskSharedsPtr =
4263 Address(CGF.EmitLoadOfScalar(
4264 CGF.EmitLValueForField(
4265 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4266 KmpTaskTShareds)),
4267 Loc),
4268 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004269 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00004270 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004271 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00004272 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004273 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00004274 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4275 SharedsTy, SharedsPtrTy, Data, Privates,
4276 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00004277 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4278 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
4279 Result.TaskDupFn = emitTaskDupFunction(
4280 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4281 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4282 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00004283 }
4284 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00004285 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4286 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00004287 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00004288 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
4289 auto *KmpCmplrdataUD = (*FI)->getType()->getAsUnionType()->getDecl();
4290 if (NeedsCleanup) {
4291 llvm::Value *DestructorFn = emitDestructorsFunction(
4292 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4293 KmpTaskTWithPrivatesQTy);
4294 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4295 LValue DestructorsLV = CGF.EmitLValueForField(
4296 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4297 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4298 DestructorFn, KmpRoutineEntryPtrTy),
4299 DestructorsLV);
4300 }
4301 // Set priority.
4302 if (Data.Priority.getInt()) {
4303 LValue Data2LV = CGF.EmitLValueForField(
4304 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
4305 LValue PriorityLV = CGF.EmitLValueForField(
4306 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
4307 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
4308 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004309 Result.NewTask = NewTask;
4310 Result.TaskEntry = TaskEntry;
4311 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
4312 Result.TDBase = TDBase;
4313 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
4314 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00004315}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004316
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004317void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
4318 const OMPExecutableDirective &D,
4319 llvm::Value *TaskFunction,
4320 QualType SharedsTy, Address Shareds,
4321 const Expr *IfCond,
4322 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004323 if (!CGF.HaveInsertPoint())
4324 return;
4325
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004326 TaskResultTy Result =
4327 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
4328 llvm::Value *NewTask = Result.NewTask;
4329 llvm::Value *TaskEntry = Result.TaskEntry;
4330 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
4331 LValue TDBase = Result.TDBase;
4332 RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
Alexey Bataev7292c292016-04-25 12:22:29 +00004333 auto &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004334 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00004335 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004336 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00004337 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004338 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00004339 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004340 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
4341 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004342 QualType FlagsTy =
4343 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004344 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
4345 if (KmpDependInfoTy.isNull()) {
4346 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
4347 KmpDependInfoRD->startDefinition();
4348 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
4349 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
4350 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
4351 KmpDependInfoRD->completeDefinition();
4352 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004353 } else
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004354 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
John McCall7f416cc2015-09-08 08:05:57 +00004355 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004356 // Define type kmp_depend_info[<Dependences.size()>];
4357 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00004358 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004359 ArrayType::Normal, /*IndexTypeQuals=*/0);
4360 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00004361 DependenciesArray =
4362 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
John McCall7f416cc2015-09-08 08:05:57 +00004363 for (unsigned i = 0; i < NumDependencies; ++i) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004364 const Expr *E = Data.Dependences[i].second;
John McCall7f416cc2015-09-08 08:05:57 +00004365 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004366 llvm::Value *Size;
4367 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004368 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
4369 LValue UpAddrLVal =
4370 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
4371 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00004372 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004373 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00004374 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00004375 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
4376 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004377 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00004378 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00004379 auto Base = CGF.MakeAddrLValue(
4380 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004381 KmpDependInfoTy);
4382 // deps[i].base_addr = &<Dependences[i].second>;
4383 auto BaseAddrLVal = CGF.EmitLValueForField(
4384 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00004385 CGF.EmitStoreOfScalar(
4386 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
4387 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004388 // deps[i].len = sizeof(<Dependences[i].second>);
4389 auto LenLVal = CGF.EmitLValueForField(
4390 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
4391 CGF.EmitStoreOfScalar(Size, LenLVal);
4392 // deps[i].flags = <Dependences[i].first>;
4393 RTLDependenceKindTy DepKind;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004394 switch (Data.Dependences[i].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004395 case OMPC_DEPEND_in:
4396 DepKind = DepIn;
4397 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00004398 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004399 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004400 case OMPC_DEPEND_inout:
4401 DepKind = DepInOut;
4402 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00004403 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004404 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004405 case OMPC_DEPEND_unknown:
4406 llvm_unreachable("Unknown task dependence type");
4407 }
4408 auto FlagsLVal = CGF.EmitLValueForField(
4409 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
4410 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
4411 FlagsLVal);
4412 }
John McCall7f416cc2015-09-08 08:05:57 +00004413 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4414 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004415 CGF.VoidPtrTy);
4416 }
4417
Alexey Bataev62b63b12015-03-10 07:28:44 +00004418 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4419 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004420 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
4421 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
4422 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
4423 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00004424 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004425 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00004426 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
4427 llvm::Value *DepTaskArgs[7];
4428 if (NumDependencies) {
4429 DepTaskArgs[0] = UpLoc;
4430 DepTaskArgs[1] = ThreadID;
4431 DepTaskArgs[2] = NewTask;
4432 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
4433 DepTaskArgs[4] = DependenciesArray.getPointer();
4434 DepTaskArgs[5] = CGF.Builder.getInt32(0);
4435 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4436 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00004437 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
4438 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004439 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004440 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004441 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4442 auto PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
4443 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
4444 }
John McCall7f416cc2015-09-08 08:05:57 +00004445 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004446 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00004447 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00004448 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004449 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00004450 TaskArgs);
4451 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00004452 // Check if parent region is untied and build return for untied task;
4453 if (auto *Region =
4454 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4455 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00004456 };
John McCall7f416cc2015-09-08 08:05:57 +00004457
4458 llvm::Value *DepWaitTaskArgs[6];
4459 if (NumDependencies) {
4460 DepWaitTaskArgs[0] = UpLoc;
4461 DepWaitTaskArgs[1] = ThreadID;
4462 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
4463 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
4464 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
4465 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4466 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004467 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
4468 NumDependencies, &DepWaitTaskArgs](CodeGenFunction &CGF,
4469 PrePostActionTy &) {
4470 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004471 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
4472 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
4473 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
4474 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
4475 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00004476 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004477 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004478 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004479 // Call proxy_task_entry(gtid, new_task);
4480 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy](
4481 CodeGenFunction &CGF, PrePostActionTy &Action) {
4482 Action.Enter(CGF);
4483 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
4484 CGF.EmitCallOrInvoke(TaskEntry, OutlinedFnArgs);
4485 };
4486
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004487 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
4488 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004489 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
4490 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004491 RegionCodeGenTy RCG(CodeGen);
4492 CommonActionTy Action(
4493 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
4494 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
4495 RCG.setAction(Action);
4496 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004497 };
John McCall7f416cc2015-09-08 08:05:57 +00004498
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004499 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00004500 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004501 else {
4502 RegionCodeGenTy ThenRCG(ThenCodeGen);
4503 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00004504 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004505}
4506
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004507void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
4508 const OMPLoopDirective &D,
4509 llvm::Value *TaskFunction,
4510 QualType SharedsTy, Address Shareds,
4511 const Expr *IfCond,
4512 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004513 if (!CGF.HaveInsertPoint())
4514 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004515 TaskResultTy Result =
4516 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004517 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4518 // libcall.
4519 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
4520 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
4521 // sched, kmp_uint64 grainsize, void *task_dup);
4522 llvm::Value *ThreadID = getThreadID(CGF, Loc);
4523 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
4524 llvm::Value *IfVal;
4525 if (IfCond) {
4526 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
4527 /*isSigned=*/true);
4528 } else
4529 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
4530
4531 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004532 Result.TDBase,
4533 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004534 auto *LBVar =
4535 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
4536 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
4537 /*IsInitializer=*/true);
4538 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004539 Result.TDBase,
4540 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004541 auto *UBVar =
4542 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
4543 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
4544 /*IsInitializer=*/true);
4545 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004546 Result.TDBase,
4547 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataev7292c292016-04-25 12:22:29 +00004548 auto *StVar =
4549 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
4550 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
4551 /*IsInitializer=*/true);
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004552 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00004553 llvm::Value *TaskArgs[] = {
Alexey Bataev33446032017-07-12 18:09:32 +00004554 UpLoc,
4555 ThreadID,
4556 Result.NewTask,
4557 IfVal,
4558 LBLVal.getPointer(),
4559 UBLVal.getPointer(),
4560 CGF.EmitLoadOfScalar(StLVal, SourceLocation()),
4561 llvm::ConstantInt::getNullValue(
4562 CGF.IntTy), // Always 0 because taskgroup emitted by the compiler
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004563 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004564 CGF.IntTy, Data.Schedule.getPointer()
4565 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004566 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004567 Data.Schedule.getPointer()
4568 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004569 /*isSigned=*/false)
4570 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataev33446032017-07-12 18:09:32 +00004571 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4572 Result.TaskDupFn, CGF.VoidPtrTy)
4573 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00004574 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
4575}
4576
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004577/// \brief Emit reduction operation for each element of array (required for
4578/// array sections) LHS op = RHS.
4579/// \param Type Type of array.
4580/// \param LHSVar Variable on the left side of the reduction operation
4581/// (references element of array in original variable).
4582/// \param RHSVar Variable on the right side of the reduction operation
4583/// (references element of array in original variable).
4584/// \param RedOpGen Generator of reduction operation with use of LHSVar and
4585/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00004586static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004587 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
4588 const VarDecl *RHSVar,
4589 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
4590 const Expr *, const Expr *)> &RedOpGen,
4591 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
4592 const Expr *UpExpr = nullptr) {
4593 // Perform element-by-element initialization.
4594 QualType ElementTy;
4595 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
4596 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
4597
4598 // Drill down to the base element type on both arrays.
4599 auto ArrayTy = Type->getAsArrayTypeUnsafe();
4600 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
4601
4602 auto RHSBegin = RHSAddr.getPointer();
4603 auto LHSBegin = LHSAddr.getPointer();
4604 // Cast from pointer to array type to pointer to single element.
4605 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
4606 // The basic structure here is a while-do loop.
4607 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
4608 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
4609 auto IsEmpty =
4610 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
4611 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
4612
4613 // Enter the loop body, making that address the current address.
4614 auto EntryBB = CGF.Builder.GetInsertBlock();
4615 CGF.EmitBlock(BodyBB);
4616
4617 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
4618
4619 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
4620 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
4621 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
4622 Address RHSElementCurrent =
4623 Address(RHSElementPHI,
4624 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4625
4626 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
4627 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
4628 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
4629 Address LHSElementCurrent =
4630 Address(LHSElementPHI,
4631 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4632
4633 // Emit copy.
4634 CodeGenFunction::OMPPrivateScope Scope(CGF);
4635 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
4636 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
4637 Scope.Privatize();
4638 RedOpGen(CGF, XExpr, EExpr, UpExpr);
4639 Scope.ForceCleanup();
4640
4641 // Shift the address forward by one element.
4642 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
4643 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
4644 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
4645 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
4646 // Check whether we've reached the end.
4647 auto Done =
4648 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
4649 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
4650 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
4651 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
4652
4653 // Done.
4654 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
4655}
4656
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004657/// Emit reduction combiner. If the combiner is a simple expression emit it as
4658/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
4659/// UDR combiner function.
4660static void emitReductionCombiner(CodeGenFunction &CGF,
4661 const Expr *ReductionOp) {
4662 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
4663 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
4664 if (auto *DRE =
4665 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
4666 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
4667 std::pair<llvm::Function *, llvm::Function *> Reduction =
4668 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
4669 RValue Func = RValue::get(Reduction.first);
4670 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
4671 CGF.EmitIgnoredExpr(ReductionOp);
4672 return;
4673 }
4674 CGF.EmitIgnoredExpr(ReductionOp);
4675}
4676
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004677llvm::Value *CGOpenMPRuntime::emitReductionFunction(
4678 CodeGenModule &CGM, llvm::Type *ArgsType, ArrayRef<const Expr *> Privates,
4679 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs,
4680 ArrayRef<const Expr *> ReductionOps) {
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004681 auto &C = CGM.getContext();
4682
4683 // void reduction_func(void *LHSArg, void *RHSArg);
4684 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00004685 ImplicitParamDecl LHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
4686 ImplicitParamDecl RHSArg(C, C.VoidPtrTy, ImplicitParamDecl::Other);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004687 Args.push_back(&LHSArg);
4688 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00004689 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004690 auto *Fn = llvm::Function::Create(
4691 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
4692 ".omp.reduction.reduction_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004693 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004694 CodeGenFunction CGF(CGM);
4695 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
4696
4697 // Dst = (void*[n])(LHSArg);
4698 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00004699 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4700 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
4701 ArgsType), CGF.getPointerAlign());
4702 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4703 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
4704 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004705
4706 // ...
4707 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
4708 // ...
4709 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004710 auto IPriv = Privates.begin();
4711 unsigned Idx = 0;
4712 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004713 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
4714 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004715 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004716 });
4717 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
4718 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004719 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004720 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004721 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004722 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004723 // Get array size and emit VLA type.
4724 ++Idx;
4725 Address Elem =
4726 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
4727 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004728 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
4729 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004730 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00004731 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004732 CGF.EmitVariablyModifiedType(PrivTy);
4733 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004734 }
4735 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004736 IPriv = Privates.begin();
4737 auto ILHS = LHSExprs.begin();
4738 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004739 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004740 if ((*IPriv)->getType()->isArrayType()) {
4741 // Emit reduction for array section.
4742 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4743 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004744 EmitOMPAggregateReduction(
4745 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4746 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4747 emitReductionCombiner(CGF, E);
4748 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004749 } else
4750 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004751 emitReductionCombiner(CGF, E);
Richard Trieucc3949d2016-02-18 22:34:54 +00004752 ++IPriv;
4753 ++ILHS;
4754 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004755 }
4756 Scope.ForceCleanup();
4757 CGF.FinishFunction();
4758 return Fn;
4759}
4760
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004761void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF,
4762 const Expr *ReductionOp,
4763 const Expr *PrivateRef,
4764 const DeclRefExpr *LHS,
4765 const DeclRefExpr *RHS) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004766 if (PrivateRef->getType()->isArrayType()) {
4767 // Emit reduction for array section.
4768 auto *LHSVar = cast<VarDecl>(LHS->getDecl());
4769 auto *RHSVar = cast<VarDecl>(RHS->getDecl());
4770 EmitOMPAggregateReduction(
4771 CGF, PrivateRef->getType(), LHSVar, RHSVar,
4772 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4773 emitReductionCombiner(CGF, ReductionOp);
4774 });
4775 } else
4776 // Emit reduction for array subscript or single variable.
4777 emitReductionCombiner(CGF, ReductionOp);
4778}
4779
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004780void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004781 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004782 ArrayRef<const Expr *> LHSExprs,
4783 ArrayRef<const Expr *> RHSExprs,
4784 ArrayRef<const Expr *> ReductionOps,
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004785 ReductionOptionsTy Options) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004786 if (!CGF.HaveInsertPoint())
4787 return;
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004788
4789 bool WithNowait = Options.WithNowait;
4790 bool SimpleReduction = Options.SimpleReduction;
4791
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004792 // Next code should be emitted for reduction:
4793 //
4794 // static kmp_critical_name lock = { 0 };
4795 //
4796 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
4797 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
4798 // ...
4799 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
4800 // *(Type<n>-1*)rhs[<n>-1]);
4801 // }
4802 //
4803 // ...
4804 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
4805 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4806 // RedList, reduce_func, &<lock>)) {
4807 // case 1:
4808 // ...
4809 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4810 // ...
4811 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4812 // break;
4813 // case 2:
4814 // ...
4815 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4816 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00004817 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004818 // break;
4819 // default:;
4820 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004821 //
4822 // if SimpleReduction is true, only the next code is generated:
4823 // ...
4824 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4825 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004826
4827 auto &C = CGM.getContext();
4828
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004829 if (SimpleReduction) {
4830 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004831 auto IPriv = Privates.begin();
4832 auto ILHS = LHSExprs.begin();
4833 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004834 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004835 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4836 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00004837 ++IPriv;
4838 ++ILHS;
4839 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004840 }
4841 return;
4842 }
4843
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004844 // 1. Build a list of reduction variables.
4845 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004846 auto Size = RHSExprs.size();
4847 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00004848 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004849 // Reserve place for array size.
4850 ++Size;
4851 }
4852 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004853 QualType ReductionArrayTy =
4854 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4855 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00004856 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004857 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004858 auto IPriv = Privates.begin();
4859 unsigned Idx = 0;
4860 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004861 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004862 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00004863 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004864 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004865 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4866 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004867 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004868 // Store array size.
4869 ++Idx;
4870 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
4871 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00004872 llvm::Value *Size = CGF.Builder.CreateIntCast(
4873 CGF.getVLASize(
4874 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4875 .first,
4876 CGF.SizeTy, /*isSigned=*/false);
4877 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4878 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004879 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004880 }
4881
4882 // 2. Emit reduce_func().
4883 auto *ReductionFn = emitReductionFunction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004884 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
4885 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004886
4887 // 3. Create static kmp_critical_name lock = { 0 };
4888 auto *Lock = getCriticalRegionLock(".reduction");
4889
4890 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4891 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00004892 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004893 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004894 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
Samuel Antao4c8035b2016-12-12 18:00:20 +00004895 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4896 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004897 llvm::Value *Args[] = {
4898 IdentTLoc, // ident_t *<loc>
4899 ThreadId, // i32 <gtid>
4900 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
4901 ReductionArrayTySize, // size_type sizeof(RedList)
4902 RL, // void *RedList
4903 ReductionFn, // void (*) (void *, void *) <reduce_func>
4904 Lock // kmp_critical_name *&<lock>
4905 };
4906 auto Res = CGF.EmitRuntimeCall(
4907 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
4908 : OMPRTL__kmpc_reduce),
4909 Args);
4910
4911 // 5. Build switch(res)
4912 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
4913 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
4914
4915 // 6. Build case 1:
4916 // ...
4917 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4918 // ...
4919 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4920 // break;
4921 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
4922 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
4923 CGF.EmitBlock(Case1BB);
4924
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004925 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4926 llvm::Value *EndArgs[] = {
4927 IdentTLoc, // ident_t *<loc>
4928 ThreadId, // i32 <gtid>
4929 Lock // kmp_critical_name *&<lock>
4930 };
4931 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
4932 CodeGenFunction &CGF, PrePostActionTy &Action) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004933 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004934 auto IPriv = Privates.begin();
4935 auto ILHS = LHSExprs.begin();
4936 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004937 for (auto *E : ReductionOps) {
Arpith Chacko Jacob101e8fb2017-02-16 16:20:16 +00004938 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4939 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00004940 ++IPriv;
4941 ++ILHS;
4942 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004943 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004944 };
4945 RegionCodeGenTy RCG(CodeGen);
4946 CommonActionTy Action(
4947 nullptr, llvm::None,
4948 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
4949 : OMPRTL__kmpc_end_reduce),
4950 EndArgs);
4951 RCG.setAction(Action);
4952 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004953
4954 CGF.EmitBranch(DefaultBB);
4955
4956 // 7. Build case 2:
4957 // ...
4958 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4959 // ...
4960 // break;
4961 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
4962 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
4963 CGF.EmitBlock(Case2BB);
4964
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004965 auto &&AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs, &ReductionOps](
4966 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004967 auto ILHS = LHSExprs.begin();
4968 auto IRHS = RHSExprs.begin();
4969 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004970 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004971 const Expr *XExpr = nullptr;
4972 const Expr *EExpr = nullptr;
4973 const Expr *UpExpr = nullptr;
4974 BinaryOperatorKind BO = BO_Comma;
4975 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
4976 if (BO->getOpcode() == BO_Assign) {
4977 XExpr = BO->getLHS();
4978 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004979 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004980 }
4981 // Try to emit update expression as a simple atomic.
4982 auto *RHSExpr = UpExpr;
4983 if (RHSExpr) {
4984 // Analyze RHS part of the whole expression.
4985 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
4986 RHSExpr->IgnoreParenImpCasts())) {
4987 // If this is a conditional operator, analyze its condition for
4988 // min/max reduction operator.
4989 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00004990 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004991 if (auto *BORHS =
4992 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
4993 EExpr = BORHS->getRHS();
4994 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004995 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004996 }
4997 if (XExpr) {
4998 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00004999 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005000 Loc](CodeGenFunction &CGF, const Expr *XExpr,
5001 const Expr *EExpr, const Expr *UpExpr) {
5002 LValue X = CGF.EmitLValue(XExpr);
5003 RValue E;
5004 if (EExpr)
5005 E = CGF.EmitAnyExpr(EExpr);
5006 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00005007 X, E, BO, /*IsXLHSInRHSPart=*/true,
5008 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005009 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005010 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
5011 PrivateScope.addPrivate(
5012 VD, [&CGF, VD, XRValue, Loc]() -> Address {
5013 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
5014 CGF.emitOMPSimpleStore(
5015 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
5016 VD->getType().getNonReferenceType(), Loc);
5017 return LHSTemp;
5018 });
5019 (void)PrivateScope.Privatize();
5020 return CGF.EmitAnyExpr(UpExpr);
5021 });
5022 };
5023 if ((*IPriv)->getType()->isArrayType()) {
5024 // Emit atomic reduction for array section.
5025 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5026 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
5027 AtomicRedGen, XExpr, EExpr, UpExpr);
5028 } else
5029 // Emit atomic reduction for array subscript or single variable.
5030 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
5031 } else {
5032 // Emit as a critical region.
5033 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
5034 const Expr *, const Expr *) {
5035 auto &RT = CGF.CGM.getOpenMPRuntime();
5036 RT.emitCriticalRegion(
5037 CGF, ".atomic_reduction",
5038 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
5039 Action.Enter(CGF);
5040 emitReductionCombiner(CGF, E);
5041 },
5042 Loc);
5043 };
5044 if ((*IPriv)->getType()->isArrayType()) {
5045 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
5046 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
5047 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
5048 CritRedGen);
5049 } else
5050 CritRedGen(CGF, nullptr, nullptr, nullptr);
5051 }
Richard Trieucc3949d2016-02-18 22:34:54 +00005052 ++ILHS;
5053 ++IRHS;
5054 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005055 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005056 };
5057 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
5058 if (!WithNowait) {
5059 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
5060 llvm::Value *EndArgs[] = {
5061 IdentTLoc, // ident_t *<loc>
5062 ThreadId, // i32 <gtid>
5063 Lock // kmp_critical_name *&<lock>
5064 };
5065 CommonActionTy Action(nullptr, llvm::None,
5066 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
5067 EndArgs);
5068 AtomicRCG.setAction(Action);
5069 AtomicRCG(CGF);
5070 } else
5071 AtomicRCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00005072
5073 CGF.EmitBranch(DefaultBB);
5074 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
5075}
5076
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005077void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
5078 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005079 if (!CGF.HaveInsertPoint())
5080 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005081 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
5082 // global_tid);
5083 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
5084 // Ignore return result until untied tasks are supported.
5085 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00005086 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
5087 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00005088}
5089
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005090void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005091 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005092 const RegionCodeGenTy &CodeGen,
5093 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005094 if (!CGF.HaveInsertPoint())
5095 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005096 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00005097 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00005098}
5099
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005100namespace {
5101enum RTCancelKind {
5102 CancelNoreq = 0,
5103 CancelParallel = 1,
5104 CancelLoop = 2,
5105 CancelSections = 3,
5106 CancelTaskgroup = 4
5107};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00005108} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005109
5110static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
5111 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00005112 if (CancelRegion == OMPD_parallel)
5113 CancelKind = CancelParallel;
5114 else if (CancelRegion == OMPD_for)
5115 CancelKind = CancelLoop;
5116 else if (CancelRegion == OMPD_sections)
5117 CancelKind = CancelSections;
5118 else {
5119 assert(CancelRegion == OMPD_taskgroup);
5120 CancelKind = CancelTaskgroup;
5121 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005122 return CancelKind;
5123}
5124
5125void CGOpenMPRuntime::emitCancellationPointCall(
5126 CodeGenFunction &CGF, SourceLocation Loc,
5127 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005128 if (!CGF.HaveInsertPoint())
5129 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005130 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
5131 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005132 if (auto *OMPRegionInfo =
5133 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Jonas Hahnfeldb07931f2017-02-17 18:32:58 +00005134 // For 'cancellation point taskgroup', the task region info may not have a
5135 // cancel. This may instead happen in another adjacent task.
5136 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005137 llvm::Value *Args[] = {
5138 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
5139 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005140 // Ignore return result until untied tasks are supported.
5141 auto *Result = CGF.EmitRuntimeCall(
5142 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
5143 // if (__kmpc_cancellationpoint()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005144 // exit from construct;
5145 // }
5146 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5147 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5148 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5149 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5150 CGF.EmitBlock(ExitBB);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005151 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00005152 auto CancelDest =
5153 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00005154 CGF.EmitBranchThroughCleanup(CancelDest);
5155 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5156 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005157 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00005158}
5159
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005160void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00005161 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005162 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005163 if (!CGF.HaveInsertPoint())
5164 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005165 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
5166 // kmp_int32 cncl_kind);
5167 if (auto *OMPRegionInfo =
5168 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005169 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
5170 PrePostActionTy &) {
5171 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00005172 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005173 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00005174 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
5175 // Ignore return result until untied tasks are supported.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005176 auto *Result = CGF.EmitRuntimeCall(
5177 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00005178 // if (__kmpc_cancel()) {
Alexey Bataev87933c72015-09-18 08:07:34 +00005179 // exit from construct;
5180 // }
5181 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
5182 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
5183 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
5184 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
5185 CGF.EmitBlock(ExitBB);
Alexey Bataev87933c72015-09-18 08:07:34 +00005186 // exit from construct;
5187 auto CancelDest =
5188 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
5189 CGF.EmitBranchThroughCleanup(CancelDest);
5190 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
5191 };
5192 if (IfCond)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005193 emitOMPIfClause(CGF, IfCond, ThenGen,
5194 [](CodeGenFunction &, PrePostActionTy &) {});
5195 else {
5196 RegionCodeGenTy ThenRCG(ThenGen);
5197 ThenRCG(CGF);
5198 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00005199 }
5200}
Samuel Antaobed3c462015-10-02 16:14:20 +00005201
Samuel Antaoee8fb302016-01-06 13:42:12 +00005202/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00005203/// consists of the file and device IDs as well as line number associated with
5204/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005205static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
5206 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005207 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005208
5209 auto &SM = C.getSourceManager();
5210
5211 // The loc should be always valid and have a file ID (the user cannot use
5212 // #pragma directives in macros)
5213
5214 assert(Loc.isValid() && "Source location is expected to be always valid.");
5215 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
5216
5217 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
5218 assert(PLoc.isValid() && "Source location is expected to be always valid.");
5219
5220 llvm::sys::fs::UniqueID ID;
5221 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
5222 llvm_unreachable("Source file with target region no longer exists!");
5223
5224 DeviceID = ID.getDevice();
5225 FileID = ID.getFile();
5226 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00005227}
5228
5229void CGOpenMPRuntime::emitTargetOutlinedFunction(
5230 const OMPExecutableDirective &D, StringRef ParentName,
5231 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005232 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00005233 assert(!ParentName.empty() && "Invalid target region parent name!");
5234
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005235 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
5236 IsOffloadEntry, CodeGen);
5237}
5238
5239void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
5240 const OMPExecutableDirective &D, StringRef ParentName,
5241 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
5242 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00005243 // Create a unique name for the entry function using the source location
5244 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00005245 //
Samuel Antao2de62b02016-02-13 23:35:10 +00005246 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00005247 //
5248 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00005249 // mangled name of the function that encloses the target region and BB is the
5250 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00005251
5252 unsigned DeviceID;
5253 unsigned FileID;
5254 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005255 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005256 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005257 SmallString<64> EntryFnName;
5258 {
5259 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00005260 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
5261 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005262 }
5263
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00005264 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5265
Samuel Antaobed3c462015-10-02 16:14:20 +00005266 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005267 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00005268 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005269
Samuel Antao6d004262016-06-16 18:39:34 +00005270 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005271
5272 // If this target outline function is not an offload entry, we don't need to
5273 // register it.
5274 if (!IsOffloadEntry)
5275 return;
5276
5277 // The target region ID is used by the runtime library to identify the current
5278 // target region, so it only has to be unique and not necessarily point to
5279 // anything. It could be the pointer to the outlined function that implements
5280 // the target region, but we aren't using that so that the compiler doesn't
5281 // need to keep that, and could therefore inline the host function if proven
5282 // worthwhile during optimization. In the other hand, if emitting code for the
5283 // device, the ID has to be the function address so that it can retrieved from
5284 // the offloading entry and launched by the runtime library. We also mark the
5285 // outlined function to have external linkage in case we are emitting code for
5286 // the device, because these functions will be entry points to the device.
5287
5288 if (CGM.getLangOpts().OpenMPIsDevice) {
5289 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
5290 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
5291 } else
5292 OutlinedFnID = new llvm::GlobalVariable(
5293 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
5294 llvm::GlobalValue::PrivateLinkage,
5295 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
5296
5297 // Register the information for the entry associated with this target region.
5298 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00005299 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
5300 /*Flags=*/0);
Samuel Antaobed3c462015-10-02 16:14:20 +00005301}
5302
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005303/// discard all CompoundStmts intervening between two constructs
5304static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
5305 while (auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
5306 Body = CS->body_front();
5307
5308 return Body;
5309}
5310
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005311/// Emit the number of teams for a target directive. Inspect the num_teams
5312/// clause associated with a teams construct combined or closely nested
5313/// with the target directive.
5314///
5315/// Emit a team of size one for directives such as 'target parallel' that
5316/// have no associated teams construct.
5317///
5318/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00005319static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005320emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
5321 CodeGenFunction &CGF,
5322 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005323
5324 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
5325 "teams directive expected to be "
5326 "emitted only for the host!");
5327
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005328 auto &Bld = CGF.Builder;
5329
5330 // If the target directive is combined with a teams directive:
5331 // Return the value in the num_teams clause, if any.
5332 // Otherwise, return 0 to denote the runtime default.
5333 if (isOpenMPTeamsDirective(D.getDirectiveKind())) {
5334 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) {
5335 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF);
5336 auto NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(),
5337 /*IgnoreResultAssign*/ true);
5338 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5339 /*IsSigned=*/true);
5340 }
5341
5342 // The default value is 0.
5343 return Bld.getInt32(0);
5344 }
5345
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005346 // If the target directive is combined with a parallel directive but not a
5347 // teams directive, start one team.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005348 if (isOpenMPParallelDirective(D.getDirectiveKind()))
5349 return Bld.getInt32(1);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005350
5351 // If the current target region has a teams region enclosed, we need to get
5352 // the number of teams to pass to the runtime function call. This is done
5353 // by generating the expression in a inlined region. This is required because
5354 // the expression is captured in the enclosing target environment when the
5355 // teams directive is not combined with target.
5356
5357 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5358
5359 // FIXME: Accommodate other combined directives with teams when they become
5360 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005361 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
5362 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005363 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
5364 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5365 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5366 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005367 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty,
5368 /*IsSigned=*/true);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005369 }
5370
5371 // If we have an enclosed teams directive but no num_teams clause we use
5372 // the default value 0.
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005373 return Bld.getInt32(0);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005374 }
5375
5376 // No teams associated with the directive.
5377 return nullptr;
5378}
5379
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005380/// Emit the number of threads for a target directive. Inspect the
5381/// thread_limit clause associated with a teams construct combined or closely
5382/// nested with the target directive.
5383///
5384/// Emit the num_threads clause for directives such as 'target parallel' that
5385/// have no associated teams construct.
5386///
5387/// Otherwise, return nullptr.
Samuel Antaob68e2db2016-03-03 16:20:23 +00005388static llvm::Value *
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005389emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime,
5390 CodeGenFunction &CGF,
5391 const OMPExecutableDirective &D) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005392
5393 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
5394 "teams directive expected to be "
5395 "emitted only for the host!");
5396
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005397 auto &Bld = CGF.Builder;
5398
5399 //
5400 // If the target directive is combined with a teams directive:
5401 // Return the value in the thread_limit clause, if any.
5402 //
5403 // If the target directive is combined with a parallel directive:
5404 // Return the value in the num_threads clause, if any.
5405 //
5406 // If both clauses are set, select the minimum of the two.
5407 //
5408 // If neither teams or parallel combined directives set the number of threads
5409 // in a team, return 0 to denote the runtime default.
5410 //
5411 // If this is not a teams directive return nullptr.
5412
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005413 if (isOpenMPTeamsDirective(D.getDirectiveKind()) ||
5414 isOpenMPParallelDirective(D.getDirectiveKind())) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005415 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0);
5416 llvm::Value *NumThreadsVal = nullptr;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005417 llvm::Value *ThreadLimitVal = nullptr;
5418
5419 if (const auto *ThreadLimitClause =
5420 D.getSingleClause<OMPThreadLimitClause>()) {
5421 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF);
5422 auto ThreadLimit = CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(),
5423 /*IgnoreResultAssign*/ true);
5424 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5425 /*IsSigned=*/true);
5426 }
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00005427
5428 if (const auto *NumThreadsClause =
5429 D.getSingleClause<OMPNumThreadsClause>()) {
5430 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF);
5431 llvm::Value *NumThreads =
5432 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(),
5433 /*IgnoreResultAssign*/ true);
5434 NumThreadsVal =
5435 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true);
5436 }
5437
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005438 // Select the lesser of thread_limit and num_threads.
5439 if (NumThreadsVal)
5440 ThreadLimitVal = ThreadLimitVal
5441 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal,
5442 ThreadLimitVal),
5443 NumThreadsVal, ThreadLimitVal)
5444 : NumThreadsVal;
Samuel Antaob68e2db2016-03-03 16:20:23 +00005445
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00005446 // Set default value passed to the runtime if either teams or a target
5447 // parallel type directive is found but no clause is specified.
5448 if (!ThreadLimitVal)
5449 ThreadLimitVal = DefaultThreadLimitVal;
5450
5451 return ThreadLimitVal;
5452 }
Arpith Chacko Jacob86f9e462017-01-25 01:45:59 +00005453
Samuel Antaob68e2db2016-03-03 16:20:23 +00005454 // If the current target region has a teams region enclosed, we need to get
5455 // the thread limit to pass to the runtime function call. This is done
5456 // by generating the expression in a inlined region. This is required because
5457 // the expression is captured in the enclosing target environment when the
5458 // teams directive is not combined with target.
5459
5460 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5461
5462 // FIXME: Accommodate other combined directives with teams when they become
5463 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00005464 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
5465 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00005466 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
5467 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
5468 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
5469 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
5470 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
5471 /*IsSigned=*/true);
5472 }
5473
5474 // If we have an enclosed teams directive but no thread_limit clause we use
5475 // the default value 0.
5476 return CGF.Builder.getInt32(0);
5477 }
5478
5479 // No teams associated with the directive.
5480 return nullptr;
5481}
5482
Samuel Antao86ace552016-04-27 22:40:57 +00005483namespace {
5484// \brief Utility to handle information from clauses associated with a given
5485// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
5486// It provides a convenient interface to obtain the information and generate
5487// code for that information.
5488class MappableExprsHandler {
5489public:
5490 /// \brief Values for bit flags used to specify the mapping type for
5491 /// offloading.
5492 enum OpenMPOffloadMappingFlags {
Samuel Antao86ace552016-04-27 22:40:57 +00005493 /// \brief Allocate memory on the device and move data from host to device.
5494 OMP_MAP_TO = 0x01,
5495 /// \brief Allocate memory on the device and move data from device to host.
5496 OMP_MAP_FROM = 0x02,
5497 /// \brief Always perform the requested mapping action on the element, even
5498 /// if it was already mapped before.
5499 OMP_MAP_ALWAYS = 0x04,
Samuel Antao86ace552016-04-27 22:40:57 +00005500 /// \brief Delete the element from the device environment, ignoring the
5501 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00005502 OMP_MAP_DELETE = 0x08,
5503 /// \brief The element being mapped is a pointer, therefore the pointee
5504 /// should be mapped as well.
5505 OMP_MAP_IS_PTR = 0x10,
5506 /// \brief This flags signals that an argument is the first one relating to
5507 /// a map/private clause expression. For some cases a single
5508 /// map/privatization results in multiple arguments passed to the runtime
5509 /// library.
5510 OMP_MAP_FIRST_REF = 0x20,
Samuel Antaocc10b852016-07-28 14:23:26 +00005511 /// \brief Signal that the runtime library has to return the device pointer
5512 /// in the current position for the data being mapped.
5513 OMP_MAP_RETURN_PTR = 0x40,
Samuel Antaod486f842016-05-26 16:53:38 +00005514 /// \brief This flag signals that the reference being passed is a pointer to
5515 /// private data.
5516 OMP_MAP_PRIVATE_PTR = 0x80,
Samuel Antao86ace552016-04-27 22:40:57 +00005517 /// \brief Pass the element to the device by value.
Samuel Antao6782e942016-05-26 16:48:10 +00005518 OMP_MAP_PRIVATE_VAL = 0x100,
Samuel Antao86ace552016-04-27 22:40:57 +00005519 };
5520
Samuel Antaocc10b852016-07-28 14:23:26 +00005521 /// Class that associates information with a base pointer to be passed to the
5522 /// runtime library.
5523 class BasePointerInfo {
5524 /// The base pointer.
5525 llvm::Value *Ptr = nullptr;
5526 /// The base declaration that refers to this device pointer, or null if
5527 /// there is none.
5528 const ValueDecl *DevPtrDecl = nullptr;
5529
5530 public:
5531 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
5532 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
5533 llvm::Value *operator*() const { return Ptr; }
5534 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
5535 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
5536 };
5537
5538 typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00005539 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
5540 typedef SmallVector<unsigned, 16> MapFlagsArrayTy;
5541
5542private:
5543 /// \brief Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00005544 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00005545
5546 /// \brief Function the directive is being generated for.
5547 CodeGenFunction &CGF;
5548
Samuel Antaod486f842016-05-26 16:53:38 +00005549 /// \brief Set of all first private variables in the current directive.
5550 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
5551
Samuel Antao6890b092016-07-28 14:25:09 +00005552 /// Map between device pointer declarations and their expression components.
5553 /// The key value for declarations in 'this' is null.
5554 llvm::DenseMap<
5555 const ValueDecl *,
5556 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
5557 DevPointersMap;
5558
Samuel Antao86ace552016-04-27 22:40:57 +00005559 llvm::Value *getExprTypeSize(const Expr *E) const {
5560 auto ExprTy = E->getType().getCanonicalType();
5561
5562 // Reference types are ignored for mapping purposes.
5563 if (auto *RefTy = ExprTy->getAs<ReferenceType>())
5564 ExprTy = RefTy->getPointeeType().getCanonicalType();
5565
5566 // Given that an array section is considered a built-in type, we need to
5567 // do the calculation based on the length of the section instead of relying
5568 // on CGF.getTypeSize(E->getType()).
5569 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
5570 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
5571 OAE->getBase()->IgnoreParenImpCasts())
5572 .getCanonicalType();
5573
5574 // If there is no length associated with the expression, that means we
5575 // are using the whole length of the base.
5576 if (!OAE->getLength() && OAE->getColonLoc().isValid())
5577 return CGF.getTypeSize(BaseTy);
5578
5579 llvm::Value *ElemSize;
5580 if (auto *PTy = BaseTy->getAs<PointerType>())
5581 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
5582 else {
5583 auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
5584 assert(ATy && "Expecting array type if not a pointer type.");
5585 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
5586 }
5587
5588 // If we don't have a length at this point, that is because we have an
5589 // array section with a single element.
5590 if (!OAE->getLength())
5591 return ElemSize;
5592
5593 auto *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
5594 LengthVal =
5595 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
5596 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
5597 }
5598 return CGF.getTypeSize(ExprTy);
5599 }
5600
5601 /// \brief Return the corresponding bits for a given map clause modifier. Add
5602 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00005603 /// map as the first one of a series of maps that relate to the same map
5604 /// expression.
Samuel Antao86ace552016-04-27 22:40:57 +00005605 unsigned getMapTypeBits(OpenMPMapClauseKind MapType,
5606 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
Samuel Antao6782e942016-05-26 16:48:10 +00005607 bool AddIsFirstFlag) const {
Samuel Antao86ace552016-04-27 22:40:57 +00005608 unsigned Bits = 0u;
5609 switch (MapType) {
5610 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00005611 case OMPC_MAP_release:
5612 // alloc and release is the default behavior in the runtime library, i.e.
5613 // if we don't pass any bits alloc/release that is what the runtime is
5614 // going to do. Therefore, we don't need to signal anything for these two
5615 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00005616 break;
5617 case OMPC_MAP_to:
5618 Bits = OMP_MAP_TO;
5619 break;
5620 case OMPC_MAP_from:
5621 Bits = OMP_MAP_FROM;
5622 break;
5623 case OMPC_MAP_tofrom:
5624 Bits = OMP_MAP_TO | OMP_MAP_FROM;
5625 break;
5626 case OMPC_MAP_delete:
5627 Bits = OMP_MAP_DELETE;
5628 break;
Samuel Antao86ace552016-04-27 22:40:57 +00005629 default:
5630 llvm_unreachable("Unexpected map type!");
5631 break;
5632 }
5633 if (AddPtrFlag)
Samuel Antao6782e942016-05-26 16:48:10 +00005634 Bits |= OMP_MAP_IS_PTR;
5635 if (AddIsFirstFlag)
5636 Bits |= OMP_MAP_FIRST_REF;
Samuel Antao86ace552016-04-27 22:40:57 +00005637 if (MapTypeModifier == OMPC_MAP_always)
5638 Bits |= OMP_MAP_ALWAYS;
5639 return Bits;
5640 }
5641
5642 /// \brief Return true if the provided expression is a final array section. A
5643 /// final array section, is one whose length can't be proved to be one.
5644 bool isFinalArraySectionExpression(const Expr *E) const {
5645 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
5646
5647 // It is not an array section and therefore not a unity-size one.
5648 if (!OASE)
5649 return false;
5650
5651 // An array section with no colon always refer to a single element.
5652 if (OASE->getColonLoc().isInvalid())
5653 return false;
5654
5655 auto *Length = OASE->getLength();
5656
5657 // If we don't have a length we have to check if the array has size 1
5658 // for this dimension. Also, we should always expect a length if the
5659 // base type is pointer.
5660 if (!Length) {
5661 auto BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
5662 OASE->getBase()->IgnoreParenImpCasts())
5663 .getCanonicalType();
5664 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
5665 return ATy->getSize().getSExtValue() != 1;
5666 // If we don't have a constant dimension length, we have to consider
5667 // the current section as having any size, so it is not necessarily
5668 // unitary. If it happen to be unity size, that's user fault.
5669 return true;
5670 }
5671
5672 // Check if the length evaluates to 1.
5673 llvm::APSInt ConstLength;
5674 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
5675 return true; // Can have more that size 1.
5676
5677 return ConstLength.getSExtValue() != 1;
5678 }
5679
5680 /// \brief Generate the base pointers, section pointers, sizes and map type
5681 /// bits for the provided map type, map modifier, and expression components.
5682 /// \a IsFirstComponent should be set to true if the provided set of
5683 /// components is the first associated with a capture.
5684 void generateInfoForComponentList(
5685 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
5686 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00005687 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00005688 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
5689 bool IsFirstComponentList) const {
5690
5691 // The following summarizes what has to be generated for each map and the
5692 // types bellow. The generated information is expressed in this order:
5693 // base pointer, section pointer, size, flags
5694 // (to add to the ones that come from the map type and modifier).
5695 //
5696 // double d;
5697 // int i[100];
5698 // float *p;
5699 //
5700 // struct S1 {
5701 // int i;
5702 // float f[50];
5703 // }
5704 // struct S2 {
5705 // int i;
5706 // float f[50];
5707 // S1 s;
5708 // double *p;
5709 // struct S2 *ps;
5710 // }
5711 // S2 s;
5712 // S2 *ps;
5713 //
5714 // map(d)
5715 // &d, &d, sizeof(double), noflags
5716 //
5717 // map(i)
5718 // &i, &i, 100*sizeof(int), noflags
5719 //
5720 // map(i[1:23])
5721 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
5722 //
5723 // map(p)
5724 // &p, &p, sizeof(float*), noflags
5725 //
5726 // map(p[1:24])
5727 // p, &p[1], 24*sizeof(float), noflags
5728 //
5729 // map(s)
5730 // &s, &s, sizeof(S2), noflags
5731 //
5732 // map(s.i)
5733 // &s, &(s.i), sizeof(int), noflags
5734 //
5735 // map(s.s.f)
5736 // &s, &(s.i.f), 50*sizeof(int), noflags
5737 //
5738 // map(s.p)
5739 // &s, &(s.p), sizeof(double*), noflags
5740 //
5741 // map(s.p[:22], s.a s.b)
5742 // &s, &(s.p), sizeof(double*), noflags
5743 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag + extra_flag
5744 //
5745 // map(s.ps)
5746 // &s, &(s.ps), sizeof(S2*), noflags
5747 //
5748 // map(s.ps->s.i)
5749 // &s, &(s.ps), sizeof(S2*), noflags
5750 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag + extra_flag
5751 //
5752 // map(s.ps->ps)
5753 // &s, &(s.ps), sizeof(S2*), noflags
5754 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5755 //
5756 // map(s.ps->ps->ps)
5757 // &s, &(s.ps), sizeof(S2*), noflags
5758 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5759 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5760 //
5761 // map(s.ps->ps->s.f[:22])
5762 // &s, &(s.ps), sizeof(S2*), noflags
5763 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5764 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag + extra_flag
5765 //
5766 // map(ps)
5767 // &ps, &ps, sizeof(S2*), noflags
5768 //
5769 // map(ps->i)
5770 // ps, &(ps->i), sizeof(int), noflags
5771 //
5772 // map(ps->s.f)
5773 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
5774 //
5775 // map(ps->p)
5776 // ps, &(ps->p), sizeof(double*), noflags
5777 //
5778 // map(ps->p[:22])
5779 // ps, &(ps->p), sizeof(double*), noflags
5780 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag + extra_flag
5781 //
5782 // map(ps->ps)
5783 // ps, &(ps->ps), sizeof(S2*), noflags
5784 //
5785 // map(ps->ps->s.i)
5786 // ps, &(ps->ps), sizeof(S2*), noflags
5787 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag + extra_flag
5788 //
5789 // map(ps->ps->ps)
5790 // ps, &(ps->ps), sizeof(S2*), noflags
5791 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5792 //
5793 // map(ps->ps->ps->ps)
5794 // ps, &(ps->ps), sizeof(S2*), noflags
5795 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5796 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5797 //
5798 // map(ps->ps->ps->s.f[:22])
5799 // ps, &(ps->ps), sizeof(S2*), noflags
5800 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5801 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag +
5802 // extra_flag
5803
5804 // Track if the map information being generated is the first for a capture.
5805 bool IsCaptureFirstInfo = IsFirstComponentList;
5806
5807 // Scan the components from the base to the complete expression.
5808 auto CI = Components.rbegin();
5809 auto CE = Components.rend();
5810 auto I = CI;
5811
5812 // Track if the map information being generated is the first for a list of
5813 // components.
5814 bool IsExpressionFirstInfo = true;
5815 llvm::Value *BP = nullptr;
5816
5817 if (auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
5818 // The base is the 'this' pointer. The content of the pointer is going
5819 // to be the base of the field being mapped.
5820 BP = CGF.EmitScalarExpr(ME->getBase());
5821 } else {
5822 // The base is the reference to the variable.
5823 // BP = &Var.
5824 BP = CGF.EmitLValue(cast<DeclRefExpr>(I->getAssociatedExpression()))
5825 .getPointer();
5826
5827 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00005828 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00005829 // reference. References are ignored for mapping purposes.
5830 QualType Ty =
5831 I->getAssociatedDeclaration()->getType().getNonReferenceType();
5832 if (Ty->isAnyPointerType() && std::next(I) != CE) {
5833 auto PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
Samuel Antao86ace552016-04-27 22:40:57 +00005834 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
Samuel Antao403ffd42016-07-27 22:49:49 +00005835 Ty->castAs<PointerType>())
Samuel Antao86ace552016-04-27 22:40:57 +00005836 .getPointer();
5837
5838 // We do not need to generate individual map information for the
5839 // pointer, it can be associated with the combined storage.
5840 ++I;
5841 }
5842 }
5843
5844 for (; I != CE; ++I) {
5845 auto Next = std::next(I);
5846
5847 // We need to generate the addresses and sizes if this is the last
5848 // component, if the component is a pointer or if it is an array section
5849 // whose length can't be proved to be one. If this is a pointer, it
5850 // becomes the base address for the following components.
5851
5852 // A final array section, is one whose length can't be proved to be one.
5853 bool IsFinalArraySection =
5854 isFinalArraySectionExpression(I->getAssociatedExpression());
5855
5856 // Get information on whether the element is a pointer. Have to do a
5857 // special treatment for array sections given that they are built-in
5858 // types.
5859 const auto *OASE =
5860 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
5861 bool IsPointer =
5862 (OASE &&
5863 OMPArraySectionExpr::getBaseOriginalType(OASE)
5864 .getCanonicalType()
5865 ->isAnyPointerType()) ||
5866 I->getAssociatedExpression()->getType()->isAnyPointerType();
5867
5868 if (Next == CE || IsPointer || IsFinalArraySection) {
5869
5870 // If this is not the last component, we expect the pointer to be
5871 // associated with an array expression or member expression.
5872 assert((Next == CE ||
5873 isa<MemberExpr>(Next->getAssociatedExpression()) ||
5874 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
5875 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
5876 "Unexpected expression");
5877
Samuel Antao86ace552016-04-27 22:40:57 +00005878 auto *LB = CGF.EmitLValue(I->getAssociatedExpression()).getPointer();
5879 auto *Size = getExprTypeSize(I->getAssociatedExpression());
5880
Samuel Antao03a3cec2016-07-27 22:52:16 +00005881 // If we have a member expression and the current component is a
5882 // reference, we have to map the reference too. Whenever we have a
5883 // reference, the section that reference refers to is going to be a
5884 // load instruction from the storage assigned to the reference.
5885 if (isa<MemberExpr>(I->getAssociatedExpression()) &&
5886 I->getAssociatedDeclaration()->getType()->isReferenceType()) {
5887 auto *LI = cast<llvm::LoadInst>(LB);
5888 auto *RefAddr = LI->getPointerOperand();
5889
5890 BasePointers.push_back(BP);
5891 Pointers.push_back(RefAddr);
5892 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
5893 Types.push_back(getMapTypeBits(
5894 /*MapType*/ OMPC_MAP_alloc, /*MapTypeModifier=*/OMPC_MAP_unknown,
5895 !IsExpressionFirstInfo, IsCaptureFirstInfo));
5896 IsExpressionFirstInfo = false;
5897 IsCaptureFirstInfo = false;
5898 // The reference will be the next base address.
5899 BP = RefAddr;
5900 }
5901
5902 BasePointers.push_back(BP);
Samuel Antao86ace552016-04-27 22:40:57 +00005903 Pointers.push_back(LB);
5904 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00005905
Samuel Antao6782e942016-05-26 16:48:10 +00005906 // We need to add a pointer flag for each map that comes from the
5907 // same expression except for the first one. We also need to signal
5908 // this map is the first one that relates with the current capture
5909 // (there is a set of entries for each capture).
Samuel Antao86ace552016-04-27 22:40:57 +00005910 Types.push_back(getMapTypeBits(MapType, MapTypeModifier,
5911 !IsExpressionFirstInfo,
Samuel Antao6782e942016-05-26 16:48:10 +00005912 IsCaptureFirstInfo));
Samuel Antao86ace552016-04-27 22:40:57 +00005913
5914 // If we have a final array section, we are done with this expression.
5915 if (IsFinalArraySection)
5916 break;
5917
5918 // The pointer becomes the base for the next element.
5919 if (Next != CE)
5920 BP = LB;
5921
5922 IsExpressionFirstInfo = false;
5923 IsCaptureFirstInfo = false;
5924 continue;
5925 }
5926 }
5927 }
5928
Samuel Antaod486f842016-05-26 16:53:38 +00005929 /// \brief Return the adjusted map modifiers if the declaration a capture
5930 /// refers to appears in a first-private clause. This is expected to be used
5931 /// only with directives that start with 'target'.
5932 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
5933 unsigned CurrentModifiers) {
5934 assert(Cap.capturesVariable() && "Expected capture by reference only!");
5935
5936 // A first private variable captured by reference will use only the
5937 // 'private ptr' and 'map to' flag. Return the right flags if the captured
5938 // declaration is known as first-private in this handler.
5939 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
5940 return MappableExprsHandler::OMP_MAP_PRIVATE_PTR |
5941 MappableExprsHandler::OMP_MAP_TO;
5942
5943 // We didn't modify anything.
5944 return CurrentModifiers;
5945 }
5946
Samuel Antao86ace552016-04-27 22:40:57 +00005947public:
5948 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
Samuel Antao44bcdb32016-07-28 15:31:29 +00005949 : CurDir(Dir), CGF(CGF) {
Samuel Antaod486f842016-05-26 16:53:38 +00005950 // Extract firstprivate clause information.
5951 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
5952 for (const auto *D : C->varlists())
5953 FirstPrivateDecls.insert(
5954 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
Samuel Antao6890b092016-07-28 14:25:09 +00005955 // Extract device pointer clause information.
5956 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
5957 for (auto L : C->component_lists())
5958 DevPointersMap[L.first].push_back(L.second);
Samuel Antaod486f842016-05-26 16:53:38 +00005959 }
Samuel Antao86ace552016-04-27 22:40:57 +00005960
5961 /// \brief Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00005962 /// types for the extracted mappable expressions. Also, for each item that
5963 /// relates with a device pointer, a pair of the relevant declaration and
5964 /// index where it occurs is appended to the device pointers info array.
5965 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00005966 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
5967 MapFlagsArrayTy &Types) const {
5968 BasePointers.clear();
5969 Pointers.clear();
5970 Sizes.clear();
5971 Types.clear();
5972
5973 struct MapInfo {
Samuel Antaocc10b852016-07-28 14:23:26 +00005974 /// Kind that defines how a device pointer has to be returned.
5975 enum ReturnPointerKind {
5976 // Don't have to return any pointer.
5977 RPK_None,
5978 // Pointer is the base of the declaration.
5979 RPK_Base,
5980 // Pointer is a member of the base declaration - 'this'
5981 RPK_Member,
5982 // Pointer is a reference and a member of the base declaration - 'this'
5983 RPK_MemberReference,
5984 };
Samuel Antao86ace552016-04-27 22:40:57 +00005985 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
Hans Wennborgbc1b58d2016-07-30 00:41:37 +00005986 OpenMPMapClauseKind MapType;
5987 OpenMPMapClauseKind MapTypeModifier;
5988 ReturnPointerKind ReturnDevicePointer;
5989
5990 MapInfo()
5991 : MapType(OMPC_MAP_unknown), MapTypeModifier(OMPC_MAP_unknown),
5992 ReturnDevicePointer(RPK_None) {}
Samuel Antaocc10b852016-07-28 14:23:26 +00005993 MapInfo(
5994 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
5995 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
5996 ReturnPointerKind ReturnDevicePointer)
5997 : Components(Components), MapType(MapType),
5998 MapTypeModifier(MapTypeModifier),
5999 ReturnDevicePointer(ReturnDevicePointer) {}
Samuel Antao86ace552016-04-27 22:40:57 +00006000 };
6001
6002 // We have to process the component lists that relate with the same
6003 // declaration in a single chunk so that we can generate the map flags
6004 // correctly. Therefore, we organize all lists in a map.
Alexey Bataev5d1c3f62017-06-27 15:46:42 +00006005 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00006006
6007 // Helper function to fill the information map for the different supported
6008 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00006009 auto &&InfoGen = [&Info](
6010 const ValueDecl *D,
6011 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
6012 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006013 MapInfo::ReturnPointerKind ReturnDevicePointer) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006014 const ValueDecl *VD =
6015 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
6016 Info[VD].push_back({L, MapType, MapModifier, ReturnDevicePointer});
6017 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00006018
Paul Robinson78fb1322016-08-01 22:12:46 +00006019 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006020 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00006021 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006022 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
6023 MapInfo::RPK_None);
Paul Robinson15c84002016-07-29 20:46:16 +00006024 for (auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00006025 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006026 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
6027 MapInfo::RPK_None);
Paul Robinson15c84002016-07-29 20:46:16 +00006028 for (auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00006029 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00006030 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
6031 MapInfo::RPK_None);
Samuel Antao86ace552016-04-27 22:40:57 +00006032
Samuel Antaocc10b852016-07-28 14:23:26 +00006033 // Look at the use_device_ptr clause information and mark the existing map
6034 // entries as such. If there is no map information for an entry in the
6035 // use_device_ptr list, we create one with map type 'alloc' and zero size
6036 // section. It is the user fault if that was not mapped before.
Paul Robinson78fb1322016-08-01 22:12:46 +00006037 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006038 for (auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
Samuel Antaocc10b852016-07-28 14:23:26 +00006039 for (auto L : C->component_lists()) {
6040 assert(!L.second.empty() && "Not expecting empty list of components!");
6041 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
6042 VD = cast<ValueDecl>(VD->getCanonicalDecl());
6043 auto *IE = L.second.back().getAssociatedExpression();
6044 // If the first component is a member expression, we have to look into
6045 // 'this', which maps to null in the map of map information. Otherwise
6046 // look directly for the information.
6047 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
6048
6049 // We potentially have map information for this declaration already.
6050 // Look for the first set of components that refer to it.
6051 if (It != Info.end()) {
6052 auto CI = std::find_if(
6053 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
6054 return MI.Components.back().getAssociatedDeclaration() == VD;
6055 });
6056 // If we found a map entry, signal that the pointer has to be returned
6057 // and move on to the next declaration.
6058 if (CI != It->second.end()) {
6059 CI->ReturnDevicePointer = isa<MemberExpr>(IE)
6060 ? (VD->getType()->isReferenceType()
6061 ? MapInfo::RPK_MemberReference
6062 : MapInfo::RPK_Member)
6063 : MapInfo::RPK_Base;
6064 continue;
6065 }
6066 }
6067
6068 // We didn't find any match in our map information - generate a zero
6069 // size array section.
Paul Robinson78fb1322016-08-01 22:12:46 +00006070 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Samuel Antaocc10b852016-07-28 14:23:26 +00006071 llvm::Value *Ptr =
Paul Robinson15c84002016-07-29 20:46:16 +00006072 this->CGF
6073 .EmitLoadOfLValue(this->CGF.EmitLValue(IE), SourceLocation())
Samuel Antaocc10b852016-07-28 14:23:26 +00006074 .getScalarVal();
6075 BasePointers.push_back({Ptr, VD});
6076 Pointers.push_back(Ptr);
Paul Robinson15c84002016-07-29 20:46:16 +00006077 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
Samuel Antaocc10b852016-07-28 14:23:26 +00006078 Types.push_back(OMP_MAP_RETURN_PTR | OMP_MAP_FIRST_REF);
6079 }
6080
Samuel Antao86ace552016-04-27 22:40:57 +00006081 for (auto &M : Info) {
6082 // We need to know when we generate information for the first component
6083 // associated with a capture, because the mapping flags depend on it.
6084 bool IsFirstComponentList = true;
6085 for (MapInfo &L : M.second) {
6086 assert(!L.Components.empty() &&
6087 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00006088
6089 // Remember the current base pointer index.
6090 unsigned CurrentBasePointersIdx = BasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00006091 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Paul Robinson15c84002016-07-29 20:46:16 +00006092 this->generateInfoForComponentList(L.MapType, L.MapTypeModifier,
6093 L.Components, BasePointers, Pointers,
6094 Sizes, Types, IsFirstComponentList);
Samuel Antaocc10b852016-07-28 14:23:26 +00006095
6096 // If this entry relates with a device pointer, set the relevant
6097 // declaration and add the 'return pointer' flag.
6098 if (IsFirstComponentList &&
6099 L.ReturnDevicePointer != MapInfo::RPK_None) {
6100 // If the pointer is not the base of the map, we need to skip the
6101 // base. If it is a reference in a member field, we also need to skip
6102 // the map of the reference.
6103 if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
6104 ++CurrentBasePointersIdx;
6105 if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
6106 ++CurrentBasePointersIdx;
6107 }
6108 assert(BasePointers.size() > CurrentBasePointersIdx &&
6109 "Unexpected number of mapped base pointers.");
6110
6111 auto *RelevantVD = L.Components.back().getAssociatedDeclaration();
6112 assert(RelevantVD &&
6113 "No relevant declaration related with device pointer??");
6114
6115 BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
6116 Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PTR;
6117 }
Samuel Antao86ace552016-04-27 22:40:57 +00006118 IsFirstComponentList = false;
6119 }
6120 }
6121 }
6122
6123 /// \brief Generate the base pointers, section pointers, sizes and map types
6124 /// associated to a given capture.
6125 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00006126 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006127 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006128 MapValuesArrayTy &Pointers,
6129 MapValuesArrayTy &Sizes,
6130 MapFlagsArrayTy &Types) const {
6131 assert(!Cap->capturesVariableArrayType() &&
6132 "Not expecting to generate map info for a variable array type!");
6133
6134 BasePointers.clear();
6135 Pointers.clear();
6136 Sizes.clear();
6137 Types.clear();
6138
Samuel Antao6890b092016-07-28 14:25:09 +00006139 // We need to know when we generating information for the first component
6140 // associated with a capture, because the mapping flags depend on it.
6141 bool IsFirstComponentList = true;
6142
Samuel Antao86ace552016-04-27 22:40:57 +00006143 const ValueDecl *VD =
6144 Cap->capturesThis()
6145 ? nullptr
6146 : cast<ValueDecl>(Cap->getCapturedVar()->getCanonicalDecl());
6147
Samuel Antao6890b092016-07-28 14:25:09 +00006148 // If this declaration appears in a is_device_ptr clause we just have to
6149 // pass the pointer by value. If it is a reference to a declaration, we just
6150 // pass its value, otherwise, if it is a member expression, we need to map
6151 // 'to' the field.
6152 if (!VD) {
6153 auto It = DevPointersMap.find(VD);
6154 if (It != DevPointersMap.end()) {
6155 for (auto L : It->second) {
6156 generateInfoForComponentList(
6157 /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
6158 BasePointers, Pointers, Sizes, Types, IsFirstComponentList);
6159 IsFirstComponentList = false;
6160 }
6161 return;
6162 }
6163 } else if (DevPointersMap.count(VD)) {
6164 BasePointers.push_back({Arg, VD});
6165 Pointers.push_back(Arg);
6166 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
6167 Types.push_back(OMP_MAP_PRIVATE_VAL | OMP_MAP_FIRST_REF);
6168 return;
6169 }
6170
Paul Robinson78fb1322016-08-01 22:12:46 +00006171 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00006172 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao86ace552016-04-27 22:40:57 +00006173 for (auto L : C->decl_component_lists(VD)) {
6174 assert(L.first == VD &&
6175 "We got information for the wrong declaration??");
6176 assert(!L.second.empty() &&
6177 "Not expecting declaration with no component lists.");
6178 generateInfoForComponentList(C->getMapType(), C->getMapTypeModifier(),
6179 L.second, BasePointers, Pointers, Sizes,
6180 Types, IsFirstComponentList);
6181 IsFirstComponentList = false;
6182 }
6183
6184 return;
6185 }
Samuel Antaod486f842016-05-26 16:53:38 +00006186
6187 /// \brief Generate the default map information for a given capture \a CI,
6188 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00006189 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
6190 const FieldDecl &RI, llvm::Value *CV,
6191 MapBaseValuesArrayTy &CurBasePointers,
6192 MapValuesArrayTy &CurPointers,
6193 MapValuesArrayTy &CurSizes,
6194 MapFlagsArrayTy &CurMapTypes) {
Samuel Antaod486f842016-05-26 16:53:38 +00006195
6196 // Do the default mapping.
6197 if (CI.capturesThis()) {
6198 CurBasePointers.push_back(CV);
6199 CurPointers.push_back(CV);
6200 const PointerType *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
6201 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
6202 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00006203 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00006204 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00006205 CurBasePointers.push_back(CV);
6206 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00006207 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00006208 // We have to signal to the runtime captures passed by value that are
6209 // not pointers.
Samuel Antaocc10b852016-07-28 14:23:26 +00006210 CurMapTypes.push_back(OMP_MAP_PRIVATE_VAL);
Samuel Antaod486f842016-05-26 16:53:38 +00006211 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
6212 } else {
6213 // Pointers are implicitly mapped with a zero size and no flags
6214 // (other than first map that is added for all implicit maps).
6215 CurMapTypes.push_back(0u);
Samuel Antaod486f842016-05-26 16:53:38 +00006216 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
6217 }
6218 } else {
6219 assert(CI.capturesVariable() && "Expected captured reference.");
6220 CurBasePointers.push_back(CV);
6221 CurPointers.push_back(CV);
6222
6223 const ReferenceType *PtrTy =
6224 cast<ReferenceType>(RI.getType().getTypePtr());
6225 QualType ElementType = PtrTy->getPointeeType();
6226 CurSizes.push_back(CGF.getTypeSize(ElementType));
6227 // The default map type for a scalar/complex type is 'to' because by
6228 // default the value doesn't have to be retrieved. For an aggregate
6229 // type, the default is 'tofrom'.
6230 CurMapTypes.push_back(ElementType->isAggregateType()
Samuel Antaocc10b852016-07-28 14:23:26 +00006231 ? (OMP_MAP_TO | OMP_MAP_FROM)
6232 : OMP_MAP_TO);
Samuel Antaod486f842016-05-26 16:53:38 +00006233
6234 // If we have a capture by reference we may need to add the private
6235 // pointer flag if the base declaration shows in some first-private
6236 // clause.
6237 CurMapTypes.back() =
6238 adjustMapModifiersForPrivateClauses(CI, CurMapTypes.back());
6239 }
6240 // Every default map produces a single argument, so, it is always the
6241 // first one.
Samuel Antaocc10b852016-07-28 14:23:26 +00006242 CurMapTypes.back() |= OMP_MAP_FIRST_REF;
Samuel Antaod486f842016-05-26 16:53:38 +00006243 }
Samuel Antao86ace552016-04-27 22:40:57 +00006244};
Samuel Antaodf158d52016-04-27 22:58:19 +00006245
6246enum OpenMPOffloadingReservedDeviceIDs {
6247 /// \brief Device ID if the device was not defined, runtime should get it
6248 /// from environment variables in the spec.
6249 OMP_DEVICEID_UNDEF = -1,
6250};
6251} // anonymous namespace
6252
6253/// \brief Emit the arrays used to pass the captures and map information to the
6254/// offloading runtime library. If there is no map or capture information,
6255/// return nullptr by reference.
6256static void
Samuel Antaocc10b852016-07-28 14:23:26 +00006257emitOffloadingArrays(CodeGenFunction &CGF,
6258 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00006259 MappableExprsHandler::MapValuesArrayTy &Pointers,
6260 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00006261 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
6262 CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006263 auto &CGM = CGF.CGM;
6264 auto &Ctx = CGF.getContext();
6265
Samuel Antaocc10b852016-07-28 14:23:26 +00006266 // Reset the array information.
6267 Info.clearArrayInfo();
6268 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00006269
Samuel Antaocc10b852016-07-28 14:23:26 +00006270 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006271 // Detect if we have any capture size requiring runtime evaluation of the
6272 // size so that a constant array could be eventually used.
6273 bool hasRuntimeEvaluationCaptureSize = false;
6274 for (auto *S : Sizes)
6275 if (!isa<llvm::Constant>(S)) {
6276 hasRuntimeEvaluationCaptureSize = true;
6277 break;
6278 }
6279
Samuel Antaocc10b852016-07-28 14:23:26 +00006280 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00006281 QualType PointerArrayType =
6282 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
6283 /*IndexTypeQuals=*/0);
6284
Samuel Antaocc10b852016-07-28 14:23:26 +00006285 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006286 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00006287 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006288 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
6289
6290 // If we don't have any VLA types or other types that require runtime
6291 // evaluation, we can use a constant array for the map sizes, otherwise we
6292 // need to fill up the arrays as we do for the pointers.
6293 if (hasRuntimeEvaluationCaptureSize) {
6294 QualType SizeArrayType = Ctx.getConstantArrayType(
6295 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
6296 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00006297 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00006298 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
6299 } else {
6300 // We expect all the sizes to be constant, so we collect them to create
6301 // a constant array.
6302 SmallVector<llvm::Constant *, 16> ConstSizes;
6303 for (auto S : Sizes)
6304 ConstSizes.push_back(cast<llvm::Constant>(S));
6305
6306 auto *SizesArrayInit = llvm::ConstantArray::get(
6307 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
6308 auto *SizesArrayGbl = new llvm::GlobalVariable(
6309 CGM.getModule(), SizesArrayInit->getType(),
6310 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
6311 SizesArrayInit, ".offload_sizes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00006312 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00006313 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00006314 }
6315
6316 // The map types are always constant so we don't need to generate code to
6317 // fill arrays. Instead, we create an array constant.
6318 llvm::Constant *MapTypesArrayInit =
6319 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
6320 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
6321 CGM.getModule(), MapTypesArrayInit->getType(),
6322 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
6323 MapTypesArrayInit, ".offload_maptypes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00006324 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00006325 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00006326
Samuel Antaocc10b852016-07-28 14:23:26 +00006327 for (unsigned i = 0; i < Info.NumberOfPtrs; ++i) {
6328 llvm::Value *BPVal = *BasePointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00006329 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006330 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6331 Info.BasePointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00006332 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6333 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00006334 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
6335 CGF.Builder.CreateStore(BPVal, BPAddr);
6336
Samuel Antaocc10b852016-07-28 14:23:26 +00006337 if (Info.requiresDevicePointerInfo())
6338 if (auto *DevVD = BasePointers[i].getDevicePtrDecl())
6339 Info.CaptureDeviceAddrMap.insert(std::make_pair(DevVD, BPAddr));
6340
Samuel Antaodf158d52016-04-27 22:58:19 +00006341 llvm::Value *PVal = Pointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00006342 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006343 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6344 Info.PointersArray, 0, i);
Alexey Bataev1fdfdf72017-06-29 16:43:05 +00006345 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6346 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0));
Samuel Antaodf158d52016-04-27 22:58:19 +00006347 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
6348 CGF.Builder.CreateStore(PVal, PAddr);
6349
6350 if (hasRuntimeEvaluationCaptureSize) {
6351 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006352 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
6353 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006354 /*Idx0=*/0,
6355 /*Idx1=*/i);
6356 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
6357 CGF.Builder.CreateStore(
6358 CGF.Builder.CreateIntCast(Sizes[i], CGM.SizeTy, /*isSigned=*/true),
6359 SAddr);
6360 }
6361 }
6362 }
6363}
6364/// \brief Emit the arguments to be passed to the runtime library based on the
6365/// arrays of pointers, sizes and map types.
6366static void emitOffloadingArraysArgument(
6367 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
6368 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006369 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006370 auto &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00006371 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006372 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006373 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6374 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006375 /*Idx0=*/0, /*Idx1=*/0);
6376 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006377 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
6378 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006379 /*Idx0=*/0,
6380 /*Idx1=*/0);
6381 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006382 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006383 /*Idx0=*/0, /*Idx1=*/0);
6384 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00006385 llvm::ArrayType::get(CGM.Int32Ty, Info.NumberOfPtrs),
6386 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00006387 /*Idx0=*/0,
6388 /*Idx1=*/0);
6389 } else {
6390 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
6391 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
6392 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
6393 MapTypesArrayArg =
6394 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo());
6395 }
Samuel Antao86ace552016-04-27 22:40:57 +00006396}
6397
Samuel Antaobed3c462015-10-02 16:14:20 +00006398void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
6399 const OMPExecutableDirective &D,
6400 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00006401 llvm::Value *OutlinedFnID,
Samuel Antaobed3c462015-10-02 16:14:20 +00006402 const Expr *IfCond, const Expr *Device,
6403 ArrayRef<llvm::Value *> CapturedVars) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00006404 if (!CGF.HaveInsertPoint())
6405 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00006406
Samuel Antaoee8fb302016-01-06 13:42:12 +00006407 assert(OutlinedFn && "Invalid outlined function!");
6408
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006409 auto &Ctx = CGF.getContext();
6410
Samuel Antao86ace552016-04-27 22:40:57 +00006411 // Fill up the arrays with all the captured variables.
6412 MappableExprsHandler::MapValuesArrayTy KernelArgs;
Samuel Antaocc10b852016-07-28 14:23:26 +00006413 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00006414 MappableExprsHandler::MapValuesArrayTy Pointers;
6415 MappableExprsHandler::MapValuesArrayTy Sizes;
6416 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobed3c462015-10-02 16:14:20 +00006417
Samuel Antaocc10b852016-07-28 14:23:26 +00006418 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00006419 MappableExprsHandler::MapValuesArrayTy CurPointers;
6420 MappableExprsHandler::MapValuesArrayTy CurSizes;
6421 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
6422
Samuel Antaod486f842016-05-26 16:53:38 +00006423 // Get mappable expression information.
6424 MappableExprsHandler MEHandler(D, CGF);
Samuel Antaobed3c462015-10-02 16:14:20 +00006425
6426 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
6427 auto RI = CS.getCapturedRecordDecl()->field_begin();
Samuel Antaobed3c462015-10-02 16:14:20 +00006428 auto CV = CapturedVars.begin();
6429 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
6430 CE = CS.capture_end();
6431 CI != CE; ++CI, ++RI, ++CV) {
6432 StringRef Name;
6433 QualType Ty;
Samuel Antaobed3c462015-10-02 16:14:20 +00006434
Samuel Antao86ace552016-04-27 22:40:57 +00006435 CurBasePointers.clear();
6436 CurPointers.clear();
6437 CurSizes.clear();
6438 CurMapTypes.clear();
6439
6440 // VLA sizes are passed to the outlined region by copy and do not have map
6441 // information associated.
Samuel Antaobed3c462015-10-02 16:14:20 +00006442 if (CI->capturesVariableArrayType()) {
Samuel Antao86ace552016-04-27 22:40:57 +00006443 CurBasePointers.push_back(*CV);
6444 CurPointers.push_back(*CV);
6445 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006446 // Copy to the device as an argument. No need to retrieve it.
Samuel Antao6782e942016-05-26 16:48:10 +00006447 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_PRIVATE_VAL |
6448 MappableExprsHandler::OMP_MAP_FIRST_REF);
Samuel Antaobed3c462015-10-02 16:14:20 +00006449 } else {
Samuel Antao86ace552016-04-27 22:40:57 +00006450 // If we have any information in the map clause, we use it, otherwise we
6451 // just do a default mapping.
Samuel Antao6890b092016-07-28 14:25:09 +00006452 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Samuel Antao86ace552016-04-27 22:40:57 +00006453 CurSizes, CurMapTypes);
Samuel Antaod486f842016-05-26 16:53:38 +00006454 if (CurBasePointers.empty())
6455 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
6456 CurPointers, CurSizes, CurMapTypes);
Samuel Antaobed3c462015-10-02 16:14:20 +00006457 }
Samuel Antao86ace552016-04-27 22:40:57 +00006458 // We expect to have at least an element of information for this capture.
6459 assert(!CurBasePointers.empty() && "Non-existing map pointer for capture!");
6460 assert(CurBasePointers.size() == CurPointers.size() &&
6461 CurBasePointers.size() == CurSizes.size() &&
6462 CurBasePointers.size() == CurMapTypes.size() &&
6463 "Inconsistent map information sizes!");
Samuel Antaobed3c462015-10-02 16:14:20 +00006464
Samuel Antao86ace552016-04-27 22:40:57 +00006465 // The kernel args are always the first elements of the base pointers
6466 // associated with a capture.
Samuel Antaocc10b852016-07-28 14:23:26 +00006467 KernelArgs.push_back(*CurBasePointers.front());
Samuel Antao86ace552016-04-27 22:40:57 +00006468 // We need to append the results of this capture to what we already have.
6469 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
6470 Pointers.append(CurPointers.begin(), CurPointers.end());
6471 Sizes.append(CurSizes.begin(), CurSizes.end());
6472 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
Samuel Antaobed3c462015-10-02 16:14:20 +00006473 }
6474
6475 // Keep track on whether the host function has to be executed.
6476 auto OffloadErrorQType =
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006477 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006478 auto OffloadError = CGF.MakeAddrLValue(
6479 CGF.CreateMemTemp(OffloadErrorQType, ".run_host_version"),
6480 OffloadErrorQType);
6481 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty),
6482 OffloadError);
6483
6484 // Fill up the pointer arrays and transfer execution to the device.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00006485 auto &&ThenGen = [&BasePointers, &Pointers, &Sizes, &MapTypes, Device,
6486 OutlinedFnID, OffloadError,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006487 &D](CodeGenFunction &CGF, PrePostActionTy &) {
6488 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antaodf158d52016-04-27 22:58:19 +00006489 // Emit the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00006490 TargetDataInfo Info;
6491 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
6492 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
6493 Info.PointersArray, Info.SizesArray,
6494 Info.MapTypesArray, Info);
Samuel Antaobed3c462015-10-02 16:14:20 +00006495
6496 // On top of the arrays that were filled up, the target offloading call
6497 // takes as arguments the device id as well as the host pointer. The host
6498 // pointer is used by the runtime library to identify the current target
6499 // region, so it only has to be unique and not necessarily point to
6500 // anything. It could be the pointer to the outlined function that
6501 // implements the target region, but we aren't using that so that the
6502 // compiler doesn't need to keep that, and could therefore inline the host
6503 // function if proven worthwhile during optimization.
6504
Samuel Antaoee8fb302016-01-06 13:42:12 +00006505 // From this point on, we need to have an ID of the target region defined.
6506 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00006507
6508 // Emit device ID if any.
6509 llvm::Value *DeviceID;
6510 if (Device)
6511 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006512 CGF.Int32Ty, /*isSigned=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006513 else
6514 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6515
Samuel Antaodf158d52016-04-27 22:58:19 +00006516 // Emit the number of elements in the offloading arrays.
6517 llvm::Value *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6518
Samuel Antaob68e2db2016-03-03 16:20:23 +00006519 // Return value of the runtime offloading call.
6520 llvm::Value *Return;
6521
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006522 auto *NumTeams = emitNumTeamsForTargetDirective(RT, CGF, D);
6523 auto *NumThreads = emitNumThreadsForTargetDirective(RT, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006524
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006525 // The target region is an outlined function launched by the runtime
6526 // via calls __tgt_target() or __tgt_target_teams().
6527 //
6528 // __tgt_target() launches a target region with one team and one thread,
6529 // executing a serial region. This master thread may in turn launch
6530 // more threads within its team upon encountering a parallel region,
6531 // however, no additional teams can be launched on the device.
6532 //
6533 // __tgt_target_teams() launches a target region with one or more teams,
6534 // each with one or more threads. This call is required for target
6535 // constructs such as:
6536 // 'target teams'
6537 // 'target' / 'teams'
6538 // 'target teams distribute parallel for'
6539 // 'target parallel'
6540 // and so on.
6541 //
6542 // Note that on the host and CPU targets, the runtime implementation of
6543 // these calls simply call the outlined function without forking threads.
6544 // The outlined functions themselves have runtime calls to
6545 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by
6546 // the compiler in emitTeamsCall() and emitParallelCall().
6547 //
6548 // In contrast, on the NVPTX target, the implementation of
6549 // __tgt_target_teams() launches a GPU kernel with the requested number
6550 // of teams and threads so no additional calls to the runtime are required.
Samuel Antaob68e2db2016-03-03 16:20:23 +00006551 if (NumTeams) {
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006552 // If we have NumTeams defined this means that we have an enclosed teams
6553 // region. Therefore we also expect to have NumThreads defined. These two
6554 // values should be defined in the presence of a teams directive,
6555 // regardless of having any clauses associated. If the user is using teams
6556 // but no clauses, these two values will be the default that should be
6557 // passed to the runtime library - a 32-bit integer with the value zero.
6558 assert(NumThreads && "Thread limit expression should be available along "
6559 "with number of teams.");
Samuel Antaob68e2db2016-03-03 16:20:23 +00006560 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00006561 DeviceID, OutlinedFnID,
6562 PointerNum, Info.BasePointersArray,
6563 Info.PointersArray, Info.SizesArray,
6564 Info.MapTypesArray, NumTeams,
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00006565 NumThreads};
Samuel Antaob68e2db2016-03-03 16:20:23 +00006566 Return = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006567 RT.createRuntimeFunction(OMPRTL__tgt_target_teams), OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006568 } else {
6569 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00006570 DeviceID, OutlinedFnID,
6571 PointerNum, Info.BasePointersArray,
6572 Info.PointersArray, Info.SizesArray,
6573 Info.MapTypesArray};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006574 Return = CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target),
Samuel Antaob68e2db2016-03-03 16:20:23 +00006575 OffloadingArgs);
6576 }
Samuel Antaobed3c462015-10-02 16:14:20 +00006577
6578 CGF.EmitStoreOfScalar(Return, OffloadError);
6579 };
6580
Samuel Antaoee8fb302016-01-06 13:42:12 +00006581 // Notify that the host version must be executed.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006582 auto &&ElseGen = [OffloadError](CodeGenFunction &CGF, PrePostActionTy &) {
6583 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/-1u),
Samuel Antaoee8fb302016-01-06 13:42:12 +00006584 OffloadError);
6585 };
6586
6587 // If we have a target function ID it means that we need to support
6588 // offloading, otherwise, just execute on the host. We need to execute on host
6589 // regardless of the conditional in the if clause if, e.g., the user do not
6590 // specify target triples.
6591 if (OutlinedFnID) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006592 if (IfCond)
Samuel Antaoee8fb302016-01-06 13:42:12 +00006593 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006594 else {
6595 RegionCodeGenTy ThenRCG(ThenGen);
6596 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00006597 }
6598 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006599 RegionCodeGenTy ElseRCG(ElseGen);
6600 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00006601 }
Samuel Antaobed3c462015-10-02 16:14:20 +00006602
6603 // Check the error code and execute the host version if required.
6604 auto OffloadFailedBlock = CGF.createBasicBlock("omp_offload.failed");
6605 auto OffloadContBlock = CGF.createBasicBlock("omp_offload.cont");
6606 auto OffloadErrorVal = CGF.EmitLoadOfScalar(OffloadError, SourceLocation());
6607 auto Failed = CGF.Builder.CreateIsNotNull(OffloadErrorVal);
6608 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
6609
6610 CGF.EmitBlock(OffloadFailedBlock);
Samuel Antao86ace552016-04-27 22:40:57 +00006611 CGF.Builder.CreateCall(OutlinedFn, KernelArgs);
Samuel Antaobed3c462015-10-02 16:14:20 +00006612 CGF.EmitBranch(OffloadContBlock);
6613
6614 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006615}
Samuel Antaoee8fb302016-01-06 13:42:12 +00006616
6617void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
6618 StringRef ParentName) {
6619 if (!S)
6620 return;
6621
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00006622 // Codegen OMP target directives that offload compute to the device.
6623 bool requiresDeviceCodegen =
6624 isa<OMPExecutableDirective>(S) &&
6625 isOpenMPTargetExecutionDirective(
6626 cast<OMPExecutableDirective>(S)->getDirectiveKind());
Samuel Antaoee8fb302016-01-06 13:42:12 +00006627
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00006628 if (requiresDeviceCodegen) {
6629 auto &E = *cast<OMPExecutableDirective>(S);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006630 unsigned DeviceID;
6631 unsigned FileID;
6632 unsigned Line;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00006633 getTargetEntryUniqueInfo(CGM.getContext(), E.getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00006634 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006635
6636 // Is this a target region that should not be emitted as an entry point? If
6637 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00006638 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
6639 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00006640 return;
6641
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00006642 switch (S->getStmtClass()) {
6643 case Stmt::OMPTargetDirectiveClass:
6644 CodeGenFunction::EmitOMPTargetDeviceFunction(
6645 CGM, ParentName, cast<OMPTargetDirective>(*S));
6646 break;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00006647 case Stmt::OMPTargetParallelDirectiveClass:
6648 CodeGenFunction::EmitOMPTargetParallelDeviceFunction(
6649 CGM, ParentName, cast<OMPTargetParallelDirective>(*S));
6650 break;
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00006651 case Stmt::OMPTargetTeamsDirectiveClass:
6652 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction(
6653 CGM, ParentName, cast<OMPTargetTeamsDirective>(*S));
6654 break;
Arpith Chacko Jacob43a8b7b2017-01-16 15:26:02 +00006655 default:
6656 llvm_unreachable("Unknown target directive for OpenMP device codegen.");
6657 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00006658 return;
6659 }
6660
6661 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
Samuel Antaoe49645c2016-05-08 06:43:56 +00006662 if (!E->hasAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00006663 return;
6664
6665 scanForTargetRegionsFunctions(
6666 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
6667 ParentName);
6668 return;
6669 }
6670
6671 // If this is a lambda function, look into its body.
6672 if (auto *L = dyn_cast<LambdaExpr>(S))
6673 S = L->getBody();
6674
6675 // Keep looking for target regions recursively.
6676 for (auto *II : S->children())
6677 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006678}
6679
6680bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
6681 auto &FD = *cast<FunctionDecl>(GD.getDecl());
6682
6683 // If emitting code for the host, we do not process FD here. Instead we do
6684 // the normal code generation.
6685 if (!CGM.getLangOpts().OpenMPIsDevice)
6686 return false;
6687
6688 // Try to detect target regions in the function.
6689 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
6690
Samuel Antao4b75b872016-12-12 19:26:31 +00006691 // We should not emit any function other that the ones created during the
Samuel Antaoee8fb302016-01-06 13:42:12 +00006692 // scanning. Therefore, we signal that this function is completely dealt
6693 // with.
6694 return true;
6695}
6696
6697bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
6698 if (!CGM.getLangOpts().OpenMPIsDevice)
6699 return false;
6700
6701 // Check if there are Ctors/Dtors in this declaration and look for target
6702 // regions in it. We use the complete variant to produce the kernel name
6703 // mangling.
6704 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
6705 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
6706 for (auto *Ctor : RD->ctors()) {
6707 StringRef ParentName =
6708 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
6709 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
6710 }
6711 auto *Dtor = RD->getDestructor();
6712 if (Dtor) {
6713 StringRef ParentName =
6714 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
6715 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
6716 }
6717 }
6718
Gheorghe-Teodor Bercea47633db2017-06-13 15:35:27 +00006719 // If we are in target mode, we do not emit any global (declare target is not
Samuel Antaoee8fb302016-01-06 13:42:12 +00006720 // implemented yet). Therefore we signal that GD was processed in this case.
6721 return true;
6722}
6723
6724bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
6725 auto *VD = GD.getDecl();
6726 if (isa<FunctionDecl>(VD))
6727 return emitTargetFunctions(GD);
6728
6729 return emitTargetGlobalVariable(GD);
6730}
6731
6732llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
6733 // If we have offloading in the current module, we need to emit the entries
6734 // now and register the offloading descriptor.
6735 createOffloadEntriesAndInfoMetadata();
6736
6737 // Create and register the offloading binary descriptors. This is the main
6738 // entity that captures all the information about offloading in the current
6739 // compilation unit.
6740 return createOffloadingBinaryDescriptorRegistration();
6741}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006742
6743void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
6744 const OMPExecutableDirective &D,
6745 SourceLocation Loc,
6746 llvm::Value *OutlinedFn,
6747 ArrayRef<llvm::Value *> CapturedVars) {
6748 if (!CGF.HaveInsertPoint())
6749 return;
6750
6751 auto *RTLoc = emitUpdateLocation(CGF, Loc);
6752 CodeGenFunction::RunCleanupsScope Scope(CGF);
6753
6754 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
6755 llvm::Value *Args[] = {
6756 RTLoc,
6757 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
6758 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
6759 llvm::SmallVector<llvm::Value *, 16> RealArgs;
6760 RealArgs.append(std::begin(Args), std::end(Args));
6761 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
6762
6763 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
6764 CGF.EmitRuntimeCall(RTLFn, RealArgs);
6765}
6766
6767void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00006768 const Expr *NumTeams,
6769 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006770 SourceLocation Loc) {
6771 if (!CGF.HaveInsertPoint())
6772 return;
6773
6774 auto *RTLoc = emitUpdateLocation(CGF, Loc);
6775
Carlo Bertollic6872252016-04-04 15:55:02 +00006776 llvm::Value *NumTeamsVal =
6777 (NumTeams)
6778 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
6779 CGF.CGM.Int32Ty, /* isSigned = */ true)
6780 : CGF.Builder.getInt32(0);
6781
6782 llvm::Value *ThreadLimitVal =
6783 (ThreadLimit)
6784 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
6785 CGF.CGM.Int32Ty, /* isSigned = */ true)
6786 : CGF.Builder.getInt32(0);
6787
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006788 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00006789 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
6790 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006791 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
6792 PushNumTeamsArgs);
6793}
Samuel Antaodf158d52016-04-27 22:58:19 +00006794
Samuel Antaocc10b852016-07-28 14:23:26 +00006795void CGOpenMPRuntime::emitTargetDataCalls(
6796 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
6797 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006798 if (!CGF.HaveInsertPoint())
6799 return;
6800
Samuel Antaocc10b852016-07-28 14:23:26 +00006801 // Action used to replace the default codegen action and turn privatization
6802 // off.
6803 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00006804
6805 // Generate the code for the opening of the data environment. Capture all the
6806 // arguments of the runtime call by reference because they are used in the
6807 // closing of the region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00006808 auto &&BeginThenGen = [&D, Device, &Info, &CodeGen](CodeGenFunction &CGF,
6809 PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006810 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00006811 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00006812 MappableExprsHandler::MapValuesArrayTy Pointers;
6813 MappableExprsHandler::MapValuesArrayTy Sizes;
6814 MappableExprsHandler::MapFlagsArrayTy MapTypes;
6815
6816 // Get map clause information.
6817 MappableExprsHandler MCHandler(D, CGF);
6818 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00006819
6820 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00006821 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00006822
6823 llvm::Value *BasePointersArrayArg = nullptr;
6824 llvm::Value *PointersArrayArg = nullptr;
6825 llvm::Value *SizesArrayArg = nullptr;
6826 llvm::Value *MapTypesArrayArg = nullptr;
6827 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006828 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00006829
6830 // Emit device ID if any.
6831 llvm::Value *DeviceID = nullptr;
6832 if (Device)
6833 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6834 CGF.Int32Ty, /*isSigned=*/true);
6835 else
6836 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6837
6838 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00006839 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00006840
6841 llvm::Value *OffloadingArgs[] = {
6842 DeviceID, PointerNum, BasePointersArrayArg,
6843 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
6844 auto &RT = CGF.CGM.getOpenMPRuntime();
6845 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_begin),
6846 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00006847
6848 // If device pointer privatization is required, emit the body of the region
6849 // here. It will have to be duplicated: with and without privatization.
6850 if (!Info.CaptureDeviceAddrMap.empty())
6851 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00006852 };
6853
6854 // Generate code for the closing of the data region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00006855 auto &&EndThenGen = [Device, &Info](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006856 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00006857
6858 llvm::Value *BasePointersArrayArg = nullptr;
6859 llvm::Value *PointersArrayArg = nullptr;
6860 llvm::Value *SizesArrayArg = nullptr;
6861 llvm::Value *MapTypesArrayArg = nullptr;
6862 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006863 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00006864
6865 // Emit device ID if any.
6866 llvm::Value *DeviceID = nullptr;
6867 if (Device)
6868 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6869 CGF.Int32Ty, /*isSigned=*/true);
6870 else
6871 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6872
6873 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00006874 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00006875
6876 llvm::Value *OffloadingArgs[] = {
6877 DeviceID, PointerNum, BasePointersArrayArg,
6878 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
6879 auto &RT = CGF.CGM.getOpenMPRuntime();
6880 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_end),
6881 OffloadingArgs);
6882 };
6883
Samuel Antaocc10b852016-07-28 14:23:26 +00006884 // If we need device pointer privatization, we need to emit the body of the
6885 // region with no privatization in the 'else' branch of the conditional.
6886 // Otherwise, we don't have to do anything.
6887 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
6888 PrePostActionTy &) {
6889 if (!Info.CaptureDeviceAddrMap.empty()) {
6890 CodeGen.setAction(NoPrivAction);
6891 CodeGen(CGF);
6892 }
6893 };
6894
6895 // We don't have to do anything to close the region if the if clause evaluates
6896 // to false.
6897 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00006898
6899 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006900 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00006901 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00006902 RegionCodeGenTy RCG(BeginThenGen);
6903 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00006904 }
6905
Samuel Antaocc10b852016-07-28 14:23:26 +00006906 // If we don't require privatization of device pointers, we emit the body in
6907 // between the runtime calls. This avoids duplicating the body code.
6908 if (Info.CaptureDeviceAddrMap.empty()) {
6909 CodeGen.setAction(NoPrivAction);
6910 CodeGen(CGF);
6911 }
Samuel Antaodf158d52016-04-27 22:58:19 +00006912
6913 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006914 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00006915 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00006916 RegionCodeGenTy RCG(EndThenGen);
6917 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00006918 }
6919}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006920
Samuel Antao8d2d7302016-05-26 18:30:22 +00006921void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00006922 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
6923 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006924 if (!CGF.HaveInsertPoint())
6925 return;
6926
Samuel Antao8dd66282016-04-27 23:14:30 +00006927 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00006928 isa<OMPTargetExitDataDirective>(D) ||
6929 isa<OMPTargetUpdateDirective>(D)) &&
6930 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00006931
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006932 // Generate the code for the opening of the data environment.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00006933 auto &&ThenGen = [&D, Device](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006934 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00006935 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006936 MappableExprsHandler::MapValuesArrayTy Pointers;
6937 MappableExprsHandler::MapValuesArrayTy Sizes;
6938 MappableExprsHandler::MapFlagsArrayTy MapTypes;
6939
6940 // Get map clause information.
Samuel Antao8d2d7302016-05-26 18:30:22 +00006941 MappableExprsHandler MEHandler(D, CGF);
6942 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006943
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006944 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00006945 TargetDataInfo Info;
6946 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
6947 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
6948 Info.PointersArray, Info.SizesArray,
6949 Info.MapTypesArray, Info);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006950
6951 // Emit device ID if any.
6952 llvm::Value *DeviceID = nullptr;
6953 if (Device)
6954 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6955 CGF.Int32Ty, /*isSigned=*/true);
6956 else
6957 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6958
6959 // Emit the number of elements in the offloading arrays.
6960 auto *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6961
6962 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00006963 DeviceID, PointerNum, Info.BasePointersArray,
6964 Info.PointersArray, Info.SizesArray, Info.MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00006965
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006966 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antao8d2d7302016-05-26 18:30:22 +00006967 // Select the right runtime function call for each expected standalone
6968 // directive.
6969 OpenMPRTLFunction RTLFn;
6970 switch (D.getDirectiveKind()) {
6971 default:
6972 llvm_unreachable("Unexpected standalone target data directive.");
6973 break;
6974 case OMPD_target_enter_data:
6975 RTLFn = OMPRTL__tgt_target_data_begin;
6976 break;
6977 case OMPD_target_exit_data:
6978 RTLFn = OMPRTL__tgt_target_data_end;
6979 break;
6980 case OMPD_target_update:
6981 RTLFn = OMPRTL__tgt_target_data_update;
6982 break;
6983 }
6984 CGF.EmitRuntimeCall(RT.createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006985 };
6986
6987 // In the event we get an if clause, we don't have to take any action on the
6988 // else side.
6989 auto &&ElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
6990
6991 if (IfCond) {
6992 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
6993 } else {
6994 RegionCodeGenTy ThenGenRCG(ThenGen);
6995 ThenGenRCG(CGF);
6996 }
6997}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00006998
6999namespace {
7000 /// Kind of parameter in a function with 'declare simd' directive.
7001 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
7002 /// Attribute set of the parameter.
7003 struct ParamAttrTy {
7004 ParamKindTy Kind = Vector;
7005 llvm::APSInt StrideOrArg;
7006 llvm::APSInt Alignment;
7007 };
7008} // namespace
7009
7010static unsigned evaluateCDTSize(const FunctionDecl *FD,
7011 ArrayRef<ParamAttrTy> ParamAttrs) {
7012 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
7013 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
7014 // of that clause. The VLEN value must be power of 2.
7015 // In other case the notion of the function`s "characteristic data type" (CDT)
7016 // is used to compute the vector length.
7017 // CDT is defined in the following order:
7018 // a) For non-void function, the CDT is the return type.
7019 // b) If the function has any non-uniform, non-linear parameters, then the
7020 // CDT is the type of the first such parameter.
7021 // c) If the CDT determined by a) or b) above is struct, union, or class
7022 // type which is pass-by-value (except for the type that maps to the
7023 // built-in complex data type), the characteristic data type is int.
7024 // d) If none of the above three cases is applicable, the CDT is int.
7025 // The VLEN is then determined based on the CDT and the size of vector
7026 // register of that ISA for which current vector version is generated. The
7027 // VLEN is computed using the formula below:
7028 // VLEN = sizeof(vector_register) / sizeof(CDT),
7029 // where vector register size specified in section 3.2.1 Registers and the
7030 // Stack Frame of original AMD64 ABI document.
7031 QualType RetType = FD->getReturnType();
7032 if (RetType.isNull())
7033 return 0;
7034 ASTContext &C = FD->getASTContext();
7035 QualType CDT;
7036 if (!RetType.isNull() && !RetType->isVoidType())
7037 CDT = RetType;
7038 else {
7039 unsigned Offset = 0;
7040 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
7041 if (ParamAttrs[Offset].Kind == Vector)
7042 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
7043 ++Offset;
7044 }
7045 if (CDT.isNull()) {
7046 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
7047 if (ParamAttrs[I + Offset].Kind == Vector) {
7048 CDT = FD->getParamDecl(I)->getType();
7049 break;
7050 }
7051 }
7052 }
7053 }
7054 if (CDT.isNull())
7055 CDT = C.IntTy;
7056 CDT = CDT->getCanonicalTypeUnqualified();
7057 if (CDT->isRecordType() || CDT->isUnionType())
7058 CDT = C.IntTy;
7059 return C.getTypeSize(CDT);
7060}
7061
7062static void
7063emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00007064 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007065 ArrayRef<ParamAttrTy> ParamAttrs,
7066 OMPDeclareSimdDeclAttr::BranchStateTy State) {
7067 struct ISADataTy {
7068 char ISA;
7069 unsigned VecRegSize;
7070 };
7071 ISADataTy ISAData[] = {
7072 {
7073 'b', 128
7074 }, // SSE
7075 {
7076 'c', 256
7077 }, // AVX
7078 {
7079 'd', 256
7080 }, // AVX2
7081 {
7082 'e', 512
7083 }, // AVX512
7084 };
7085 llvm::SmallVector<char, 2> Masked;
7086 switch (State) {
7087 case OMPDeclareSimdDeclAttr::BS_Undefined:
7088 Masked.push_back('N');
7089 Masked.push_back('M');
7090 break;
7091 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
7092 Masked.push_back('N');
7093 break;
7094 case OMPDeclareSimdDeclAttr::BS_Inbranch:
7095 Masked.push_back('M');
7096 break;
7097 }
7098 for (auto Mask : Masked) {
7099 for (auto &Data : ISAData) {
7100 SmallString<256> Buffer;
7101 llvm::raw_svector_ostream Out(Buffer);
7102 Out << "_ZGV" << Data.ISA << Mask;
7103 if (!VLENVal) {
7104 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
7105 evaluateCDTSize(FD, ParamAttrs));
7106 } else
7107 Out << VLENVal;
7108 for (auto &ParamAttr : ParamAttrs) {
7109 switch (ParamAttr.Kind){
7110 case LinearWithVarStride:
7111 Out << 's' << ParamAttr.StrideOrArg;
7112 break;
7113 case Linear:
7114 Out << 'l';
7115 if (!!ParamAttr.StrideOrArg)
7116 Out << ParamAttr.StrideOrArg;
7117 break;
7118 case Uniform:
7119 Out << 'u';
7120 break;
7121 case Vector:
7122 Out << 'v';
7123 break;
7124 }
7125 if (!!ParamAttr.Alignment)
7126 Out << 'a' << ParamAttr.Alignment;
7127 }
7128 Out << '_' << Fn->getName();
7129 Fn->addFnAttr(Out.str());
7130 }
7131 }
7132}
7133
7134void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
7135 llvm::Function *Fn) {
7136 ASTContext &C = CGM.getContext();
7137 FD = FD->getCanonicalDecl();
7138 // Map params to their positions in function decl.
7139 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
7140 if (isa<CXXMethodDecl>(FD))
7141 ParamPositions.insert({FD, 0});
7142 unsigned ParamPos = ParamPositions.size();
David Majnemer59f77922016-06-24 04:05:48 +00007143 for (auto *P : FD->parameters()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00007144 ParamPositions.insert({P->getCanonicalDecl(), ParamPos});
7145 ++ParamPos;
7146 }
7147 for (auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
7148 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
7149 // Mark uniform parameters.
7150 for (auto *E : Attr->uniforms()) {
7151 E = E->IgnoreParenImpCasts();
7152 unsigned Pos;
7153 if (isa<CXXThisExpr>(E))
7154 Pos = ParamPositions[FD];
7155 else {
7156 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7157 ->getCanonicalDecl();
7158 Pos = ParamPositions[PVD];
7159 }
7160 ParamAttrs[Pos].Kind = Uniform;
7161 }
7162 // Get alignment info.
7163 auto NI = Attr->alignments_begin();
7164 for (auto *E : Attr->aligneds()) {
7165 E = E->IgnoreParenImpCasts();
7166 unsigned Pos;
7167 QualType ParmTy;
7168 if (isa<CXXThisExpr>(E)) {
7169 Pos = ParamPositions[FD];
7170 ParmTy = E->getType();
7171 } else {
7172 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7173 ->getCanonicalDecl();
7174 Pos = ParamPositions[PVD];
7175 ParmTy = PVD->getType();
7176 }
7177 ParamAttrs[Pos].Alignment =
7178 (*NI) ? (*NI)->EvaluateKnownConstInt(C)
7179 : llvm::APSInt::getUnsigned(
7180 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
7181 .getQuantity());
7182 ++NI;
7183 }
7184 // Mark linear parameters.
7185 auto SI = Attr->steps_begin();
7186 auto MI = Attr->modifiers_begin();
7187 for (auto *E : Attr->linears()) {
7188 E = E->IgnoreParenImpCasts();
7189 unsigned Pos;
7190 if (isa<CXXThisExpr>(E))
7191 Pos = ParamPositions[FD];
7192 else {
7193 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
7194 ->getCanonicalDecl();
7195 Pos = ParamPositions[PVD];
7196 }
7197 auto &ParamAttr = ParamAttrs[Pos];
7198 ParamAttr.Kind = Linear;
7199 if (*SI) {
7200 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
7201 Expr::SE_AllowSideEffects)) {
7202 if (auto *DRE = cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
7203 if (auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
7204 ParamAttr.Kind = LinearWithVarStride;
7205 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
7206 ParamPositions[StridePVD->getCanonicalDecl()]);
7207 }
7208 }
7209 }
7210 }
7211 ++SI;
7212 ++MI;
7213 }
7214 llvm::APSInt VLENVal;
7215 if (const Expr *VLEN = Attr->getSimdlen())
7216 VLENVal = VLEN->EvaluateKnownConstInt(C);
7217 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
7218 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
7219 CGM.getTriple().getArch() == llvm::Triple::x86_64)
7220 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
7221 }
7222}
Alexey Bataev8b427062016-05-25 12:36:08 +00007223
7224namespace {
7225/// Cleanup action for doacross support.
7226class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
7227public:
7228 static const int DoacrossFinArgs = 2;
7229
7230private:
7231 llvm::Value *RTLFn;
7232 llvm::Value *Args[DoacrossFinArgs];
7233
7234public:
7235 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
7236 : RTLFn(RTLFn) {
7237 assert(CallArgs.size() == DoacrossFinArgs);
7238 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
7239 }
7240 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
7241 if (!CGF.HaveInsertPoint())
7242 return;
7243 CGF.EmitRuntimeCall(RTLFn, Args);
7244 }
7245};
7246} // namespace
7247
7248void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
7249 const OMPLoopDirective &D) {
7250 if (!CGF.HaveInsertPoint())
7251 return;
7252
7253 ASTContext &C = CGM.getContext();
7254 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
7255 RecordDecl *RD;
7256 if (KmpDimTy.isNull()) {
7257 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
7258 // kmp_int64 lo; // lower
7259 // kmp_int64 up; // upper
7260 // kmp_int64 st; // stride
7261 // };
7262 RD = C.buildImplicitRecord("kmp_dim");
7263 RD->startDefinition();
7264 addFieldToRecordDecl(C, RD, Int64Ty);
7265 addFieldToRecordDecl(C, RD, Int64Ty);
7266 addFieldToRecordDecl(C, RD, Int64Ty);
7267 RD->completeDefinition();
7268 KmpDimTy = C.getRecordType(RD);
7269 } else
7270 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
7271
7272 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
7273 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
7274 enum { LowerFD = 0, UpperFD, StrideFD };
7275 // Fill dims with data.
7276 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
7277 // dims.upper = num_iterations;
7278 LValue UpperLVal =
7279 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
7280 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
7281 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
7282 Int64Ty, D.getNumIterations()->getExprLoc());
7283 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
7284 // dims.stride = 1;
7285 LValue StrideLVal =
7286 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
7287 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
7288 StrideLVal);
7289
7290 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
7291 // kmp_int32 num_dims, struct kmp_dim * dims);
7292 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
7293 getThreadID(CGF, D.getLocStart()),
7294 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
7295 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
7296 DimsAddr.getPointer(), CGM.VoidPtrTy)};
7297
7298 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
7299 CGF.EmitRuntimeCall(RTLFn, Args);
7300 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
7301 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
7302 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
7303 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
7304 llvm::makeArrayRef(FiniArgs));
7305}
7306
7307void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
7308 const OMPDependClause *C) {
7309 QualType Int64Ty =
7310 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
7311 const Expr *CounterVal = C->getCounterValue();
7312 assert(CounterVal);
7313 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
7314 CounterVal->getType(), Int64Ty,
7315 CounterVal->getExprLoc());
7316 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
7317 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
7318 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
7319 getThreadID(CGF, C->getLocStart()),
7320 CntAddr.getPointer()};
7321 llvm::Value *RTLFn;
7322 if (C->getDependencyKind() == OMPC_DEPEND_source)
7323 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
7324 else {
7325 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
7326 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
7327 }
7328 CGF.EmitRuntimeCall(RTLFn, Args);
7329}
7330