blob: 357bec16bd2c373641ec1d3fedcd96453a1b7075 [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 McCall6c9f1fdb2016-11-19 08:17:24 +000018#include "ConstantBuilder.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000019#include "clang/AST/Decl.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000020#include "clang/AST/StmtOpenMP.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000021#include "llvm/ADT/ArrayRef.h"
Teresa Johnsonffc4e242016-11-11 05:35:12 +000022#include "llvm/Bitcode/BitcodeReader.h"
Alexey Bataevd74d0602014-10-13 06:02:40 +000023#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000024#include "llvm/IR/DerivedTypes.h"
25#include "llvm/IR/GlobalValue.h"
26#include "llvm/IR/Value.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000027#include "llvm/Support/Format.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000028#include "llvm/Support/raw_ostream.h"
Alexey Bataev23b69422014-06-18 07:08:49 +000029#include <cassert>
Alexey Bataev9959db52014-05-06 10:08:46 +000030
31using namespace clang;
32using namespace CodeGen;
33
Benjamin Kramerc52193f2014-10-10 13:57:57 +000034namespace {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000035/// \brief Base class for handling code generation inside OpenMP regions.
Alexey Bataev18095712014-10-10 12:19:54 +000036class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
37public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000038 /// \brief Kinds of OpenMP regions used in codegen.
39 enum CGOpenMPRegionKind {
40 /// \brief Region with outlined function for standalone 'parallel'
41 /// directive.
42 ParallelOutlinedRegion,
43 /// \brief Region with outlined function for standalone 'task' directive.
44 TaskOutlinedRegion,
45 /// \brief Region for constructs that do not require function outlining,
46 /// like 'for', 'sections', 'atomic' etc. directives.
47 InlinedRegion,
Samuel Antaobed3c462015-10-02 16:14:20 +000048 /// \brief Region with outlined function for standalone 'target' directive.
49 TargetRegion,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000050 };
Alexey Bataev18095712014-10-10 12:19:54 +000051
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000052 CGOpenMPRegionInfo(const CapturedStmt &CS,
53 const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000054 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
55 bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000056 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
Alexey Bataev25e5b442015-09-15 12:52:43 +000057 CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000058
59 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000060 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
61 bool HasCancel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +000062 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
Alexey Bataev25e5b442015-09-15 12:52:43 +000063 Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000064
65 /// \brief Get a variable or parameter for storing global thread id
Alexey Bataev18095712014-10-10 12:19:54 +000066 /// inside OpenMP construct.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000067 virtual const VarDecl *getThreadIDVariable() const = 0;
Alexey Bataev18095712014-10-10 12:19:54 +000068
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000069 /// \brief Emit the captured statement body.
Hans Wennborg7eb54642015-09-10 17:07:54 +000070 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000071
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000072 /// \brief Get an LValue for the current ThreadID variable.
Alexey Bataev62b63b12015-03-10 07:28:44 +000073 /// \return LValue for thread id variable. This LValue always has type int32*.
74 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
Alexey Bataev18095712014-10-10 12:19:54 +000075
Alexey Bataev48591dd2016-04-20 04:01:36 +000076 virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {}
77
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000078 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000079
Alexey Bataev81c7ea02015-07-03 09:56:58 +000080 OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
81
Alexey Bataev25e5b442015-09-15 12:52:43 +000082 bool hasCancel() const { return HasCancel; }
83
Alexey Bataev18095712014-10-10 12:19:54 +000084 static bool classof(const CGCapturedStmtInfo *Info) {
85 return Info->getKind() == CR_OpenMP;
86 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000087
Alexey Bataev48591dd2016-04-20 04:01:36 +000088 ~CGOpenMPRegionInfo() override = default;
89
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000090protected:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000091 CGOpenMPRegionKind RegionKind;
Hans Wennborg45c74392016-01-12 20:54:36 +000092 RegionCodeGenTy CodeGen;
Alexey Bataev81c7ea02015-07-03 09:56:58 +000093 OpenMPDirectiveKind Kind;
Alexey Bataev25e5b442015-09-15 12:52:43 +000094 bool HasCancel;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000095};
Alexey Bataev18095712014-10-10 12:19:54 +000096
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000097/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +000098class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000099public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000100 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000101 const RegionCodeGenTy &CodeGen,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000102 OpenMPDirectiveKind Kind, bool HasCancel,
103 StringRef HelperName)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000104 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
105 HasCancel),
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000106 ThreadIDVar(ThreadIDVar), HelperName(HelperName) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000107 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
108 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000109
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000110 /// \brief Get a variable or parameter for storing global thread id
111 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000112 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000113
Alexey Bataev18095712014-10-10 12:19:54 +0000114 /// \brief Get the name of the capture helper.
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000115 StringRef getHelperName() const override { return HelperName; }
Alexey Bataev18095712014-10-10 12:19:54 +0000116
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000117 static bool classof(const CGCapturedStmtInfo *Info) {
118 return CGOpenMPRegionInfo::classof(Info) &&
119 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
120 ParallelOutlinedRegion;
121 }
122
Alexey Bataev18095712014-10-10 12:19:54 +0000123private:
124 /// \brief A variable or parameter storing global thread id for OpenMP
125 /// constructs.
126 const VarDecl *ThreadIDVar;
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000127 StringRef HelperName;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000128};
129
Alexey Bataev62b63b12015-03-10 07:28:44 +0000130/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000131class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000132public:
Alexey Bataev48591dd2016-04-20 04:01:36 +0000133 class UntiedTaskActionTy final : public PrePostActionTy {
134 bool Untied;
135 const VarDecl *PartIDVar;
136 const RegionCodeGenTy UntiedCodeGen;
137 llvm::SwitchInst *UntiedSwitch = nullptr;
138
139 public:
140 UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
141 const RegionCodeGenTy &UntiedCodeGen)
142 : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
143 void Enter(CodeGenFunction &CGF) override {
144 if (Untied) {
145 // Emit task switching point.
146 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
147 CGF.GetAddrOfLocalVar(PartIDVar),
148 PartIDVar->getType()->castAs<PointerType>());
149 auto *Res = CGF.EmitLoadOfScalar(PartIdLVal, SourceLocation());
150 auto *DoneBB = CGF.createBasicBlock(".untied.done.");
151 UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
152 CGF.EmitBlock(DoneBB);
153 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
154 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
155 UntiedSwitch->addCase(CGF.Builder.getInt32(0),
156 CGF.Builder.GetInsertBlock());
157 emitUntiedSwitch(CGF);
158 }
159 }
160 void emitUntiedSwitch(CodeGenFunction &CGF) const {
161 if (Untied) {
162 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
163 CGF.GetAddrOfLocalVar(PartIDVar),
164 PartIDVar->getType()->castAs<PointerType>());
165 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
166 PartIdLVal);
167 UntiedCodeGen(CGF);
168 CodeGenFunction::JumpDest CurPoint =
169 CGF.getJumpDestInCurrentScope(".untied.next.");
170 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
171 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
172 UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
173 CGF.Builder.GetInsertBlock());
174 CGF.EmitBranchThroughCleanup(CurPoint);
175 CGF.EmitBlock(CurPoint.getBlock());
176 }
177 }
178 unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
179 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000180 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000181 const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000182 const RegionCodeGenTy &CodeGen,
Alexey Bataev48591dd2016-04-20 04:01:36 +0000183 OpenMPDirectiveKind Kind, bool HasCancel,
184 const UntiedTaskActionTy &Action)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000185 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
Alexey Bataev48591dd2016-04-20 04:01:36 +0000186 ThreadIDVar(ThreadIDVar), Action(Action) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000187 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
188 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000189
Alexey Bataev62b63b12015-03-10 07:28:44 +0000190 /// \brief Get a variable or parameter for storing global thread id
191 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000192 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000193
194 /// \brief Get an LValue for the current ThreadID variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000195 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000196
Alexey Bataev62b63b12015-03-10 07:28:44 +0000197 /// \brief Get the name of the capture helper.
198 StringRef getHelperName() const override { return ".omp_outlined."; }
199
Alexey Bataev48591dd2016-04-20 04:01:36 +0000200 void emitUntiedSwitch(CodeGenFunction &CGF) override {
201 Action.emitUntiedSwitch(CGF);
202 }
203
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000204 static bool classof(const CGCapturedStmtInfo *Info) {
205 return CGOpenMPRegionInfo::classof(Info) &&
206 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
207 TaskOutlinedRegion;
208 }
209
Alexey Bataev62b63b12015-03-10 07:28:44 +0000210private:
211 /// \brief A variable or parameter storing global thread id for OpenMP
212 /// constructs.
213 const VarDecl *ThreadIDVar;
Alexey Bataev48591dd2016-04-20 04:01:36 +0000214 /// Action for emitting code for untied tasks.
215 const UntiedTaskActionTy &Action;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000216};
217
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000218/// \brief API for inlined captured statement code generation in OpenMP
219/// constructs.
220class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
221public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000222 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000223 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000224 OpenMPDirectiveKind Kind, bool HasCancel)
225 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
226 OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000227 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000228
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000229 // \brief Retrieve the value of the context parameter.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000230 llvm::Value *getContextValue() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000231 if (OuterRegionInfo)
232 return OuterRegionInfo->getContextValue();
233 llvm_unreachable("No context value for inlined OpenMP region");
234 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000235
Hans Wennborg7eb54642015-09-10 17:07:54 +0000236 void setContextValue(llvm::Value *V) override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000237 if (OuterRegionInfo) {
238 OuterRegionInfo->setContextValue(V);
239 return;
240 }
241 llvm_unreachable("No context value for inlined OpenMP region");
242 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000243
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000244 /// \brief Lookup the captured field decl for a variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000245 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000246 if (OuterRegionInfo)
247 return OuterRegionInfo->lookup(VD);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000248 // If there is no outer outlined region,no need to lookup in a list of
249 // captured variables, we can use the original one.
250 return nullptr;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000251 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000252
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000253 FieldDecl *getThisFieldDecl() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000254 if (OuterRegionInfo)
255 return OuterRegionInfo->getThisFieldDecl();
256 return nullptr;
257 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000258
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000259 /// \brief Get a variable or parameter for storing global thread id
260 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000261 const VarDecl *getThreadIDVariable() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000262 if (OuterRegionInfo)
263 return OuterRegionInfo->getThreadIDVariable();
264 return nullptr;
265 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000266
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000267 /// \brief Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000268 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000269 if (auto *OuterRegionInfo = getOldCSI())
270 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000271 llvm_unreachable("No helper name for inlined OpenMP construct");
272 }
273
Alexey Bataev48591dd2016-04-20 04:01:36 +0000274 void emitUntiedSwitch(CodeGenFunction &CGF) override {
275 if (OuterRegionInfo)
276 OuterRegionInfo->emitUntiedSwitch(CGF);
277 }
278
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000279 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
280
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000281 static bool classof(const CGCapturedStmtInfo *Info) {
282 return CGOpenMPRegionInfo::classof(Info) &&
283 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
284 }
285
Alexey Bataev48591dd2016-04-20 04:01:36 +0000286 ~CGOpenMPInlinedRegionInfo() override = default;
287
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000288private:
289 /// \brief CodeGen info about outer OpenMP region.
290 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
291 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000292};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000293
Samuel Antaobed3c462015-10-02 16:14:20 +0000294/// \brief API for captured statement code generation in OpenMP target
295/// constructs. For this captures, implicit parameters are used instead of the
Samuel Antaoee8fb302016-01-06 13:42:12 +0000296/// captured fields. The name of the target region has to be unique in a given
297/// application so it is provided by the client, because only the client has
298/// the information to generate that.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000299class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
Samuel Antaobed3c462015-10-02 16:14:20 +0000300public:
301 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000302 const RegionCodeGenTy &CodeGen, StringRef HelperName)
Samuel Antaobed3c462015-10-02 16:14:20 +0000303 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000304 /*HasCancel=*/false),
305 HelperName(HelperName) {}
Samuel Antaobed3c462015-10-02 16:14:20 +0000306
307 /// \brief This is unused for target regions because each starts executing
308 /// with a single thread.
309 const VarDecl *getThreadIDVariable() const override { return nullptr; }
310
311 /// \brief Get the name of the capture helper.
Samuel Antaoee8fb302016-01-06 13:42:12 +0000312 StringRef getHelperName() const override { return HelperName; }
Samuel Antaobed3c462015-10-02 16:14:20 +0000313
314 static bool classof(const CGCapturedStmtInfo *Info) {
315 return CGOpenMPRegionInfo::classof(Info) &&
316 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
317 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000318
319private:
320 StringRef HelperName;
Samuel Antaobed3c462015-10-02 16:14:20 +0000321};
322
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000323static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000324 llvm_unreachable("No codegen for expressions");
325}
326/// \brief API for generation of expressions captured in a innermost OpenMP
327/// region.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000328class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000329public:
330 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
331 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
332 OMPD_unknown,
333 /*HasCancel=*/false),
334 PrivScope(CGF) {
335 // Make sure the globals captured in the provided statement are local by
336 // using the privatization logic. We assume the same variable is not
337 // captured more than once.
338 for (auto &C : CS.captures()) {
339 if (!C.capturesVariable() && !C.capturesVariableByCopy())
340 continue;
341
342 const VarDecl *VD = C.getCapturedVar();
343 if (VD->isLocalVarDeclOrParm())
344 continue;
345
346 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
347 /*RefersToEnclosingVariableOrCapture=*/false,
348 VD->getType().getNonReferenceType(), VK_LValue,
349 SourceLocation());
350 PrivScope.addPrivate(VD, [&CGF, &DRE]() -> Address {
351 return CGF.EmitLValue(&DRE).getAddress();
352 });
353 }
354 (void)PrivScope.Privatize();
355 }
356
357 /// \brief Lookup the captured field decl for a variable.
358 const FieldDecl *lookup(const VarDecl *VD) const override {
359 if (auto *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
360 return FD;
361 return nullptr;
362 }
363
364 /// \brief Emit the captured statement body.
365 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
366 llvm_unreachable("No body for expressions");
367 }
368
369 /// \brief Get a variable or parameter for storing global thread id
370 /// inside OpenMP construct.
371 const VarDecl *getThreadIDVariable() const override {
372 llvm_unreachable("No thread id for expressions");
373 }
374
375 /// \brief Get the name of the capture helper.
376 StringRef getHelperName() const override {
377 llvm_unreachable("No helper name for expressions");
378 }
379
380 static bool classof(const CGCapturedStmtInfo *Info) { return false; }
381
382private:
383 /// Private scope to capture global variables.
384 CodeGenFunction::OMPPrivateScope PrivScope;
385};
386
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000387/// \brief RAII for emitting code of OpenMP constructs.
388class InlinedOpenMPRegionRAII {
389 CodeGenFunction &CGF;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000390 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
391 FieldDecl *LambdaThisCaptureField = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000392
393public:
394 /// \brief Constructs region for combined constructs.
395 /// \param CodeGen Code generation sequence for combined directives. Includes
396 /// a list of functions used for code generation of implicitly inlined
397 /// regions.
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000398 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000399 OpenMPDirectiveKind Kind, bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000400 : CGF(CGF) {
401 // Start emission for the construct.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000402 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
403 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000404 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
405 LambdaThisCaptureField = CGF.LambdaThisCaptureField;
406 CGF.LambdaThisCaptureField = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000407 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000408
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000409 ~InlinedOpenMPRegionRAII() {
410 // Restore original CapturedStmtInfo only if we're done with code emission.
411 auto *OldCSI =
412 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
413 delete CGF.CapturedStmtInfo;
414 CGF.CapturedStmtInfo = OldCSI;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000415 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
416 CGF.LambdaThisCaptureField = LambdaThisCaptureField;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000417 }
418};
419
Alexey Bataev50b3c952016-02-19 10:38:26 +0000420/// \brief Values for bit flags used in the ident_t to describe the fields.
421/// All enumeric elements are named and described in accordance with the code
422/// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
423enum OpenMPLocationFlags {
424 /// \brief Use trampoline for internal microtask.
425 OMP_IDENT_IMD = 0x01,
426 /// \brief Use c-style ident structure.
427 OMP_IDENT_KMPC = 0x02,
428 /// \brief Atomic reduction option for kmpc_reduce.
429 OMP_ATOMIC_REDUCE = 0x10,
430 /// \brief Explicit 'barrier' directive.
431 OMP_IDENT_BARRIER_EXPL = 0x20,
432 /// \brief Implicit barrier in code.
433 OMP_IDENT_BARRIER_IMPL = 0x40,
434 /// \brief Implicit barrier in 'for' directive.
435 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
436 /// \brief Implicit barrier in 'sections' directive.
437 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
438 /// \brief Implicit barrier in 'single' directive.
439 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140
440};
441
442/// \brief Describes ident structure that describes a source location.
443/// All descriptions are taken from
444/// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
445/// Original structure:
446/// typedef struct ident {
447/// kmp_int32 reserved_1; /**< might be used in Fortran;
448/// see above */
449/// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
450/// KMP_IDENT_KMPC identifies this union
451/// member */
452/// kmp_int32 reserved_2; /**< not really used in Fortran any more;
453/// see above */
454///#if USE_ITT_BUILD
455/// /* but currently used for storing
456/// region-specific ITT */
457/// /* contextual information. */
458///#endif /* USE_ITT_BUILD */
459/// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
460/// C++ */
461/// char const *psource; /**< String describing the source location.
462/// The string is composed of semi-colon separated
463// fields which describe the source file,
464/// the function and a pair of line numbers that
465/// delimit the construct.
466/// */
467/// } ident_t;
468enum IdentFieldIndex {
469 /// \brief might be used in Fortran
470 IdentField_Reserved_1,
471 /// \brief OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
472 IdentField_Flags,
473 /// \brief Not really used in Fortran any more
474 IdentField_Reserved_2,
475 /// \brief Source[4] in Fortran, do not use for C++
476 IdentField_Reserved_3,
477 /// \brief String describing the source location. The string is composed of
478 /// semi-colon separated fields which describe the source file, the function
479 /// and a pair of line numbers that delimit the construct.
480 IdentField_PSource
481};
482
483/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
484/// the enum sched_type in kmp.h).
485enum OpenMPSchedType {
486 /// \brief Lower bound for default (unordered) versions.
487 OMP_sch_lower = 32,
488 OMP_sch_static_chunked = 33,
489 OMP_sch_static = 34,
490 OMP_sch_dynamic_chunked = 35,
491 OMP_sch_guided_chunked = 36,
492 OMP_sch_runtime = 37,
493 OMP_sch_auto = 38,
Alexey Bataev6cff6242016-05-30 13:05:14 +0000494 /// static with chunk adjustment (e.g., simd)
Samuel Antao4c8035b2016-12-12 18:00:20 +0000495 OMP_sch_static_balanced_chunked = 45,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000496 /// \brief Lower bound for 'ordered' versions.
497 OMP_ord_lower = 64,
498 OMP_ord_static_chunked = 65,
499 OMP_ord_static = 66,
500 OMP_ord_dynamic_chunked = 67,
501 OMP_ord_guided_chunked = 68,
502 OMP_ord_runtime = 69,
503 OMP_ord_auto = 70,
504 OMP_sch_default = OMP_sch_static,
Carlo Bertollifc35ad22016-03-07 16:04:49 +0000505 /// \brief dist_schedule types
506 OMP_dist_sch_static_chunked = 91,
507 OMP_dist_sch_static = 92,
Alexey Bataev9ebd7422016-05-10 09:57:36 +0000508 /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
509 /// Set if the monotonic schedule modifier was present.
510 OMP_sch_modifier_monotonic = (1 << 29),
511 /// Set if the nonmonotonic schedule modifier was present.
512 OMP_sch_modifier_nonmonotonic = (1 << 30),
Alexey Bataev50b3c952016-02-19 10:38:26 +0000513};
514
515enum OpenMPRTLFunction {
516 /// \brief Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
517 /// kmpc_micro microtask, ...);
518 OMPRTL__kmpc_fork_call,
519 /// \brief Call to void *__kmpc_threadprivate_cached(ident_t *loc,
520 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
521 OMPRTL__kmpc_threadprivate_cached,
522 /// \brief Call to void __kmpc_threadprivate_register( ident_t *,
523 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
524 OMPRTL__kmpc_threadprivate_register,
525 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
526 OMPRTL__kmpc_global_thread_num,
527 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
528 // kmp_critical_name *crit);
529 OMPRTL__kmpc_critical,
530 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
531 // global_tid, kmp_critical_name *crit, uintptr_t hint);
532 OMPRTL__kmpc_critical_with_hint,
533 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
534 // kmp_critical_name *crit);
535 OMPRTL__kmpc_end_critical,
536 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
537 // global_tid);
538 OMPRTL__kmpc_cancel_barrier,
539 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
540 OMPRTL__kmpc_barrier,
541 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
542 OMPRTL__kmpc_for_static_fini,
543 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
544 // global_tid);
545 OMPRTL__kmpc_serialized_parallel,
546 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
547 // global_tid);
548 OMPRTL__kmpc_end_serialized_parallel,
549 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
550 // kmp_int32 num_threads);
551 OMPRTL__kmpc_push_num_threads,
552 // Call to void __kmpc_flush(ident_t *loc);
553 OMPRTL__kmpc_flush,
554 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
555 OMPRTL__kmpc_master,
556 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
557 OMPRTL__kmpc_end_master,
558 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
559 // int end_part);
560 OMPRTL__kmpc_omp_taskyield,
561 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
562 OMPRTL__kmpc_single,
563 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
564 OMPRTL__kmpc_end_single,
565 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
566 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
567 // kmp_routine_entry_t *task_entry);
568 OMPRTL__kmpc_omp_task_alloc,
569 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
570 // new_task);
571 OMPRTL__kmpc_omp_task,
572 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
573 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
574 // kmp_int32 didit);
575 OMPRTL__kmpc_copyprivate,
576 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
577 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
578 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
579 OMPRTL__kmpc_reduce,
580 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
581 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
582 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
583 // *lck);
584 OMPRTL__kmpc_reduce_nowait,
585 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
586 // kmp_critical_name *lck);
587 OMPRTL__kmpc_end_reduce,
588 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
589 // kmp_critical_name *lck);
590 OMPRTL__kmpc_end_reduce_nowait,
591 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
592 // kmp_task_t * new_task);
593 OMPRTL__kmpc_omp_task_begin_if0,
594 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
595 // kmp_task_t * new_task);
596 OMPRTL__kmpc_omp_task_complete_if0,
597 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
598 OMPRTL__kmpc_ordered,
599 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
600 OMPRTL__kmpc_end_ordered,
601 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
602 // global_tid);
603 OMPRTL__kmpc_omp_taskwait,
604 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
605 OMPRTL__kmpc_taskgroup,
606 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
607 OMPRTL__kmpc_end_taskgroup,
608 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
609 // int proc_bind);
610 OMPRTL__kmpc_push_proc_bind,
611 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
612 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
613 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
614 OMPRTL__kmpc_omp_task_with_deps,
615 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
616 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
617 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
618 OMPRTL__kmpc_omp_wait_deps,
619 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
620 // global_tid, kmp_int32 cncl_kind);
621 OMPRTL__kmpc_cancellationpoint,
622 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
623 // kmp_int32 cncl_kind);
624 OMPRTL__kmpc_cancel,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000625 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
626 // kmp_int32 num_teams, kmp_int32 thread_limit);
627 OMPRTL__kmpc_push_num_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000628 // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
629 // microtask, ...);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000630 OMPRTL__kmpc_fork_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000631 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
632 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
633 // sched, kmp_uint64 grainsize, void *task_dup);
634 OMPRTL__kmpc_taskloop,
Alexey Bataev8b427062016-05-25 12:36:08 +0000635 // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
636 // num_dims, struct kmp_dim *dims);
637 OMPRTL__kmpc_doacross_init,
638 // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
639 OMPRTL__kmpc_doacross_fini,
640 // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
641 // *vec);
642 OMPRTL__kmpc_doacross_post,
643 // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
644 // *vec);
645 OMPRTL__kmpc_doacross_wait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000646
647 //
648 // Offloading related calls
649 //
650 // Call to int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
651 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
652 // *arg_types);
653 OMPRTL__tgt_target,
Samuel Antaob68e2db2016-03-03 16:20:23 +0000654 // Call to int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
655 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
656 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
657 OMPRTL__tgt_target_teams,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000658 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
659 OMPRTL__tgt_register_lib,
660 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
661 OMPRTL__tgt_unregister_lib,
Samuel Antaodf158d52016-04-27 22:58:19 +0000662 // Call to void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
663 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
664 OMPRTL__tgt_target_data_begin,
665 // Call to void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
666 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
667 OMPRTL__tgt_target_data_end,
Samuel Antao8d2d7302016-05-26 18:30:22 +0000668 // Call to void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
669 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
670 OMPRTL__tgt_target_data_update,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000671};
672
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000673/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
674/// region.
675class CleanupTy final : public EHScopeStack::Cleanup {
676 PrePostActionTy *Action;
677
678public:
679 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
680 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
681 if (!CGF.HaveInsertPoint())
682 return;
683 Action->Exit(CGF);
684 }
685};
686
Hans Wennborg7eb54642015-09-10 17:07:54 +0000687} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000688
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000689void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
690 CodeGenFunction::RunCleanupsScope Scope(CGF);
691 if (PrePostAction) {
692 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
693 Callback(CodeGen, CGF, *PrePostAction);
694 } else {
695 PrePostActionTy Action;
696 Callback(CodeGen, CGF, Action);
697 }
698}
699
Alexey Bataev18095712014-10-10 12:19:54 +0000700LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +0000701 return CGF.EmitLoadOfPointerLValue(
702 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
703 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +0000704}
705
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000706void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000707 if (!CGF.HaveInsertPoint())
708 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000709 // 1.2.2 OpenMP Language Terminology
710 // Structured block - An executable statement with a single entry at the
711 // top and a single exit at the bottom.
712 // The point of exit cannot be a branch out of the structured block.
713 // longjmp() and throw() must not violate the entry/exit criteria.
714 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000715 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000716 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000717}
718
Alexey Bataev62b63b12015-03-10 07:28:44 +0000719LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
720 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000721 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
722 getThreadIDVariable()->getType(),
723 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000724}
725
Alexey Bataev9959db52014-05-06 10:08:46 +0000726CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000727 : CGM(CGM), OffloadEntriesInfoManager(CGM) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000728 IdentTy = llvm::StructType::create(
729 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
730 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Alexander Musmanfdfa8552014-09-11 08:10:57 +0000731 CGM.Int8PtrTy /* psource */, nullptr);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000732 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +0000733
734 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +0000735}
736
Alexey Bataev91797552015-03-18 04:13:55 +0000737void CGOpenMPRuntime::clear() {
738 InternalVars.clear();
739}
740
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000741static llvm::Function *
742emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
743 const Expr *CombinerInitializer, const VarDecl *In,
744 const VarDecl *Out, bool IsCombiner) {
745 // void .omp_combiner.(Ty *in, Ty *out);
746 auto &C = CGM.getContext();
747 QualType PtrTy = C.getPointerType(Ty).withRestrict();
748 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000749 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
750 /*Id=*/nullptr, PtrTy);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000751 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
752 /*Id=*/nullptr, PtrTy);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000753 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000754 Args.push_back(&OmpInParm);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000755 auto &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +0000756 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000757 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
758 auto *Fn = llvm::Function::Create(
759 FnTy, llvm::GlobalValue::InternalLinkage,
760 IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
761 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +0000762 Fn->removeFnAttr(llvm::Attribute::NoInline);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000763 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000764 CodeGenFunction CGF(CGM);
765 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
766 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
767 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
768 CodeGenFunction::OMPPrivateScope Scope(CGF);
769 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
770 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
771 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
772 .getAddress();
773 });
774 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
775 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
776 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
777 .getAddress();
778 });
779 (void)Scope.Privatize();
780 CGF.EmitIgnoredExpr(CombinerInitializer);
781 Scope.ForceCleanup();
782 CGF.FinishFunction();
783 return Fn;
784}
785
786void CGOpenMPRuntime::emitUserDefinedReduction(
787 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
788 if (UDRMap.count(D) > 0)
789 return;
790 auto &C = CGM.getContext();
791 if (!In || !Out) {
792 In = &C.Idents.get("omp_in");
793 Out = &C.Idents.get("omp_out");
794 }
795 llvm::Function *Combiner = emitCombinerOrInitializer(
796 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
797 cast<VarDecl>(D->lookup(Out).front()),
798 /*IsCombiner=*/true);
799 llvm::Function *Initializer = nullptr;
800 if (auto *Init = D->getInitializer()) {
801 if (!Priv || !Orig) {
802 Priv = &C.Idents.get("omp_priv");
803 Orig = &C.Idents.get("omp_orig");
804 }
805 Initializer = emitCombinerOrInitializer(
806 CGM, D->getType(), Init, cast<VarDecl>(D->lookup(Orig).front()),
807 cast<VarDecl>(D->lookup(Priv).front()),
808 /*IsCombiner=*/false);
809 }
810 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
811 if (CGF) {
812 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
813 Decls.second.push_back(D);
814 }
815}
816
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000817std::pair<llvm::Function *, llvm::Function *>
818CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
819 auto I = UDRMap.find(D);
820 if (I != UDRMap.end())
821 return I->second;
822 emitUserDefinedReduction(/*CGF=*/nullptr, D);
823 return UDRMap.lookup(D);
824}
825
John McCall7f416cc2015-09-08 08:05:57 +0000826// Layout information for ident_t.
827static CharUnits getIdentAlign(CodeGenModule &CGM) {
828 return CGM.getPointerAlign();
829}
830static CharUnits getIdentSize(CodeGenModule &CGM) {
831 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
832 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
833}
Alexey Bataev50b3c952016-02-19 10:38:26 +0000834static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
John McCall7f416cc2015-09-08 08:05:57 +0000835 // All the fields except the last are i32, so this works beautifully.
836 return unsigned(Field) * CharUnits::fromQuantity(4);
837}
838static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000839 IdentFieldIndex Field,
John McCall7f416cc2015-09-08 08:05:57 +0000840 const llvm::Twine &Name = "") {
841 auto Offset = getOffsetOfIdentField(Field);
842 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
843}
844
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000845llvm::Value *CGOpenMPRuntime::emitParallelOrTeamsOutlinedFunction(
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000846 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
847 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000848 assert(ThreadIDVar->getType()->isPointerType() &&
849 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +0000850 const CapturedStmt *CS = cast<CapturedStmt>(D.getAssociatedStmt());
851 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +0000852 bool HasCancel = false;
853 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
854 HasCancel = OPD->hasCancel();
855 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
856 HasCancel = OPSD->hasCancel();
857 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
858 HasCancel = OPFD->hasCancel();
859 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +0000860 HasCancel, getOutlinedHelperName());
Alexey Bataevd157d472015-06-24 03:35:38 +0000861 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000862 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +0000863}
864
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000865llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
866 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +0000867 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
868 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
869 bool Tied, unsigned &NumberOfParts) {
870 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
871 PrePostActionTy &) {
872 auto *ThreadID = getThreadID(CGF, D.getLocStart());
873 auto *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
874 llvm::Value *TaskArgs[] = {
875 UpLoc, ThreadID,
876 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
877 TaskTVar->getType()->castAs<PointerType>())
878 .getPointer()};
879 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
880 };
881 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
882 UntiedCodeGen);
883 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000884 assert(!ThreadIDVar->getType()->isPointerType() &&
885 "thread id variable must be of type kmp_int32 for tasks");
886 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
Alexey Bataev7292c292016-04-25 12:22:29 +0000887 auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000888 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +0000889 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
890 InnermostKind,
891 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +0000892 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev48591dd2016-04-20 04:01:36 +0000893 auto *Res = CGF.GenerateCapturedStmtFunction(*CS);
894 if (!Tied)
895 NumberOfParts = Action.getNumberOfParts();
896 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000897}
898
Alexey Bataev50b3c952016-02-19 10:38:26 +0000899Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +0000900 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +0000901 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000902 if (!Entry) {
903 if (!DefaultOpenMPPSource) {
904 // Initialize default location for psource field of ident_t structure of
905 // all ident_t objects. Format is ";file;function;line;column;;".
906 // Taken from
907 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
908 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +0000909 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000910 DefaultOpenMPPSource =
911 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
912 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000913
John McCall23c9dc62016-11-28 22:18:27 +0000914 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +0000915 auto fields = builder.beginStruct(IdentTy);
916 fields.addInt(CGM.Int32Ty, 0);
917 fields.addInt(CGM.Int32Ty, Flags);
918 fields.addInt(CGM.Int32Ty, 0);
919 fields.addInt(CGM.Int32Ty, 0);
920 fields.add(DefaultOpenMPPSource);
921 auto DefaultOpenMPLocation =
922 fields.finishAndCreateGlobal("", Align, /*isConstant*/ true,
923 llvm::GlobalValue::PrivateLinkage);
924 DefaultOpenMPLocation->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
925
John McCall7f416cc2015-09-08 08:05:57 +0000926 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +0000927 }
John McCall7f416cc2015-09-08 08:05:57 +0000928 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +0000929}
930
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000931llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
932 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000933 unsigned Flags) {
934 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +0000935 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +0000936 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +0000937 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +0000938 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000939
940 assert(CGF.CurFn && "No function in current CodeGenFunction.");
941
John McCall7f416cc2015-09-08 08:05:57 +0000942 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000943 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
944 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +0000945 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
946
Alexander Musmanc6388682014-12-15 07:07:06 +0000947 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
948 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +0000949 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000950 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +0000951 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
952 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +0000953 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +0000954 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000955 LocValue = AI;
956
957 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
958 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000959 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +0000960 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +0000961 }
962
963 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +0000964 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +0000965
Alexey Bataevf002aca2014-05-30 05:48:40 +0000966 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
967 if (OMPDebugLoc == nullptr) {
968 SmallString<128> Buffer2;
969 llvm::raw_svector_ostream OS2(Buffer2);
970 // Build debug location
971 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
972 OS2 << ";" << PLoc.getFilename() << ";";
973 if (const FunctionDecl *FD =
974 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
975 OS2 << FD->getQualifiedNameAsString();
976 }
977 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
978 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
979 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +0000980 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000981 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +0000982 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
983
John McCall7f416cc2015-09-08 08:05:57 +0000984 // Our callers always pass this to a runtime function, so for
985 // convenience, go ahead and return a naked pointer.
986 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000987}
988
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000989llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
990 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000991 assert(CGF.CurFn && "No function in current CodeGenFunction.");
992
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000993 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +0000994 // Check whether we've already cached a load of the thread id in this
995 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000996 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +0000997 if (I != OpenMPLocThreadIDMap.end()) {
998 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +0000999 if (ThreadID != nullptr)
1000 return ThreadID;
1001 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001002 if (auto *OMPRegionInfo =
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001003 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001004 if (OMPRegionInfo->getThreadIDVariable()) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001005 // Check if this an outlined function with thread id passed as argument.
1006 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001007 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
1008 // If value loaded in entry block, cache it and use it everywhere in
1009 // function.
1010 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1011 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1012 Elem.second.ThreadID = ThreadID;
1013 }
1014 return ThreadID;
Alexey Bataevd6c57552014-07-25 07:55:17 +00001015 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001016 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001017
1018 // This is not an outlined function region - need to call __kmpc_int32
1019 // kmpc_global_thread_num(ident_t *loc).
1020 // Generate thread id value and cache this value for use across the
1021 // function.
1022 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1023 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
1024 ThreadID =
1025 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1026 emitUpdateLocation(CGF, Loc));
1027 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1028 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001029 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +00001030}
1031
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001032void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001033 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001034 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1035 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001036 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1037 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
1038 UDRMap.erase(D);
1039 }
1040 FunctionUDRMap.erase(CGF.CurFn);
1041 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001042}
1043
1044llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001045 if (!IdentTy) {
1046 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001047 return llvm::PointerType::getUnqual(IdentTy);
1048}
1049
1050llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001051 if (!Kmpc_MicroTy) {
1052 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1053 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1054 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1055 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1056 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001057 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1058}
1059
1060llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001061CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001062 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001063 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001064 case OMPRTL__kmpc_fork_call: {
1065 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1066 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001067 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1068 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001069 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001070 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001071 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1072 break;
1073 }
1074 case OMPRTL__kmpc_global_thread_num: {
1075 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001076 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001077 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001078 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001079 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1080 break;
1081 }
Alexey Bataev97720002014-11-11 04:05:39 +00001082 case OMPRTL__kmpc_threadprivate_cached: {
1083 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1084 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1085 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1086 CGM.VoidPtrTy, CGM.SizeTy,
1087 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1088 llvm::FunctionType *FnTy =
1089 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1090 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1091 break;
1092 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001093 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001094 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1095 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001096 llvm::Type *TypeParams[] = {
1097 getIdentTyPointerTy(), CGM.Int32Ty,
1098 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1099 llvm::FunctionType *FnTy =
1100 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1101 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1102 break;
1103 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001104 case OMPRTL__kmpc_critical_with_hint: {
1105 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1106 // kmp_critical_name *crit, uintptr_t hint);
1107 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1108 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1109 CGM.IntPtrTy};
1110 llvm::FunctionType *FnTy =
1111 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1112 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1113 break;
1114 }
Alexey Bataev97720002014-11-11 04:05:39 +00001115 case OMPRTL__kmpc_threadprivate_register: {
1116 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1117 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1118 // typedef void *(*kmpc_ctor)(void *);
1119 auto KmpcCtorTy =
1120 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1121 /*isVarArg*/ false)->getPointerTo();
1122 // typedef void *(*kmpc_cctor)(void *, void *);
1123 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1124 auto KmpcCopyCtorTy =
1125 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1126 /*isVarArg*/ false)->getPointerTo();
1127 // typedef void (*kmpc_dtor)(void *);
1128 auto KmpcDtorTy =
1129 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1130 ->getPointerTo();
1131 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1132 KmpcCopyCtorTy, KmpcDtorTy};
1133 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1134 /*isVarArg*/ false);
1135 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1136 break;
1137 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001138 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001139 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1140 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001141 llvm::Type *TypeParams[] = {
1142 getIdentTyPointerTy(), CGM.Int32Ty,
1143 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1144 llvm::FunctionType *FnTy =
1145 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1146 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1147 break;
1148 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001149 case OMPRTL__kmpc_cancel_barrier: {
1150 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1151 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001152 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1153 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001154 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1155 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001156 break;
1157 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001158 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001159 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001160 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1161 llvm::FunctionType *FnTy =
1162 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1163 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1164 break;
1165 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001166 case OMPRTL__kmpc_for_static_fini: {
1167 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1168 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1169 llvm::FunctionType *FnTy =
1170 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1171 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1172 break;
1173 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001174 case OMPRTL__kmpc_push_num_threads: {
1175 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1176 // kmp_int32 num_threads)
1177 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1178 CGM.Int32Ty};
1179 llvm::FunctionType *FnTy =
1180 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1181 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1182 break;
1183 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001184 case OMPRTL__kmpc_serialized_parallel: {
1185 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1186 // global_tid);
1187 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1188 llvm::FunctionType *FnTy =
1189 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1190 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1191 break;
1192 }
1193 case OMPRTL__kmpc_end_serialized_parallel: {
1194 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1195 // global_tid);
1196 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1197 llvm::FunctionType *FnTy =
1198 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1199 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1200 break;
1201 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001202 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001203 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001204 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1205 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001206 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001207 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1208 break;
1209 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001210 case OMPRTL__kmpc_master: {
1211 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1212 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1213 llvm::FunctionType *FnTy =
1214 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1215 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1216 break;
1217 }
1218 case OMPRTL__kmpc_end_master: {
1219 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1220 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1221 llvm::FunctionType *FnTy =
1222 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1223 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1224 break;
1225 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001226 case OMPRTL__kmpc_omp_taskyield: {
1227 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1228 // int end_part);
1229 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1230 llvm::FunctionType *FnTy =
1231 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1232 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1233 break;
1234 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001235 case OMPRTL__kmpc_single: {
1236 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1237 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1238 llvm::FunctionType *FnTy =
1239 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1240 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1241 break;
1242 }
1243 case OMPRTL__kmpc_end_single: {
1244 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1245 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1246 llvm::FunctionType *FnTy =
1247 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1248 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1249 break;
1250 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001251 case OMPRTL__kmpc_omp_task_alloc: {
1252 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1253 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1254 // kmp_routine_entry_t *task_entry);
1255 assert(KmpRoutineEntryPtrTy != nullptr &&
1256 "Type kmp_routine_entry_t must be created.");
1257 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1258 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1259 // Return void * and then cast to particular kmp_task_t type.
1260 llvm::FunctionType *FnTy =
1261 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1262 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1263 break;
1264 }
1265 case OMPRTL__kmpc_omp_task: {
1266 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1267 // *new_task);
1268 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1269 CGM.VoidPtrTy};
1270 llvm::FunctionType *FnTy =
1271 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1272 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1273 break;
1274 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001275 case OMPRTL__kmpc_copyprivate: {
1276 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001277 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001278 // kmp_int32 didit);
1279 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1280 auto *CpyFnTy =
1281 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001282 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001283 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1284 CGM.Int32Ty};
1285 llvm::FunctionType *FnTy =
1286 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1287 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1288 break;
1289 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001290 case OMPRTL__kmpc_reduce: {
1291 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1292 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1293 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1294 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1295 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1296 /*isVarArg=*/false);
1297 llvm::Type *TypeParams[] = {
1298 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1299 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1300 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1301 llvm::FunctionType *FnTy =
1302 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1303 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1304 break;
1305 }
1306 case OMPRTL__kmpc_reduce_nowait: {
1307 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1308 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1309 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1310 // *lck);
1311 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1312 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1313 /*isVarArg=*/false);
1314 llvm::Type *TypeParams[] = {
1315 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1316 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1317 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1318 llvm::FunctionType *FnTy =
1319 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1320 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1321 break;
1322 }
1323 case OMPRTL__kmpc_end_reduce: {
1324 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1325 // kmp_critical_name *lck);
1326 llvm::Type *TypeParams[] = {
1327 getIdentTyPointerTy(), CGM.Int32Ty,
1328 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1329 llvm::FunctionType *FnTy =
1330 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1331 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1332 break;
1333 }
1334 case OMPRTL__kmpc_end_reduce_nowait: {
1335 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1336 // kmp_critical_name *lck);
1337 llvm::Type *TypeParams[] = {
1338 getIdentTyPointerTy(), CGM.Int32Ty,
1339 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1340 llvm::FunctionType *FnTy =
1341 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1342 RTLFn =
1343 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1344 break;
1345 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001346 case OMPRTL__kmpc_omp_task_begin_if0: {
1347 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1348 // *new_task);
1349 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1350 CGM.VoidPtrTy};
1351 llvm::FunctionType *FnTy =
1352 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1353 RTLFn =
1354 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1355 break;
1356 }
1357 case OMPRTL__kmpc_omp_task_complete_if0: {
1358 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1359 // *new_task);
1360 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1361 CGM.VoidPtrTy};
1362 llvm::FunctionType *FnTy =
1363 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1364 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1365 /*Name=*/"__kmpc_omp_task_complete_if0");
1366 break;
1367 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001368 case OMPRTL__kmpc_ordered: {
1369 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1370 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1371 llvm::FunctionType *FnTy =
1372 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1373 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1374 break;
1375 }
1376 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001377 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001378 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1379 llvm::FunctionType *FnTy =
1380 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1381 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1382 break;
1383 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001384 case OMPRTL__kmpc_omp_taskwait: {
1385 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1386 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1387 llvm::FunctionType *FnTy =
1388 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1389 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1390 break;
1391 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001392 case OMPRTL__kmpc_taskgroup: {
1393 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1394 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1395 llvm::FunctionType *FnTy =
1396 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1397 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1398 break;
1399 }
1400 case OMPRTL__kmpc_end_taskgroup: {
1401 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1402 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1403 llvm::FunctionType *FnTy =
1404 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1405 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1406 break;
1407 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001408 case OMPRTL__kmpc_push_proc_bind: {
1409 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1410 // int proc_bind)
1411 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1412 llvm::FunctionType *FnTy =
1413 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1414 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1415 break;
1416 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001417 case OMPRTL__kmpc_omp_task_with_deps: {
1418 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1419 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1420 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1421 llvm::Type *TypeParams[] = {
1422 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1423 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1424 llvm::FunctionType *FnTy =
1425 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1426 RTLFn =
1427 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1428 break;
1429 }
1430 case OMPRTL__kmpc_omp_wait_deps: {
1431 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1432 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1433 // kmp_depend_info_t *noalias_dep_list);
1434 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1435 CGM.Int32Ty, CGM.VoidPtrTy,
1436 CGM.Int32Ty, CGM.VoidPtrTy};
1437 llvm::FunctionType *FnTy =
1438 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1439 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1440 break;
1441 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001442 case OMPRTL__kmpc_cancellationpoint: {
1443 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1444 // global_tid, kmp_int32 cncl_kind)
1445 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1446 llvm::FunctionType *FnTy =
1447 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1448 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1449 break;
1450 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001451 case OMPRTL__kmpc_cancel: {
1452 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1453 // kmp_int32 cncl_kind)
1454 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1455 llvm::FunctionType *FnTy =
1456 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1457 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1458 break;
1459 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001460 case OMPRTL__kmpc_push_num_teams: {
1461 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1462 // kmp_int32 num_teams, kmp_int32 num_threads)
1463 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1464 CGM.Int32Ty};
1465 llvm::FunctionType *FnTy =
1466 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1467 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1468 break;
1469 }
1470 case OMPRTL__kmpc_fork_teams: {
1471 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1472 // microtask, ...);
1473 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1474 getKmpc_MicroPointerTy()};
1475 llvm::FunctionType *FnTy =
1476 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1477 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1478 break;
1479 }
Alexey Bataev7292c292016-04-25 12:22:29 +00001480 case OMPRTL__kmpc_taskloop: {
1481 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
1482 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
1483 // sched, kmp_uint64 grainsize, void *task_dup);
1484 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1485 CGM.IntTy,
1486 CGM.VoidPtrTy,
1487 CGM.IntTy,
1488 CGM.Int64Ty->getPointerTo(),
1489 CGM.Int64Ty->getPointerTo(),
1490 CGM.Int64Ty,
1491 CGM.IntTy,
1492 CGM.IntTy,
1493 CGM.Int64Ty,
1494 CGM.VoidPtrTy};
1495 llvm::FunctionType *FnTy =
1496 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1497 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
1498 break;
1499 }
Alexey Bataev8b427062016-05-25 12:36:08 +00001500 case OMPRTL__kmpc_doacross_init: {
1501 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
1502 // num_dims, struct kmp_dim *dims);
1503 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1504 CGM.Int32Ty,
1505 CGM.Int32Ty,
1506 CGM.VoidPtrTy};
1507 llvm::FunctionType *FnTy =
1508 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1509 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
1510 break;
1511 }
1512 case OMPRTL__kmpc_doacross_fini: {
1513 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
1514 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1515 llvm::FunctionType *FnTy =
1516 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1517 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
1518 break;
1519 }
1520 case OMPRTL__kmpc_doacross_post: {
1521 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
1522 // *vec);
1523 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1524 CGM.Int64Ty->getPointerTo()};
1525 llvm::FunctionType *FnTy =
1526 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1527 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
1528 break;
1529 }
1530 case OMPRTL__kmpc_doacross_wait: {
1531 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
1532 // *vec);
1533 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1534 CGM.Int64Ty->getPointerTo()};
1535 llvm::FunctionType *FnTy =
1536 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1537 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
1538 break;
1539 }
Samuel Antaobed3c462015-10-02 16:14:20 +00001540 case OMPRTL__tgt_target: {
1541 // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
1542 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
1543 // *arg_types);
1544 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1545 CGM.VoidPtrTy,
1546 CGM.Int32Ty,
1547 CGM.VoidPtrPtrTy,
1548 CGM.VoidPtrPtrTy,
1549 CGM.SizeTy->getPointerTo(),
1550 CGM.Int32Ty->getPointerTo()};
1551 llvm::FunctionType *FnTy =
1552 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1553 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
1554 break;
1555 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00001556 case OMPRTL__tgt_target_teams: {
1557 // Build int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
1558 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
1559 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
1560 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1561 CGM.VoidPtrTy,
1562 CGM.Int32Ty,
1563 CGM.VoidPtrPtrTy,
1564 CGM.VoidPtrPtrTy,
1565 CGM.SizeTy->getPointerTo(),
1566 CGM.Int32Ty->getPointerTo(),
1567 CGM.Int32Ty,
1568 CGM.Int32Ty};
1569 llvm::FunctionType *FnTy =
1570 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1571 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
1572 break;
1573 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00001574 case OMPRTL__tgt_register_lib: {
1575 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
1576 QualType ParamTy =
1577 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1578 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1579 llvm::FunctionType *FnTy =
1580 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1581 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
1582 break;
1583 }
1584 case OMPRTL__tgt_unregister_lib: {
1585 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
1586 QualType ParamTy =
1587 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1588 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1589 llvm::FunctionType *FnTy =
1590 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1591 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
1592 break;
1593 }
Samuel Antaodf158d52016-04-27 22:58:19 +00001594 case OMPRTL__tgt_target_data_begin: {
1595 // Build void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
1596 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1597 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1598 CGM.Int32Ty,
1599 CGM.VoidPtrPtrTy,
1600 CGM.VoidPtrPtrTy,
1601 CGM.SizeTy->getPointerTo(),
1602 CGM.Int32Ty->getPointerTo()};
1603 llvm::FunctionType *FnTy =
1604 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1605 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
1606 break;
1607 }
1608 case OMPRTL__tgt_target_data_end: {
1609 // Build void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
1610 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1611 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1612 CGM.Int32Ty,
1613 CGM.VoidPtrPtrTy,
1614 CGM.VoidPtrPtrTy,
1615 CGM.SizeTy->getPointerTo(),
1616 CGM.Int32Ty->getPointerTo()};
1617 llvm::FunctionType *FnTy =
1618 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1619 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
1620 break;
1621 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00001622 case OMPRTL__tgt_target_data_update: {
1623 // Build void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
1624 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1625 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1626 CGM.Int32Ty,
1627 CGM.VoidPtrPtrTy,
1628 CGM.VoidPtrPtrTy,
1629 CGM.SizeTy->getPointerTo(),
1630 CGM.Int32Ty->getPointerTo()};
1631 llvm::FunctionType *FnTy =
1632 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1633 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
1634 break;
1635 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001636 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00001637 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00001638 return RTLFn;
1639}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001640
Alexander Musman21212e42015-03-13 10:38:23 +00001641llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
1642 bool IVSigned) {
1643 assert((IVSize == 32 || IVSize == 64) &&
1644 "IV size is not compatible with the omp runtime");
1645 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
1646 : "__kmpc_for_static_init_4u")
1647 : (IVSigned ? "__kmpc_for_static_init_8"
1648 : "__kmpc_for_static_init_8u");
1649 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1650 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1651 llvm::Type *TypeParams[] = {
1652 getIdentTyPointerTy(), // loc
1653 CGM.Int32Ty, // tid
1654 CGM.Int32Ty, // schedtype
1655 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1656 PtrTy, // p_lower
1657 PtrTy, // p_upper
1658 PtrTy, // p_stride
1659 ITy, // incr
1660 ITy // chunk
1661 };
1662 llvm::FunctionType *FnTy =
1663 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1664 return CGM.CreateRuntimeFunction(FnTy, Name);
1665}
1666
Alexander Musman92bdaab2015-03-12 13:37:50 +00001667llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
1668 bool IVSigned) {
1669 assert((IVSize == 32 || IVSize == 64) &&
1670 "IV size is not compatible with the omp runtime");
1671 auto Name =
1672 IVSize == 32
1673 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
1674 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
1675 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1676 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
1677 CGM.Int32Ty, // tid
1678 CGM.Int32Ty, // schedtype
1679 ITy, // lower
1680 ITy, // upper
1681 ITy, // stride
1682 ITy // chunk
1683 };
1684 llvm::FunctionType *FnTy =
1685 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1686 return CGM.CreateRuntimeFunction(FnTy, Name);
1687}
1688
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001689llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
1690 bool IVSigned) {
1691 assert((IVSize == 32 || IVSize == 64) &&
1692 "IV size is not compatible with the omp runtime");
1693 auto Name =
1694 IVSize == 32
1695 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
1696 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
1697 llvm::Type *TypeParams[] = {
1698 getIdentTyPointerTy(), // loc
1699 CGM.Int32Ty, // tid
1700 };
1701 llvm::FunctionType *FnTy =
1702 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1703 return CGM.CreateRuntimeFunction(FnTy, Name);
1704}
1705
Alexander Musman92bdaab2015-03-12 13:37:50 +00001706llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
1707 bool IVSigned) {
1708 assert((IVSize == 32 || IVSize == 64) &&
1709 "IV size is not compatible with the omp runtime");
1710 auto Name =
1711 IVSize == 32
1712 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
1713 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
1714 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1715 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1716 llvm::Type *TypeParams[] = {
1717 getIdentTyPointerTy(), // loc
1718 CGM.Int32Ty, // tid
1719 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1720 PtrTy, // p_lower
1721 PtrTy, // p_upper
1722 PtrTy // p_stride
1723 };
1724 llvm::FunctionType *FnTy =
1725 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1726 return CGM.CreateRuntimeFunction(FnTy, Name);
1727}
1728
Alexey Bataev97720002014-11-11 04:05:39 +00001729llvm::Constant *
1730CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001731 assert(!CGM.getLangOpts().OpenMPUseTLS ||
1732 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00001733 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001734 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001735 Twine(CGM.getMangledName(VD)) + ".cache.");
1736}
1737
John McCall7f416cc2015-09-08 08:05:57 +00001738Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
1739 const VarDecl *VD,
1740 Address VDAddr,
1741 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001742 if (CGM.getLangOpts().OpenMPUseTLS &&
1743 CGM.getContext().getTargetInfo().isTLSSupported())
1744 return VDAddr;
1745
John McCall7f416cc2015-09-08 08:05:57 +00001746 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001747 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00001748 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1749 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001750 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
1751 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00001752 return Address(CGF.EmitRuntimeCall(
1753 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
1754 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00001755}
1756
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001757void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00001758 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00001759 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
1760 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
1761 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001762 auto OMPLoc = emitUpdateLocation(CGF, Loc);
1763 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00001764 OMPLoc);
1765 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
1766 // to register constructor/destructor for variable.
1767 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00001768 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1769 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001770 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001771 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001772 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001773}
1774
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001775llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00001776 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00001777 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001778 if (CGM.getLangOpts().OpenMPUseTLS &&
1779 CGM.getContext().getTargetInfo().isTLSSupported())
1780 return nullptr;
1781
Alexey Bataev97720002014-11-11 04:05:39 +00001782 VD = VD->getDefinition(CGM.getContext());
1783 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
1784 ThreadPrivateWithDefinition.insert(VD);
1785 QualType ASTTy = VD->getType();
1786
1787 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
1788 auto Init = VD->getAnyInitializer();
1789 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
1790 // Generate function that re-emits the declaration's initializer into the
1791 // threadprivate copy of the variable VD
1792 CodeGenFunction CtorCGF(CGM);
1793 FunctionArgList Args;
1794 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1795 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1796 Args.push_back(&Dst);
1797
John McCallc56a8b32016-03-11 04:30:31 +00001798 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1799 CGM.getContext().VoidPtrTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001800 auto FTy = CGM.getTypes().GetFunctionType(FI);
1801 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001802 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001803 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
1804 Args, SourceLocation());
1805 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001806 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001807 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001808 Address Arg = Address(ArgVal, VDAddr.getAlignment());
1809 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
1810 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00001811 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
1812 /*IsInitializer=*/true);
1813 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001814 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001815 CGM.getContext().VoidPtrTy, Dst.getLocation());
1816 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
1817 CtorCGF.FinishFunction();
1818 Ctor = Fn;
1819 }
1820 if (VD->getType().isDestructedType() != QualType::DK_none) {
1821 // Generate function that emits destructor call for the threadprivate copy
1822 // of the variable VD
1823 CodeGenFunction DtorCGF(CGM);
1824 FunctionArgList Args;
1825 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1826 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1827 Args.push_back(&Dst);
1828
John McCallc56a8b32016-03-11 04:30:31 +00001829 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1830 CGM.getContext().VoidTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001831 auto FTy = CGM.getTypes().GetFunctionType(FI);
1832 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001833 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00001834 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00001835 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
1836 SourceLocation());
Adrian Prantl1858c662016-04-24 22:22:29 +00001837 // Create a scope with an artificial location for the body of this function.
1838 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00001839 auto ArgVal = DtorCGF.EmitLoadOfScalar(
1840 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00001841 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
1842 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001843 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
1844 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
1845 DtorCGF.FinishFunction();
1846 Dtor = Fn;
1847 }
1848 // Do not emit init function if it is not required.
1849 if (!Ctor && !Dtor)
1850 return nullptr;
1851
1852 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1853 auto CopyCtorTy =
1854 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
1855 /*isVarArg=*/false)->getPointerTo();
1856 // Copying constructor for the threadprivate variable.
1857 // Must be NULL - reserved by runtime, but currently it requires that this
1858 // parameter is always NULL. Otherwise it fires assertion.
1859 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
1860 if (Ctor == nullptr) {
1861 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1862 /*isVarArg=*/false)->getPointerTo();
1863 Ctor = llvm::Constant::getNullValue(CtorTy);
1864 }
1865 if (Dtor == nullptr) {
1866 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
1867 /*isVarArg=*/false)->getPointerTo();
1868 Dtor = llvm::Constant::getNullValue(DtorTy);
1869 }
1870 if (!CGF) {
1871 auto InitFunctionTy =
1872 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
1873 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001874 InitFunctionTy, ".__omp_threadprivate_init_.",
1875 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00001876 CodeGenFunction InitCGF(CGM);
1877 FunctionArgList ArgList;
1878 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
1879 CGM.getTypes().arrangeNullaryFunction(), ArgList,
1880 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001881 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001882 InitCGF.FinishFunction();
1883 return InitFunction;
1884 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001885 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001886 }
1887 return nullptr;
1888}
1889
Alexey Bataev1d677132015-04-22 13:57:31 +00001890/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
1891/// function. Here is the logic:
1892/// if (Cond) {
1893/// ThenGen();
1894/// } else {
1895/// ElseGen();
1896/// }
Arpith Chacko Jacobbb36fe82017-01-10 15:42:51 +00001897void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
1898 const RegionCodeGenTy &ThenGen,
1899 const RegionCodeGenTy &ElseGen) {
Alexey Bataev1d677132015-04-22 13:57:31 +00001900 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
1901
1902 // If the condition constant folds and can be elided, try to avoid emitting
1903 // the condition and the dead arm of the if/else.
1904 bool CondConstant;
1905 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001906 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00001907 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001908 else
Alexey Bataev1d677132015-04-22 13:57:31 +00001909 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001910 return;
1911 }
1912
1913 // Otherwise, the condition did not fold, or we couldn't elide it. Just
1914 // emit the conditional branch.
1915 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
1916 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
1917 auto ContBlock = CGF.createBasicBlock("omp_if.end");
1918 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
1919
1920 // Emit the 'then' code.
1921 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001922 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001923 CGF.EmitBranch(ContBlock);
1924 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001925 // There is no need to emit line number for unconditional branch.
1926 (void)ApplyDebugLocation::CreateEmpty(CGF);
1927 CGF.EmitBlock(ElseBlock);
1928 ElseGen(CGF);
1929 // There is no need to emit line number for unconditional branch.
1930 (void)ApplyDebugLocation::CreateEmpty(CGF);
1931 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00001932 // Emit the continuation block for code after the if.
1933 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001934}
1935
Alexey Bataev1d677132015-04-22 13:57:31 +00001936void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
1937 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001938 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00001939 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001940 if (!CGF.HaveInsertPoint())
1941 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00001942 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001943 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
1944 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001945 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001946 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00001947 llvm::Value *Args[] = {
1948 RTLoc,
1949 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001950 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00001951 llvm::SmallVector<llvm::Value *, 16> RealArgs;
1952 RealArgs.append(std::begin(Args), std::end(Args));
1953 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
1954
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001955 auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001956 CGF.EmitRuntimeCall(RTLFn, RealArgs);
1957 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001958 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
1959 PrePostActionTy &) {
1960 auto &RT = CGF.CGM.getOpenMPRuntime();
1961 auto ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00001962 // Build calls:
1963 // __kmpc_serialized_parallel(&Loc, GTid);
1964 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001965 CGF.EmitRuntimeCall(
1966 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001967
Alexey Bataev1d677132015-04-22 13:57:31 +00001968 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001969 auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00001970 Address ZeroAddr =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001971 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
1972 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00001973 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00001974 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
1975 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
1976 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1977 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev1d677132015-04-22 13:57:31 +00001978 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001979
Alexey Bataev1d677132015-04-22 13:57:31 +00001980 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001981 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00001982 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001983 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
1984 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00001985 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001986 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00001987 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001988 else {
1989 RegionCodeGenTy ThenRCG(ThenGen);
1990 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00001991 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001992}
1993
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00001994// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00001995// thread-ID variable (it is passed in a first argument of the outlined function
1996// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
1997// regular serial code region, get thread ID by calling kmp_int32
1998// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
1999// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00002000Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2001 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002002 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002003 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002004 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002005 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002006
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002007 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002008 auto Int32Ty =
2009 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2010 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2011 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002012 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002013
2014 return ThreadIDTemp;
2015}
2016
Alexey Bataev97720002014-11-11 04:05:39 +00002017llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002018CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002019 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002020 SmallString<256> Buffer;
2021 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002022 Out << Name;
2023 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00002024 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
2025 if (Elem.second) {
2026 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002027 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002028 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002029 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002030
David Blaikie13156b62014-11-19 03:06:06 +00002031 return Elem.second = new llvm::GlobalVariable(
2032 CGM.getModule(), Ty, /*IsConstant*/ false,
2033 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2034 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002035}
2036
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002037llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00002038 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002039 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002040}
2041
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002042namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002043/// Common pre(post)-action for different OpenMP constructs.
2044class CommonActionTy final : public PrePostActionTy {
2045 llvm::Value *EnterCallee;
2046 ArrayRef<llvm::Value *> EnterArgs;
2047 llvm::Value *ExitCallee;
2048 ArrayRef<llvm::Value *> ExitArgs;
2049 bool Conditional;
2050 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002051
2052public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002053 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2054 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2055 bool Conditional = false)
2056 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2057 ExitArgs(ExitArgs), Conditional(Conditional) {}
2058 void Enter(CodeGenFunction &CGF) override {
2059 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2060 if (Conditional) {
2061 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2062 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2063 ContBlock = CGF.createBasicBlock("omp_if.end");
2064 // Generate the branch (If-stmt)
2065 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2066 CGF.EmitBlock(ThenBlock);
2067 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002068 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002069 void Done(CodeGenFunction &CGF) {
2070 // Emit the rest of blocks/branches
2071 CGF.EmitBranch(ContBlock);
2072 CGF.EmitBlock(ContBlock, true);
2073 }
2074 void Exit(CodeGenFunction &CGF) override {
2075 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002076 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002077};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002078} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002079
2080void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2081 StringRef CriticalName,
2082 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002083 SourceLocation Loc, const Expr *Hint) {
2084 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002085 // CriticalOpGen();
2086 // __kmpc_end_critical(ident_t *, gtid, Lock);
2087 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002088 if (!CGF.HaveInsertPoint())
2089 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002090 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2091 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002092 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2093 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002094 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002095 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2096 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2097 }
2098 CommonActionTy Action(
2099 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2100 : OMPRTL__kmpc_critical),
2101 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2102 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002103 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002104}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002105
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002106void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002107 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002108 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002109 if (!CGF.HaveInsertPoint())
2110 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002111 // if(__kmpc_master(ident_t *, gtid)) {
2112 // MasterOpGen();
2113 // __kmpc_end_master(ident_t *, gtid);
2114 // }
2115 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002116 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002117 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2118 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2119 /*Conditional=*/true);
2120 MasterOpGen.setAction(Action);
2121 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2122 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002123}
2124
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002125void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2126 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002127 if (!CGF.HaveInsertPoint())
2128 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00002129 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2130 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002131 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00002132 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002133 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002134 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2135 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00002136}
2137
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002138void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2139 const RegionCodeGenTy &TaskgroupOpGen,
2140 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002141 if (!CGF.HaveInsertPoint())
2142 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002143 // __kmpc_taskgroup(ident_t *, gtid);
2144 // TaskgroupOpGen();
2145 // __kmpc_end_taskgroup(ident_t *, gtid);
2146 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002147 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2148 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2149 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2150 Args);
2151 TaskgroupOpGen.setAction(Action);
2152 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002153}
2154
John McCall7f416cc2015-09-08 08:05:57 +00002155/// Given an array of pointers to variables, project the address of a
2156/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002157static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2158 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00002159 // Pull out the pointer to the variable.
2160 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002161 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00002162 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2163
2164 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002165 Addr = CGF.Builder.CreateElementBitCast(
2166 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002167 return Addr;
2168}
2169
Alexey Bataeva63048e2015-03-23 06:18:07 +00002170static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00002171 CodeGenModule &CGM, llvm::Type *ArgsType,
2172 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
2173 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002174 auto &C = CGM.getContext();
2175 // void copy_func(void *LHSArg, void *RHSArg);
2176 FunctionArgList Args;
2177 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2178 C.VoidPtrTy);
2179 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2180 C.VoidPtrTy);
2181 Args.push_back(&LHSArg);
2182 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00002183 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002184 auto *Fn = llvm::Function::Create(
2185 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2186 ".omp.copyprivate.copy_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002187 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002188 CodeGenFunction CGF(CGM);
2189 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00002190 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002191 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00002192 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2193 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2194 ArgsType), CGF.getPointerAlign());
2195 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2196 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2197 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002198 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2199 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2200 // ...
2201 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00002202 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002203 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2204 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2205
2206 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2207 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2208
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002209 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2210 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00002211 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002212 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002213 CGF.FinishFunction();
2214 return Fn;
2215}
2216
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002217void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002218 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00002219 SourceLocation Loc,
2220 ArrayRef<const Expr *> CopyprivateVars,
2221 ArrayRef<const Expr *> SrcExprs,
2222 ArrayRef<const Expr *> DstExprs,
2223 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002224 if (!CGF.HaveInsertPoint())
2225 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002226 assert(CopyprivateVars.size() == SrcExprs.size() &&
2227 CopyprivateVars.size() == DstExprs.size() &&
2228 CopyprivateVars.size() == AssignmentOps.size());
2229 auto &C = CGM.getContext();
2230 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002231 // if(__kmpc_single(ident_t *, gtid)) {
2232 // SingleOpGen();
2233 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002234 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002235 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002236 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2237 // <copy_func>, did_it);
2238
John McCall7f416cc2015-09-08 08:05:57 +00002239 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00002240 if (!CopyprivateVars.empty()) {
2241 // int32 did_it = 0;
2242 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2243 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00002244 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002245 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002246 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002247 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002248 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
2249 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
2250 /*Conditional=*/true);
2251 SingleOpGen.setAction(Action);
2252 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2253 if (DidIt.isValid()) {
2254 // did_it = 1;
2255 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2256 }
2257 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002258 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2259 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00002260 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002261 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2262 auto CopyprivateArrayTy =
2263 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2264 /*IndexTypeQuals=*/0);
2265 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00002266 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00002267 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2268 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002269 Address Elem = CGF.Builder.CreateConstArrayGEP(
2270 CopyprivateList, I, CGF.getPointerSize());
2271 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00002272 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002273 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2274 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002275 }
2276 // Build function that copies private values from single region to all other
2277 // threads in the corresponding parallel region.
2278 auto *CpyFn = emitCopyprivateCopyFunction(
2279 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00002280 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev1189bd02016-01-26 12:20:39 +00002281 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00002282 Address CL =
2283 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2284 CGF.VoidPtrTy);
2285 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002286 llvm::Value *Args[] = {
2287 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2288 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00002289 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00002290 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00002291 CpyFn, // void (*) (void *, void *) <copy_func>
2292 DidItVal // i32 did_it
2293 };
2294 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2295 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002296}
2297
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002298void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2299 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00002300 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002301 if (!CGF.HaveInsertPoint())
2302 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002303 // __kmpc_ordered(ident_t *, gtid);
2304 // OrderedOpGen();
2305 // __kmpc_end_ordered(ident_t *, gtid);
2306 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00002307 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002308 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002309 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
2310 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2311 Args);
2312 OrderedOpGen.setAction(Action);
2313 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2314 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002315 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002316 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002317}
2318
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002319void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002320 OpenMPDirectiveKind Kind, bool EmitChecks,
2321 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002322 if (!CGF.HaveInsertPoint())
2323 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002324 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002325 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002326 unsigned Flags;
2327 if (Kind == OMPD_for)
2328 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2329 else if (Kind == OMPD_sections)
2330 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2331 else if (Kind == OMPD_single)
2332 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2333 else if (Kind == OMPD_barrier)
2334 Flags = OMP_IDENT_BARRIER_EXPL;
2335 else
2336 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002337 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2338 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002339 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2340 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002341 if (auto *OMPRegionInfo =
2342 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00002343 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002344 auto *Result = CGF.EmitRuntimeCall(
2345 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002346 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002347 // if (__kmpc_cancel_barrier()) {
2348 // exit from construct;
2349 // }
2350 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2351 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2352 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2353 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2354 CGF.EmitBlock(ExitBB);
2355 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002356 auto CancelDestination =
2357 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002358 CGF.EmitBranchThroughCleanup(CancelDestination);
2359 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2360 }
2361 return;
2362 }
2363 }
2364 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002365}
2366
Alexander Musmanc6388682014-12-15 07:07:06 +00002367/// \brief Map the OpenMP loop schedule to the runtime enumeration.
2368static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002369 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002370 switch (ScheduleKind) {
2371 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002372 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2373 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00002374 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002375 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002376 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002377 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002378 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002379 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2380 case OMPC_SCHEDULE_auto:
2381 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00002382 case OMPC_SCHEDULE_unknown:
2383 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002384 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00002385 }
2386 llvm_unreachable("Unexpected runtime schedule");
2387}
2388
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002389/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
2390static OpenMPSchedType
2391getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2392 // only static is allowed for dist_schedule
2393 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
2394}
2395
Alexander Musmanc6388682014-12-15 07:07:06 +00002396bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2397 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002398 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00002399 return Schedule == OMP_sch_static;
2400}
2401
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002402bool CGOpenMPRuntime::isStaticNonchunked(
2403 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2404 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2405 return Schedule == OMP_dist_sch_static;
2406}
2407
2408
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002409bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002410 auto Schedule =
2411 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002412 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2413 return Schedule != OMP_sch_static;
2414}
2415
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002416static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
2417 OpenMPScheduleClauseModifier M1,
2418 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00002419 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002420 switch (M1) {
2421 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002422 Modifier = OMP_sch_modifier_monotonic;
2423 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002424 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002425 Modifier = OMP_sch_modifier_nonmonotonic;
2426 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002427 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002428 if (Schedule == OMP_sch_static_chunked)
2429 Schedule = OMP_sch_static_balanced_chunked;
2430 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002431 case OMPC_SCHEDULE_MODIFIER_last:
2432 case OMPC_SCHEDULE_MODIFIER_unknown:
2433 break;
2434 }
2435 switch (M2) {
2436 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002437 Modifier = OMP_sch_modifier_monotonic;
2438 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002439 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002440 Modifier = OMP_sch_modifier_nonmonotonic;
2441 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002442 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002443 if (Schedule == OMP_sch_static_chunked)
2444 Schedule = OMP_sch_static_balanced_chunked;
2445 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002446 case OMPC_SCHEDULE_MODIFIER_last:
2447 case OMPC_SCHEDULE_MODIFIER_unknown:
2448 break;
2449 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00002450 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002451}
2452
John McCall7f416cc2015-09-08 08:05:57 +00002453void CGOpenMPRuntime::emitForDispatchInit(CodeGenFunction &CGF,
2454 SourceLocation Loc,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002455 const OpenMPScheduleTy &ScheduleKind,
John McCall7f416cc2015-09-08 08:05:57 +00002456 unsigned IVSize, bool IVSigned,
2457 bool Ordered, llvm::Value *UB,
2458 llvm::Value *Chunk) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002459 if (!CGF.HaveInsertPoint())
2460 return;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002461 OpenMPSchedType Schedule =
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002462 getRuntimeSchedule(ScheduleKind.Schedule, Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00002463 assert(Ordered ||
2464 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00002465 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
2466 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00002467 // Call __kmpc_dispatch_init(
2468 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2469 // kmp_int[32|64] lower, kmp_int[32|64] upper,
2470 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002471
John McCall7f416cc2015-09-08 08:05:57 +00002472 // If the Chunk was not specified in the clause - use default value 1.
2473 if (Chunk == nullptr)
2474 Chunk = CGF.Builder.getIntN(IVSize, 1);
2475 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002476 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2477 CGF.Builder.getInt32(addMonoNonMonoModifier(
2478 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
2479 CGF.Builder.getIntN(IVSize, 0), // Lower
2480 UB, // Upper
2481 CGF.Builder.getIntN(IVSize, 1), // Stride
2482 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00002483 };
2484 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2485}
2486
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002487static void emitForStaticInitCall(
2488 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
2489 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
2490 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
2491 unsigned IVSize, bool Ordered, Address IL, Address LB, Address UB,
2492 Address ST, llvm::Value *Chunk) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002493 if (!CGF.HaveInsertPoint())
2494 return;
2495
2496 assert(!Ordered);
2497 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
Alexey Bataev6cff6242016-05-30 13:05:14 +00002498 Schedule == OMP_sch_static_balanced_chunked ||
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002499 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
2500 Schedule == OMP_dist_sch_static ||
2501 Schedule == OMP_dist_sch_static_chunked);
2502
2503 // Call __kmpc_for_static_init(
2504 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2505 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2506 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2507 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
2508 if (Chunk == nullptr) {
2509 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
2510 Schedule == OMP_dist_sch_static) &&
2511 "expected static non-chunked schedule");
2512 // If the Chunk was not specified in the clause - use default value 1.
2513 Chunk = CGF.Builder.getIntN(IVSize, 1);
2514 } else {
2515 assert((Schedule == OMP_sch_static_chunked ||
Alexey Bataev6cff6242016-05-30 13:05:14 +00002516 Schedule == OMP_sch_static_balanced_chunked ||
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002517 Schedule == OMP_ord_static_chunked ||
2518 Schedule == OMP_dist_sch_static_chunked) &&
2519 "expected static chunked schedule");
2520 }
2521 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002522 UpdateLocation, ThreadId, CGF.Builder.getInt32(addMonoNonMonoModifier(
2523 Schedule, M1, M2)), // Schedule type
2524 IL.getPointer(), // &isLastIter
2525 LB.getPointer(), // &LB
2526 UB.getPointer(), // &UB
2527 ST.getPointer(), // &Stride
2528 CGF.Builder.getIntN(IVSize, 1), // Incr
2529 Chunk // Chunk
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002530 };
2531 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
2532}
2533
John McCall7f416cc2015-09-08 08:05:57 +00002534void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
2535 SourceLocation Loc,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002536 const OpenMPScheduleTy &ScheduleKind,
John McCall7f416cc2015-09-08 08:05:57 +00002537 unsigned IVSize, bool IVSigned,
2538 bool Ordered, Address IL, Address LB,
2539 Address UB, Address ST,
2540 llvm::Value *Chunk) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002541 OpenMPSchedType ScheduleNum =
2542 getRuntimeSchedule(ScheduleKind.Schedule, Chunk != nullptr, Ordered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002543 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2544 auto *ThreadId = getThreadID(CGF, Loc);
2545 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002546 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
2547 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, IVSize,
2548 Ordered, IL, LB, UB, ST, Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002549}
John McCall7f416cc2015-09-08 08:05:57 +00002550
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002551void CGOpenMPRuntime::emitDistributeStaticInit(
2552 CodeGenFunction &CGF, SourceLocation Loc,
2553 OpenMPDistScheduleClauseKind SchedKind, unsigned IVSize, bool IVSigned,
2554 bool Ordered, Address IL, Address LB, Address UB, Address ST,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002555 llvm::Value *Chunk) {
2556 OpenMPSchedType ScheduleNum = getRuntimeSchedule(SchedKind, Chunk != nullptr);
2557 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2558 auto *ThreadId = getThreadID(CGF, Loc);
2559 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002560 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
2561 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
2562 OMPC_SCHEDULE_MODIFIER_unknown, IVSize, Ordered, IL, LB,
2563 UB, ST, Chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002564}
2565
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002566void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
2567 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002568 if (!CGF.HaveInsertPoint())
2569 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00002570 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002571 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002572 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
2573 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00002574}
2575
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002576void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
2577 SourceLocation Loc,
2578 unsigned IVSize,
2579 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002580 if (!CGF.HaveInsertPoint())
2581 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002582 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002583 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002584 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
2585}
2586
Alexander Musman92bdaab2015-03-12 13:37:50 +00002587llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
2588 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00002589 bool IVSigned, Address IL,
2590 Address LB, Address UB,
2591 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00002592 // Call __kmpc_dispatch_next(
2593 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
2594 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
2595 // kmp_int[32|64] *p_stride);
2596 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00002597 emitUpdateLocation(CGF, Loc),
2598 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002599 IL.getPointer(), // &isLastIter
2600 LB.getPointer(), // &Lower
2601 UB.getPointer(), // &Upper
2602 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00002603 };
2604 llvm::Value *Call =
2605 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
2606 return CGF.EmitScalarConversion(
2607 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002608 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002609}
2610
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002611void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
2612 llvm::Value *NumThreads,
2613 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002614 if (!CGF.HaveInsertPoint())
2615 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00002616 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
2617 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002618 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00002619 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002620 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
2621 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00002622}
2623
Alexey Bataev7f210c62015-06-18 13:40:03 +00002624void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
2625 OpenMPProcBindClauseKind ProcBind,
2626 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002627 if (!CGF.HaveInsertPoint())
2628 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00002629 // Constants for proc bind value accepted by the runtime.
2630 enum ProcBindTy {
2631 ProcBindFalse = 0,
2632 ProcBindTrue,
2633 ProcBindMaster,
2634 ProcBindClose,
2635 ProcBindSpread,
2636 ProcBindIntel,
2637 ProcBindDefault
2638 } RuntimeProcBind;
2639 switch (ProcBind) {
2640 case OMPC_PROC_BIND_master:
2641 RuntimeProcBind = ProcBindMaster;
2642 break;
2643 case OMPC_PROC_BIND_close:
2644 RuntimeProcBind = ProcBindClose;
2645 break;
2646 case OMPC_PROC_BIND_spread:
2647 RuntimeProcBind = ProcBindSpread;
2648 break;
2649 case OMPC_PROC_BIND_unknown:
2650 llvm_unreachable("Unsupported proc_bind value.");
2651 }
2652 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
2653 llvm::Value *Args[] = {
2654 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2655 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
2656 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
2657}
2658
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002659void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
2660 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002661 if (!CGF.HaveInsertPoint())
2662 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00002663 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002664 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
2665 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002666}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002667
Alexey Bataev62b63b12015-03-10 07:28:44 +00002668namespace {
2669/// \brief Indexes of fields for type kmp_task_t.
2670enum KmpTaskTFields {
2671 /// \brief List of shared variables.
2672 KmpTaskTShareds,
2673 /// \brief Task routine.
2674 KmpTaskTRoutine,
2675 /// \brief Partition id for the untied tasks.
2676 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00002677 /// Function with call of destructors for private variables.
2678 Data1,
2679 /// Task priority.
2680 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00002681 /// (Taskloops only) Lower bound.
2682 KmpTaskTLowerBound,
2683 /// (Taskloops only) Upper bound.
2684 KmpTaskTUpperBound,
2685 /// (Taskloops only) Stride.
2686 KmpTaskTStride,
2687 /// (Taskloops only) Is last iteration flag.
2688 KmpTaskTLastIter,
Alexey Bataev62b63b12015-03-10 07:28:44 +00002689};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002690} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00002691
Samuel Antaoee8fb302016-01-06 13:42:12 +00002692bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
2693 // FIXME: Add other entries type when they become supported.
2694 return OffloadEntriesTargetRegion.empty();
2695}
2696
2697/// \brief Initialize target region entry.
2698void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2699 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2700 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00002701 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002702 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
2703 "only required for the device "
2704 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00002705 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaof83efdb2017-01-05 16:02:49 +00002706 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
2707 /*Flags=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002708 ++OffloadingEntriesNum;
2709}
2710
2711void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2712 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2713 StringRef ParentName, unsigned LineNum,
Samuel Antaof83efdb2017-01-05 16:02:49 +00002714 llvm::Constant *Addr, llvm::Constant *ID,
2715 int32_t Flags) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002716 // If we are emitting code for a target, the entry is already initialized,
2717 // only has to be registered.
2718 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00002719 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00002720 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00002721 auto &Entry =
2722 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00002723 assert(Entry.isValid() && "Entry not initialized!");
2724 Entry.setAddress(Addr);
2725 Entry.setID(ID);
Samuel Antaof83efdb2017-01-05 16:02:49 +00002726 Entry.setFlags(Flags);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002727 return;
2728 } else {
Samuel Antaof83efdb2017-01-05 16:02:49 +00002729 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID, Flags);
Samuel Antao2de62b02016-02-13 23:35:10 +00002730 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002731 }
2732}
2733
2734bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00002735 unsigned DeviceID, unsigned FileID, StringRef ParentName,
2736 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002737 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
2738 if (PerDevice == OffloadEntriesTargetRegion.end())
2739 return false;
2740 auto PerFile = PerDevice->second.find(FileID);
2741 if (PerFile == PerDevice->second.end())
2742 return false;
2743 auto PerParentName = PerFile->second.find(ParentName);
2744 if (PerParentName == PerFile->second.end())
2745 return false;
2746 auto PerLine = PerParentName->second.find(LineNum);
2747 if (PerLine == PerParentName->second.end())
2748 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002749 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00002750 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00002751 return false;
2752 return true;
2753}
2754
2755void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
2756 const OffloadTargetRegionEntryInfoActTy &Action) {
2757 // Scan all target region entries and perform the provided action.
2758 for (auto &D : OffloadEntriesTargetRegion)
2759 for (auto &F : D.second)
2760 for (auto &P : F.second)
2761 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00002762 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002763}
2764
2765/// \brief Create a Ctor/Dtor-like function whose body is emitted through
2766/// \a Codegen. This is used to emit the two functions that register and
2767/// unregister the descriptor of the current compilation unit.
2768static llvm::Function *
2769createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
2770 const RegionCodeGenTy &Codegen) {
2771 auto &C = CGM.getContext();
2772 FunctionArgList Args;
2773 ImplicitParamDecl DummyPtr(C, /*DC=*/nullptr, SourceLocation(),
2774 /*Id=*/nullptr, C.VoidPtrTy);
2775 Args.push_back(&DummyPtr);
2776
2777 CodeGenFunction CGF(CGM);
John McCallc56a8b32016-03-11 04:30:31 +00002778 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002779 auto FTy = CGM.getTypes().GetFunctionType(FI);
2780 auto *Fn =
2781 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
2782 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
2783 Codegen(CGF);
2784 CGF.FinishFunction();
2785 return Fn;
2786}
2787
2788llvm::Function *
2789CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
2790
2791 // If we don't have entries or if we are emitting code for the device, we
2792 // don't need to do anything.
2793 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
2794 return nullptr;
2795
2796 auto &M = CGM.getModule();
2797 auto &C = CGM.getContext();
2798
2799 // Get list of devices we care about
2800 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
2801
2802 // We should be creating an offloading descriptor only if there are devices
2803 // specified.
2804 assert(!Devices.empty() && "No OpenMP offloading devices??");
2805
2806 // Create the external variables that will point to the begin and end of the
2807 // host entries section. These will be defined by the linker.
2808 auto *OffloadEntryTy =
2809 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
2810 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
2811 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002812 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002813 ".omp_offloading.entries_begin");
2814 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
2815 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002816 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002817 ".omp_offloading.entries_end");
2818
2819 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00002820 auto *DeviceImageTy = cast<llvm::StructType>(
2821 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00002822 ConstantInitBuilder DeviceImagesBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002823 auto DeviceImagesEntries = DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002824
2825 for (unsigned i = 0; i < Devices.size(); ++i) {
2826 StringRef T = Devices[i].getTriple();
2827 auto *ImgBegin = new llvm::GlobalVariable(
2828 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002829 /*Initializer=*/nullptr,
2830 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002831 auto *ImgEnd = new llvm::GlobalVariable(
2832 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002833 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002834
John McCall6c9f1fdb2016-11-19 08:17:24 +00002835 auto Dev = DeviceImagesEntries.beginStruct(DeviceImageTy);
2836 Dev.add(ImgBegin);
2837 Dev.add(ImgEnd);
2838 Dev.add(HostEntriesBegin);
2839 Dev.add(HostEntriesEnd);
John McCallf1788632016-11-28 22:18:30 +00002840 Dev.finishAndAddTo(DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002841 }
2842
2843 // Create device images global array.
John McCall6c9f1fdb2016-11-19 08:17:24 +00002844 llvm::GlobalVariable *DeviceImages =
2845 DeviceImagesEntries.finishAndCreateGlobal(".omp_offloading.device_images",
2846 CGM.getPointerAlign(),
2847 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002848 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002849
2850 // This is a Zero array to be used in the creation of the constant expressions
2851 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
2852 llvm::Constant::getNullValue(CGM.Int32Ty)};
2853
2854 // Create the target region descriptor.
2855 auto *BinaryDescriptorTy = cast<llvm::StructType>(
2856 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00002857 ConstantInitBuilder DescBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002858 auto DescInit = DescBuilder.beginStruct(BinaryDescriptorTy);
2859 DescInit.addInt(CGM.Int32Ty, Devices.size());
2860 DescInit.add(llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
2861 DeviceImages,
2862 Index));
2863 DescInit.add(HostEntriesBegin);
2864 DescInit.add(HostEntriesEnd);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002865
John McCall6c9f1fdb2016-11-19 08:17:24 +00002866 auto *Desc = DescInit.finishAndCreateGlobal(".omp_offloading.descriptor",
2867 CGM.getPointerAlign(),
2868 /*isConstant=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002869
2870 // Emit code to register or unregister the descriptor at execution
2871 // startup or closing, respectively.
2872
2873 // Create a variable to drive the registration and unregistration of the
2874 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
2875 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
2876 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
2877 IdentInfo, C.CharTy);
2878
2879 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002880 CGM, ".omp_offloading.descriptor_unreg",
2881 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002882 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
2883 Desc);
2884 });
2885 auto *RegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002886 CGM, ".omp_offloading.descriptor_reg",
2887 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002888 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_register_lib),
2889 Desc);
2890 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
2891 });
2892 return RegFn;
2893}
2894
Samuel Antao2de62b02016-02-13 23:35:10 +00002895void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
Samuel Antaof83efdb2017-01-05 16:02:49 +00002896 llvm::Constant *Addr, uint64_t Size,
2897 int32_t Flags) {
Samuel Antao2de62b02016-02-13 23:35:10 +00002898 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00002899 auto *TgtOffloadEntryType = cast<llvm::StructType>(
2900 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
2901 llvm::LLVMContext &C = CGM.getModule().getContext();
2902 llvm::Module &M = CGM.getModule();
2903
2904 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00002905 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002906
2907 // Create constant string with the name.
2908 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
2909
2910 llvm::GlobalVariable *Str =
2911 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
2912 llvm::GlobalValue::InternalLinkage, StrPtrInit,
2913 ".omp_offloading.entry_name");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002914 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002915 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
2916
John McCall6c9f1fdb2016-11-19 08:17:24 +00002917 // We can't have any padding between symbols, so we need to have 1-byte
2918 // alignment.
2919 auto Align = CharUnits::fromQuantity(1);
2920
Samuel Antaoee8fb302016-01-06 13:42:12 +00002921 // Create the entry struct.
John McCall23c9dc62016-11-28 22:18:27 +00002922 ConstantInitBuilder EntryBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002923 auto EntryInit = EntryBuilder.beginStruct(TgtOffloadEntryType);
2924 EntryInit.add(AddrPtr);
2925 EntryInit.add(StrPtr);
2926 EntryInit.addInt(CGM.SizeTy, Size);
Samuel Antaof83efdb2017-01-05 16:02:49 +00002927 EntryInit.addInt(CGM.Int32Ty, Flags);
2928 EntryInit.addInt(CGM.Int32Ty, 0);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002929 llvm::GlobalVariable *Entry =
2930 EntryInit.finishAndCreateGlobal(".omp_offloading.entry",
2931 Align,
2932 /*constant*/ true,
2933 llvm::GlobalValue::ExternalLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002934
2935 // The entry has to be created in the section the linker expects it to be.
2936 Entry->setSection(".omp_offloading.entries");
Samuel Antaoee8fb302016-01-06 13:42:12 +00002937}
2938
2939void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
2940 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00002941 // can easily figure out what to emit. The produced metadata looks like
2942 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00002943 //
2944 // !omp_offload.info = !{!1, ...}
2945 //
2946 // Right now we only generate metadata for function that contain target
2947 // regions.
2948
2949 // If we do not have entries, we dont need to do anything.
2950 if (OffloadEntriesInfoManager.empty())
2951 return;
2952
2953 llvm::Module &M = CGM.getModule();
2954 llvm::LLVMContext &C = M.getContext();
2955 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
2956 OrderedEntries(OffloadEntriesInfoManager.size());
2957
2958 // Create the offloading info metadata node.
2959 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
2960
2961 // Auxiliar methods to create metadata values and strings.
2962 auto getMDInt = [&](unsigned v) {
2963 return llvm::ConstantAsMetadata::get(
2964 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
2965 };
2966
2967 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
2968
2969 // Create function that emits metadata for each target region entry;
2970 auto &&TargetRegionMetadataEmitter = [&](
2971 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002972 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
2973 llvm::SmallVector<llvm::Metadata *, 32> Ops;
2974 // Generate metadata for target regions. Each entry of this metadata
2975 // contains:
2976 // - Entry 0 -> Kind of this type of metadata (0).
2977 // - Entry 1 -> Device ID of the file where the entry was identified.
2978 // - Entry 2 -> File ID of the file where the entry was identified.
2979 // - Entry 3 -> Mangled name of the function where the entry was identified.
2980 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00002981 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00002982 // The first element of the metadata node is the kind.
2983 Ops.push_back(getMDInt(E.getKind()));
2984 Ops.push_back(getMDInt(DeviceID));
2985 Ops.push_back(getMDInt(FileID));
2986 Ops.push_back(getMDString(ParentName));
2987 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002988 Ops.push_back(getMDInt(E.getOrder()));
2989
2990 // Save this entry in the right position of the ordered entries array.
2991 OrderedEntries[E.getOrder()] = &E;
2992
2993 // Add metadata to the named metadata node.
2994 MD->addOperand(llvm::MDNode::get(C, Ops));
2995 };
2996
2997 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
2998 TargetRegionMetadataEmitter);
2999
3000 for (auto *E : OrderedEntries) {
3001 assert(E && "All ordered entries must exist!");
3002 if (auto *CE =
3003 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3004 E)) {
3005 assert(CE->getID() && CE->getAddress() &&
3006 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00003007 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003008 } else
3009 llvm_unreachable("Unsupported entry kind.");
3010 }
3011}
3012
3013/// \brief Loads all the offload entries information from the host IR
3014/// metadata.
3015void CGOpenMPRuntime::loadOffloadInfoMetadata() {
3016 // If we are in target mode, load the metadata from the host IR. This code has
3017 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
3018
3019 if (!CGM.getLangOpts().OpenMPIsDevice)
3020 return;
3021
3022 if (CGM.getLangOpts().OMPHostIRFile.empty())
3023 return;
3024
3025 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
3026 if (Buf.getError())
3027 return;
3028
3029 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00003030 auto ME = expectedToErrorOrAndEmitErrors(
3031 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003032
3033 if (ME.getError())
3034 return;
3035
3036 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
3037 if (!MD)
3038 return;
3039
3040 for (auto I : MD->operands()) {
3041 llvm::MDNode *MN = cast<llvm::MDNode>(I);
3042
3043 auto getMDInt = [&](unsigned Idx) {
3044 llvm::ConstantAsMetadata *V =
3045 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
3046 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
3047 };
3048
3049 auto getMDString = [&](unsigned Idx) {
3050 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
3051 return V->getString();
3052 };
3053
3054 switch (getMDInt(0)) {
3055 default:
3056 llvm_unreachable("Unexpected metadata!");
3057 break;
3058 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3059 OFFLOAD_ENTRY_INFO_TARGET_REGION:
3060 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
3061 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
3062 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00003063 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003064 break;
3065 }
3066 }
3067}
3068
Alexey Bataev62b63b12015-03-10 07:28:44 +00003069void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
3070 if (!KmpRoutineEntryPtrTy) {
3071 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
3072 auto &C = CGM.getContext();
3073 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
3074 FunctionProtoType::ExtProtoInfo EPI;
3075 KmpRoutineEntryPtrQTy = C.getPointerType(
3076 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
3077 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
3078 }
3079}
3080
Alexey Bataevc71a4092015-09-11 10:29:41 +00003081static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
3082 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003083 auto *Field = FieldDecl::Create(
3084 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
3085 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
3086 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
3087 Field->setAccess(AS_public);
3088 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003089 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003090}
3091
Samuel Antaoee8fb302016-01-06 13:42:12 +00003092QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
3093
3094 // Make sure the type of the entry is already created. This is the type we
3095 // have to create:
3096 // struct __tgt_offload_entry{
3097 // void *addr; // Pointer to the offload entry info.
3098 // // (function or global)
3099 // char *name; // Name of the function or global.
3100 // size_t size; // Size of the entry info (0 if it a function).
Samuel Antaof83efdb2017-01-05 16:02:49 +00003101 // int32_t flags; // Flags associated with the entry, e.g. 'link'.
3102 // int32_t reserved; // Reserved, to use by the runtime library.
Samuel Antaoee8fb302016-01-06 13:42:12 +00003103 // };
3104 if (TgtOffloadEntryQTy.isNull()) {
3105 ASTContext &C = CGM.getContext();
3106 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
3107 RD->startDefinition();
3108 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3109 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
3110 addFieldToRecordDecl(C, RD, C.getSizeType());
Samuel Antaof83efdb2017-01-05 16:02:49 +00003111 addFieldToRecordDecl(
3112 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3113 addFieldToRecordDecl(
3114 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003115 RD->completeDefinition();
3116 TgtOffloadEntryQTy = C.getRecordType(RD);
3117 }
3118 return TgtOffloadEntryQTy;
3119}
3120
3121QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
3122 // These are the types we need to build:
3123 // struct __tgt_device_image{
3124 // void *ImageStart; // Pointer to the target code start.
3125 // void *ImageEnd; // Pointer to the target code end.
3126 // // We also add the host entries to the device image, as it may be useful
3127 // // for the target runtime to have access to that information.
3128 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
3129 // // the entries.
3130 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3131 // // entries (non inclusive).
3132 // };
3133 if (TgtDeviceImageQTy.isNull()) {
3134 ASTContext &C = CGM.getContext();
3135 auto *RD = C.buildImplicitRecord("__tgt_device_image");
3136 RD->startDefinition();
3137 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3138 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3139 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3140 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3141 RD->completeDefinition();
3142 TgtDeviceImageQTy = C.getRecordType(RD);
3143 }
3144 return TgtDeviceImageQTy;
3145}
3146
3147QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
3148 // struct __tgt_bin_desc{
3149 // int32_t NumDevices; // Number of devices supported.
3150 // __tgt_device_image *DeviceImages; // Arrays of device images
3151 // // (one per device).
3152 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
3153 // // entries.
3154 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3155 // // entries (non inclusive).
3156 // };
3157 if (TgtBinaryDescriptorQTy.isNull()) {
3158 ASTContext &C = CGM.getContext();
3159 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
3160 RD->startDefinition();
3161 addFieldToRecordDecl(
3162 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3163 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
3164 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3165 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3166 RD->completeDefinition();
3167 TgtBinaryDescriptorQTy = C.getRecordType(RD);
3168 }
3169 return TgtBinaryDescriptorQTy;
3170}
3171
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003172namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00003173struct PrivateHelpersTy {
3174 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
3175 const VarDecl *PrivateElemInit)
3176 : Original(Original), PrivateCopy(PrivateCopy),
3177 PrivateElemInit(PrivateElemInit) {}
3178 const VarDecl *Original;
3179 const VarDecl *PrivateCopy;
3180 const VarDecl *PrivateElemInit;
3181};
3182typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00003183} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003184
Alexey Bataev9e034042015-05-05 04:05:12 +00003185static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00003186createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003187 if (!Privates.empty()) {
3188 auto &C = CGM.getContext();
3189 // Build struct .kmp_privates_t. {
3190 // /* private vars */
3191 // };
3192 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
3193 RD->startDefinition();
3194 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00003195 auto *VD = Pair.second.Original;
3196 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003197 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00003198 auto *FD = addFieldToRecordDecl(C, RD, Type);
3199 if (VD->hasAttrs()) {
3200 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
3201 E(VD->getAttrs().end());
3202 I != E; ++I)
3203 FD->addAttr(*I);
3204 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003205 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003206 RD->completeDefinition();
3207 return RD;
3208 }
3209 return nullptr;
3210}
3211
Alexey Bataev9e034042015-05-05 04:05:12 +00003212static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00003213createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
3214 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003215 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003216 auto &C = CGM.getContext();
3217 // Build struct kmp_task_t {
3218 // void * shareds;
3219 // kmp_routine_entry_t routine;
3220 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00003221 // kmp_cmplrdata_t data1;
3222 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00003223 // For taskloops additional fields:
3224 // kmp_uint64 lb;
3225 // kmp_uint64 ub;
3226 // kmp_int64 st;
3227 // kmp_int32 liter;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003228 // };
Alexey Bataevad537bb2016-05-30 09:06:50 +00003229 auto *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
3230 UD->startDefinition();
3231 addFieldToRecordDecl(C, UD, KmpInt32Ty);
3232 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
3233 UD->completeDefinition();
3234 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003235 auto *RD = C.buildImplicitRecord("kmp_task_t");
3236 RD->startDefinition();
3237 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3238 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
3239 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00003240 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3241 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003242 if (isOpenMPTaskLoopDirective(Kind)) {
3243 QualType KmpUInt64Ty =
3244 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3245 QualType KmpInt64Ty =
3246 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3247 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3248 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3249 addFieldToRecordDecl(C, RD, KmpInt64Ty);
3250 addFieldToRecordDecl(C, RD, KmpInt32Ty);
3251 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003252 RD->completeDefinition();
3253 return RD;
3254}
3255
3256static RecordDecl *
3257createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003258 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003259 auto &C = CGM.getContext();
3260 // Build struct kmp_task_t_with_privates {
3261 // kmp_task_t task_data;
3262 // .kmp_privates_t. privates;
3263 // };
3264 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
3265 RD->startDefinition();
3266 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003267 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
3268 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
3269 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003270 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003271 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003272}
3273
3274/// \brief Emit a proxy function which accepts kmp_task_t as the second
3275/// argument.
3276/// \code
3277/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003278/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00003279/// For taskloops:
3280/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003281/// tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003282/// return 0;
3283/// }
3284/// \endcode
3285static llvm::Value *
3286emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00003287 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
3288 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003289 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003290 QualType SharedsPtrTy, llvm::Value *TaskFunction,
3291 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003292 auto &C = CGM.getContext();
3293 FunctionArgList Args;
3294 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
3295 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00003296 /*Id=*/nullptr,
3297 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003298 Args.push_back(&GtidArg);
3299 Args.push_back(&TaskTypeArg);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003300 auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003301 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003302 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
3303 auto *TaskEntry =
3304 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
3305 ".omp_task_entry.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003306 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003307 CodeGenFunction CGF(CGM);
3308 CGF.disableDebugInfo();
3309 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
3310
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003311 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00003312 // tt,
3313 // For taskloops:
3314 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3315 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003316 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00003317 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003318 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3319 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3320 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003321 auto *KmpTaskTWithPrivatesQTyRD =
3322 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003323 LValue Base =
3324 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003325 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3326 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3327 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003328 auto *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003329
3330 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3331 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003332 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003333 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003334 CGF.ConvertTypeForMem(SharedsPtrTy));
3335
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003336 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3337 llvm::Value *PrivatesParam;
3338 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3339 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3340 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003341 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003342 } else
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003343 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003344
Alexey Bataev7292c292016-04-25 12:22:29 +00003345 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
3346 TaskPrivatesMap,
3347 CGF.Builder
3348 .CreatePointerBitCastOrAddrSpaceCast(
3349 TDBase.getAddress(), CGF.VoidPtrTy)
3350 .getPointer()};
3351 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
3352 std::end(CommonArgs));
3353 if (isOpenMPTaskLoopDirective(Kind)) {
3354 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
3355 auto LBLVal = CGF.EmitLValueForField(Base, *LBFI);
3356 auto *LBParam = CGF.EmitLoadOfLValue(LBLVal, Loc).getScalarVal();
3357 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
3358 auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
3359 auto *UBParam = CGF.EmitLoadOfLValue(UBLVal, Loc).getScalarVal();
3360 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
3361 auto StLVal = CGF.EmitLValueForField(Base, *StFI);
3362 auto *StParam = CGF.EmitLoadOfLValue(StLVal, Loc).getScalarVal();
3363 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3364 auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
3365 auto *LIParam = CGF.EmitLoadOfLValue(LILVal, Loc).getScalarVal();
3366 CallArgs.push_back(LBParam);
3367 CallArgs.push_back(UBParam);
3368 CallArgs.push_back(StParam);
3369 CallArgs.push_back(LIParam);
3370 }
3371 CallArgs.push_back(SharedsParam);
3372
Alexey Bataev62b63b12015-03-10 07:28:44 +00003373 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
3374 CGF.EmitStoreThroughLValue(
3375 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00003376 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00003377 CGF.FinishFunction();
3378 return TaskEntry;
3379}
3380
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003381static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
3382 SourceLocation Loc,
3383 QualType KmpInt32Ty,
3384 QualType KmpTaskTWithPrivatesPtrQTy,
3385 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003386 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003387 FunctionArgList Args;
3388 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
3389 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00003390 /*Id=*/nullptr,
3391 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003392 Args.push_back(&GtidArg);
3393 Args.push_back(&TaskTypeArg);
3394 FunctionType::ExtInfo Info;
3395 auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003396 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003397 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
3398 auto *DestructorFn =
3399 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
3400 ".omp_task_destructor.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003401 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
3402 DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003403 CodeGenFunction CGF(CGM);
3404 CGF.disableDebugInfo();
3405 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
3406 Args);
3407
Alexey Bataev31300ed2016-02-04 11:27:03 +00003408 LValue Base = CGF.EmitLoadOfPointerLValue(
3409 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3410 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003411 auto *KmpTaskTWithPrivatesQTyRD =
3412 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3413 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003414 Base = CGF.EmitLValueForField(Base, *FI);
3415 for (auto *Field :
3416 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
3417 if (auto DtorKind = Field->getType().isDestructedType()) {
3418 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
3419 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
3420 }
3421 }
3422 CGF.FinishFunction();
3423 return DestructorFn;
3424}
3425
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003426/// \brief Emit a privates mapping function for correct handling of private and
3427/// firstprivate variables.
3428/// \code
3429/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
3430/// **noalias priv1,..., <tyn> **noalias privn) {
3431/// *priv1 = &.privates.priv1;
3432/// ...;
3433/// *privn = &.privates.privn;
3434/// }
3435/// \endcode
3436static llvm::Value *
3437emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00003438 ArrayRef<const Expr *> PrivateVars,
3439 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00003440 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003441 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003442 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003443 auto &C = CGM.getContext();
3444 FunctionArgList Args;
3445 ImplicitParamDecl TaskPrivatesArg(
3446 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3447 C.getPointerType(PrivatesQTy).withConst().withRestrict());
3448 Args.push_back(&TaskPrivatesArg);
3449 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
3450 unsigned Counter = 1;
3451 for (auto *E: PrivateVars) {
3452 Args.push_back(ImplicitParamDecl::Create(
3453 C, /*DC=*/nullptr, Loc,
3454 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3455 .withConst()
3456 .withRestrict()));
3457 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3458 PrivateVarsPos[VD] = Counter;
3459 ++Counter;
3460 }
3461 for (auto *E : FirstprivateVars) {
3462 Args.push_back(ImplicitParamDecl::Create(
3463 C, /*DC=*/nullptr, Loc,
3464 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3465 .withConst()
3466 .withRestrict()));
3467 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3468 PrivateVarsPos[VD] = Counter;
3469 ++Counter;
3470 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003471 for (auto *E: LastprivateVars) {
3472 Args.push_back(ImplicitParamDecl::Create(
3473 C, /*DC=*/nullptr, Loc,
3474 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3475 .withConst()
3476 .withRestrict()));
3477 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3478 PrivateVarsPos[VD] = Counter;
3479 ++Counter;
3480 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003481 auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003482 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003483 auto *TaskPrivatesMapTy =
3484 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
3485 auto *TaskPrivatesMap = llvm::Function::Create(
3486 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
3487 ".omp_task_privates_map.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003488 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
3489 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00003490 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00003491 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003492 CodeGenFunction CGF(CGM);
3493 CGF.disableDebugInfo();
3494 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
3495 TaskPrivatesMapFnInfo, Args);
3496
3497 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003498 LValue Base = CGF.EmitLoadOfPointerLValue(
3499 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
3500 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003501 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
3502 Counter = 0;
3503 for (auto *Field : PrivatesQTyRD->fields()) {
3504 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
3505 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00003506 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00003507 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
3508 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00003509 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003510 ++Counter;
3511 }
3512 CGF.FinishFunction();
3513 return TaskPrivatesMap;
3514}
3515
Alexey Bataev9e034042015-05-05 04:05:12 +00003516static int array_pod_sort_comparator(const PrivateDataTy *P1,
3517 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003518 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
3519}
3520
Alexey Bataevf93095a2016-05-05 08:46:22 +00003521/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00003522static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00003523 const OMPExecutableDirective &D,
3524 Address KmpTaskSharedsPtr, LValue TDBase,
3525 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
3526 QualType SharedsTy, QualType SharedsPtrTy,
3527 const OMPTaskDataTy &Data,
3528 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
3529 auto &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00003530 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3531 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
3532 LValue SrcBase;
3533 if (!Data.FirstprivateVars.empty()) {
3534 SrcBase = CGF.MakeAddrLValue(
3535 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3536 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
3537 SharedsTy);
3538 }
3539 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
3540 cast<CapturedStmt>(*D.getAssociatedStmt()));
3541 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
3542 for (auto &&Pair : Privates) {
3543 auto *VD = Pair.second.PrivateCopy;
3544 auto *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00003545 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
3546 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00003547 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003548 if (auto *Elem = Pair.second.PrivateElemInit) {
3549 auto *OriginalVD = Pair.second.Original;
3550 auto *SharedField = CapturesInfo.lookup(OriginalVD);
3551 auto SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
3552 SharedRefLValue = CGF.MakeAddrLValue(
3553 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
3554 SharedRefLValue.getType(), AlignmentSource::Decl);
3555 QualType Type = OriginalVD->getType();
3556 if (Type->isArrayType()) {
3557 // Initialize firstprivate array.
3558 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
3559 // Perform simple memcpy.
3560 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
3561 SharedRefLValue.getAddress(), Type);
3562 } else {
3563 // Initialize firstprivate array using element-by-element
3564 // intialization.
3565 CGF.EmitOMPAggregateAssign(
3566 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
3567 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
3568 Address SrcElement) {
3569 // Clean up any temporaries needed by the initialization.
3570 CodeGenFunction::OMPPrivateScope InitScope(CGF);
3571 InitScope.addPrivate(
3572 Elem, [SrcElement]() -> Address { return SrcElement; });
3573 (void)InitScope.Privatize();
3574 // Emit initialization for single element.
3575 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
3576 CGF, &CapturesInfo);
3577 CGF.EmitAnyExprToMem(Init, DestElement,
3578 Init->getType().getQualifiers(),
3579 /*IsInitializer=*/false);
3580 });
3581 }
3582 } else {
3583 CodeGenFunction::OMPPrivateScope InitScope(CGF);
3584 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
3585 return SharedRefLValue.getAddress();
3586 });
3587 (void)InitScope.Privatize();
3588 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
3589 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
3590 /*capturedByInit=*/false);
3591 }
3592 } else
3593 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
3594 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003595 ++FI;
3596 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003597}
3598
3599/// Check if duplication function is required for taskloops.
3600static bool checkInitIsRequired(CodeGenFunction &CGF,
3601 ArrayRef<PrivateDataTy> Privates) {
3602 bool InitRequired = false;
3603 for (auto &&Pair : Privates) {
3604 auto *VD = Pair.second.PrivateCopy;
3605 auto *Init = VD->getAnyInitializer();
3606 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
3607 !CGF.isTrivialInitializer(Init));
3608 }
3609 return InitRequired;
3610}
3611
3612
3613/// Emit task_dup function (for initialization of
3614/// private/firstprivate/lastprivate vars and last_iter flag)
3615/// \code
3616/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
3617/// lastpriv) {
3618/// // setup lastprivate flag
3619/// task_dst->last = lastpriv;
3620/// // could be constructor calls here...
3621/// }
3622/// \endcode
3623static llvm::Value *
3624emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
3625 const OMPExecutableDirective &D,
3626 QualType KmpTaskTWithPrivatesPtrQTy,
3627 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
3628 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
3629 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
3630 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
3631 auto &C = CGM.getContext();
3632 FunctionArgList Args;
3633 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc,
3634 /*Id=*/nullptr, KmpTaskTWithPrivatesPtrQTy);
3635 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc,
3636 /*Id=*/nullptr, KmpTaskTWithPrivatesPtrQTy);
3637 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc,
3638 /*Id=*/nullptr, C.IntTy);
3639 Args.push_back(&DstArg);
3640 Args.push_back(&SrcArg);
3641 Args.push_back(&LastprivArg);
3642 auto &TaskDupFnInfo =
3643 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3644 auto *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
3645 auto *TaskDup =
3646 llvm::Function::Create(TaskDupTy, llvm::GlobalValue::InternalLinkage,
3647 ".omp_task_dup.", &CGM.getModule());
3648 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskDup, TaskDupFnInfo);
3649 CodeGenFunction CGF(CGM);
3650 CGF.disableDebugInfo();
3651 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args);
3652
3653 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3654 CGF.GetAddrOfLocalVar(&DstArg),
3655 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3656 // task_dst->liter = lastpriv;
3657 if (WithLastIter) {
3658 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3659 LValue Base = CGF.EmitLValueForField(
3660 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
3661 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
3662 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
3663 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
3664 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
3665 }
3666
3667 // Emit initial values for private copies (if any).
3668 assert(!Privates.empty());
3669 Address KmpTaskSharedsPtr = Address::invalid();
3670 if (!Data.FirstprivateVars.empty()) {
3671 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3672 CGF.GetAddrOfLocalVar(&SrcArg),
3673 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3674 LValue Base = CGF.EmitLValueForField(
3675 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
3676 KmpTaskSharedsPtr = Address(
3677 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
3678 Base, *std::next(KmpTaskTQTyRD->field_begin(),
3679 KmpTaskTShareds)),
3680 Loc),
3681 CGF.getNaturalTypeAlignment(SharedsTy));
3682 }
Alexey Bataev8a831592016-05-10 10:36:51 +00003683 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
3684 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003685 CGF.FinishFunction();
3686 return TaskDup;
3687}
3688
Alexey Bataev8a831592016-05-10 10:36:51 +00003689/// Checks if destructor function is required to be generated.
3690/// \return true if cleanups are required, false otherwise.
3691static bool
3692checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
3693 bool NeedsCleanup = false;
3694 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3695 auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
3696 for (auto *FD : PrivateRD->fields()) {
3697 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
3698 if (NeedsCleanup)
3699 break;
3700 }
3701 return NeedsCleanup;
3702}
3703
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003704CGOpenMPRuntime::TaskResultTy
3705CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
3706 const OMPExecutableDirective &D,
3707 llvm::Value *TaskFunction, QualType SharedsTy,
3708 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003709 auto &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00003710 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003711 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003712 auto I = Data.PrivateCopies.begin();
3713 for (auto *E : Data.PrivateVars) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003714 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3715 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00003716 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00003717 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3718 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003719 ++I;
3720 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003721 I = Data.FirstprivateCopies.begin();
3722 auto IElemInitRef = Data.FirstprivateInits.begin();
3723 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003724 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3725 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00003726 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00003727 PrivateHelpersTy(
3728 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3729 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
Richard Trieucc3949d2016-02-18 22:34:54 +00003730 ++I;
3731 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00003732 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003733 I = Data.LastprivateCopies.begin();
3734 for (auto *E : Data.LastprivateVars) {
3735 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3736 Privates.push_back(std::make_pair(
3737 C.getDeclAlign(VD),
3738 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3739 /*PrivateElemInit=*/nullptr)));
3740 ++I;
3741 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003742 llvm::array_pod_sort(Privates.begin(), Privates.end(),
3743 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003744 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
3745 // Build type kmp_routine_entry_t (if not built yet).
3746 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003747 // Build type kmp_task_t (if not built yet).
3748 if (KmpTaskTQTy.isNull()) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003749 KmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
3750 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003751 }
3752 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003753 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003754 auto *KmpTaskTWithPrivatesQTyRD =
3755 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
3756 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
3757 QualType KmpTaskTWithPrivatesPtrQTy =
3758 C.getPointerType(KmpTaskTWithPrivatesQTy);
3759 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
3760 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00003761 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003762 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
3763
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003764 // Emit initial values for private copies (if any).
3765 llvm::Value *TaskPrivatesMap = nullptr;
3766 auto *TaskPrivatesMapTy =
3767 std::next(cast<llvm::Function>(TaskFunction)->getArgumentList().begin(),
3768 3)
3769 ->getType();
3770 if (!Privates.empty()) {
3771 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00003772 TaskPrivatesMap = emitTaskPrivateMappingFunction(
3773 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
3774 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003775 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3776 TaskPrivatesMap, TaskPrivatesMapTy);
3777 } else {
3778 TaskPrivatesMap = llvm::ConstantPointerNull::get(
3779 cast<llvm::PointerType>(TaskPrivatesMapTy));
3780 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003781 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
3782 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003783 auto *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00003784 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
3785 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
3786 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003787
3788 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
3789 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
3790 // kmp_routine_entry_t *task_entry);
3791 // Task flags. Format is taken from
3792 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
3793 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00003794 enum {
3795 TiedFlag = 0x1,
3796 FinalFlag = 0x2,
3797 DestructorsFlag = 0x8,
3798 PriorityFlag = 0x20
3799 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003800 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00003801 bool NeedsCleanup = false;
3802 if (!Privates.empty()) {
3803 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
3804 if (NeedsCleanup)
3805 Flags = Flags | DestructorsFlag;
3806 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00003807 if (Data.Priority.getInt())
3808 Flags = Flags | PriorityFlag;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003809 auto *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003810 Data.Final.getPointer()
3811 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00003812 CGF.Builder.getInt32(FinalFlag),
3813 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003814 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003815 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00003816 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003817 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
3818 getThreadID(CGF, Loc), TaskFlags,
3819 KmpTaskTWithPrivatesTySize, SharedsSize,
3820 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3821 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00003822 auto *NewTask = CGF.EmitRuntimeCall(
3823 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003824 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3825 NewTask, KmpTaskTWithPrivatesPtrTy);
3826 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
3827 KmpTaskTWithPrivatesQTy);
3828 LValue TDBase =
3829 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003830 // Fill the data in the resulting kmp_task_t record.
3831 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00003832 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003833 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00003834 KmpTaskSharedsPtr =
3835 Address(CGF.EmitLoadOfScalar(
3836 CGF.EmitLValueForField(
3837 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
3838 KmpTaskTShareds)),
3839 Loc),
3840 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003841 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003842 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003843 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00003844 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003845 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00003846 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
3847 SharedsTy, SharedsPtrTy, Data, Privates,
3848 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003849 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
3850 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
3851 Result.TaskDupFn = emitTaskDupFunction(
3852 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
3853 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
3854 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003855 }
3856 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00003857 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
3858 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00003859 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00003860 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
3861 auto *KmpCmplrdataUD = (*FI)->getType()->getAsUnionType()->getDecl();
3862 if (NeedsCleanup) {
3863 llvm::Value *DestructorFn = emitDestructorsFunction(
3864 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
3865 KmpTaskTWithPrivatesQTy);
3866 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
3867 LValue DestructorsLV = CGF.EmitLValueForField(
3868 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
3869 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3870 DestructorFn, KmpRoutineEntryPtrTy),
3871 DestructorsLV);
3872 }
3873 // Set priority.
3874 if (Data.Priority.getInt()) {
3875 LValue Data2LV = CGF.EmitLValueForField(
3876 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
3877 LValue PriorityLV = CGF.EmitLValueForField(
3878 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
3879 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
3880 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003881 Result.NewTask = NewTask;
3882 Result.TaskEntry = TaskEntry;
3883 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
3884 Result.TDBase = TDBase;
3885 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
3886 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00003887}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003888
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003889void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
3890 const OMPExecutableDirective &D,
3891 llvm::Value *TaskFunction,
3892 QualType SharedsTy, Address Shareds,
3893 const Expr *IfCond,
3894 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003895 if (!CGF.HaveInsertPoint())
3896 return;
3897
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003898 TaskResultTy Result =
3899 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
3900 llvm::Value *NewTask = Result.NewTask;
3901 llvm::Value *TaskEntry = Result.TaskEntry;
3902 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
3903 LValue TDBase = Result.TDBase;
3904 RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
Alexey Bataev7292c292016-04-25 12:22:29 +00003905 auto &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003906 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00003907 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003908 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00003909 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003910 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00003911 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003912 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
3913 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003914 QualType FlagsTy =
3915 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003916 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
3917 if (KmpDependInfoTy.isNull()) {
3918 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
3919 KmpDependInfoRD->startDefinition();
3920 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
3921 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
3922 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
3923 KmpDependInfoRD->completeDefinition();
3924 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003925 } else
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003926 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003927 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003928 // Define type kmp_depend_info[<Dependences.size()>];
3929 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00003930 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003931 ArrayType::Normal, /*IndexTypeQuals=*/0);
3932 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00003933 DependenciesArray =
3934 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
John McCall7f416cc2015-09-08 08:05:57 +00003935 for (unsigned i = 0; i < NumDependencies; ++i) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003936 const Expr *E = Data.Dependences[i].second;
John McCall7f416cc2015-09-08 08:05:57 +00003937 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003938 llvm::Value *Size;
3939 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003940 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
3941 LValue UpAddrLVal =
3942 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
3943 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00003944 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003945 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00003946 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003947 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
3948 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003949 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00003950 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003951 auto Base = CGF.MakeAddrLValue(
3952 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003953 KmpDependInfoTy);
3954 // deps[i].base_addr = &<Dependences[i].second>;
3955 auto BaseAddrLVal = CGF.EmitLValueForField(
3956 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00003957 CGF.EmitStoreOfScalar(
3958 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
3959 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003960 // deps[i].len = sizeof(<Dependences[i].second>);
3961 auto LenLVal = CGF.EmitLValueForField(
3962 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
3963 CGF.EmitStoreOfScalar(Size, LenLVal);
3964 // deps[i].flags = <Dependences[i].first>;
3965 RTLDependenceKindTy DepKind;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003966 switch (Data.Dependences[i].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003967 case OMPC_DEPEND_in:
3968 DepKind = DepIn;
3969 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00003970 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003971 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003972 case OMPC_DEPEND_inout:
3973 DepKind = DepInOut;
3974 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00003975 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003976 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003977 case OMPC_DEPEND_unknown:
3978 llvm_unreachable("Unknown task dependence type");
3979 }
3980 auto FlagsLVal = CGF.EmitLValueForField(
3981 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
3982 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
3983 FlagsLVal);
3984 }
John McCall7f416cc2015-09-08 08:05:57 +00003985 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3986 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003987 CGF.VoidPtrTy);
3988 }
3989
Alexey Bataev62b63b12015-03-10 07:28:44 +00003990 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
3991 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003992 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
3993 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
3994 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
3995 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00003996 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003997 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00003998 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
3999 llvm::Value *DepTaskArgs[7];
4000 if (NumDependencies) {
4001 DepTaskArgs[0] = UpLoc;
4002 DepTaskArgs[1] = ThreadID;
4003 DepTaskArgs[2] = NewTask;
4004 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
4005 DepTaskArgs[4] = DependenciesArray.getPointer();
4006 DepTaskArgs[5] = CGF.Builder.getInt32(0);
4007 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4008 }
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00004009 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies,
4010 &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004011 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004012 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004013 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4014 auto PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
4015 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
4016 }
John McCall7f416cc2015-09-08 08:05:57 +00004017 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004018 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00004019 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00004020 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004021 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00004022 TaskArgs);
4023 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00004024 // Check if parent region is untied and build return for untied task;
4025 if (auto *Region =
4026 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4027 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00004028 };
John McCall7f416cc2015-09-08 08:05:57 +00004029
4030 llvm::Value *DepWaitTaskArgs[6];
4031 if (NumDependencies) {
4032 DepWaitTaskArgs[0] = UpLoc;
4033 DepWaitTaskArgs[1] = ThreadID;
4034 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
4035 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
4036 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
4037 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4038 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004039 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
4040 NumDependencies, &DepWaitTaskArgs](CodeGenFunction &CGF,
4041 PrePostActionTy &) {
4042 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004043 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
4044 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
4045 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
4046 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
4047 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00004048 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004049 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004050 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004051 // Call proxy_task_entry(gtid, new_task);
4052 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy](
4053 CodeGenFunction &CGF, PrePostActionTy &Action) {
4054 Action.Enter(CGF);
4055 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
4056 CGF.EmitCallOrInvoke(TaskEntry, OutlinedFnArgs);
4057 };
4058
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004059 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
4060 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004061 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
4062 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004063 RegionCodeGenTy RCG(CodeGen);
4064 CommonActionTy Action(
4065 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
4066 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
4067 RCG.setAction(Action);
4068 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004069 };
John McCall7f416cc2015-09-08 08:05:57 +00004070
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004071 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00004072 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004073 else {
4074 RegionCodeGenTy ThenRCG(ThenCodeGen);
4075 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00004076 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004077}
4078
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004079void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
4080 const OMPLoopDirective &D,
4081 llvm::Value *TaskFunction,
4082 QualType SharedsTy, Address Shareds,
4083 const Expr *IfCond,
4084 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004085 if (!CGF.HaveInsertPoint())
4086 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004087 TaskResultTy Result =
4088 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004089 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4090 // libcall.
4091 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
4092 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
4093 // sched, kmp_uint64 grainsize, void *task_dup);
4094 llvm::Value *ThreadID = getThreadID(CGF, Loc);
4095 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
4096 llvm::Value *IfVal;
4097 if (IfCond) {
4098 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
4099 /*isSigned=*/true);
4100 } else
4101 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
4102
4103 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004104 Result.TDBase,
4105 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004106 auto *LBVar =
4107 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
4108 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
4109 /*IsInitializer=*/true);
4110 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004111 Result.TDBase,
4112 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004113 auto *UBVar =
4114 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
4115 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
4116 /*IsInitializer=*/true);
4117 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004118 Result.TDBase,
4119 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataev7292c292016-04-25 12:22:29 +00004120 auto *StVar =
4121 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
4122 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
4123 /*IsInitializer=*/true);
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004124 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00004125 llvm::Value *TaskArgs[] = {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004126 UpLoc, ThreadID, Result.NewTask, IfVal, LBLVal.getPointer(),
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004127 UBLVal.getPointer(), CGF.EmitLoadOfScalar(StLVal, SourceLocation()),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004128 llvm::ConstantInt::getSigned(CGF.IntTy, Data.Nogroup ? 1 : 0),
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004129 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004130 CGF.IntTy, Data.Schedule.getPointer()
4131 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004132 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004133 Data.Schedule.getPointer()
4134 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004135 /*isSigned=*/false)
4136 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataevf93095a2016-05-05 08:46:22 +00004137 Result.TaskDupFn
4138 ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Result.TaskDupFn,
4139 CGF.VoidPtrTy)
4140 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00004141 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
4142}
4143
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004144/// \brief Emit reduction operation for each element of array (required for
4145/// array sections) LHS op = RHS.
4146/// \param Type Type of array.
4147/// \param LHSVar Variable on the left side of the reduction operation
4148/// (references element of array in original variable).
4149/// \param RHSVar Variable on the right side of the reduction operation
4150/// (references element of array in original variable).
4151/// \param RedOpGen Generator of reduction operation with use of LHSVar and
4152/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00004153static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004154 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
4155 const VarDecl *RHSVar,
4156 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
4157 const Expr *, const Expr *)> &RedOpGen,
4158 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
4159 const Expr *UpExpr = nullptr) {
4160 // Perform element-by-element initialization.
4161 QualType ElementTy;
4162 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
4163 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
4164
4165 // Drill down to the base element type on both arrays.
4166 auto ArrayTy = Type->getAsArrayTypeUnsafe();
4167 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
4168
4169 auto RHSBegin = RHSAddr.getPointer();
4170 auto LHSBegin = LHSAddr.getPointer();
4171 // Cast from pointer to array type to pointer to single element.
4172 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
4173 // The basic structure here is a while-do loop.
4174 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
4175 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
4176 auto IsEmpty =
4177 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
4178 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
4179
4180 // Enter the loop body, making that address the current address.
4181 auto EntryBB = CGF.Builder.GetInsertBlock();
4182 CGF.EmitBlock(BodyBB);
4183
4184 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
4185
4186 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
4187 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
4188 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
4189 Address RHSElementCurrent =
4190 Address(RHSElementPHI,
4191 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4192
4193 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
4194 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
4195 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
4196 Address LHSElementCurrent =
4197 Address(LHSElementPHI,
4198 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4199
4200 // Emit copy.
4201 CodeGenFunction::OMPPrivateScope Scope(CGF);
4202 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
4203 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
4204 Scope.Privatize();
4205 RedOpGen(CGF, XExpr, EExpr, UpExpr);
4206 Scope.ForceCleanup();
4207
4208 // Shift the address forward by one element.
4209 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
4210 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
4211 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
4212 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
4213 // Check whether we've reached the end.
4214 auto Done =
4215 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
4216 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
4217 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
4218 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
4219
4220 // Done.
4221 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
4222}
4223
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004224/// Emit reduction combiner. If the combiner is a simple expression emit it as
4225/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
4226/// UDR combiner function.
4227static void emitReductionCombiner(CodeGenFunction &CGF,
4228 const Expr *ReductionOp) {
4229 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
4230 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
4231 if (auto *DRE =
4232 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
4233 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
4234 std::pair<llvm::Function *, llvm::Function *> Reduction =
4235 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
4236 RValue Func = RValue::get(Reduction.first);
4237 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
4238 CGF.EmitIgnoredExpr(ReductionOp);
4239 return;
4240 }
4241 CGF.EmitIgnoredExpr(ReductionOp);
4242}
4243
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004244static llvm::Value *emitReductionFunction(CodeGenModule &CGM,
4245 llvm::Type *ArgsType,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004246 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004247 ArrayRef<const Expr *> LHSExprs,
4248 ArrayRef<const Expr *> RHSExprs,
4249 ArrayRef<const Expr *> ReductionOps) {
4250 auto &C = CGM.getContext();
4251
4252 // void reduction_func(void *LHSArg, void *RHSArg);
4253 FunctionArgList Args;
4254 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
4255 C.VoidPtrTy);
4256 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
4257 C.VoidPtrTy);
4258 Args.push_back(&LHSArg);
4259 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00004260 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004261 auto *Fn = llvm::Function::Create(
4262 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
4263 ".omp.reduction.reduction_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004264 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004265 CodeGenFunction CGF(CGM);
4266 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
4267
4268 // Dst = (void*[n])(LHSArg);
4269 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00004270 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4271 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
4272 ArgsType), CGF.getPointerAlign());
4273 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4274 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
4275 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004276
4277 // ...
4278 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
4279 // ...
4280 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004281 auto IPriv = Privates.begin();
4282 unsigned Idx = 0;
4283 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004284 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
4285 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004286 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004287 });
4288 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
4289 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004290 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004291 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004292 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004293 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004294 // Get array size and emit VLA type.
4295 ++Idx;
4296 Address Elem =
4297 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
4298 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004299 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
4300 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004301 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00004302 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004303 CGF.EmitVariablyModifiedType(PrivTy);
4304 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004305 }
4306 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004307 IPriv = Privates.begin();
4308 auto ILHS = LHSExprs.begin();
4309 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004310 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004311 if ((*IPriv)->getType()->isArrayType()) {
4312 // Emit reduction for array section.
4313 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4314 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004315 EmitOMPAggregateReduction(
4316 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4317 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4318 emitReductionCombiner(CGF, E);
4319 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004320 } else
4321 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004322 emitReductionCombiner(CGF, E);
Richard Trieucc3949d2016-02-18 22:34:54 +00004323 ++IPriv;
4324 ++ILHS;
4325 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004326 }
4327 Scope.ForceCleanup();
4328 CGF.FinishFunction();
4329 return Fn;
4330}
4331
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004332static void emitSingleReductionCombiner(CodeGenFunction &CGF,
4333 const Expr *ReductionOp,
4334 const Expr *PrivateRef,
4335 const DeclRefExpr *LHS,
4336 const DeclRefExpr *RHS) {
4337 if (PrivateRef->getType()->isArrayType()) {
4338 // Emit reduction for array section.
4339 auto *LHSVar = cast<VarDecl>(LHS->getDecl());
4340 auto *RHSVar = cast<VarDecl>(RHS->getDecl());
4341 EmitOMPAggregateReduction(
4342 CGF, PrivateRef->getType(), LHSVar, RHSVar,
4343 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4344 emitReductionCombiner(CGF, ReductionOp);
4345 });
4346 } else
4347 // Emit reduction for array subscript or single variable.
4348 emitReductionCombiner(CGF, ReductionOp);
4349}
4350
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004351void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004352 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004353 ArrayRef<const Expr *> LHSExprs,
4354 ArrayRef<const Expr *> RHSExprs,
4355 ArrayRef<const Expr *> ReductionOps,
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004356 bool WithNowait, bool SimpleReduction) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004357 if (!CGF.HaveInsertPoint())
4358 return;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004359 // Next code should be emitted for reduction:
4360 //
4361 // static kmp_critical_name lock = { 0 };
4362 //
4363 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
4364 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
4365 // ...
4366 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
4367 // *(Type<n>-1*)rhs[<n>-1]);
4368 // }
4369 //
4370 // ...
4371 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
4372 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4373 // RedList, reduce_func, &<lock>)) {
4374 // case 1:
4375 // ...
4376 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4377 // ...
4378 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4379 // break;
4380 // case 2:
4381 // ...
4382 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4383 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00004384 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004385 // break;
4386 // default:;
4387 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004388 //
4389 // if SimpleReduction is true, only the next code is generated:
4390 // ...
4391 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4392 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004393
4394 auto &C = CGM.getContext();
4395
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004396 if (SimpleReduction) {
4397 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004398 auto IPriv = Privates.begin();
4399 auto ILHS = LHSExprs.begin();
4400 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004401 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004402 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4403 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00004404 ++IPriv;
4405 ++ILHS;
4406 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004407 }
4408 return;
4409 }
4410
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004411 // 1. Build a list of reduction variables.
4412 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004413 auto Size = RHSExprs.size();
4414 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00004415 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004416 // Reserve place for array size.
4417 ++Size;
4418 }
4419 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004420 QualType ReductionArrayTy =
4421 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4422 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00004423 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004424 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004425 auto IPriv = Privates.begin();
4426 unsigned Idx = 0;
4427 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004428 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004429 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00004430 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004431 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004432 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4433 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004434 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004435 // Store array size.
4436 ++Idx;
4437 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
4438 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00004439 llvm::Value *Size = CGF.Builder.CreateIntCast(
4440 CGF.getVLASize(
4441 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4442 .first,
4443 CGF.SizeTy, /*isSigned=*/false);
4444 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4445 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004446 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004447 }
4448
4449 // 2. Emit reduce_func().
4450 auto *ReductionFn = emitReductionFunction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004451 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
4452 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004453
4454 // 3. Create static kmp_critical_name lock = { 0 };
4455 auto *Lock = getCriticalRegionLock(".reduction");
4456
4457 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4458 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00004459 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004460 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004461 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
Samuel Antao4c8035b2016-12-12 18:00:20 +00004462 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4463 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004464 llvm::Value *Args[] = {
4465 IdentTLoc, // ident_t *<loc>
4466 ThreadId, // i32 <gtid>
4467 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
4468 ReductionArrayTySize, // size_type sizeof(RedList)
4469 RL, // void *RedList
4470 ReductionFn, // void (*) (void *, void *) <reduce_func>
4471 Lock // kmp_critical_name *&<lock>
4472 };
4473 auto Res = CGF.EmitRuntimeCall(
4474 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
4475 : OMPRTL__kmpc_reduce),
4476 Args);
4477
4478 // 5. Build switch(res)
4479 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
4480 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
4481
4482 // 6. Build case 1:
4483 // ...
4484 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4485 // ...
4486 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4487 // break;
4488 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
4489 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
4490 CGF.EmitBlock(Case1BB);
4491
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004492 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4493 llvm::Value *EndArgs[] = {
4494 IdentTLoc, // ident_t *<loc>
4495 ThreadId, // i32 <gtid>
4496 Lock // kmp_critical_name *&<lock>
4497 };
4498 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
4499 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004500 auto IPriv = Privates.begin();
4501 auto ILHS = LHSExprs.begin();
4502 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004503 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004504 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4505 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00004506 ++IPriv;
4507 ++ILHS;
4508 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004509 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004510 };
4511 RegionCodeGenTy RCG(CodeGen);
4512 CommonActionTy Action(
4513 nullptr, llvm::None,
4514 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
4515 : OMPRTL__kmpc_end_reduce),
4516 EndArgs);
4517 RCG.setAction(Action);
4518 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004519
4520 CGF.EmitBranch(DefaultBB);
4521
4522 // 7. Build case 2:
4523 // ...
4524 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4525 // ...
4526 // break;
4527 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
4528 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
4529 CGF.EmitBlock(Case2BB);
4530
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004531 auto &&AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs, &ReductionOps](
4532 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004533 auto ILHS = LHSExprs.begin();
4534 auto IRHS = RHSExprs.begin();
4535 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004536 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004537 const Expr *XExpr = nullptr;
4538 const Expr *EExpr = nullptr;
4539 const Expr *UpExpr = nullptr;
4540 BinaryOperatorKind BO = BO_Comma;
4541 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
4542 if (BO->getOpcode() == BO_Assign) {
4543 XExpr = BO->getLHS();
4544 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004545 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004546 }
4547 // Try to emit update expression as a simple atomic.
4548 auto *RHSExpr = UpExpr;
4549 if (RHSExpr) {
4550 // Analyze RHS part of the whole expression.
4551 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
4552 RHSExpr->IgnoreParenImpCasts())) {
4553 // If this is a conditional operator, analyze its condition for
4554 // min/max reduction operator.
4555 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00004556 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004557 if (auto *BORHS =
4558 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
4559 EExpr = BORHS->getRHS();
4560 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004561 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004562 }
4563 if (XExpr) {
4564 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00004565 auto &&AtomicRedGen = [BO, VD,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004566 Loc](CodeGenFunction &CGF, const Expr *XExpr,
4567 const Expr *EExpr, const Expr *UpExpr) {
4568 LValue X = CGF.EmitLValue(XExpr);
4569 RValue E;
4570 if (EExpr)
4571 E = CGF.EmitAnyExpr(EExpr);
4572 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00004573 X, E, BO, /*IsXLHSInRHSPart=*/true,
4574 llvm::AtomicOrdering::Monotonic, Loc,
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00004575 [&CGF, UpExpr, VD, Loc](RValue XRValue) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004576 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4577 PrivateScope.addPrivate(
4578 VD, [&CGF, VD, XRValue, Loc]() -> Address {
4579 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
4580 CGF.emitOMPSimpleStore(
4581 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
4582 VD->getType().getNonReferenceType(), Loc);
4583 return LHSTemp;
4584 });
4585 (void)PrivateScope.Privatize();
4586 return CGF.EmitAnyExpr(UpExpr);
4587 });
4588 };
4589 if ((*IPriv)->getType()->isArrayType()) {
4590 // Emit atomic reduction for array section.
4591 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
4592 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
4593 AtomicRedGen, XExpr, EExpr, UpExpr);
4594 } else
4595 // Emit atomic reduction for array subscript or single variable.
4596 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
4597 } else {
4598 // Emit as a critical region.
4599 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
4600 const Expr *, const Expr *) {
4601 auto &RT = CGF.CGM.getOpenMPRuntime();
4602 RT.emitCriticalRegion(
4603 CGF, ".atomic_reduction",
4604 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
4605 Action.Enter(CGF);
4606 emitReductionCombiner(CGF, E);
4607 },
4608 Loc);
4609 };
4610 if ((*IPriv)->getType()->isArrayType()) {
4611 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4612 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
4613 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4614 CritRedGen);
4615 } else
4616 CritRedGen(CGF, nullptr, nullptr, nullptr);
4617 }
Richard Trieucc3949d2016-02-18 22:34:54 +00004618 ++ILHS;
4619 ++IRHS;
4620 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004621 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004622 };
4623 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
4624 if (!WithNowait) {
4625 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
4626 llvm::Value *EndArgs[] = {
4627 IdentTLoc, // ident_t *<loc>
4628 ThreadId, // i32 <gtid>
4629 Lock // kmp_critical_name *&<lock>
4630 };
4631 CommonActionTy Action(nullptr, llvm::None,
4632 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
4633 EndArgs);
4634 AtomicRCG.setAction(Action);
4635 AtomicRCG(CGF);
4636 } else
4637 AtomicRCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004638
4639 CGF.EmitBranch(DefaultBB);
4640 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
4641}
4642
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004643void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
4644 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004645 if (!CGF.HaveInsertPoint())
4646 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004647 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
4648 // global_tid);
4649 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
4650 // Ignore return result until untied tasks are supported.
4651 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00004652 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4653 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004654}
4655
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00004656void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004657 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004658 const RegionCodeGenTy &CodeGen,
4659 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004660 if (!CGF.HaveInsertPoint())
4661 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004662 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00004663 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00004664}
4665
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004666namespace {
4667enum RTCancelKind {
4668 CancelNoreq = 0,
4669 CancelParallel = 1,
4670 CancelLoop = 2,
4671 CancelSections = 3,
4672 CancelTaskgroup = 4
4673};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00004674} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004675
4676static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
4677 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00004678 if (CancelRegion == OMPD_parallel)
4679 CancelKind = CancelParallel;
4680 else if (CancelRegion == OMPD_for)
4681 CancelKind = CancelLoop;
4682 else if (CancelRegion == OMPD_sections)
4683 CancelKind = CancelSections;
4684 else {
4685 assert(CancelRegion == OMPD_taskgroup);
4686 CancelKind = CancelTaskgroup;
4687 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004688 return CancelKind;
4689}
4690
4691void CGOpenMPRuntime::emitCancellationPointCall(
4692 CodeGenFunction &CGF, SourceLocation Loc,
4693 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004694 if (!CGF.HaveInsertPoint())
4695 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004696 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
4697 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004698 if (auto *OMPRegionInfo =
4699 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00004700 if (OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004701 llvm::Value *Args[] = {
4702 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
4703 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004704 // Ignore return result until untied tasks are supported.
4705 auto *Result = CGF.EmitRuntimeCall(
4706 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
4707 // if (__kmpc_cancellationpoint()) {
4708 // __kmpc_cancel_barrier();
4709 // exit from construct;
4710 // }
4711 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4712 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4713 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4714 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4715 CGF.EmitBlock(ExitBB);
4716 // __kmpc_cancel_barrier();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004717 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004718 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004719 auto CancelDest =
4720 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004721 CGF.EmitBranchThroughCleanup(CancelDest);
4722 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4723 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00004724 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00004725}
4726
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004727void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00004728 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004729 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004730 if (!CGF.HaveInsertPoint())
4731 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004732 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
4733 // kmp_int32 cncl_kind);
4734 if (auto *OMPRegionInfo =
4735 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004736 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
4737 PrePostActionTy &) {
4738 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00004739 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004740 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00004741 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
4742 // Ignore return result until untied tasks are supported.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004743 auto *Result = CGF.EmitRuntimeCall(
4744 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00004745 // if (__kmpc_cancel()) {
4746 // __kmpc_cancel_barrier();
4747 // exit from construct;
4748 // }
4749 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4750 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4751 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4752 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4753 CGF.EmitBlock(ExitBB);
4754 // __kmpc_cancel_barrier();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004755 RT.emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
Alexey Bataev87933c72015-09-18 08:07:34 +00004756 // exit from construct;
4757 auto CancelDest =
4758 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
4759 CGF.EmitBranchThroughCleanup(CancelDest);
4760 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4761 };
4762 if (IfCond)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004763 emitOMPIfClause(CGF, IfCond, ThenGen,
4764 [](CodeGenFunction &, PrePostActionTy &) {});
4765 else {
4766 RegionCodeGenTy ThenRCG(ThenGen);
4767 ThenRCG(CGF);
4768 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004769 }
4770}
Samuel Antaobed3c462015-10-02 16:14:20 +00004771
Samuel Antaoee8fb302016-01-06 13:42:12 +00004772/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00004773/// consists of the file and device IDs as well as line number associated with
4774/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004775static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
4776 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004777 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004778
4779 auto &SM = C.getSourceManager();
4780
4781 // The loc should be always valid and have a file ID (the user cannot use
4782 // #pragma directives in macros)
4783
4784 assert(Loc.isValid() && "Source location is expected to be always valid.");
4785 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
4786
4787 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
4788 assert(PLoc.isValid() && "Source location is expected to be always valid.");
4789
4790 llvm::sys::fs::UniqueID ID;
4791 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
4792 llvm_unreachable("Source file with target region no longer exists!");
4793
4794 DeviceID = ID.getDevice();
4795 FileID = ID.getFile();
4796 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004797}
4798
4799void CGOpenMPRuntime::emitTargetOutlinedFunction(
4800 const OMPExecutableDirective &D, StringRef ParentName,
4801 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004802 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004803 assert(!ParentName.empty() && "Invalid target region parent name!");
4804
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00004805 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
4806 IsOffloadEntry, CodeGen);
4807}
4808
4809void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
4810 const OMPExecutableDirective &D, StringRef ParentName,
4811 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
4812 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00004813 // Create a unique name for the entry function using the source location
4814 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00004815 //
Samuel Antao2de62b02016-02-13 23:35:10 +00004816 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00004817 //
4818 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00004819 // mangled name of the function that encloses the target region and BB is the
4820 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004821
4822 unsigned DeviceID;
4823 unsigned FileID;
4824 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004825 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004826 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004827 SmallString<64> EntryFnName;
4828 {
4829 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00004830 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
4831 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004832 }
4833
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00004834 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4835
Samuel Antaobed3c462015-10-02 16:14:20 +00004836 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004837 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00004838 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004839
Samuel Antao6d004262016-06-16 18:39:34 +00004840 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004841
4842 // If this target outline function is not an offload entry, we don't need to
4843 // register it.
4844 if (!IsOffloadEntry)
4845 return;
4846
4847 // The target region ID is used by the runtime library to identify the current
4848 // target region, so it only has to be unique and not necessarily point to
4849 // anything. It could be the pointer to the outlined function that implements
4850 // the target region, but we aren't using that so that the compiler doesn't
4851 // need to keep that, and could therefore inline the host function if proven
4852 // worthwhile during optimization. In the other hand, if emitting code for the
4853 // device, the ID has to be the function address so that it can retrieved from
4854 // the offloading entry and launched by the runtime library. We also mark the
4855 // outlined function to have external linkage in case we are emitting code for
4856 // the device, because these functions will be entry points to the device.
4857
4858 if (CGM.getLangOpts().OpenMPIsDevice) {
4859 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
4860 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
4861 } else
4862 OutlinedFnID = new llvm::GlobalVariable(
4863 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
4864 llvm::GlobalValue::PrivateLinkage,
4865 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
4866
4867 // Register the information for the entry associated with this target region.
4868 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antaof83efdb2017-01-05 16:02:49 +00004869 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID,
4870 /*Flags=*/0);
Samuel Antaobed3c462015-10-02 16:14:20 +00004871}
4872
Carlo Bertolli6eee9062016-04-29 01:37:30 +00004873/// discard all CompoundStmts intervening between two constructs
4874static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
4875 while (auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
4876 Body = CS->body_front();
4877
4878 return Body;
4879}
4880
Samuel Antaob68e2db2016-03-03 16:20:23 +00004881/// \brief Emit the num_teams clause of an enclosed teams directive at the
4882/// target region scope. If there is no teams directive associated with the
4883/// target directive, or if there is no num_teams clause associated with the
4884/// enclosed teams directive, return nullptr.
4885static llvm::Value *
4886emitNumTeamsClauseForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4887 CodeGenFunction &CGF,
4888 const OMPExecutableDirective &D) {
4889
4890 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4891 "teams directive expected to be "
4892 "emitted only for the host!");
4893
4894 // FIXME: For the moment we do not support combined directives with target and
4895 // teams, so we do not expect to get any num_teams clause in the provided
4896 // directive. Once we support that, this assertion can be replaced by the
4897 // actual emission of the clause expression.
4898 assert(D.getSingleClause<OMPNumTeamsClause>() == nullptr &&
4899 "Not expecting clause in directive.");
4900
4901 // If the current target region has a teams region enclosed, we need to get
4902 // the number of teams to pass to the runtime function call. This is done
4903 // by generating the expression in a inlined region. This is required because
4904 // the expression is captured in the enclosing target environment when the
4905 // teams directive is not combined with target.
4906
4907 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4908
4909 // FIXME: Accommodate other combined directives with teams when they become
4910 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00004911 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
4912 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00004913 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
4914 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4915 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4916 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
4917 return CGF.Builder.CreateIntCast(NumTeams, CGF.Int32Ty,
4918 /*IsSigned=*/true);
4919 }
4920
4921 // If we have an enclosed teams directive but no num_teams clause we use
4922 // the default value 0.
4923 return CGF.Builder.getInt32(0);
4924 }
4925
4926 // No teams associated with the directive.
4927 return nullptr;
4928}
4929
4930/// \brief Emit the thread_limit clause of an enclosed teams directive at the
4931/// target region scope. If there is no teams directive associated with the
4932/// target directive, or if there is no thread_limit clause associated with the
4933/// enclosed teams directive, return nullptr.
4934static llvm::Value *
4935emitThreadLimitClauseForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4936 CodeGenFunction &CGF,
4937 const OMPExecutableDirective &D) {
4938
4939 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4940 "teams directive expected to be "
4941 "emitted only for the host!");
4942
4943 // FIXME: For the moment we do not support combined directives with target and
4944 // teams, so we do not expect to get any thread_limit clause in the provided
4945 // directive. Once we support that, this assertion can be replaced by the
4946 // actual emission of the clause expression.
4947 assert(D.getSingleClause<OMPThreadLimitClause>() == nullptr &&
4948 "Not expecting clause in directive.");
4949
4950 // If the current target region has a teams region enclosed, we need to get
4951 // the thread limit to pass to the runtime function call. This is done
4952 // by generating the expression in a inlined region. This is required because
4953 // the expression is captured in the enclosing target environment when the
4954 // teams directive is not combined with target.
4955
4956 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4957
4958 // FIXME: Accommodate other combined directives with teams when they become
4959 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00004960 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
4961 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00004962 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
4963 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4964 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4965 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
4966 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
4967 /*IsSigned=*/true);
4968 }
4969
4970 // If we have an enclosed teams directive but no thread_limit clause we use
4971 // the default value 0.
4972 return CGF.Builder.getInt32(0);
4973 }
4974
4975 // No teams associated with the directive.
4976 return nullptr;
4977}
4978
Samuel Antao86ace552016-04-27 22:40:57 +00004979namespace {
4980// \brief Utility to handle information from clauses associated with a given
4981// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
4982// It provides a convenient interface to obtain the information and generate
4983// code for that information.
4984class MappableExprsHandler {
4985public:
4986 /// \brief Values for bit flags used to specify the mapping type for
4987 /// offloading.
4988 enum OpenMPOffloadMappingFlags {
Samuel Antao86ace552016-04-27 22:40:57 +00004989 /// \brief Allocate memory on the device and move data from host to device.
4990 OMP_MAP_TO = 0x01,
4991 /// \brief Allocate memory on the device and move data from device to host.
4992 OMP_MAP_FROM = 0x02,
4993 /// \brief Always perform the requested mapping action on the element, even
4994 /// if it was already mapped before.
4995 OMP_MAP_ALWAYS = 0x04,
Samuel Antao86ace552016-04-27 22:40:57 +00004996 /// \brief Delete the element from the device environment, ignoring the
4997 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00004998 OMP_MAP_DELETE = 0x08,
4999 /// \brief The element being mapped is a pointer, therefore the pointee
5000 /// should be mapped as well.
5001 OMP_MAP_IS_PTR = 0x10,
5002 /// \brief This flags signals that an argument is the first one relating to
5003 /// a map/private clause expression. For some cases a single
5004 /// map/privatization results in multiple arguments passed to the runtime
5005 /// library.
5006 OMP_MAP_FIRST_REF = 0x20,
Samuel Antaocc10b852016-07-28 14:23:26 +00005007 /// \brief Signal that the runtime library has to return the device pointer
5008 /// in the current position for the data being mapped.
5009 OMP_MAP_RETURN_PTR = 0x40,
Samuel Antaod486f842016-05-26 16:53:38 +00005010 /// \brief This flag signals that the reference being passed is a pointer to
5011 /// private data.
5012 OMP_MAP_PRIVATE_PTR = 0x80,
Samuel Antao86ace552016-04-27 22:40:57 +00005013 /// \brief Pass the element to the device by value.
Samuel Antao6782e942016-05-26 16:48:10 +00005014 OMP_MAP_PRIVATE_VAL = 0x100,
Samuel Antao86ace552016-04-27 22:40:57 +00005015 };
5016
Samuel Antaocc10b852016-07-28 14:23:26 +00005017 /// Class that associates information with a base pointer to be passed to the
5018 /// runtime library.
5019 class BasePointerInfo {
5020 /// The base pointer.
5021 llvm::Value *Ptr = nullptr;
5022 /// The base declaration that refers to this device pointer, or null if
5023 /// there is none.
5024 const ValueDecl *DevPtrDecl = nullptr;
5025
5026 public:
5027 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
5028 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
5029 llvm::Value *operator*() const { return Ptr; }
5030 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
5031 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
5032 };
5033
5034 typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00005035 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
5036 typedef SmallVector<unsigned, 16> MapFlagsArrayTy;
5037
5038private:
5039 /// \brief Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00005040 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00005041
5042 /// \brief Function the directive is being generated for.
5043 CodeGenFunction &CGF;
5044
Samuel Antaod486f842016-05-26 16:53:38 +00005045 /// \brief Set of all first private variables in the current directive.
5046 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
5047
Samuel Antao6890b092016-07-28 14:25:09 +00005048 /// Map between device pointer declarations and their expression components.
5049 /// The key value for declarations in 'this' is null.
5050 llvm::DenseMap<
5051 const ValueDecl *,
5052 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
5053 DevPointersMap;
5054
Samuel Antao86ace552016-04-27 22:40:57 +00005055 llvm::Value *getExprTypeSize(const Expr *E) const {
5056 auto ExprTy = E->getType().getCanonicalType();
5057
5058 // Reference types are ignored for mapping purposes.
5059 if (auto *RefTy = ExprTy->getAs<ReferenceType>())
5060 ExprTy = RefTy->getPointeeType().getCanonicalType();
5061
5062 // Given that an array section is considered a built-in type, we need to
5063 // do the calculation based on the length of the section instead of relying
5064 // on CGF.getTypeSize(E->getType()).
5065 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
5066 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
5067 OAE->getBase()->IgnoreParenImpCasts())
5068 .getCanonicalType();
5069
5070 // If there is no length associated with the expression, that means we
5071 // are using the whole length of the base.
5072 if (!OAE->getLength() && OAE->getColonLoc().isValid())
5073 return CGF.getTypeSize(BaseTy);
5074
5075 llvm::Value *ElemSize;
5076 if (auto *PTy = BaseTy->getAs<PointerType>())
5077 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
5078 else {
5079 auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
5080 assert(ATy && "Expecting array type if not a pointer type.");
5081 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
5082 }
5083
5084 // If we don't have a length at this point, that is because we have an
5085 // array section with a single element.
5086 if (!OAE->getLength())
5087 return ElemSize;
5088
5089 auto *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
5090 LengthVal =
5091 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
5092 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
5093 }
5094 return CGF.getTypeSize(ExprTy);
5095 }
5096
5097 /// \brief Return the corresponding bits for a given map clause modifier. Add
5098 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00005099 /// map as the first one of a series of maps that relate to the same map
5100 /// expression.
Samuel Antao86ace552016-04-27 22:40:57 +00005101 unsigned getMapTypeBits(OpenMPMapClauseKind MapType,
5102 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
Samuel Antao6782e942016-05-26 16:48:10 +00005103 bool AddIsFirstFlag) const {
Samuel Antao86ace552016-04-27 22:40:57 +00005104 unsigned Bits = 0u;
5105 switch (MapType) {
5106 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00005107 case OMPC_MAP_release:
5108 // alloc and release is the default behavior in the runtime library, i.e.
5109 // if we don't pass any bits alloc/release that is what the runtime is
5110 // going to do. Therefore, we don't need to signal anything for these two
5111 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00005112 break;
5113 case OMPC_MAP_to:
5114 Bits = OMP_MAP_TO;
5115 break;
5116 case OMPC_MAP_from:
5117 Bits = OMP_MAP_FROM;
5118 break;
5119 case OMPC_MAP_tofrom:
5120 Bits = OMP_MAP_TO | OMP_MAP_FROM;
5121 break;
5122 case OMPC_MAP_delete:
5123 Bits = OMP_MAP_DELETE;
5124 break;
Samuel Antao86ace552016-04-27 22:40:57 +00005125 default:
5126 llvm_unreachable("Unexpected map type!");
5127 break;
5128 }
5129 if (AddPtrFlag)
Samuel Antao6782e942016-05-26 16:48:10 +00005130 Bits |= OMP_MAP_IS_PTR;
5131 if (AddIsFirstFlag)
5132 Bits |= OMP_MAP_FIRST_REF;
Samuel Antao86ace552016-04-27 22:40:57 +00005133 if (MapTypeModifier == OMPC_MAP_always)
5134 Bits |= OMP_MAP_ALWAYS;
5135 return Bits;
5136 }
5137
5138 /// \brief Return true if the provided expression is a final array section. A
5139 /// final array section, is one whose length can't be proved to be one.
5140 bool isFinalArraySectionExpression(const Expr *E) const {
5141 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
5142
5143 // It is not an array section and therefore not a unity-size one.
5144 if (!OASE)
5145 return false;
5146
5147 // An array section with no colon always refer to a single element.
5148 if (OASE->getColonLoc().isInvalid())
5149 return false;
5150
5151 auto *Length = OASE->getLength();
5152
5153 // If we don't have a length we have to check if the array has size 1
5154 // for this dimension. Also, we should always expect a length if the
5155 // base type is pointer.
5156 if (!Length) {
5157 auto BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
5158 OASE->getBase()->IgnoreParenImpCasts())
5159 .getCanonicalType();
5160 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
5161 return ATy->getSize().getSExtValue() != 1;
5162 // If we don't have a constant dimension length, we have to consider
5163 // the current section as having any size, so it is not necessarily
5164 // unitary. If it happen to be unity size, that's user fault.
5165 return true;
5166 }
5167
5168 // Check if the length evaluates to 1.
5169 llvm::APSInt ConstLength;
5170 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
5171 return true; // Can have more that size 1.
5172
5173 return ConstLength.getSExtValue() != 1;
5174 }
5175
5176 /// \brief Generate the base pointers, section pointers, sizes and map type
5177 /// bits for the provided map type, map modifier, and expression components.
5178 /// \a IsFirstComponent should be set to true if the provided set of
5179 /// components is the first associated with a capture.
5180 void generateInfoForComponentList(
5181 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
5182 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00005183 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00005184 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
5185 bool IsFirstComponentList) const {
5186
5187 // The following summarizes what has to be generated for each map and the
5188 // types bellow. The generated information is expressed in this order:
5189 // base pointer, section pointer, size, flags
5190 // (to add to the ones that come from the map type and modifier).
5191 //
5192 // double d;
5193 // int i[100];
5194 // float *p;
5195 //
5196 // struct S1 {
5197 // int i;
5198 // float f[50];
5199 // }
5200 // struct S2 {
5201 // int i;
5202 // float f[50];
5203 // S1 s;
5204 // double *p;
5205 // struct S2 *ps;
5206 // }
5207 // S2 s;
5208 // S2 *ps;
5209 //
5210 // map(d)
5211 // &d, &d, sizeof(double), noflags
5212 //
5213 // map(i)
5214 // &i, &i, 100*sizeof(int), noflags
5215 //
5216 // map(i[1:23])
5217 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
5218 //
5219 // map(p)
5220 // &p, &p, sizeof(float*), noflags
5221 //
5222 // map(p[1:24])
5223 // p, &p[1], 24*sizeof(float), noflags
5224 //
5225 // map(s)
5226 // &s, &s, sizeof(S2), noflags
5227 //
5228 // map(s.i)
5229 // &s, &(s.i), sizeof(int), noflags
5230 //
5231 // map(s.s.f)
5232 // &s, &(s.i.f), 50*sizeof(int), noflags
5233 //
5234 // map(s.p)
5235 // &s, &(s.p), sizeof(double*), noflags
5236 //
5237 // map(s.p[:22], s.a s.b)
5238 // &s, &(s.p), sizeof(double*), noflags
5239 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag + extra_flag
5240 //
5241 // map(s.ps)
5242 // &s, &(s.ps), sizeof(S2*), noflags
5243 //
5244 // map(s.ps->s.i)
5245 // &s, &(s.ps), sizeof(S2*), noflags
5246 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag + extra_flag
5247 //
5248 // map(s.ps->ps)
5249 // &s, &(s.ps), sizeof(S2*), noflags
5250 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5251 //
5252 // map(s.ps->ps->ps)
5253 // &s, &(s.ps), sizeof(S2*), noflags
5254 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5255 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5256 //
5257 // map(s.ps->ps->s.f[:22])
5258 // &s, &(s.ps), sizeof(S2*), noflags
5259 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5260 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag + extra_flag
5261 //
5262 // map(ps)
5263 // &ps, &ps, sizeof(S2*), noflags
5264 //
5265 // map(ps->i)
5266 // ps, &(ps->i), sizeof(int), noflags
5267 //
5268 // map(ps->s.f)
5269 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
5270 //
5271 // map(ps->p)
5272 // ps, &(ps->p), sizeof(double*), noflags
5273 //
5274 // map(ps->p[:22])
5275 // ps, &(ps->p), sizeof(double*), noflags
5276 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag + extra_flag
5277 //
5278 // map(ps->ps)
5279 // ps, &(ps->ps), sizeof(S2*), noflags
5280 //
5281 // map(ps->ps->s.i)
5282 // ps, &(ps->ps), sizeof(S2*), noflags
5283 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag + extra_flag
5284 //
5285 // map(ps->ps->ps)
5286 // ps, &(ps->ps), sizeof(S2*), noflags
5287 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5288 //
5289 // map(ps->ps->ps->ps)
5290 // ps, &(ps->ps), sizeof(S2*), noflags
5291 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5292 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5293 //
5294 // map(ps->ps->ps->s.f[:22])
5295 // ps, &(ps->ps), sizeof(S2*), noflags
5296 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5297 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag +
5298 // extra_flag
5299
5300 // Track if the map information being generated is the first for a capture.
5301 bool IsCaptureFirstInfo = IsFirstComponentList;
5302
5303 // Scan the components from the base to the complete expression.
5304 auto CI = Components.rbegin();
5305 auto CE = Components.rend();
5306 auto I = CI;
5307
5308 // Track if the map information being generated is the first for a list of
5309 // components.
5310 bool IsExpressionFirstInfo = true;
5311 llvm::Value *BP = nullptr;
5312
5313 if (auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
5314 // The base is the 'this' pointer. The content of the pointer is going
5315 // to be the base of the field being mapped.
5316 BP = CGF.EmitScalarExpr(ME->getBase());
5317 } else {
5318 // The base is the reference to the variable.
5319 // BP = &Var.
5320 BP = CGF.EmitLValue(cast<DeclRefExpr>(I->getAssociatedExpression()))
5321 .getPointer();
5322
5323 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00005324 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00005325 // reference. References are ignored for mapping purposes.
5326 QualType Ty =
5327 I->getAssociatedDeclaration()->getType().getNonReferenceType();
5328 if (Ty->isAnyPointerType() && std::next(I) != CE) {
5329 auto PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
Samuel Antao86ace552016-04-27 22:40:57 +00005330 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
Samuel Antao403ffd42016-07-27 22:49:49 +00005331 Ty->castAs<PointerType>())
Samuel Antao86ace552016-04-27 22:40:57 +00005332 .getPointer();
5333
5334 // We do not need to generate individual map information for the
5335 // pointer, it can be associated with the combined storage.
5336 ++I;
5337 }
5338 }
5339
5340 for (; I != CE; ++I) {
5341 auto Next = std::next(I);
5342
5343 // We need to generate the addresses and sizes if this is the last
5344 // component, if the component is a pointer or if it is an array section
5345 // whose length can't be proved to be one. If this is a pointer, it
5346 // becomes the base address for the following components.
5347
5348 // A final array section, is one whose length can't be proved to be one.
5349 bool IsFinalArraySection =
5350 isFinalArraySectionExpression(I->getAssociatedExpression());
5351
5352 // Get information on whether the element is a pointer. Have to do a
5353 // special treatment for array sections given that they are built-in
5354 // types.
5355 const auto *OASE =
5356 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
5357 bool IsPointer =
5358 (OASE &&
5359 OMPArraySectionExpr::getBaseOriginalType(OASE)
5360 .getCanonicalType()
5361 ->isAnyPointerType()) ||
5362 I->getAssociatedExpression()->getType()->isAnyPointerType();
5363
5364 if (Next == CE || IsPointer || IsFinalArraySection) {
5365
5366 // If this is not the last component, we expect the pointer to be
5367 // associated with an array expression or member expression.
5368 assert((Next == CE ||
5369 isa<MemberExpr>(Next->getAssociatedExpression()) ||
5370 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
5371 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
5372 "Unexpected expression");
5373
Samuel Antao86ace552016-04-27 22:40:57 +00005374 auto *LB = CGF.EmitLValue(I->getAssociatedExpression()).getPointer();
5375 auto *Size = getExprTypeSize(I->getAssociatedExpression());
5376
Samuel Antao03a3cec2016-07-27 22:52:16 +00005377 // If we have a member expression and the current component is a
5378 // reference, we have to map the reference too. Whenever we have a
5379 // reference, the section that reference refers to is going to be a
5380 // load instruction from the storage assigned to the reference.
5381 if (isa<MemberExpr>(I->getAssociatedExpression()) &&
5382 I->getAssociatedDeclaration()->getType()->isReferenceType()) {
5383 auto *LI = cast<llvm::LoadInst>(LB);
5384 auto *RefAddr = LI->getPointerOperand();
5385
5386 BasePointers.push_back(BP);
5387 Pointers.push_back(RefAddr);
5388 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
5389 Types.push_back(getMapTypeBits(
5390 /*MapType*/ OMPC_MAP_alloc, /*MapTypeModifier=*/OMPC_MAP_unknown,
5391 !IsExpressionFirstInfo, IsCaptureFirstInfo));
5392 IsExpressionFirstInfo = false;
5393 IsCaptureFirstInfo = false;
5394 // The reference will be the next base address.
5395 BP = RefAddr;
5396 }
5397
5398 BasePointers.push_back(BP);
Samuel Antao86ace552016-04-27 22:40:57 +00005399 Pointers.push_back(LB);
5400 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00005401
Samuel Antao6782e942016-05-26 16:48:10 +00005402 // We need to add a pointer flag for each map that comes from the
5403 // same expression except for the first one. We also need to signal
5404 // this map is the first one that relates with the current capture
5405 // (there is a set of entries for each capture).
Samuel Antao86ace552016-04-27 22:40:57 +00005406 Types.push_back(getMapTypeBits(MapType, MapTypeModifier,
5407 !IsExpressionFirstInfo,
Samuel Antao6782e942016-05-26 16:48:10 +00005408 IsCaptureFirstInfo));
Samuel Antao86ace552016-04-27 22:40:57 +00005409
5410 // If we have a final array section, we are done with this expression.
5411 if (IsFinalArraySection)
5412 break;
5413
5414 // The pointer becomes the base for the next element.
5415 if (Next != CE)
5416 BP = LB;
5417
5418 IsExpressionFirstInfo = false;
5419 IsCaptureFirstInfo = false;
5420 continue;
5421 }
5422 }
5423 }
5424
Samuel Antaod486f842016-05-26 16:53:38 +00005425 /// \brief Return the adjusted map modifiers if the declaration a capture
5426 /// refers to appears in a first-private clause. This is expected to be used
5427 /// only with directives that start with 'target'.
5428 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
5429 unsigned CurrentModifiers) {
5430 assert(Cap.capturesVariable() && "Expected capture by reference only!");
5431
5432 // A first private variable captured by reference will use only the
5433 // 'private ptr' and 'map to' flag. Return the right flags if the captured
5434 // declaration is known as first-private in this handler.
5435 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
5436 return MappableExprsHandler::OMP_MAP_PRIVATE_PTR |
5437 MappableExprsHandler::OMP_MAP_TO;
5438
5439 // We didn't modify anything.
5440 return CurrentModifiers;
5441 }
5442
Samuel Antao86ace552016-04-27 22:40:57 +00005443public:
5444 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
Samuel Antao44bcdb32016-07-28 15:31:29 +00005445 : CurDir(Dir), CGF(CGF) {
Samuel Antaod486f842016-05-26 16:53:38 +00005446 // Extract firstprivate clause information.
5447 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
5448 for (const auto *D : C->varlists())
5449 FirstPrivateDecls.insert(
5450 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
Samuel Antao6890b092016-07-28 14:25:09 +00005451 // Extract device pointer clause information.
5452 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
5453 for (auto L : C->component_lists())
5454 DevPointersMap[L.first].push_back(L.second);
Samuel Antaod486f842016-05-26 16:53:38 +00005455 }
Samuel Antao86ace552016-04-27 22:40:57 +00005456
5457 /// \brief Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00005458 /// types for the extracted mappable expressions. Also, for each item that
5459 /// relates with a device pointer, a pair of the relevant declaration and
5460 /// index where it occurs is appended to the device pointers info array.
5461 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00005462 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
5463 MapFlagsArrayTy &Types) const {
5464 BasePointers.clear();
5465 Pointers.clear();
5466 Sizes.clear();
5467 Types.clear();
5468
5469 struct MapInfo {
Samuel Antaocc10b852016-07-28 14:23:26 +00005470 /// Kind that defines how a device pointer has to be returned.
5471 enum ReturnPointerKind {
5472 // Don't have to return any pointer.
5473 RPK_None,
5474 // Pointer is the base of the declaration.
5475 RPK_Base,
5476 // Pointer is a member of the base declaration - 'this'
5477 RPK_Member,
5478 // Pointer is a reference and a member of the base declaration - 'this'
5479 RPK_MemberReference,
5480 };
Samuel Antao86ace552016-04-27 22:40:57 +00005481 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
Hans Wennborgbc1b58d2016-07-30 00:41:37 +00005482 OpenMPMapClauseKind MapType;
5483 OpenMPMapClauseKind MapTypeModifier;
5484 ReturnPointerKind ReturnDevicePointer;
5485
5486 MapInfo()
5487 : MapType(OMPC_MAP_unknown), MapTypeModifier(OMPC_MAP_unknown),
5488 ReturnDevicePointer(RPK_None) {}
Samuel Antaocc10b852016-07-28 14:23:26 +00005489 MapInfo(
5490 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
5491 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
5492 ReturnPointerKind ReturnDevicePointer)
5493 : Components(Components), MapType(MapType),
5494 MapTypeModifier(MapTypeModifier),
5495 ReturnDevicePointer(ReturnDevicePointer) {}
Samuel Antao86ace552016-04-27 22:40:57 +00005496 };
5497
5498 // We have to process the component lists that relate with the same
5499 // declaration in a single chunk so that we can generate the map flags
5500 // correctly. Therefore, we organize all lists in a map.
5501 llvm::DenseMap<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00005502
5503 // Helper function to fill the information map for the different supported
5504 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00005505 auto &&InfoGen = [&Info](
5506 const ValueDecl *D,
5507 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
5508 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Samuel Antaocf3f83e2016-07-28 14:47:35 +00005509 MapInfo::ReturnPointerKind ReturnDevicePointer) {
Samuel Antaocc10b852016-07-28 14:23:26 +00005510 const ValueDecl *VD =
5511 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
5512 Info[VD].push_back({L, MapType, MapModifier, ReturnDevicePointer});
5513 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00005514
Paul Robinson78fb1322016-08-01 22:12:46 +00005515 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00005516 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005517 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00005518 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
5519 MapInfo::RPK_None);
Paul Robinson15c84002016-07-29 20:46:16 +00005520 for (auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005521 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00005522 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
5523 MapInfo::RPK_None);
Paul Robinson15c84002016-07-29 20:46:16 +00005524 for (auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005525 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00005526 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
5527 MapInfo::RPK_None);
Samuel Antao86ace552016-04-27 22:40:57 +00005528
Samuel Antaocc10b852016-07-28 14:23:26 +00005529 // Look at the use_device_ptr clause information and mark the existing map
5530 // entries as such. If there is no map information for an entry in the
5531 // use_device_ptr list, we create one with map type 'alloc' and zero size
5532 // section. It is the user fault if that was not mapped before.
Paul Robinson78fb1322016-08-01 22:12:46 +00005533 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00005534 for (auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
Samuel Antaocc10b852016-07-28 14:23:26 +00005535 for (auto L : C->component_lists()) {
5536 assert(!L.second.empty() && "Not expecting empty list of components!");
5537 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
5538 VD = cast<ValueDecl>(VD->getCanonicalDecl());
5539 auto *IE = L.second.back().getAssociatedExpression();
5540 // If the first component is a member expression, we have to look into
5541 // 'this', which maps to null in the map of map information. Otherwise
5542 // look directly for the information.
5543 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
5544
5545 // We potentially have map information for this declaration already.
5546 // Look for the first set of components that refer to it.
5547 if (It != Info.end()) {
5548 auto CI = std::find_if(
5549 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
5550 return MI.Components.back().getAssociatedDeclaration() == VD;
5551 });
5552 // If we found a map entry, signal that the pointer has to be returned
5553 // and move on to the next declaration.
5554 if (CI != It->second.end()) {
5555 CI->ReturnDevicePointer = isa<MemberExpr>(IE)
5556 ? (VD->getType()->isReferenceType()
5557 ? MapInfo::RPK_MemberReference
5558 : MapInfo::RPK_Member)
5559 : MapInfo::RPK_Base;
5560 continue;
5561 }
5562 }
5563
5564 // We didn't find any match in our map information - generate a zero
5565 // size array section.
Paul Robinson78fb1322016-08-01 22:12:46 +00005566 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Samuel Antaocc10b852016-07-28 14:23:26 +00005567 llvm::Value *Ptr =
Paul Robinson15c84002016-07-29 20:46:16 +00005568 this->CGF
5569 .EmitLoadOfLValue(this->CGF.EmitLValue(IE), SourceLocation())
Samuel Antaocc10b852016-07-28 14:23:26 +00005570 .getScalarVal();
5571 BasePointers.push_back({Ptr, VD});
5572 Pointers.push_back(Ptr);
Paul Robinson15c84002016-07-29 20:46:16 +00005573 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
Samuel Antaocc10b852016-07-28 14:23:26 +00005574 Types.push_back(OMP_MAP_RETURN_PTR | OMP_MAP_FIRST_REF);
5575 }
5576
Samuel Antao86ace552016-04-27 22:40:57 +00005577 for (auto &M : Info) {
5578 // We need to know when we generate information for the first component
5579 // associated with a capture, because the mapping flags depend on it.
5580 bool IsFirstComponentList = true;
5581 for (MapInfo &L : M.second) {
5582 assert(!L.Components.empty() &&
5583 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00005584
5585 // Remember the current base pointer index.
5586 unsigned CurrentBasePointersIdx = BasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00005587 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Paul Robinson15c84002016-07-29 20:46:16 +00005588 this->generateInfoForComponentList(L.MapType, L.MapTypeModifier,
5589 L.Components, BasePointers, Pointers,
5590 Sizes, Types, IsFirstComponentList);
Samuel Antaocc10b852016-07-28 14:23:26 +00005591
5592 // If this entry relates with a device pointer, set the relevant
5593 // declaration and add the 'return pointer' flag.
5594 if (IsFirstComponentList &&
5595 L.ReturnDevicePointer != MapInfo::RPK_None) {
5596 // If the pointer is not the base of the map, we need to skip the
5597 // base. If it is a reference in a member field, we also need to skip
5598 // the map of the reference.
5599 if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
5600 ++CurrentBasePointersIdx;
5601 if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
5602 ++CurrentBasePointersIdx;
5603 }
5604 assert(BasePointers.size() > CurrentBasePointersIdx &&
5605 "Unexpected number of mapped base pointers.");
5606
5607 auto *RelevantVD = L.Components.back().getAssociatedDeclaration();
5608 assert(RelevantVD &&
5609 "No relevant declaration related with device pointer??");
5610
5611 BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
5612 Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PTR;
5613 }
Samuel Antao86ace552016-04-27 22:40:57 +00005614 IsFirstComponentList = false;
5615 }
5616 }
5617 }
5618
5619 /// \brief Generate the base pointers, section pointers, sizes and map types
5620 /// associated to a given capture.
5621 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00005622 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00005623 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00005624 MapValuesArrayTy &Pointers,
5625 MapValuesArrayTy &Sizes,
5626 MapFlagsArrayTy &Types) const {
5627 assert(!Cap->capturesVariableArrayType() &&
5628 "Not expecting to generate map info for a variable array type!");
5629
5630 BasePointers.clear();
5631 Pointers.clear();
5632 Sizes.clear();
5633 Types.clear();
5634
Samuel Antao6890b092016-07-28 14:25:09 +00005635 // We need to know when we generating information for the first component
5636 // associated with a capture, because the mapping flags depend on it.
5637 bool IsFirstComponentList = true;
5638
Samuel Antao86ace552016-04-27 22:40:57 +00005639 const ValueDecl *VD =
5640 Cap->capturesThis()
5641 ? nullptr
5642 : cast<ValueDecl>(Cap->getCapturedVar()->getCanonicalDecl());
5643
Samuel Antao6890b092016-07-28 14:25:09 +00005644 // If this declaration appears in a is_device_ptr clause we just have to
5645 // pass the pointer by value. If it is a reference to a declaration, we just
5646 // pass its value, otherwise, if it is a member expression, we need to map
5647 // 'to' the field.
5648 if (!VD) {
5649 auto It = DevPointersMap.find(VD);
5650 if (It != DevPointersMap.end()) {
5651 for (auto L : It->second) {
5652 generateInfoForComponentList(
5653 /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
5654 BasePointers, Pointers, Sizes, Types, IsFirstComponentList);
5655 IsFirstComponentList = false;
5656 }
5657 return;
5658 }
5659 } else if (DevPointersMap.count(VD)) {
5660 BasePointers.push_back({Arg, VD});
5661 Pointers.push_back(Arg);
5662 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
5663 Types.push_back(OMP_MAP_PRIVATE_VAL | OMP_MAP_FIRST_REF);
5664 return;
5665 }
5666
Paul Robinson78fb1322016-08-01 22:12:46 +00005667 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00005668 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao86ace552016-04-27 22:40:57 +00005669 for (auto L : C->decl_component_lists(VD)) {
5670 assert(L.first == VD &&
5671 "We got information for the wrong declaration??");
5672 assert(!L.second.empty() &&
5673 "Not expecting declaration with no component lists.");
5674 generateInfoForComponentList(C->getMapType(), C->getMapTypeModifier(),
5675 L.second, BasePointers, Pointers, Sizes,
5676 Types, IsFirstComponentList);
5677 IsFirstComponentList = false;
5678 }
5679
5680 return;
5681 }
Samuel Antaod486f842016-05-26 16:53:38 +00005682
5683 /// \brief Generate the default map information for a given capture \a CI,
5684 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00005685 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
5686 const FieldDecl &RI, llvm::Value *CV,
5687 MapBaseValuesArrayTy &CurBasePointers,
5688 MapValuesArrayTy &CurPointers,
5689 MapValuesArrayTy &CurSizes,
5690 MapFlagsArrayTy &CurMapTypes) {
Samuel Antaod486f842016-05-26 16:53:38 +00005691
5692 // Do the default mapping.
5693 if (CI.capturesThis()) {
5694 CurBasePointers.push_back(CV);
5695 CurPointers.push_back(CV);
5696 const PointerType *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
5697 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
5698 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00005699 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00005700 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00005701 CurBasePointers.push_back(CV);
5702 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00005703 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00005704 // We have to signal to the runtime captures passed by value that are
5705 // not pointers.
Samuel Antaocc10b852016-07-28 14:23:26 +00005706 CurMapTypes.push_back(OMP_MAP_PRIVATE_VAL);
Samuel Antaod486f842016-05-26 16:53:38 +00005707 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
5708 } else {
5709 // Pointers are implicitly mapped with a zero size and no flags
5710 // (other than first map that is added for all implicit maps).
5711 CurMapTypes.push_back(0u);
Samuel Antaod486f842016-05-26 16:53:38 +00005712 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
5713 }
5714 } else {
5715 assert(CI.capturesVariable() && "Expected captured reference.");
5716 CurBasePointers.push_back(CV);
5717 CurPointers.push_back(CV);
5718
5719 const ReferenceType *PtrTy =
5720 cast<ReferenceType>(RI.getType().getTypePtr());
5721 QualType ElementType = PtrTy->getPointeeType();
5722 CurSizes.push_back(CGF.getTypeSize(ElementType));
5723 // The default map type for a scalar/complex type is 'to' because by
5724 // default the value doesn't have to be retrieved. For an aggregate
5725 // type, the default is 'tofrom'.
5726 CurMapTypes.push_back(ElementType->isAggregateType()
Samuel Antaocc10b852016-07-28 14:23:26 +00005727 ? (OMP_MAP_TO | OMP_MAP_FROM)
5728 : OMP_MAP_TO);
Samuel Antaod486f842016-05-26 16:53:38 +00005729
5730 // If we have a capture by reference we may need to add the private
5731 // pointer flag if the base declaration shows in some first-private
5732 // clause.
5733 CurMapTypes.back() =
5734 adjustMapModifiersForPrivateClauses(CI, CurMapTypes.back());
5735 }
5736 // Every default map produces a single argument, so, it is always the
5737 // first one.
Samuel Antaocc10b852016-07-28 14:23:26 +00005738 CurMapTypes.back() |= OMP_MAP_FIRST_REF;
Samuel Antaod486f842016-05-26 16:53:38 +00005739 }
Samuel Antao86ace552016-04-27 22:40:57 +00005740};
Samuel Antaodf158d52016-04-27 22:58:19 +00005741
5742enum OpenMPOffloadingReservedDeviceIDs {
5743 /// \brief Device ID if the device was not defined, runtime should get it
5744 /// from environment variables in the spec.
5745 OMP_DEVICEID_UNDEF = -1,
5746};
5747} // anonymous namespace
5748
5749/// \brief Emit the arrays used to pass the captures and map information to the
5750/// offloading runtime library. If there is no map or capture information,
5751/// return nullptr by reference.
5752static void
Samuel Antaocc10b852016-07-28 14:23:26 +00005753emitOffloadingArrays(CodeGenFunction &CGF,
5754 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00005755 MappableExprsHandler::MapValuesArrayTy &Pointers,
5756 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00005757 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
5758 CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00005759 auto &CGM = CGF.CGM;
5760 auto &Ctx = CGF.getContext();
5761
Samuel Antaocc10b852016-07-28 14:23:26 +00005762 // Reset the array information.
5763 Info.clearArrayInfo();
5764 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00005765
Samuel Antaocc10b852016-07-28 14:23:26 +00005766 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00005767 // Detect if we have any capture size requiring runtime evaluation of the
5768 // size so that a constant array could be eventually used.
5769 bool hasRuntimeEvaluationCaptureSize = false;
5770 for (auto *S : Sizes)
5771 if (!isa<llvm::Constant>(S)) {
5772 hasRuntimeEvaluationCaptureSize = true;
5773 break;
5774 }
5775
Samuel Antaocc10b852016-07-28 14:23:26 +00005776 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00005777 QualType PointerArrayType =
5778 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
5779 /*IndexTypeQuals=*/0);
5780
Samuel Antaocc10b852016-07-28 14:23:26 +00005781 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00005782 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00005783 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00005784 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
5785
5786 // If we don't have any VLA types or other types that require runtime
5787 // evaluation, we can use a constant array for the map sizes, otherwise we
5788 // need to fill up the arrays as we do for the pointers.
5789 if (hasRuntimeEvaluationCaptureSize) {
5790 QualType SizeArrayType = Ctx.getConstantArrayType(
5791 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
5792 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00005793 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00005794 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
5795 } else {
5796 // We expect all the sizes to be constant, so we collect them to create
5797 // a constant array.
5798 SmallVector<llvm::Constant *, 16> ConstSizes;
5799 for (auto S : Sizes)
5800 ConstSizes.push_back(cast<llvm::Constant>(S));
5801
5802 auto *SizesArrayInit = llvm::ConstantArray::get(
5803 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
5804 auto *SizesArrayGbl = new llvm::GlobalVariable(
5805 CGM.getModule(), SizesArrayInit->getType(),
5806 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
5807 SizesArrayInit, ".offload_sizes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00005808 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00005809 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00005810 }
5811
5812 // The map types are always constant so we don't need to generate code to
5813 // fill arrays. Instead, we create an array constant.
5814 llvm::Constant *MapTypesArrayInit =
5815 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
5816 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
5817 CGM.getModule(), MapTypesArrayInit->getType(),
5818 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
5819 MapTypesArrayInit, ".offload_maptypes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00005820 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00005821 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00005822
Samuel Antaocc10b852016-07-28 14:23:26 +00005823 for (unsigned i = 0; i < Info.NumberOfPtrs; ++i) {
5824 llvm::Value *BPVal = *BasePointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00005825 if (BPVal->getType()->isPointerTy())
5826 BPVal = CGF.Builder.CreateBitCast(BPVal, CGM.VoidPtrTy);
5827 else {
5828 assert(BPVal->getType()->isIntegerTy() &&
5829 "If not a pointer, the value type must be an integer.");
5830 BPVal = CGF.Builder.CreateIntToPtr(BPVal, CGM.VoidPtrTy);
5831 }
5832 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005833 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5834 Info.BasePointersArray, 0, i);
Samuel Antaodf158d52016-04-27 22:58:19 +00005835 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
5836 CGF.Builder.CreateStore(BPVal, BPAddr);
5837
Samuel Antaocc10b852016-07-28 14:23:26 +00005838 if (Info.requiresDevicePointerInfo())
5839 if (auto *DevVD = BasePointers[i].getDevicePtrDecl())
5840 Info.CaptureDeviceAddrMap.insert(std::make_pair(DevVD, BPAddr));
5841
Samuel Antaodf158d52016-04-27 22:58:19 +00005842 llvm::Value *PVal = Pointers[i];
5843 if (PVal->getType()->isPointerTy())
5844 PVal = CGF.Builder.CreateBitCast(PVal, CGM.VoidPtrTy);
5845 else {
5846 assert(PVal->getType()->isIntegerTy() &&
5847 "If not a pointer, the value type must be an integer.");
5848 PVal = CGF.Builder.CreateIntToPtr(PVal, CGM.VoidPtrTy);
5849 }
5850 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005851 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5852 Info.PointersArray, 0, i);
Samuel Antaodf158d52016-04-27 22:58:19 +00005853 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
5854 CGF.Builder.CreateStore(PVal, PAddr);
5855
5856 if (hasRuntimeEvaluationCaptureSize) {
5857 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005858 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
5859 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005860 /*Idx0=*/0,
5861 /*Idx1=*/i);
5862 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
5863 CGF.Builder.CreateStore(
5864 CGF.Builder.CreateIntCast(Sizes[i], CGM.SizeTy, /*isSigned=*/true),
5865 SAddr);
5866 }
5867 }
5868 }
5869}
5870/// \brief Emit the arguments to be passed to the runtime library based on the
5871/// arrays of pointers, sizes and map types.
5872static void emitOffloadingArraysArgument(
5873 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
5874 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00005875 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00005876 auto &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00005877 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00005878 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005879 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5880 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005881 /*Idx0=*/0, /*Idx1=*/0);
5882 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005883 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5884 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005885 /*Idx0=*/0,
5886 /*Idx1=*/0);
5887 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005888 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005889 /*Idx0=*/0, /*Idx1=*/0);
5890 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005891 llvm::ArrayType::get(CGM.Int32Ty, Info.NumberOfPtrs),
5892 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005893 /*Idx0=*/0,
5894 /*Idx1=*/0);
5895 } else {
5896 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
5897 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
5898 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
5899 MapTypesArrayArg =
5900 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo());
5901 }
Samuel Antao86ace552016-04-27 22:40:57 +00005902}
5903
Samuel Antaobed3c462015-10-02 16:14:20 +00005904void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
5905 const OMPExecutableDirective &D,
5906 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00005907 llvm::Value *OutlinedFnID,
Samuel Antaobed3c462015-10-02 16:14:20 +00005908 const Expr *IfCond, const Expr *Device,
5909 ArrayRef<llvm::Value *> CapturedVars) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005910 if (!CGF.HaveInsertPoint())
5911 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00005912
Samuel Antaoee8fb302016-01-06 13:42:12 +00005913 assert(OutlinedFn && "Invalid outlined function!");
5914
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005915 auto &Ctx = CGF.getContext();
5916
Samuel Antao86ace552016-04-27 22:40:57 +00005917 // Fill up the arrays with all the captured variables.
5918 MappableExprsHandler::MapValuesArrayTy KernelArgs;
Samuel Antaocc10b852016-07-28 14:23:26 +00005919 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00005920 MappableExprsHandler::MapValuesArrayTy Pointers;
5921 MappableExprsHandler::MapValuesArrayTy Sizes;
5922 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobed3c462015-10-02 16:14:20 +00005923
Samuel Antaocc10b852016-07-28 14:23:26 +00005924 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00005925 MappableExprsHandler::MapValuesArrayTy CurPointers;
5926 MappableExprsHandler::MapValuesArrayTy CurSizes;
5927 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
5928
Samuel Antaod486f842016-05-26 16:53:38 +00005929 // Get mappable expression information.
5930 MappableExprsHandler MEHandler(D, CGF);
Samuel Antaobed3c462015-10-02 16:14:20 +00005931
5932 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5933 auto RI = CS.getCapturedRecordDecl()->field_begin();
Samuel Antaobed3c462015-10-02 16:14:20 +00005934 auto CV = CapturedVars.begin();
5935 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
5936 CE = CS.capture_end();
5937 CI != CE; ++CI, ++RI, ++CV) {
5938 StringRef Name;
5939 QualType Ty;
Samuel Antaobed3c462015-10-02 16:14:20 +00005940
Samuel Antao86ace552016-04-27 22:40:57 +00005941 CurBasePointers.clear();
5942 CurPointers.clear();
5943 CurSizes.clear();
5944 CurMapTypes.clear();
5945
5946 // VLA sizes are passed to the outlined region by copy and do not have map
5947 // information associated.
Samuel Antaobed3c462015-10-02 16:14:20 +00005948 if (CI->capturesVariableArrayType()) {
Samuel Antao86ace552016-04-27 22:40:57 +00005949 CurBasePointers.push_back(*CV);
5950 CurPointers.push_back(*CV);
5951 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005952 // Copy to the device as an argument. No need to retrieve it.
Samuel Antao6782e942016-05-26 16:48:10 +00005953 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_PRIVATE_VAL |
5954 MappableExprsHandler::OMP_MAP_FIRST_REF);
Samuel Antaobed3c462015-10-02 16:14:20 +00005955 } else {
Samuel Antao86ace552016-04-27 22:40:57 +00005956 // If we have any information in the map clause, we use it, otherwise we
5957 // just do a default mapping.
Samuel Antao6890b092016-07-28 14:25:09 +00005958 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Samuel Antao86ace552016-04-27 22:40:57 +00005959 CurSizes, CurMapTypes);
Samuel Antaod486f842016-05-26 16:53:38 +00005960 if (CurBasePointers.empty())
5961 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
5962 CurPointers, CurSizes, CurMapTypes);
Samuel Antaobed3c462015-10-02 16:14:20 +00005963 }
Samuel Antao86ace552016-04-27 22:40:57 +00005964 // We expect to have at least an element of information for this capture.
5965 assert(!CurBasePointers.empty() && "Non-existing map pointer for capture!");
5966 assert(CurBasePointers.size() == CurPointers.size() &&
5967 CurBasePointers.size() == CurSizes.size() &&
5968 CurBasePointers.size() == CurMapTypes.size() &&
5969 "Inconsistent map information sizes!");
Samuel Antaobed3c462015-10-02 16:14:20 +00005970
Samuel Antao86ace552016-04-27 22:40:57 +00005971 // The kernel args are always the first elements of the base pointers
5972 // associated with a capture.
Samuel Antaocc10b852016-07-28 14:23:26 +00005973 KernelArgs.push_back(*CurBasePointers.front());
Samuel Antao86ace552016-04-27 22:40:57 +00005974 // We need to append the results of this capture to what we already have.
5975 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
5976 Pointers.append(CurPointers.begin(), CurPointers.end());
5977 Sizes.append(CurSizes.begin(), CurSizes.end());
5978 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
Samuel Antaobed3c462015-10-02 16:14:20 +00005979 }
5980
5981 // Keep track on whether the host function has to be executed.
5982 auto OffloadErrorQType =
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005983 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00005984 auto OffloadError = CGF.MakeAddrLValue(
5985 CGF.CreateMemTemp(OffloadErrorQType, ".run_host_version"),
5986 OffloadErrorQType);
5987 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty),
5988 OffloadError);
5989
5990 // Fill up the pointer arrays and transfer execution to the device.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00005991 auto &&ThenGen = [&BasePointers, &Pointers, &Sizes, &MapTypes, Device,
5992 OutlinedFnID, OffloadError,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005993 &D](CodeGenFunction &CGF, PrePostActionTy &) {
5994 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antaodf158d52016-04-27 22:58:19 +00005995 // Emit the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00005996 TargetDataInfo Info;
5997 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
5998 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
5999 Info.PointersArray, Info.SizesArray,
6000 Info.MapTypesArray, Info);
Samuel Antaobed3c462015-10-02 16:14:20 +00006001
6002 // On top of the arrays that were filled up, the target offloading call
6003 // takes as arguments the device id as well as the host pointer. The host
6004 // pointer is used by the runtime library to identify the current target
6005 // region, so it only has to be unique and not necessarily point to
6006 // anything. It could be the pointer to the outlined function that
6007 // implements the target region, but we aren't using that so that the
6008 // compiler doesn't need to keep that, and could therefore inline the host
6009 // function if proven worthwhile during optimization.
6010
Samuel Antaoee8fb302016-01-06 13:42:12 +00006011 // From this point on, we need to have an ID of the target region defined.
6012 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00006013
6014 // Emit device ID if any.
6015 llvm::Value *DeviceID;
6016 if (Device)
6017 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006018 CGF.Int32Ty, /*isSigned=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006019 else
6020 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6021
Samuel Antaodf158d52016-04-27 22:58:19 +00006022 // Emit the number of elements in the offloading arrays.
6023 llvm::Value *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6024
Samuel Antaob68e2db2016-03-03 16:20:23 +00006025 // Return value of the runtime offloading call.
6026 llvm::Value *Return;
6027
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006028 auto *NumTeams = emitNumTeamsClauseForTargetDirective(RT, CGF, D);
6029 auto *ThreadLimit = emitThreadLimitClauseForTargetDirective(RT, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006030
6031 // If we have NumTeams defined this means that we have an enclosed teams
6032 // region. Therefore we also expect to have ThreadLimit defined. These two
6033 // values should be defined in the presence of a teams directive, regardless
6034 // of having any clauses associated. If the user is using teams but no
6035 // clauses, these two values will be the default that should be passed to
6036 // the runtime library - a 32-bit integer with the value zero.
6037 if (NumTeams) {
6038 assert(ThreadLimit && "Thread limit expression should be available along "
6039 "with number of teams.");
6040 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00006041 DeviceID, OutlinedFnID,
6042 PointerNum, Info.BasePointersArray,
6043 Info.PointersArray, Info.SizesArray,
6044 Info.MapTypesArray, NumTeams,
6045 ThreadLimit};
Samuel Antaob68e2db2016-03-03 16:20:23 +00006046 Return = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006047 RT.createRuntimeFunction(OMPRTL__tgt_target_teams), OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006048 } else {
6049 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00006050 DeviceID, OutlinedFnID,
6051 PointerNum, Info.BasePointersArray,
6052 Info.PointersArray, Info.SizesArray,
6053 Info.MapTypesArray};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006054 Return = CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target),
Samuel Antaob68e2db2016-03-03 16:20:23 +00006055 OffloadingArgs);
6056 }
Samuel Antaobed3c462015-10-02 16:14:20 +00006057
6058 CGF.EmitStoreOfScalar(Return, OffloadError);
6059 };
6060
Samuel Antaoee8fb302016-01-06 13:42:12 +00006061 // Notify that the host version must be executed.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006062 auto &&ElseGen = [OffloadError](CodeGenFunction &CGF, PrePostActionTy &) {
6063 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/-1u),
Samuel Antaoee8fb302016-01-06 13:42:12 +00006064 OffloadError);
6065 };
6066
6067 // If we have a target function ID it means that we need to support
6068 // offloading, otherwise, just execute on the host. We need to execute on host
6069 // regardless of the conditional in the if clause if, e.g., the user do not
6070 // specify target triples.
6071 if (OutlinedFnID) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006072 if (IfCond)
Samuel Antaoee8fb302016-01-06 13:42:12 +00006073 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006074 else {
6075 RegionCodeGenTy ThenRCG(ThenGen);
6076 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00006077 }
6078 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006079 RegionCodeGenTy ElseRCG(ElseGen);
6080 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00006081 }
Samuel Antaobed3c462015-10-02 16:14:20 +00006082
6083 // Check the error code and execute the host version if required.
6084 auto OffloadFailedBlock = CGF.createBasicBlock("omp_offload.failed");
6085 auto OffloadContBlock = CGF.createBasicBlock("omp_offload.cont");
6086 auto OffloadErrorVal = CGF.EmitLoadOfScalar(OffloadError, SourceLocation());
6087 auto Failed = CGF.Builder.CreateIsNotNull(OffloadErrorVal);
6088 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
6089
6090 CGF.EmitBlock(OffloadFailedBlock);
Samuel Antao86ace552016-04-27 22:40:57 +00006091 CGF.Builder.CreateCall(OutlinedFn, KernelArgs);
Samuel Antaobed3c462015-10-02 16:14:20 +00006092 CGF.EmitBranch(OffloadContBlock);
6093
6094 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006095}
Samuel Antaoee8fb302016-01-06 13:42:12 +00006096
6097void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
6098 StringRef ParentName) {
6099 if (!S)
6100 return;
6101
6102 // If we find a OMP target directive, codegen the outline function and
6103 // register the result.
6104 // FIXME: Add other directives with target when they become supported.
6105 bool isTargetDirective = isa<OMPTargetDirective>(S);
6106
6107 if (isTargetDirective) {
6108 auto *E = cast<OMPExecutableDirective>(S);
6109 unsigned DeviceID;
6110 unsigned FileID;
6111 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00006112 getTargetEntryUniqueInfo(CGM.getContext(), E->getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00006113 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006114
6115 // Is this a target region that should not be emitted as an entry point? If
6116 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00006117 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
6118 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00006119 return;
6120
6121 llvm::Function *Fn;
6122 llvm::Constant *Addr;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006123 std::tie(Fn, Addr) =
6124 CodeGenFunction::EmitOMPTargetDirectiveOutlinedFunction(
6125 CGM, cast<OMPTargetDirective>(*E), ParentName,
6126 /*isOffloadEntry=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006127 assert(Fn && Addr && "Target region emission failed.");
6128 return;
6129 }
6130
6131 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
Samuel Antaoe49645c2016-05-08 06:43:56 +00006132 if (!E->hasAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00006133 return;
6134
6135 scanForTargetRegionsFunctions(
6136 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
6137 ParentName);
6138 return;
6139 }
6140
6141 // If this is a lambda function, look into its body.
6142 if (auto *L = dyn_cast<LambdaExpr>(S))
6143 S = L->getBody();
6144
6145 // Keep looking for target regions recursively.
6146 for (auto *II : S->children())
6147 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006148}
6149
6150bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
6151 auto &FD = *cast<FunctionDecl>(GD.getDecl());
6152
6153 // If emitting code for the host, we do not process FD here. Instead we do
6154 // the normal code generation.
6155 if (!CGM.getLangOpts().OpenMPIsDevice)
6156 return false;
6157
6158 // Try to detect target regions in the function.
6159 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
6160
Samuel Antao4b75b872016-12-12 19:26:31 +00006161 // We should not emit any function other that the ones created during the
Samuel Antaoee8fb302016-01-06 13:42:12 +00006162 // scanning. Therefore, we signal that this function is completely dealt
6163 // with.
6164 return true;
6165}
6166
6167bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
6168 if (!CGM.getLangOpts().OpenMPIsDevice)
6169 return false;
6170
6171 // Check if there are Ctors/Dtors in this declaration and look for target
6172 // regions in it. We use the complete variant to produce the kernel name
6173 // mangling.
6174 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
6175 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
6176 for (auto *Ctor : RD->ctors()) {
6177 StringRef ParentName =
6178 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
6179 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
6180 }
6181 auto *Dtor = RD->getDestructor();
6182 if (Dtor) {
6183 StringRef ParentName =
6184 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
6185 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
6186 }
6187 }
6188
6189 // If we are in target mode we do not emit any global (declare target is not
6190 // implemented yet). Therefore we signal that GD was processed in this case.
6191 return true;
6192}
6193
6194bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
6195 auto *VD = GD.getDecl();
6196 if (isa<FunctionDecl>(VD))
6197 return emitTargetFunctions(GD);
6198
6199 return emitTargetGlobalVariable(GD);
6200}
6201
6202llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
6203 // If we have offloading in the current module, we need to emit the entries
6204 // now and register the offloading descriptor.
6205 createOffloadEntriesAndInfoMetadata();
6206
6207 // Create and register the offloading binary descriptors. This is the main
6208 // entity that captures all the information about offloading in the current
6209 // compilation unit.
6210 return createOffloadingBinaryDescriptorRegistration();
6211}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006212
6213void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
6214 const OMPExecutableDirective &D,
6215 SourceLocation Loc,
6216 llvm::Value *OutlinedFn,
6217 ArrayRef<llvm::Value *> CapturedVars) {
6218 if (!CGF.HaveInsertPoint())
6219 return;
6220
6221 auto *RTLoc = emitUpdateLocation(CGF, Loc);
6222 CodeGenFunction::RunCleanupsScope Scope(CGF);
6223
6224 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
6225 llvm::Value *Args[] = {
6226 RTLoc,
6227 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
6228 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
6229 llvm::SmallVector<llvm::Value *, 16> RealArgs;
6230 RealArgs.append(std::begin(Args), std::end(Args));
6231 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
6232
6233 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
6234 CGF.EmitRuntimeCall(RTLFn, RealArgs);
6235}
6236
6237void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00006238 const Expr *NumTeams,
6239 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006240 SourceLocation Loc) {
6241 if (!CGF.HaveInsertPoint())
6242 return;
6243
6244 auto *RTLoc = emitUpdateLocation(CGF, Loc);
6245
Carlo Bertollic6872252016-04-04 15:55:02 +00006246 llvm::Value *NumTeamsVal =
6247 (NumTeams)
6248 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
6249 CGF.CGM.Int32Ty, /* isSigned = */ true)
6250 : CGF.Builder.getInt32(0);
6251
6252 llvm::Value *ThreadLimitVal =
6253 (ThreadLimit)
6254 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
6255 CGF.CGM.Int32Ty, /* isSigned = */ true)
6256 : CGF.Builder.getInt32(0);
6257
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006258 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00006259 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
6260 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006261 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
6262 PushNumTeamsArgs);
6263}
Samuel Antaodf158d52016-04-27 22:58:19 +00006264
Samuel Antaocc10b852016-07-28 14:23:26 +00006265void CGOpenMPRuntime::emitTargetDataCalls(
6266 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
6267 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006268 if (!CGF.HaveInsertPoint())
6269 return;
6270
Samuel Antaocc10b852016-07-28 14:23:26 +00006271 // Action used to replace the default codegen action and turn privatization
6272 // off.
6273 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00006274
6275 // Generate the code for the opening of the data environment. Capture all the
6276 // arguments of the runtime call by reference because they are used in the
6277 // closing of the region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00006278 auto &&BeginThenGen = [&D, Device, &Info, &CodeGen](CodeGenFunction &CGF,
6279 PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006280 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00006281 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00006282 MappableExprsHandler::MapValuesArrayTy Pointers;
6283 MappableExprsHandler::MapValuesArrayTy Sizes;
6284 MappableExprsHandler::MapFlagsArrayTy MapTypes;
6285
6286 // Get map clause information.
6287 MappableExprsHandler MCHandler(D, CGF);
6288 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00006289
6290 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00006291 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00006292
6293 llvm::Value *BasePointersArrayArg = nullptr;
6294 llvm::Value *PointersArrayArg = nullptr;
6295 llvm::Value *SizesArrayArg = nullptr;
6296 llvm::Value *MapTypesArrayArg = nullptr;
6297 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006298 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00006299
6300 // Emit device ID if any.
6301 llvm::Value *DeviceID = nullptr;
6302 if (Device)
6303 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6304 CGF.Int32Ty, /*isSigned=*/true);
6305 else
6306 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6307
6308 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00006309 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00006310
6311 llvm::Value *OffloadingArgs[] = {
6312 DeviceID, PointerNum, BasePointersArrayArg,
6313 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
6314 auto &RT = CGF.CGM.getOpenMPRuntime();
6315 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_begin),
6316 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00006317
6318 // If device pointer privatization is required, emit the body of the region
6319 // here. It will have to be duplicated: with and without privatization.
6320 if (!Info.CaptureDeviceAddrMap.empty())
6321 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00006322 };
6323
6324 // Generate code for the closing of the data region.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00006325 auto &&EndThenGen = [Device, &Info](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006326 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00006327
6328 llvm::Value *BasePointersArrayArg = nullptr;
6329 llvm::Value *PointersArrayArg = nullptr;
6330 llvm::Value *SizesArrayArg = nullptr;
6331 llvm::Value *MapTypesArrayArg = nullptr;
6332 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006333 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00006334
6335 // Emit device ID if any.
6336 llvm::Value *DeviceID = nullptr;
6337 if (Device)
6338 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6339 CGF.Int32Ty, /*isSigned=*/true);
6340 else
6341 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6342
6343 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00006344 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00006345
6346 llvm::Value *OffloadingArgs[] = {
6347 DeviceID, PointerNum, BasePointersArrayArg,
6348 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
6349 auto &RT = CGF.CGM.getOpenMPRuntime();
6350 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_end),
6351 OffloadingArgs);
6352 };
6353
Samuel Antaocc10b852016-07-28 14:23:26 +00006354 // If we need device pointer privatization, we need to emit the body of the
6355 // region with no privatization in the 'else' branch of the conditional.
6356 // Otherwise, we don't have to do anything.
6357 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
6358 PrePostActionTy &) {
6359 if (!Info.CaptureDeviceAddrMap.empty()) {
6360 CodeGen.setAction(NoPrivAction);
6361 CodeGen(CGF);
6362 }
6363 };
6364
6365 // We don't have to do anything to close the region if the if clause evaluates
6366 // to false.
6367 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00006368
6369 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006370 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00006371 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00006372 RegionCodeGenTy RCG(BeginThenGen);
6373 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00006374 }
6375
Samuel Antaocc10b852016-07-28 14:23:26 +00006376 // If we don't require privatization of device pointers, we emit the body in
6377 // between the runtime calls. This avoids duplicating the body code.
6378 if (Info.CaptureDeviceAddrMap.empty()) {
6379 CodeGen.setAction(NoPrivAction);
6380 CodeGen(CGF);
6381 }
Samuel Antaodf158d52016-04-27 22:58:19 +00006382
6383 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006384 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00006385 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00006386 RegionCodeGenTy RCG(EndThenGen);
6387 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00006388 }
6389}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006390
Samuel Antao8d2d7302016-05-26 18:30:22 +00006391void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00006392 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
6393 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006394 if (!CGF.HaveInsertPoint())
6395 return;
6396
Samuel Antao8dd66282016-04-27 23:14:30 +00006397 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00006398 isa<OMPTargetExitDataDirective>(D) ||
6399 isa<OMPTargetUpdateDirective>(D)) &&
6400 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00006401
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006402 // Generate the code for the opening of the data environment.
Malcolm Parsonsc6e45832017-01-13 18:55:32 +00006403 auto &&ThenGen = [&D, Device](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006404 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00006405 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006406 MappableExprsHandler::MapValuesArrayTy Pointers;
6407 MappableExprsHandler::MapValuesArrayTy Sizes;
6408 MappableExprsHandler::MapFlagsArrayTy MapTypes;
6409
6410 // Get map clause information.
Samuel Antao8d2d7302016-05-26 18:30:22 +00006411 MappableExprsHandler MEHandler(D, CGF);
6412 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006413
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006414 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00006415 TargetDataInfo Info;
6416 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
6417 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
6418 Info.PointersArray, Info.SizesArray,
6419 Info.MapTypesArray, Info);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006420
6421 // Emit device ID if any.
6422 llvm::Value *DeviceID = nullptr;
6423 if (Device)
6424 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6425 CGF.Int32Ty, /*isSigned=*/true);
6426 else
6427 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6428
6429 // Emit the number of elements in the offloading arrays.
6430 auto *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6431
6432 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00006433 DeviceID, PointerNum, Info.BasePointersArray,
6434 Info.PointersArray, Info.SizesArray, Info.MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00006435
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006436 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antao8d2d7302016-05-26 18:30:22 +00006437 // Select the right runtime function call for each expected standalone
6438 // directive.
6439 OpenMPRTLFunction RTLFn;
6440 switch (D.getDirectiveKind()) {
6441 default:
6442 llvm_unreachable("Unexpected standalone target data directive.");
6443 break;
6444 case OMPD_target_enter_data:
6445 RTLFn = OMPRTL__tgt_target_data_begin;
6446 break;
6447 case OMPD_target_exit_data:
6448 RTLFn = OMPRTL__tgt_target_data_end;
6449 break;
6450 case OMPD_target_update:
6451 RTLFn = OMPRTL__tgt_target_data_update;
6452 break;
6453 }
6454 CGF.EmitRuntimeCall(RT.createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006455 };
6456
6457 // In the event we get an if clause, we don't have to take any action on the
6458 // else side.
6459 auto &&ElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
6460
6461 if (IfCond) {
6462 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
6463 } else {
6464 RegionCodeGenTy ThenGenRCG(ThenGen);
6465 ThenGenRCG(CGF);
6466 }
6467}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00006468
6469namespace {
6470 /// Kind of parameter in a function with 'declare simd' directive.
6471 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
6472 /// Attribute set of the parameter.
6473 struct ParamAttrTy {
6474 ParamKindTy Kind = Vector;
6475 llvm::APSInt StrideOrArg;
6476 llvm::APSInt Alignment;
6477 };
6478} // namespace
6479
6480static unsigned evaluateCDTSize(const FunctionDecl *FD,
6481 ArrayRef<ParamAttrTy> ParamAttrs) {
6482 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
6483 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
6484 // of that clause. The VLEN value must be power of 2.
6485 // In other case the notion of the function`s "characteristic data type" (CDT)
6486 // is used to compute the vector length.
6487 // CDT is defined in the following order:
6488 // a) For non-void function, the CDT is the return type.
6489 // b) If the function has any non-uniform, non-linear parameters, then the
6490 // CDT is the type of the first such parameter.
6491 // c) If the CDT determined by a) or b) above is struct, union, or class
6492 // type which is pass-by-value (except for the type that maps to the
6493 // built-in complex data type), the characteristic data type is int.
6494 // d) If none of the above three cases is applicable, the CDT is int.
6495 // The VLEN is then determined based on the CDT and the size of vector
6496 // register of that ISA for which current vector version is generated. The
6497 // VLEN is computed using the formula below:
6498 // VLEN = sizeof(vector_register) / sizeof(CDT),
6499 // where vector register size specified in section 3.2.1 Registers and the
6500 // Stack Frame of original AMD64 ABI document.
6501 QualType RetType = FD->getReturnType();
6502 if (RetType.isNull())
6503 return 0;
6504 ASTContext &C = FD->getASTContext();
6505 QualType CDT;
6506 if (!RetType.isNull() && !RetType->isVoidType())
6507 CDT = RetType;
6508 else {
6509 unsigned Offset = 0;
6510 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6511 if (ParamAttrs[Offset].Kind == Vector)
6512 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
6513 ++Offset;
6514 }
6515 if (CDT.isNull()) {
6516 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
6517 if (ParamAttrs[I + Offset].Kind == Vector) {
6518 CDT = FD->getParamDecl(I)->getType();
6519 break;
6520 }
6521 }
6522 }
6523 }
6524 if (CDT.isNull())
6525 CDT = C.IntTy;
6526 CDT = CDT->getCanonicalTypeUnqualified();
6527 if (CDT->isRecordType() || CDT->isUnionType())
6528 CDT = C.IntTy;
6529 return C.getTypeSize(CDT);
6530}
6531
6532static void
6533emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00006534 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00006535 ArrayRef<ParamAttrTy> ParamAttrs,
6536 OMPDeclareSimdDeclAttr::BranchStateTy State) {
6537 struct ISADataTy {
6538 char ISA;
6539 unsigned VecRegSize;
6540 };
6541 ISADataTy ISAData[] = {
6542 {
6543 'b', 128
6544 }, // SSE
6545 {
6546 'c', 256
6547 }, // AVX
6548 {
6549 'd', 256
6550 }, // AVX2
6551 {
6552 'e', 512
6553 }, // AVX512
6554 };
6555 llvm::SmallVector<char, 2> Masked;
6556 switch (State) {
6557 case OMPDeclareSimdDeclAttr::BS_Undefined:
6558 Masked.push_back('N');
6559 Masked.push_back('M');
6560 break;
6561 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
6562 Masked.push_back('N');
6563 break;
6564 case OMPDeclareSimdDeclAttr::BS_Inbranch:
6565 Masked.push_back('M');
6566 break;
6567 }
6568 for (auto Mask : Masked) {
6569 for (auto &Data : ISAData) {
6570 SmallString<256> Buffer;
6571 llvm::raw_svector_ostream Out(Buffer);
6572 Out << "_ZGV" << Data.ISA << Mask;
6573 if (!VLENVal) {
6574 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
6575 evaluateCDTSize(FD, ParamAttrs));
6576 } else
6577 Out << VLENVal;
6578 for (auto &ParamAttr : ParamAttrs) {
6579 switch (ParamAttr.Kind){
6580 case LinearWithVarStride:
6581 Out << 's' << ParamAttr.StrideOrArg;
6582 break;
6583 case Linear:
6584 Out << 'l';
6585 if (!!ParamAttr.StrideOrArg)
6586 Out << ParamAttr.StrideOrArg;
6587 break;
6588 case Uniform:
6589 Out << 'u';
6590 break;
6591 case Vector:
6592 Out << 'v';
6593 break;
6594 }
6595 if (!!ParamAttr.Alignment)
6596 Out << 'a' << ParamAttr.Alignment;
6597 }
6598 Out << '_' << Fn->getName();
6599 Fn->addFnAttr(Out.str());
6600 }
6601 }
6602}
6603
6604void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
6605 llvm::Function *Fn) {
6606 ASTContext &C = CGM.getContext();
6607 FD = FD->getCanonicalDecl();
6608 // Map params to their positions in function decl.
6609 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
6610 if (isa<CXXMethodDecl>(FD))
6611 ParamPositions.insert({FD, 0});
6612 unsigned ParamPos = ParamPositions.size();
David Majnemer59f77922016-06-24 04:05:48 +00006613 for (auto *P : FD->parameters()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00006614 ParamPositions.insert({P->getCanonicalDecl(), ParamPos});
6615 ++ParamPos;
6616 }
6617 for (auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
6618 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
6619 // Mark uniform parameters.
6620 for (auto *E : Attr->uniforms()) {
6621 E = E->IgnoreParenImpCasts();
6622 unsigned Pos;
6623 if (isa<CXXThisExpr>(E))
6624 Pos = ParamPositions[FD];
6625 else {
6626 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
6627 ->getCanonicalDecl();
6628 Pos = ParamPositions[PVD];
6629 }
6630 ParamAttrs[Pos].Kind = Uniform;
6631 }
6632 // Get alignment info.
6633 auto NI = Attr->alignments_begin();
6634 for (auto *E : Attr->aligneds()) {
6635 E = E->IgnoreParenImpCasts();
6636 unsigned Pos;
6637 QualType ParmTy;
6638 if (isa<CXXThisExpr>(E)) {
6639 Pos = ParamPositions[FD];
6640 ParmTy = E->getType();
6641 } else {
6642 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
6643 ->getCanonicalDecl();
6644 Pos = ParamPositions[PVD];
6645 ParmTy = PVD->getType();
6646 }
6647 ParamAttrs[Pos].Alignment =
6648 (*NI) ? (*NI)->EvaluateKnownConstInt(C)
6649 : llvm::APSInt::getUnsigned(
6650 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
6651 .getQuantity());
6652 ++NI;
6653 }
6654 // Mark linear parameters.
6655 auto SI = Attr->steps_begin();
6656 auto MI = Attr->modifiers_begin();
6657 for (auto *E : Attr->linears()) {
6658 E = E->IgnoreParenImpCasts();
6659 unsigned Pos;
6660 if (isa<CXXThisExpr>(E))
6661 Pos = ParamPositions[FD];
6662 else {
6663 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
6664 ->getCanonicalDecl();
6665 Pos = ParamPositions[PVD];
6666 }
6667 auto &ParamAttr = ParamAttrs[Pos];
6668 ParamAttr.Kind = Linear;
6669 if (*SI) {
6670 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
6671 Expr::SE_AllowSideEffects)) {
6672 if (auto *DRE = cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
6673 if (auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
6674 ParamAttr.Kind = LinearWithVarStride;
6675 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
6676 ParamPositions[StridePVD->getCanonicalDecl()]);
6677 }
6678 }
6679 }
6680 }
6681 ++SI;
6682 ++MI;
6683 }
6684 llvm::APSInt VLENVal;
6685 if (const Expr *VLEN = Attr->getSimdlen())
6686 VLENVal = VLEN->EvaluateKnownConstInt(C);
6687 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
6688 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
6689 CGM.getTriple().getArch() == llvm::Triple::x86_64)
6690 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
6691 }
6692}
Alexey Bataev8b427062016-05-25 12:36:08 +00006693
6694namespace {
6695/// Cleanup action for doacross support.
6696class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
6697public:
6698 static const int DoacrossFinArgs = 2;
6699
6700private:
6701 llvm::Value *RTLFn;
6702 llvm::Value *Args[DoacrossFinArgs];
6703
6704public:
6705 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
6706 : RTLFn(RTLFn) {
6707 assert(CallArgs.size() == DoacrossFinArgs);
6708 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
6709 }
6710 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
6711 if (!CGF.HaveInsertPoint())
6712 return;
6713 CGF.EmitRuntimeCall(RTLFn, Args);
6714 }
6715};
6716} // namespace
6717
6718void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
6719 const OMPLoopDirective &D) {
6720 if (!CGF.HaveInsertPoint())
6721 return;
6722
6723 ASTContext &C = CGM.getContext();
6724 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
6725 RecordDecl *RD;
6726 if (KmpDimTy.isNull()) {
6727 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
6728 // kmp_int64 lo; // lower
6729 // kmp_int64 up; // upper
6730 // kmp_int64 st; // stride
6731 // };
6732 RD = C.buildImplicitRecord("kmp_dim");
6733 RD->startDefinition();
6734 addFieldToRecordDecl(C, RD, Int64Ty);
6735 addFieldToRecordDecl(C, RD, Int64Ty);
6736 addFieldToRecordDecl(C, RD, Int64Ty);
6737 RD->completeDefinition();
6738 KmpDimTy = C.getRecordType(RD);
6739 } else
6740 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
6741
6742 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
6743 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
6744 enum { LowerFD = 0, UpperFD, StrideFD };
6745 // Fill dims with data.
6746 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
6747 // dims.upper = num_iterations;
6748 LValue UpperLVal =
6749 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
6750 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
6751 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
6752 Int64Ty, D.getNumIterations()->getExprLoc());
6753 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
6754 // dims.stride = 1;
6755 LValue StrideLVal =
6756 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
6757 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
6758 StrideLVal);
6759
6760 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
6761 // kmp_int32 num_dims, struct kmp_dim * dims);
6762 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
6763 getThreadID(CGF, D.getLocStart()),
6764 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
6765 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6766 DimsAddr.getPointer(), CGM.VoidPtrTy)};
6767
6768 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
6769 CGF.EmitRuntimeCall(RTLFn, Args);
6770 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
6771 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
6772 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
6773 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
6774 llvm::makeArrayRef(FiniArgs));
6775}
6776
6777void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
6778 const OMPDependClause *C) {
6779 QualType Int64Ty =
6780 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
6781 const Expr *CounterVal = C->getCounterValue();
6782 assert(CounterVal);
6783 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
6784 CounterVal->getType(), Int64Ty,
6785 CounterVal->getExprLoc());
6786 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
6787 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
6788 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
6789 getThreadID(CGF, C->getLocStart()),
6790 CntAddr.getPointer()};
6791 llvm::Value *RTLFn;
6792 if (C->getDependencyKind() == OMPC_DEPEND_source)
6793 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
6794 else {
6795 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
6796 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
6797 }
6798 CGF.EmitRuntimeCall(RTLFn, Args);
6799}
6800