blob: 0624d86b564aea15535532f8ef7256d12939a787 [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,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000102 OpenMPDirectiveKind Kind, bool HasCancel)
103 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
104 HasCancel),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000105 ThreadIDVar(ThreadIDVar) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000106 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
107 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000108
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000109 /// \brief Get a variable or parameter for storing global thread id
110 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000111 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000112
Alexey Bataev18095712014-10-10 12:19:54 +0000113 /// \brief Get the name of the capture helper.
Benjamin Kramerc52193f2014-10-10 13:57:57 +0000114 StringRef getHelperName() const override { return ".omp_outlined."; }
Alexey Bataev18095712014-10-10 12:19:54 +0000115
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000116 static bool classof(const CGCapturedStmtInfo *Info) {
117 return CGOpenMPRegionInfo::classof(Info) &&
118 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
119 ParallelOutlinedRegion;
120 }
121
Alexey Bataev18095712014-10-10 12:19:54 +0000122private:
123 /// \brief A variable or parameter storing global thread id for OpenMP
124 /// constructs.
125 const VarDecl *ThreadIDVar;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000126};
127
Alexey Bataev62b63b12015-03-10 07:28:44 +0000128/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000129class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000130public:
Alexey Bataev48591dd2016-04-20 04:01:36 +0000131 class UntiedTaskActionTy final : public PrePostActionTy {
132 bool Untied;
133 const VarDecl *PartIDVar;
134 const RegionCodeGenTy UntiedCodeGen;
135 llvm::SwitchInst *UntiedSwitch = nullptr;
136
137 public:
138 UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
139 const RegionCodeGenTy &UntiedCodeGen)
140 : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
141 void Enter(CodeGenFunction &CGF) override {
142 if (Untied) {
143 // Emit task switching point.
144 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
145 CGF.GetAddrOfLocalVar(PartIDVar),
146 PartIDVar->getType()->castAs<PointerType>());
147 auto *Res = CGF.EmitLoadOfScalar(PartIdLVal, SourceLocation());
148 auto *DoneBB = CGF.createBasicBlock(".untied.done.");
149 UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
150 CGF.EmitBlock(DoneBB);
151 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
152 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
153 UntiedSwitch->addCase(CGF.Builder.getInt32(0),
154 CGF.Builder.GetInsertBlock());
155 emitUntiedSwitch(CGF);
156 }
157 }
158 void emitUntiedSwitch(CodeGenFunction &CGF) const {
159 if (Untied) {
160 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
161 CGF.GetAddrOfLocalVar(PartIDVar),
162 PartIDVar->getType()->castAs<PointerType>());
163 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
164 PartIdLVal);
165 UntiedCodeGen(CGF);
166 CodeGenFunction::JumpDest CurPoint =
167 CGF.getJumpDestInCurrentScope(".untied.next.");
168 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
169 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
170 UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
171 CGF.Builder.GetInsertBlock());
172 CGF.EmitBranchThroughCleanup(CurPoint);
173 CGF.EmitBlock(CurPoint.getBlock());
174 }
175 }
176 unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
177 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000178 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000179 const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000180 const RegionCodeGenTy &CodeGen,
Alexey Bataev48591dd2016-04-20 04:01:36 +0000181 OpenMPDirectiveKind Kind, bool HasCancel,
182 const UntiedTaskActionTy &Action)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000183 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
Alexey Bataev48591dd2016-04-20 04:01:36 +0000184 ThreadIDVar(ThreadIDVar), Action(Action) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000185 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
186 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000187
Alexey Bataev62b63b12015-03-10 07:28:44 +0000188 /// \brief Get a variable or parameter for storing global thread id
189 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000190 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000191
192 /// \brief Get an LValue for the current ThreadID variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000193 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000194
Alexey Bataev62b63b12015-03-10 07:28:44 +0000195 /// \brief Get the name of the capture helper.
196 StringRef getHelperName() const override { return ".omp_outlined."; }
197
Alexey Bataev48591dd2016-04-20 04:01:36 +0000198 void emitUntiedSwitch(CodeGenFunction &CGF) override {
199 Action.emitUntiedSwitch(CGF);
200 }
201
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000202 static bool classof(const CGCapturedStmtInfo *Info) {
203 return CGOpenMPRegionInfo::classof(Info) &&
204 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
205 TaskOutlinedRegion;
206 }
207
Alexey Bataev62b63b12015-03-10 07:28:44 +0000208private:
209 /// \brief A variable or parameter storing global thread id for OpenMP
210 /// constructs.
211 const VarDecl *ThreadIDVar;
Alexey Bataev48591dd2016-04-20 04:01:36 +0000212 /// Action for emitting code for untied tasks.
213 const UntiedTaskActionTy &Action;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000214};
215
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000216/// \brief API for inlined captured statement code generation in OpenMP
217/// constructs.
218class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
219public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000220 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000221 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000222 OpenMPDirectiveKind Kind, bool HasCancel)
223 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
224 OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000225 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000226
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000227 // \brief Retrieve the value of the context parameter.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000228 llvm::Value *getContextValue() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000229 if (OuterRegionInfo)
230 return OuterRegionInfo->getContextValue();
231 llvm_unreachable("No context value for inlined OpenMP region");
232 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000233
Hans Wennborg7eb54642015-09-10 17:07:54 +0000234 void setContextValue(llvm::Value *V) override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000235 if (OuterRegionInfo) {
236 OuterRegionInfo->setContextValue(V);
237 return;
238 }
239 llvm_unreachable("No context value for inlined OpenMP region");
240 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000241
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000242 /// \brief Lookup the captured field decl for a variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000243 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000244 if (OuterRegionInfo)
245 return OuterRegionInfo->lookup(VD);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000246 // If there is no outer outlined region,no need to lookup in a list of
247 // captured variables, we can use the original one.
248 return nullptr;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000249 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000250
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000251 FieldDecl *getThisFieldDecl() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000252 if (OuterRegionInfo)
253 return OuterRegionInfo->getThisFieldDecl();
254 return nullptr;
255 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000256
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000257 /// \brief Get a variable or parameter for storing global thread id
258 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000259 const VarDecl *getThreadIDVariable() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000260 if (OuterRegionInfo)
261 return OuterRegionInfo->getThreadIDVariable();
262 return nullptr;
263 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000264
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000265 /// \brief Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000266 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000267 if (auto *OuterRegionInfo = getOldCSI())
268 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000269 llvm_unreachable("No helper name for inlined OpenMP construct");
270 }
271
Alexey Bataev48591dd2016-04-20 04:01:36 +0000272 void emitUntiedSwitch(CodeGenFunction &CGF) override {
273 if (OuterRegionInfo)
274 OuterRegionInfo->emitUntiedSwitch(CGF);
275 }
276
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000277 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
278
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000279 static bool classof(const CGCapturedStmtInfo *Info) {
280 return CGOpenMPRegionInfo::classof(Info) &&
281 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
282 }
283
Alexey Bataev48591dd2016-04-20 04:01:36 +0000284 ~CGOpenMPInlinedRegionInfo() override = default;
285
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000286private:
287 /// \brief CodeGen info about outer OpenMP region.
288 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
289 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000290};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000291
Samuel Antaobed3c462015-10-02 16:14:20 +0000292/// \brief API for captured statement code generation in OpenMP target
293/// constructs. For this captures, implicit parameters are used instead of the
Samuel Antaoee8fb302016-01-06 13:42:12 +0000294/// captured fields. The name of the target region has to be unique in a given
295/// application so it is provided by the client, because only the client has
296/// the information to generate that.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000297class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
Samuel Antaobed3c462015-10-02 16:14:20 +0000298public:
299 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000300 const RegionCodeGenTy &CodeGen, StringRef HelperName)
Samuel Antaobed3c462015-10-02 16:14:20 +0000301 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000302 /*HasCancel=*/false),
303 HelperName(HelperName) {}
Samuel Antaobed3c462015-10-02 16:14:20 +0000304
305 /// \brief This is unused for target regions because each starts executing
306 /// with a single thread.
307 const VarDecl *getThreadIDVariable() const override { return nullptr; }
308
309 /// \brief Get the name of the capture helper.
Samuel Antaoee8fb302016-01-06 13:42:12 +0000310 StringRef getHelperName() const override { return HelperName; }
Samuel Antaobed3c462015-10-02 16:14:20 +0000311
312 static bool classof(const CGCapturedStmtInfo *Info) {
313 return CGOpenMPRegionInfo::classof(Info) &&
314 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
315 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000316
317private:
318 StringRef HelperName;
Samuel Antaobed3c462015-10-02 16:14:20 +0000319};
320
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000321static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000322 llvm_unreachable("No codegen for expressions");
323}
324/// \brief API for generation of expressions captured in a innermost OpenMP
325/// region.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000326class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000327public:
328 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
329 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
330 OMPD_unknown,
331 /*HasCancel=*/false),
332 PrivScope(CGF) {
333 // Make sure the globals captured in the provided statement are local by
334 // using the privatization logic. We assume the same variable is not
335 // captured more than once.
336 for (auto &C : CS.captures()) {
337 if (!C.capturesVariable() && !C.capturesVariableByCopy())
338 continue;
339
340 const VarDecl *VD = C.getCapturedVar();
341 if (VD->isLocalVarDeclOrParm())
342 continue;
343
344 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
345 /*RefersToEnclosingVariableOrCapture=*/false,
346 VD->getType().getNonReferenceType(), VK_LValue,
347 SourceLocation());
348 PrivScope.addPrivate(VD, [&CGF, &DRE]() -> Address {
349 return CGF.EmitLValue(&DRE).getAddress();
350 });
351 }
352 (void)PrivScope.Privatize();
353 }
354
355 /// \brief Lookup the captured field decl for a variable.
356 const FieldDecl *lookup(const VarDecl *VD) const override {
357 if (auto *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
358 return FD;
359 return nullptr;
360 }
361
362 /// \brief Emit the captured statement body.
363 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
364 llvm_unreachable("No body for expressions");
365 }
366
367 /// \brief Get a variable or parameter for storing global thread id
368 /// inside OpenMP construct.
369 const VarDecl *getThreadIDVariable() const override {
370 llvm_unreachable("No thread id for expressions");
371 }
372
373 /// \brief Get the name of the capture helper.
374 StringRef getHelperName() const override {
375 llvm_unreachable("No helper name for expressions");
376 }
377
378 static bool classof(const CGCapturedStmtInfo *Info) { return false; }
379
380private:
381 /// Private scope to capture global variables.
382 CodeGenFunction::OMPPrivateScope PrivScope;
383};
384
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000385/// \brief RAII for emitting code of OpenMP constructs.
386class InlinedOpenMPRegionRAII {
387 CodeGenFunction &CGF;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000388 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
389 FieldDecl *LambdaThisCaptureField = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000390
391public:
392 /// \brief Constructs region for combined constructs.
393 /// \param CodeGen Code generation sequence for combined directives. Includes
394 /// a list of functions used for code generation of implicitly inlined
395 /// regions.
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000396 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000397 OpenMPDirectiveKind Kind, bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000398 : CGF(CGF) {
399 // Start emission for the construct.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000400 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
401 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000402 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
403 LambdaThisCaptureField = CGF.LambdaThisCaptureField;
404 CGF.LambdaThisCaptureField = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000405 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000406
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000407 ~InlinedOpenMPRegionRAII() {
408 // Restore original CapturedStmtInfo only if we're done with code emission.
409 auto *OldCSI =
410 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
411 delete CGF.CapturedStmtInfo;
412 CGF.CapturedStmtInfo = OldCSI;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000413 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
414 CGF.LambdaThisCaptureField = LambdaThisCaptureField;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000415 }
416};
417
Alexey Bataev50b3c952016-02-19 10:38:26 +0000418/// \brief Values for bit flags used in the ident_t to describe the fields.
419/// All enumeric elements are named and described in accordance with the code
420/// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
421enum OpenMPLocationFlags {
422 /// \brief Use trampoline for internal microtask.
423 OMP_IDENT_IMD = 0x01,
424 /// \brief Use c-style ident structure.
425 OMP_IDENT_KMPC = 0x02,
426 /// \brief Atomic reduction option for kmpc_reduce.
427 OMP_ATOMIC_REDUCE = 0x10,
428 /// \brief Explicit 'barrier' directive.
429 OMP_IDENT_BARRIER_EXPL = 0x20,
430 /// \brief Implicit barrier in code.
431 OMP_IDENT_BARRIER_IMPL = 0x40,
432 /// \brief Implicit barrier in 'for' directive.
433 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
434 /// \brief Implicit barrier in 'sections' directive.
435 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
436 /// \brief Implicit barrier in 'single' directive.
437 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140
438};
439
440/// \brief Describes ident structure that describes a source location.
441/// All descriptions are taken from
442/// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
443/// Original structure:
444/// typedef struct ident {
445/// kmp_int32 reserved_1; /**< might be used in Fortran;
446/// see above */
447/// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
448/// KMP_IDENT_KMPC identifies this union
449/// member */
450/// kmp_int32 reserved_2; /**< not really used in Fortran any more;
451/// see above */
452///#if USE_ITT_BUILD
453/// /* but currently used for storing
454/// region-specific ITT */
455/// /* contextual information. */
456///#endif /* USE_ITT_BUILD */
457/// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
458/// C++ */
459/// char const *psource; /**< String describing the source location.
460/// The string is composed of semi-colon separated
461// fields which describe the source file,
462/// the function and a pair of line numbers that
463/// delimit the construct.
464/// */
465/// } ident_t;
466enum IdentFieldIndex {
467 /// \brief might be used in Fortran
468 IdentField_Reserved_1,
469 /// \brief OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
470 IdentField_Flags,
471 /// \brief Not really used in Fortran any more
472 IdentField_Reserved_2,
473 /// \brief Source[4] in Fortran, do not use for C++
474 IdentField_Reserved_3,
475 /// \brief String describing the source location. The string is composed of
476 /// semi-colon separated fields which describe the source file, the function
477 /// and a pair of line numbers that delimit the construct.
478 IdentField_PSource
479};
480
481/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
482/// the enum sched_type in kmp.h).
483enum OpenMPSchedType {
484 /// \brief Lower bound for default (unordered) versions.
485 OMP_sch_lower = 32,
486 OMP_sch_static_chunked = 33,
487 OMP_sch_static = 34,
488 OMP_sch_dynamic_chunked = 35,
489 OMP_sch_guided_chunked = 36,
490 OMP_sch_runtime = 37,
491 OMP_sch_auto = 38,
Alexey Bataev6cff6242016-05-30 13:05:14 +0000492 /// static with chunk adjustment (e.g., simd)
Samuel Antao4c8035b2016-12-12 18:00:20 +0000493 OMP_sch_static_balanced_chunked = 45,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000494 /// \brief Lower bound for 'ordered' versions.
495 OMP_ord_lower = 64,
496 OMP_ord_static_chunked = 65,
497 OMP_ord_static = 66,
498 OMP_ord_dynamic_chunked = 67,
499 OMP_ord_guided_chunked = 68,
500 OMP_ord_runtime = 69,
501 OMP_ord_auto = 70,
502 OMP_sch_default = OMP_sch_static,
Carlo Bertollifc35ad22016-03-07 16:04:49 +0000503 /// \brief dist_schedule types
504 OMP_dist_sch_static_chunked = 91,
505 OMP_dist_sch_static = 92,
Alexey Bataev9ebd7422016-05-10 09:57:36 +0000506 /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
507 /// Set if the monotonic schedule modifier was present.
508 OMP_sch_modifier_monotonic = (1 << 29),
509 /// Set if the nonmonotonic schedule modifier was present.
510 OMP_sch_modifier_nonmonotonic = (1 << 30),
Alexey Bataev50b3c952016-02-19 10:38:26 +0000511};
512
513enum OpenMPRTLFunction {
514 /// \brief Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
515 /// kmpc_micro microtask, ...);
516 OMPRTL__kmpc_fork_call,
517 /// \brief Call to void *__kmpc_threadprivate_cached(ident_t *loc,
518 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
519 OMPRTL__kmpc_threadprivate_cached,
520 /// \brief Call to void __kmpc_threadprivate_register( ident_t *,
521 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
522 OMPRTL__kmpc_threadprivate_register,
523 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
524 OMPRTL__kmpc_global_thread_num,
525 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
526 // kmp_critical_name *crit);
527 OMPRTL__kmpc_critical,
528 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
529 // global_tid, kmp_critical_name *crit, uintptr_t hint);
530 OMPRTL__kmpc_critical_with_hint,
531 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
532 // kmp_critical_name *crit);
533 OMPRTL__kmpc_end_critical,
534 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
535 // global_tid);
536 OMPRTL__kmpc_cancel_barrier,
537 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
538 OMPRTL__kmpc_barrier,
539 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
540 OMPRTL__kmpc_for_static_fini,
541 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
542 // global_tid);
543 OMPRTL__kmpc_serialized_parallel,
544 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
545 // global_tid);
546 OMPRTL__kmpc_end_serialized_parallel,
547 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
548 // kmp_int32 num_threads);
549 OMPRTL__kmpc_push_num_threads,
550 // Call to void __kmpc_flush(ident_t *loc);
551 OMPRTL__kmpc_flush,
552 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
553 OMPRTL__kmpc_master,
554 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
555 OMPRTL__kmpc_end_master,
556 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
557 // int end_part);
558 OMPRTL__kmpc_omp_taskyield,
559 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
560 OMPRTL__kmpc_single,
561 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
562 OMPRTL__kmpc_end_single,
563 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
564 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
565 // kmp_routine_entry_t *task_entry);
566 OMPRTL__kmpc_omp_task_alloc,
567 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
568 // new_task);
569 OMPRTL__kmpc_omp_task,
570 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
571 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
572 // kmp_int32 didit);
573 OMPRTL__kmpc_copyprivate,
574 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
575 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
576 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
577 OMPRTL__kmpc_reduce,
578 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
579 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
580 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
581 // *lck);
582 OMPRTL__kmpc_reduce_nowait,
583 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
584 // kmp_critical_name *lck);
585 OMPRTL__kmpc_end_reduce,
586 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
587 // kmp_critical_name *lck);
588 OMPRTL__kmpc_end_reduce_nowait,
589 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
590 // kmp_task_t * new_task);
591 OMPRTL__kmpc_omp_task_begin_if0,
592 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
593 // kmp_task_t * new_task);
594 OMPRTL__kmpc_omp_task_complete_if0,
595 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
596 OMPRTL__kmpc_ordered,
597 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
598 OMPRTL__kmpc_end_ordered,
599 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
600 // global_tid);
601 OMPRTL__kmpc_omp_taskwait,
602 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
603 OMPRTL__kmpc_taskgroup,
604 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
605 OMPRTL__kmpc_end_taskgroup,
606 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
607 // int proc_bind);
608 OMPRTL__kmpc_push_proc_bind,
609 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
610 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
611 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
612 OMPRTL__kmpc_omp_task_with_deps,
613 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
614 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
615 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
616 OMPRTL__kmpc_omp_wait_deps,
617 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
618 // global_tid, kmp_int32 cncl_kind);
619 OMPRTL__kmpc_cancellationpoint,
620 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
621 // kmp_int32 cncl_kind);
622 OMPRTL__kmpc_cancel,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000623 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
624 // kmp_int32 num_teams, kmp_int32 thread_limit);
625 OMPRTL__kmpc_push_num_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000626 // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
627 // microtask, ...);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000628 OMPRTL__kmpc_fork_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000629 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
630 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
631 // sched, kmp_uint64 grainsize, void *task_dup);
632 OMPRTL__kmpc_taskloop,
Alexey Bataev8b427062016-05-25 12:36:08 +0000633 // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
634 // num_dims, struct kmp_dim *dims);
635 OMPRTL__kmpc_doacross_init,
636 // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
637 OMPRTL__kmpc_doacross_fini,
638 // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
639 // *vec);
640 OMPRTL__kmpc_doacross_post,
641 // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
642 // *vec);
643 OMPRTL__kmpc_doacross_wait,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000644
645 //
646 // Offloading related calls
647 //
648 // Call to int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
649 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
650 // *arg_types);
651 OMPRTL__tgt_target,
Samuel Antaob68e2db2016-03-03 16:20:23 +0000652 // Call to int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
653 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
654 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
655 OMPRTL__tgt_target_teams,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000656 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
657 OMPRTL__tgt_register_lib,
658 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
659 OMPRTL__tgt_unregister_lib,
Samuel Antaodf158d52016-04-27 22:58:19 +0000660 // Call to void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
661 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
662 OMPRTL__tgt_target_data_begin,
663 // Call to void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
664 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
665 OMPRTL__tgt_target_data_end,
Samuel Antao8d2d7302016-05-26 18:30:22 +0000666 // Call to void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
667 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
668 OMPRTL__tgt_target_data_update,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000669};
670
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000671/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
672/// region.
673class CleanupTy final : public EHScopeStack::Cleanup {
674 PrePostActionTy *Action;
675
676public:
677 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
678 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
679 if (!CGF.HaveInsertPoint())
680 return;
681 Action->Exit(CGF);
682 }
683};
684
Hans Wennborg7eb54642015-09-10 17:07:54 +0000685} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000686
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000687void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
688 CodeGenFunction::RunCleanupsScope Scope(CGF);
689 if (PrePostAction) {
690 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
691 Callback(CodeGen, CGF, *PrePostAction);
692 } else {
693 PrePostActionTy Action;
694 Callback(CodeGen, CGF, Action);
695 }
696}
697
Alexey Bataev18095712014-10-10 12:19:54 +0000698LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +0000699 return CGF.EmitLoadOfPointerLValue(
700 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
701 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +0000702}
703
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000704void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000705 if (!CGF.HaveInsertPoint())
706 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000707 // 1.2.2 OpenMP Language Terminology
708 // Structured block - An executable statement with a single entry at the
709 // top and a single exit at the bottom.
710 // The point of exit cannot be a branch out of the structured block.
711 // longjmp() and throw() must not violate the entry/exit criteria.
712 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000713 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000714 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000715}
716
Alexey Bataev62b63b12015-03-10 07:28:44 +0000717LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
718 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000719 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
720 getThreadIDVariable()->getType(),
721 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000722}
723
Alexey Bataev9959db52014-05-06 10:08:46 +0000724CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000725 : CGM(CGM), OffloadEntriesInfoManager(CGM) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000726 IdentTy = llvm::StructType::create(
727 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
728 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Alexander Musmanfdfa8552014-09-11 08:10:57 +0000729 CGM.Int8PtrTy /* psource */, nullptr);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000730 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +0000731
732 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +0000733}
734
Alexey Bataev91797552015-03-18 04:13:55 +0000735void CGOpenMPRuntime::clear() {
736 InternalVars.clear();
737}
738
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000739static llvm::Function *
740emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
741 const Expr *CombinerInitializer, const VarDecl *In,
742 const VarDecl *Out, bool IsCombiner) {
743 // void .omp_combiner.(Ty *in, Ty *out);
744 auto &C = CGM.getContext();
745 QualType PtrTy = C.getPointerType(Ty).withRestrict();
746 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000747 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
748 /*Id=*/nullptr, PtrTy);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000749 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
750 /*Id=*/nullptr, PtrTy);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000751 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000752 Args.push_back(&OmpInParm);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000753 auto &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +0000754 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000755 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
756 auto *Fn = llvm::Function::Create(
757 FnTy, llvm::GlobalValue::InternalLinkage,
758 IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
759 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +0000760 Fn->removeFnAttr(llvm::Attribute::NoInline);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000761 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000762 CodeGenFunction CGF(CGM);
763 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
764 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
765 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
766 CodeGenFunction::OMPPrivateScope Scope(CGF);
767 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
768 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
769 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
770 .getAddress();
771 });
772 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
773 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
774 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
775 .getAddress();
776 });
777 (void)Scope.Privatize();
778 CGF.EmitIgnoredExpr(CombinerInitializer);
779 Scope.ForceCleanup();
780 CGF.FinishFunction();
781 return Fn;
782}
783
784void CGOpenMPRuntime::emitUserDefinedReduction(
785 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
786 if (UDRMap.count(D) > 0)
787 return;
788 auto &C = CGM.getContext();
789 if (!In || !Out) {
790 In = &C.Idents.get("omp_in");
791 Out = &C.Idents.get("omp_out");
792 }
793 llvm::Function *Combiner = emitCombinerOrInitializer(
794 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
795 cast<VarDecl>(D->lookup(Out).front()),
796 /*IsCombiner=*/true);
797 llvm::Function *Initializer = nullptr;
798 if (auto *Init = D->getInitializer()) {
799 if (!Priv || !Orig) {
800 Priv = &C.Idents.get("omp_priv");
801 Orig = &C.Idents.get("omp_orig");
802 }
803 Initializer = emitCombinerOrInitializer(
804 CGM, D->getType(), Init, cast<VarDecl>(D->lookup(Orig).front()),
805 cast<VarDecl>(D->lookup(Priv).front()),
806 /*IsCombiner=*/false);
807 }
808 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
809 if (CGF) {
810 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
811 Decls.second.push_back(D);
812 }
813}
814
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000815std::pair<llvm::Function *, llvm::Function *>
816CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
817 auto I = UDRMap.find(D);
818 if (I != UDRMap.end())
819 return I->second;
820 emitUserDefinedReduction(/*CGF=*/nullptr, D);
821 return UDRMap.lookup(D);
822}
823
John McCall7f416cc2015-09-08 08:05:57 +0000824// Layout information for ident_t.
825static CharUnits getIdentAlign(CodeGenModule &CGM) {
826 return CGM.getPointerAlign();
827}
828static CharUnits getIdentSize(CodeGenModule &CGM) {
829 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
830 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
831}
Alexey Bataev50b3c952016-02-19 10:38:26 +0000832static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
John McCall7f416cc2015-09-08 08:05:57 +0000833 // All the fields except the last are i32, so this works beautifully.
834 return unsigned(Field) * CharUnits::fromQuantity(4);
835}
836static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000837 IdentFieldIndex Field,
John McCall7f416cc2015-09-08 08:05:57 +0000838 const llvm::Twine &Name = "") {
839 auto Offset = getOffsetOfIdentField(Field);
840 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
841}
842
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000843llvm::Value *CGOpenMPRuntime::emitParallelOrTeamsOutlinedFunction(
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000844 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
845 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000846 assert(ThreadIDVar->getType()->isPointerType() &&
847 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +0000848 const CapturedStmt *CS = cast<CapturedStmt>(D.getAssociatedStmt());
849 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +0000850 bool HasCancel = false;
851 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
852 HasCancel = OPD->hasCancel();
853 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
854 HasCancel = OPSD->hasCancel();
855 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
856 HasCancel = OPFD->hasCancel();
857 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
858 HasCancel);
Alexey Bataevd157d472015-06-24 03:35:38 +0000859 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000860 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +0000861}
862
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000863llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
864 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +0000865 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
866 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
867 bool Tied, unsigned &NumberOfParts) {
868 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
869 PrePostActionTy &) {
870 auto *ThreadID = getThreadID(CGF, D.getLocStart());
871 auto *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
872 llvm::Value *TaskArgs[] = {
873 UpLoc, ThreadID,
874 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
875 TaskTVar->getType()->castAs<PointerType>())
876 .getPointer()};
877 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
878 };
879 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
880 UntiedCodeGen);
881 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000882 assert(!ThreadIDVar->getType()->isPointerType() &&
883 "thread id variable must be of type kmp_int32 for tasks");
884 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
Alexey Bataev7292c292016-04-25 12:22:29 +0000885 auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000886 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +0000887 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
888 InnermostKind,
889 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +0000890 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev48591dd2016-04-20 04:01:36 +0000891 auto *Res = CGF.GenerateCapturedStmtFunction(*CS);
892 if (!Tied)
893 NumberOfParts = Action.getNumberOfParts();
894 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000895}
896
Alexey Bataev50b3c952016-02-19 10:38:26 +0000897Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +0000898 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +0000899 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000900 if (!Entry) {
901 if (!DefaultOpenMPPSource) {
902 // Initialize default location for psource field of ident_t structure of
903 // all ident_t objects. Format is ";file;function;line;column;;".
904 // Taken from
905 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
906 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +0000907 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000908 DefaultOpenMPPSource =
909 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
910 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000911
John McCall23c9dc62016-11-28 22:18:27 +0000912 ConstantInitBuilder builder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +0000913 auto fields = builder.beginStruct(IdentTy);
914 fields.addInt(CGM.Int32Ty, 0);
915 fields.addInt(CGM.Int32Ty, Flags);
916 fields.addInt(CGM.Int32Ty, 0);
917 fields.addInt(CGM.Int32Ty, 0);
918 fields.add(DefaultOpenMPPSource);
919 auto DefaultOpenMPLocation =
920 fields.finishAndCreateGlobal("", Align, /*isConstant*/ true,
921 llvm::GlobalValue::PrivateLinkage);
922 DefaultOpenMPLocation->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
923
John McCall7f416cc2015-09-08 08:05:57 +0000924 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +0000925 }
John McCall7f416cc2015-09-08 08:05:57 +0000926 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +0000927}
928
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000929llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
930 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000931 unsigned Flags) {
932 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +0000933 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +0000934 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +0000935 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +0000936 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000937
938 assert(CGF.CurFn && "No function in current CodeGenFunction.");
939
John McCall7f416cc2015-09-08 08:05:57 +0000940 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000941 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
942 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +0000943 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
944
Alexander Musmanc6388682014-12-15 07:07:06 +0000945 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
946 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +0000947 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000948 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +0000949 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
950 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +0000951 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +0000952 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000953 LocValue = AI;
954
955 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
956 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000957 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +0000958 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +0000959 }
960
961 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +0000962 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +0000963
Alexey Bataevf002aca2014-05-30 05:48:40 +0000964 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
965 if (OMPDebugLoc == nullptr) {
966 SmallString<128> Buffer2;
967 llvm::raw_svector_ostream OS2(Buffer2);
968 // Build debug location
969 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
970 OS2 << ";" << PLoc.getFilename() << ";";
971 if (const FunctionDecl *FD =
972 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
973 OS2 << FD->getQualifiedNameAsString();
974 }
975 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
976 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
977 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +0000978 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000979 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +0000980 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
981
John McCall7f416cc2015-09-08 08:05:57 +0000982 // Our callers always pass this to a runtime function, so for
983 // convenience, go ahead and return a naked pointer.
984 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000985}
986
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000987llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
988 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000989 assert(CGF.CurFn && "No function in current CodeGenFunction.");
990
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000991 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +0000992 // Check whether we've already cached a load of the thread id in this
993 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000994 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +0000995 if (I != OpenMPLocThreadIDMap.end()) {
996 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +0000997 if (ThreadID != nullptr)
998 return ThreadID;
999 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001000 if (auto *OMPRegionInfo =
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001001 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00001002 if (OMPRegionInfo->getThreadIDVariable()) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001003 // Check if this an outlined function with thread id passed as argument.
1004 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001005 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
1006 // If value loaded in entry block, cache it and use it everywhere in
1007 // function.
1008 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
1009 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1010 Elem.second.ThreadID = ThreadID;
1011 }
1012 return ThreadID;
Alexey Bataevd6c57552014-07-25 07:55:17 +00001013 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001014 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001015
1016 // This is not an outlined function region - need to call __kmpc_int32
1017 // kmpc_global_thread_num(ident_t *loc).
1018 // Generate thread id value and cache this value for use across the
1019 // function.
1020 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1021 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
1022 ThreadID =
1023 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
1024 emitUpdateLocation(CGF, Loc));
1025 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1026 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001027 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +00001028}
1029
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001030void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001031 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001032 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1033 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001034 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1035 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
1036 UDRMap.erase(D);
1037 }
1038 FunctionUDRMap.erase(CGF.CurFn);
1039 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001040}
1041
1042llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001043 if (!IdentTy) {
1044 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001045 return llvm::PointerType::getUnqual(IdentTy);
1046}
1047
1048llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001049 if (!Kmpc_MicroTy) {
1050 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1051 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1052 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1053 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1054 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001055 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1056}
1057
1058llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001059CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001060 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001061 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001062 case OMPRTL__kmpc_fork_call: {
1063 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1064 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001065 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1066 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001067 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001068 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001069 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1070 break;
1071 }
1072 case OMPRTL__kmpc_global_thread_num: {
1073 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001074 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001075 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001076 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001077 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1078 break;
1079 }
Alexey Bataev97720002014-11-11 04:05:39 +00001080 case OMPRTL__kmpc_threadprivate_cached: {
1081 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1082 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1083 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1084 CGM.VoidPtrTy, CGM.SizeTy,
1085 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1086 llvm::FunctionType *FnTy =
1087 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1088 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1089 break;
1090 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001091 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001092 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1093 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001094 llvm::Type *TypeParams[] = {
1095 getIdentTyPointerTy(), CGM.Int32Ty,
1096 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1097 llvm::FunctionType *FnTy =
1098 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1099 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1100 break;
1101 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001102 case OMPRTL__kmpc_critical_with_hint: {
1103 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1104 // kmp_critical_name *crit, uintptr_t hint);
1105 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1106 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1107 CGM.IntPtrTy};
1108 llvm::FunctionType *FnTy =
1109 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1110 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1111 break;
1112 }
Alexey Bataev97720002014-11-11 04:05:39 +00001113 case OMPRTL__kmpc_threadprivate_register: {
1114 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1115 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1116 // typedef void *(*kmpc_ctor)(void *);
1117 auto KmpcCtorTy =
1118 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1119 /*isVarArg*/ false)->getPointerTo();
1120 // typedef void *(*kmpc_cctor)(void *, void *);
1121 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1122 auto KmpcCopyCtorTy =
1123 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1124 /*isVarArg*/ false)->getPointerTo();
1125 // typedef void (*kmpc_dtor)(void *);
1126 auto KmpcDtorTy =
1127 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1128 ->getPointerTo();
1129 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1130 KmpcCopyCtorTy, KmpcDtorTy};
1131 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1132 /*isVarArg*/ false);
1133 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1134 break;
1135 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001136 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001137 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1138 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001139 llvm::Type *TypeParams[] = {
1140 getIdentTyPointerTy(), CGM.Int32Ty,
1141 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1142 llvm::FunctionType *FnTy =
1143 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1144 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1145 break;
1146 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001147 case OMPRTL__kmpc_cancel_barrier: {
1148 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1149 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001150 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1151 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001152 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1153 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001154 break;
1155 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001156 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001157 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001158 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1159 llvm::FunctionType *FnTy =
1160 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1161 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1162 break;
1163 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001164 case OMPRTL__kmpc_for_static_fini: {
1165 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1166 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1167 llvm::FunctionType *FnTy =
1168 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1169 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1170 break;
1171 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001172 case OMPRTL__kmpc_push_num_threads: {
1173 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1174 // kmp_int32 num_threads)
1175 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1176 CGM.Int32Ty};
1177 llvm::FunctionType *FnTy =
1178 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1179 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1180 break;
1181 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001182 case OMPRTL__kmpc_serialized_parallel: {
1183 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1184 // global_tid);
1185 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1186 llvm::FunctionType *FnTy =
1187 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1188 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1189 break;
1190 }
1191 case OMPRTL__kmpc_end_serialized_parallel: {
1192 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1193 // global_tid);
1194 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1195 llvm::FunctionType *FnTy =
1196 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1197 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1198 break;
1199 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001200 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001201 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001202 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1203 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001204 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001205 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1206 break;
1207 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001208 case OMPRTL__kmpc_master: {
1209 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1210 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1211 llvm::FunctionType *FnTy =
1212 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1213 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1214 break;
1215 }
1216 case OMPRTL__kmpc_end_master: {
1217 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1218 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1219 llvm::FunctionType *FnTy =
1220 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1221 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1222 break;
1223 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001224 case OMPRTL__kmpc_omp_taskyield: {
1225 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1226 // int end_part);
1227 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1228 llvm::FunctionType *FnTy =
1229 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1230 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1231 break;
1232 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001233 case OMPRTL__kmpc_single: {
1234 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1235 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1236 llvm::FunctionType *FnTy =
1237 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1238 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1239 break;
1240 }
1241 case OMPRTL__kmpc_end_single: {
1242 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1243 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1244 llvm::FunctionType *FnTy =
1245 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1246 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1247 break;
1248 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001249 case OMPRTL__kmpc_omp_task_alloc: {
1250 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1251 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1252 // kmp_routine_entry_t *task_entry);
1253 assert(KmpRoutineEntryPtrTy != nullptr &&
1254 "Type kmp_routine_entry_t must be created.");
1255 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1256 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1257 // Return void * and then cast to particular kmp_task_t type.
1258 llvm::FunctionType *FnTy =
1259 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1260 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1261 break;
1262 }
1263 case OMPRTL__kmpc_omp_task: {
1264 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1265 // *new_task);
1266 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1267 CGM.VoidPtrTy};
1268 llvm::FunctionType *FnTy =
1269 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1270 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1271 break;
1272 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001273 case OMPRTL__kmpc_copyprivate: {
1274 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001275 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001276 // kmp_int32 didit);
1277 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1278 auto *CpyFnTy =
1279 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001280 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001281 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1282 CGM.Int32Ty};
1283 llvm::FunctionType *FnTy =
1284 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1285 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1286 break;
1287 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001288 case OMPRTL__kmpc_reduce: {
1289 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1290 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1291 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1292 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1293 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1294 /*isVarArg=*/false);
1295 llvm::Type *TypeParams[] = {
1296 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1297 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1298 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1299 llvm::FunctionType *FnTy =
1300 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1301 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1302 break;
1303 }
1304 case OMPRTL__kmpc_reduce_nowait: {
1305 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1306 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1307 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1308 // *lck);
1309 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1310 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1311 /*isVarArg=*/false);
1312 llvm::Type *TypeParams[] = {
1313 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1314 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1315 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1316 llvm::FunctionType *FnTy =
1317 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1318 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1319 break;
1320 }
1321 case OMPRTL__kmpc_end_reduce: {
1322 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1323 // kmp_critical_name *lck);
1324 llvm::Type *TypeParams[] = {
1325 getIdentTyPointerTy(), CGM.Int32Ty,
1326 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1327 llvm::FunctionType *FnTy =
1328 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1329 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1330 break;
1331 }
1332 case OMPRTL__kmpc_end_reduce_nowait: {
1333 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1334 // kmp_critical_name *lck);
1335 llvm::Type *TypeParams[] = {
1336 getIdentTyPointerTy(), CGM.Int32Ty,
1337 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1338 llvm::FunctionType *FnTy =
1339 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1340 RTLFn =
1341 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1342 break;
1343 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001344 case OMPRTL__kmpc_omp_task_begin_if0: {
1345 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1346 // *new_task);
1347 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1348 CGM.VoidPtrTy};
1349 llvm::FunctionType *FnTy =
1350 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1351 RTLFn =
1352 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1353 break;
1354 }
1355 case OMPRTL__kmpc_omp_task_complete_if0: {
1356 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1357 // *new_task);
1358 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1359 CGM.VoidPtrTy};
1360 llvm::FunctionType *FnTy =
1361 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1362 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1363 /*Name=*/"__kmpc_omp_task_complete_if0");
1364 break;
1365 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001366 case OMPRTL__kmpc_ordered: {
1367 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1368 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1369 llvm::FunctionType *FnTy =
1370 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1371 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1372 break;
1373 }
1374 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001375 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001376 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1377 llvm::FunctionType *FnTy =
1378 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1379 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1380 break;
1381 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001382 case OMPRTL__kmpc_omp_taskwait: {
1383 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1384 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1385 llvm::FunctionType *FnTy =
1386 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1387 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1388 break;
1389 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001390 case OMPRTL__kmpc_taskgroup: {
1391 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1392 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1393 llvm::FunctionType *FnTy =
1394 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1395 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1396 break;
1397 }
1398 case OMPRTL__kmpc_end_taskgroup: {
1399 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1400 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1401 llvm::FunctionType *FnTy =
1402 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1403 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1404 break;
1405 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001406 case OMPRTL__kmpc_push_proc_bind: {
1407 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1408 // int proc_bind)
1409 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1410 llvm::FunctionType *FnTy =
1411 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1412 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1413 break;
1414 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001415 case OMPRTL__kmpc_omp_task_with_deps: {
1416 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1417 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1418 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1419 llvm::Type *TypeParams[] = {
1420 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1421 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1422 llvm::FunctionType *FnTy =
1423 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1424 RTLFn =
1425 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1426 break;
1427 }
1428 case OMPRTL__kmpc_omp_wait_deps: {
1429 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1430 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1431 // kmp_depend_info_t *noalias_dep_list);
1432 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1433 CGM.Int32Ty, CGM.VoidPtrTy,
1434 CGM.Int32Ty, CGM.VoidPtrTy};
1435 llvm::FunctionType *FnTy =
1436 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1437 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1438 break;
1439 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001440 case OMPRTL__kmpc_cancellationpoint: {
1441 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1442 // global_tid, kmp_int32 cncl_kind)
1443 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1444 llvm::FunctionType *FnTy =
1445 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1446 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1447 break;
1448 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001449 case OMPRTL__kmpc_cancel: {
1450 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1451 // kmp_int32 cncl_kind)
1452 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1453 llvm::FunctionType *FnTy =
1454 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1455 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1456 break;
1457 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001458 case OMPRTL__kmpc_push_num_teams: {
1459 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1460 // kmp_int32 num_teams, kmp_int32 num_threads)
1461 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1462 CGM.Int32Ty};
1463 llvm::FunctionType *FnTy =
1464 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1465 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1466 break;
1467 }
1468 case OMPRTL__kmpc_fork_teams: {
1469 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1470 // microtask, ...);
1471 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1472 getKmpc_MicroPointerTy()};
1473 llvm::FunctionType *FnTy =
1474 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1475 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1476 break;
1477 }
Alexey Bataev7292c292016-04-25 12:22:29 +00001478 case OMPRTL__kmpc_taskloop: {
1479 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
1480 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
1481 // sched, kmp_uint64 grainsize, void *task_dup);
1482 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1483 CGM.IntTy,
1484 CGM.VoidPtrTy,
1485 CGM.IntTy,
1486 CGM.Int64Ty->getPointerTo(),
1487 CGM.Int64Ty->getPointerTo(),
1488 CGM.Int64Ty,
1489 CGM.IntTy,
1490 CGM.IntTy,
1491 CGM.Int64Ty,
1492 CGM.VoidPtrTy};
1493 llvm::FunctionType *FnTy =
1494 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1495 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
1496 break;
1497 }
Alexey Bataev8b427062016-05-25 12:36:08 +00001498 case OMPRTL__kmpc_doacross_init: {
1499 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32
1500 // num_dims, struct kmp_dim *dims);
1501 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1502 CGM.Int32Ty,
1503 CGM.Int32Ty,
1504 CGM.VoidPtrTy};
1505 llvm::FunctionType *FnTy =
1506 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1507 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init");
1508 break;
1509 }
1510 case OMPRTL__kmpc_doacross_fini: {
1511 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid);
1512 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1513 llvm::FunctionType *FnTy =
1514 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1515 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini");
1516 break;
1517 }
1518 case OMPRTL__kmpc_doacross_post: {
1519 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64
1520 // *vec);
1521 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1522 CGM.Int64Ty->getPointerTo()};
1523 llvm::FunctionType *FnTy =
1524 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1525 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post");
1526 break;
1527 }
1528 case OMPRTL__kmpc_doacross_wait: {
1529 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64
1530 // *vec);
1531 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1532 CGM.Int64Ty->getPointerTo()};
1533 llvm::FunctionType *FnTy =
1534 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1535 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait");
1536 break;
1537 }
Samuel Antaobed3c462015-10-02 16:14:20 +00001538 case OMPRTL__tgt_target: {
1539 // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
1540 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
1541 // *arg_types);
1542 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1543 CGM.VoidPtrTy,
1544 CGM.Int32Ty,
1545 CGM.VoidPtrPtrTy,
1546 CGM.VoidPtrPtrTy,
1547 CGM.SizeTy->getPointerTo(),
1548 CGM.Int32Ty->getPointerTo()};
1549 llvm::FunctionType *FnTy =
1550 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1551 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
1552 break;
1553 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00001554 case OMPRTL__tgt_target_teams: {
1555 // Build int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
1556 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
1557 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
1558 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1559 CGM.VoidPtrTy,
1560 CGM.Int32Ty,
1561 CGM.VoidPtrPtrTy,
1562 CGM.VoidPtrPtrTy,
1563 CGM.SizeTy->getPointerTo(),
1564 CGM.Int32Ty->getPointerTo(),
1565 CGM.Int32Ty,
1566 CGM.Int32Ty};
1567 llvm::FunctionType *FnTy =
1568 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1569 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
1570 break;
1571 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00001572 case OMPRTL__tgt_register_lib: {
1573 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
1574 QualType ParamTy =
1575 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1576 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1577 llvm::FunctionType *FnTy =
1578 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1579 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
1580 break;
1581 }
1582 case OMPRTL__tgt_unregister_lib: {
1583 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
1584 QualType ParamTy =
1585 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1586 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1587 llvm::FunctionType *FnTy =
1588 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1589 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
1590 break;
1591 }
Samuel Antaodf158d52016-04-27 22:58:19 +00001592 case OMPRTL__tgt_target_data_begin: {
1593 // Build void __tgt_target_data_begin(int32_t device_id, int32_t arg_num,
1594 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1595 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1596 CGM.Int32Ty,
1597 CGM.VoidPtrPtrTy,
1598 CGM.VoidPtrPtrTy,
1599 CGM.SizeTy->getPointerTo(),
1600 CGM.Int32Ty->getPointerTo()};
1601 llvm::FunctionType *FnTy =
1602 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1603 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin");
1604 break;
1605 }
1606 case OMPRTL__tgt_target_data_end: {
1607 // Build void __tgt_target_data_end(int32_t device_id, int32_t arg_num,
1608 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1609 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1610 CGM.Int32Ty,
1611 CGM.VoidPtrPtrTy,
1612 CGM.VoidPtrPtrTy,
1613 CGM.SizeTy->getPointerTo(),
1614 CGM.Int32Ty->getPointerTo()};
1615 llvm::FunctionType *FnTy =
1616 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1617 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end");
1618 break;
1619 }
Samuel Antao8d2d7302016-05-26 18:30:22 +00001620 case OMPRTL__tgt_target_data_update: {
1621 // Build void __tgt_target_data_update(int32_t device_id, int32_t arg_num,
1622 // void** args_base, void **args, size_t *arg_sizes, int32_t *arg_types);
1623 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1624 CGM.Int32Ty,
1625 CGM.VoidPtrPtrTy,
1626 CGM.VoidPtrPtrTy,
1627 CGM.SizeTy->getPointerTo(),
1628 CGM.Int32Ty->getPointerTo()};
1629 llvm::FunctionType *FnTy =
1630 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1631 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update");
1632 break;
1633 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001634 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00001635 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00001636 return RTLFn;
1637}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001638
Alexander Musman21212e42015-03-13 10:38:23 +00001639llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
1640 bool IVSigned) {
1641 assert((IVSize == 32 || IVSize == 64) &&
1642 "IV size is not compatible with the omp runtime");
1643 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
1644 : "__kmpc_for_static_init_4u")
1645 : (IVSigned ? "__kmpc_for_static_init_8"
1646 : "__kmpc_for_static_init_8u");
1647 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1648 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1649 llvm::Type *TypeParams[] = {
1650 getIdentTyPointerTy(), // loc
1651 CGM.Int32Ty, // tid
1652 CGM.Int32Ty, // schedtype
1653 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1654 PtrTy, // p_lower
1655 PtrTy, // p_upper
1656 PtrTy, // p_stride
1657 ITy, // incr
1658 ITy // chunk
1659 };
1660 llvm::FunctionType *FnTy =
1661 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1662 return CGM.CreateRuntimeFunction(FnTy, Name);
1663}
1664
Alexander Musman92bdaab2015-03-12 13:37:50 +00001665llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
1666 bool IVSigned) {
1667 assert((IVSize == 32 || IVSize == 64) &&
1668 "IV size is not compatible with the omp runtime");
1669 auto Name =
1670 IVSize == 32
1671 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
1672 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
1673 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1674 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
1675 CGM.Int32Ty, // tid
1676 CGM.Int32Ty, // schedtype
1677 ITy, // lower
1678 ITy, // upper
1679 ITy, // stride
1680 ITy // chunk
1681 };
1682 llvm::FunctionType *FnTy =
1683 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1684 return CGM.CreateRuntimeFunction(FnTy, Name);
1685}
1686
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001687llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
1688 bool IVSigned) {
1689 assert((IVSize == 32 || IVSize == 64) &&
1690 "IV size is not compatible with the omp runtime");
1691 auto Name =
1692 IVSize == 32
1693 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
1694 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
1695 llvm::Type *TypeParams[] = {
1696 getIdentTyPointerTy(), // loc
1697 CGM.Int32Ty, // tid
1698 };
1699 llvm::FunctionType *FnTy =
1700 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1701 return CGM.CreateRuntimeFunction(FnTy, Name);
1702}
1703
Alexander Musman92bdaab2015-03-12 13:37:50 +00001704llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
1705 bool IVSigned) {
1706 assert((IVSize == 32 || IVSize == 64) &&
1707 "IV size is not compatible with the omp runtime");
1708 auto Name =
1709 IVSize == 32
1710 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
1711 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
1712 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1713 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1714 llvm::Type *TypeParams[] = {
1715 getIdentTyPointerTy(), // loc
1716 CGM.Int32Ty, // tid
1717 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1718 PtrTy, // p_lower
1719 PtrTy, // p_upper
1720 PtrTy // p_stride
1721 };
1722 llvm::FunctionType *FnTy =
1723 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1724 return CGM.CreateRuntimeFunction(FnTy, Name);
1725}
1726
Alexey Bataev97720002014-11-11 04:05:39 +00001727llvm::Constant *
1728CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001729 assert(!CGM.getLangOpts().OpenMPUseTLS ||
1730 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00001731 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001732 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001733 Twine(CGM.getMangledName(VD)) + ".cache.");
1734}
1735
John McCall7f416cc2015-09-08 08:05:57 +00001736Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
1737 const VarDecl *VD,
1738 Address VDAddr,
1739 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001740 if (CGM.getLangOpts().OpenMPUseTLS &&
1741 CGM.getContext().getTargetInfo().isTLSSupported())
1742 return VDAddr;
1743
John McCall7f416cc2015-09-08 08:05:57 +00001744 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001745 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00001746 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1747 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001748 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
1749 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00001750 return Address(CGF.EmitRuntimeCall(
1751 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
1752 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00001753}
1754
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001755void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00001756 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00001757 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
1758 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
1759 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001760 auto OMPLoc = emitUpdateLocation(CGF, Loc);
1761 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00001762 OMPLoc);
1763 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
1764 // to register constructor/destructor for variable.
1765 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00001766 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1767 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001768 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001769 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001770 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001771}
1772
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001773llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00001774 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00001775 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001776 if (CGM.getLangOpts().OpenMPUseTLS &&
1777 CGM.getContext().getTargetInfo().isTLSSupported())
1778 return nullptr;
1779
Alexey Bataev97720002014-11-11 04:05:39 +00001780 VD = VD->getDefinition(CGM.getContext());
1781 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
1782 ThreadPrivateWithDefinition.insert(VD);
1783 QualType ASTTy = VD->getType();
1784
1785 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
1786 auto Init = VD->getAnyInitializer();
1787 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
1788 // Generate function that re-emits the declaration's initializer into the
1789 // threadprivate copy of the variable VD
1790 CodeGenFunction CtorCGF(CGM);
1791 FunctionArgList Args;
1792 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1793 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1794 Args.push_back(&Dst);
1795
John McCallc56a8b32016-03-11 04:30:31 +00001796 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1797 CGM.getContext().VoidPtrTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001798 auto FTy = CGM.getTypes().GetFunctionType(FI);
1799 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001800 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001801 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
1802 Args, SourceLocation());
1803 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001804 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001805 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001806 Address Arg = Address(ArgVal, VDAddr.getAlignment());
1807 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
1808 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00001809 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
1810 /*IsInitializer=*/true);
1811 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001812 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001813 CGM.getContext().VoidPtrTy, Dst.getLocation());
1814 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
1815 CtorCGF.FinishFunction();
1816 Ctor = Fn;
1817 }
1818 if (VD->getType().isDestructedType() != QualType::DK_none) {
1819 // Generate function that emits destructor call for the threadprivate copy
1820 // of the variable VD
1821 CodeGenFunction DtorCGF(CGM);
1822 FunctionArgList Args;
1823 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1824 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1825 Args.push_back(&Dst);
1826
John McCallc56a8b32016-03-11 04:30:31 +00001827 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1828 CGM.getContext().VoidTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001829 auto FTy = CGM.getTypes().GetFunctionType(FI);
1830 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001831 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00001832 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00001833 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
1834 SourceLocation());
Adrian Prantl1858c662016-04-24 22:22:29 +00001835 // Create a scope with an artificial location for the body of this function.
1836 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00001837 auto ArgVal = DtorCGF.EmitLoadOfScalar(
1838 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00001839 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
1840 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001841 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
1842 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
1843 DtorCGF.FinishFunction();
1844 Dtor = Fn;
1845 }
1846 // Do not emit init function if it is not required.
1847 if (!Ctor && !Dtor)
1848 return nullptr;
1849
1850 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1851 auto CopyCtorTy =
1852 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
1853 /*isVarArg=*/false)->getPointerTo();
1854 // Copying constructor for the threadprivate variable.
1855 // Must be NULL - reserved by runtime, but currently it requires that this
1856 // parameter is always NULL. Otherwise it fires assertion.
1857 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
1858 if (Ctor == nullptr) {
1859 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1860 /*isVarArg=*/false)->getPointerTo();
1861 Ctor = llvm::Constant::getNullValue(CtorTy);
1862 }
1863 if (Dtor == nullptr) {
1864 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
1865 /*isVarArg=*/false)->getPointerTo();
1866 Dtor = llvm::Constant::getNullValue(DtorTy);
1867 }
1868 if (!CGF) {
1869 auto InitFunctionTy =
1870 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
1871 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001872 InitFunctionTy, ".__omp_threadprivate_init_.",
1873 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00001874 CodeGenFunction InitCGF(CGM);
1875 FunctionArgList ArgList;
1876 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
1877 CGM.getTypes().arrangeNullaryFunction(), ArgList,
1878 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001879 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001880 InitCGF.FinishFunction();
1881 return InitFunction;
1882 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001883 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001884 }
1885 return nullptr;
1886}
1887
Alexey Bataev1d677132015-04-22 13:57:31 +00001888/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
1889/// function. Here is the logic:
1890/// if (Cond) {
1891/// ThenGen();
1892/// } else {
1893/// ElseGen();
1894/// }
1895static void emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
1896 const RegionCodeGenTy &ThenGen,
1897 const RegionCodeGenTy &ElseGen) {
1898 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
1899
1900 // If the condition constant folds and can be elided, try to avoid emitting
1901 // the condition and the dead arm of the if/else.
1902 bool CondConstant;
1903 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001904 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00001905 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001906 else
Alexey Bataev1d677132015-04-22 13:57:31 +00001907 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001908 return;
1909 }
1910
1911 // Otherwise, the condition did not fold, or we couldn't elide it. Just
1912 // emit the conditional branch.
1913 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
1914 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
1915 auto ContBlock = CGF.createBasicBlock("omp_if.end");
1916 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
1917
1918 // Emit the 'then' code.
1919 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001920 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001921 CGF.EmitBranch(ContBlock);
1922 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001923 // There is no need to emit line number for unconditional branch.
1924 (void)ApplyDebugLocation::CreateEmpty(CGF);
1925 CGF.EmitBlock(ElseBlock);
1926 ElseGen(CGF);
1927 // There is no need to emit line number for unconditional branch.
1928 (void)ApplyDebugLocation::CreateEmpty(CGF);
1929 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00001930 // Emit the continuation block for code after the if.
1931 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001932}
1933
Alexey Bataev1d677132015-04-22 13:57:31 +00001934void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
1935 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001936 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00001937 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001938 if (!CGF.HaveInsertPoint())
1939 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00001940 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001941 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
1942 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001943 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001944 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00001945 llvm::Value *Args[] = {
1946 RTLoc,
1947 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001948 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00001949 llvm::SmallVector<llvm::Value *, 16> RealArgs;
1950 RealArgs.append(std::begin(Args), std::end(Args));
1951 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
1952
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001953 auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001954 CGF.EmitRuntimeCall(RTLFn, RealArgs);
1955 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001956 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
1957 PrePostActionTy &) {
1958 auto &RT = CGF.CGM.getOpenMPRuntime();
1959 auto ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00001960 // Build calls:
1961 // __kmpc_serialized_parallel(&Loc, GTid);
1962 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001963 CGF.EmitRuntimeCall(
1964 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001965
Alexey Bataev1d677132015-04-22 13:57:31 +00001966 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001967 auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00001968 Address ZeroAddr =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001969 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
1970 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00001971 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00001972 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
1973 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
1974 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1975 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev1d677132015-04-22 13:57:31 +00001976 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001977
Alexey Bataev1d677132015-04-22 13:57:31 +00001978 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001979 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00001980 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001981 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
1982 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00001983 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001984 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00001985 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001986 else {
1987 RegionCodeGenTy ThenRCG(ThenGen);
1988 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00001989 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001990}
1991
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00001992// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00001993// thread-ID variable (it is passed in a first argument of the outlined function
1994// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
1995// regular serial code region, get thread ID by calling kmp_int32
1996// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
1997// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00001998Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
1999 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002000 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00002001 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002002 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00002003 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00002004
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002005 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00002006 auto Int32Ty =
2007 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2008 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2009 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00002010 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00002011
2012 return ThreadIDTemp;
2013}
2014
Alexey Bataev97720002014-11-11 04:05:39 +00002015llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002016CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00002017 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002018 SmallString<256> Buffer;
2019 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00002020 Out << Name;
2021 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00002022 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
2023 if (Elem.second) {
2024 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00002025 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00002026 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00002027 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002028
David Blaikie13156b62014-11-19 03:06:06 +00002029 return Elem.second = new llvm::GlobalVariable(
2030 CGM.getModule(), Ty, /*IsConstant*/ false,
2031 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2032 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00002033}
2034
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002035llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00002036 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002037 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002038}
2039
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002040namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002041/// Common pre(post)-action for different OpenMP constructs.
2042class CommonActionTy final : public PrePostActionTy {
2043 llvm::Value *EnterCallee;
2044 ArrayRef<llvm::Value *> EnterArgs;
2045 llvm::Value *ExitCallee;
2046 ArrayRef<llvm::Value *> ExitArgs;
2047 bool Conditional;
2048 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002049
2050public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002051 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
2052 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
2053 bool Conditional = false)
2054 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2055 ExitArgs(ExitArgs), Conditional(Conditional) {}
2056 void Enter(CodeGenFunction &CGF) override {
2057 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2058 if (Conditional) {
2059 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2060 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2061 ContBlock = CGF.createBasicBlock("omp_if.end");
2062 // Generate the branch (If-stmt)
2063 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2064 CGF.EmitBlock(ThenBlock);
2065 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00002066 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002067 void Done(CodeGenFunction &CGF) {
2068 // Emit the rest of blocks/branches
2069 CGF.EmitBranch(ContBlock);
2070 CGF.EmitBlock(ContBlock, true);
2071 }
2072 void Exit(CodeGenFunction &CGF) override {
2073 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00002074 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002075};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002076} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002077
2078void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2079 StringRef CriticalName,
2080 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00002081 SourceLocation Loc, const Expr *Hint) {
2082 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00002083 // CriticalOpGen();
2084 // __kmpc_end_critical(ident_t *, gtid, Lock);
2085 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00002086 if (!CGF.HaveInsertPoint())
2087 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00002088 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2089 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002090 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2091 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00002092 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002093 EnterArgs.push_back(CGF.Builder.CreateIntCast(
2094 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
2095 }
2096 CommonActionTy Action(
2097 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
2098 : OMPRTL__kmpc_critical),
2099 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
2100 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00002101 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00002102}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002103
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002104void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002105 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002106 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002107 if (!CGF.HaveInsertPoint())
2108 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00002109 // if(__kmpc_master(ident_t *, gtid)) {
2110 // MasterOpGen();
2111 // __kmpc_end_master(ident_t *, gtid);
2112 // }
2113 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002114 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002115 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2116 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2117 /*Conditional=*/true);
2118 MasterOpGen.setAction(Action);
2119 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2120 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002121}
2122
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002123void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2124 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002125 if (!CGF.HaveInsertPoint())
2126 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00002127 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2128 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002129 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00002130 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002131 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002132 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2133 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00002134}
2135
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002136void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2137 const RegionCodeGenTy &TaskgroupOpGen,
2138 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002139 if (!CGF.HaveInsertPoint())
2140 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002141 // __kmpc_taskgroup(ident_t *, gtid);
2142 // TaskgroupOpGen();
2143 // __kmpc_end_taskgroup(ident_t *, gtid);
2144 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002145 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2146 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2147 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2148 Args);
2149 TaskgroupOpGen.setAction(Action);
2150 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002151}
2152
John McCall7f416cc2015-09-08 08:05:57 +00002153/// Given an array of pointers to variables, project the address of a
2154/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002155static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2156 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00002157 // Pull out the pointer to the variable.
2158 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002159 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00002160 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2161
2162 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002163 Addr = CGF.Builder.CreateElementBitCast(
2164 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002165 return Addr;
2166}
2167
Alexey Bataeva63048e2015-03-23 06:18:07 +00002168static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00002169 CodeGenModule &CGM, llvm::Type *ArgsType,
2170 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
2171 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002172 auto &C = CGM.getContext();
2173 // void copy_func(void *LHSArg, void *RHSArg);
2174 FunctionArgList Args;
2175 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2176 C.VoidPtrTy);
2177 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2178 C.VoidPtrTy);
2179 Args.push_back(&LHSArg);
2180 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00002181 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002182 auto *Fn = llvm::Function::Create(
2183 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2184 ".omp.copyprivate.copy_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002185 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002186 CodeGenFunction CGF(CGM);
2187 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00002188 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002189 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00002190 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2191 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2192 ArgsType), CGF.getPointerAlign());
2193 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2194 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2195 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002196 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2197 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2198 // ...
2199 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00002200 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002201 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2202 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2203
2204 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2205 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2206
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002207 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2208 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00002209 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002210 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002211 CGF.FinishFunction();
2212 return Fn;
2213}
2214
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002215void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002216 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00002217 SourceLocation Loc,
2218 ArrayRef<const Expr *> CopyprivateVars,
2219 ArrayRef<const Expr *> SrcExprs,
2220 ArrayRef<const Expr *> DstExprs,
2221 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002222 if (!CGF.HaveInsertPoint())
2223 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002224 assert(CopyprivateVars.size() == SrcExprs.size() &&
2225 CopyprivateVars.size() == DstExprs.size() &&
2226 CopyprivateVars.size() == AssignmentOps.size());
2227 auto &C = CGM.getContext();
2228 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002229 // if(__kmpc_single(ident_t *, gtid)) {
2230 // SingleOpGen();
2231 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002232 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002233 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002234 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2235 // <copy_func>, did_it);
2236
John McCall7f416cc2015-09-08 08:05:57 +00002237 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00002238 if (!CopyprivateVars.empty()) {
2239 // int32 did_it = 0;
2240 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2241 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00002242 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002243 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002244 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002245 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002246 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
2247 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
2248 /*Conditional=*/true);
2249 SingleOpGen.setAction(Action);
2250 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2251 if (DidIt.isValid()) {
2252 // did_it = 1;
2253 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2254 }
2255 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002256 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2257 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00002258 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002259 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2260 auto CopyprivateArrayTy =
2261 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2262 /*IndexTypeQuals=*/0);
2263 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00002264 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00002265 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2266 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002267 Address Elem = CGF.Builder.CreateConstArrayGEP(
2268 CopyprivateList, I, CGF.getPointerSize());
2269 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00002270 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002271 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2272 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002273 }
2274 // Build function that copies private values from single region to all other
2275 // threads in the corresponding parallel region.
2276 auto *CpyFn = emitCopyprivateCopyFunction(
2277 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00002278 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev1189bd02016-01-26 12:20:39 +00002279 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00002280 Address CL =
2281 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2282 CGF.VoidPtrTy);
2283 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002284 llvm::Value *Args[] = {
2285 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2286 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00002287 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00002288 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00002289 CpyFn, // void (*) (void *, void *) <copy_func>
2290 DidItVal // i32 did_it
2291 };
2292 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2293 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002294}
2295
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002296void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2297 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00002298 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002299 if (!CGF.HaveInsertPoint())
2300 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002301 // __kmpc_ordered(ident_t *, gtid);
2302 // OrderedOpGen();
2303 // __kmpc_end_ordered(ident_t *, gtid);
2304 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00002305 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002306 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002307 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
2308 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2309 Args);
2310 OrderedOpGen.setAction(Action);
2311 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2312 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002313 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002314 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002315}
2316
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002317void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002318 OpenMPDirectiveKind Kind, bool EmitChecks,
2319 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002320 if (!CGF.HaveInsertPoint())
2321 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002322 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002323 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002324 unsigned Flags;
2325 if (Kind == OMPD_for)
2326 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2327 else if (Kind == OMPD_sections)
2328 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2329 else if (Kind == OMPD_single)
2330 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2331 else if (Kind == OMPD_barrier)
2332 Flags = OMP_IDENT_BARRIER_EXPL;
2333 else
2334 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002335 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2336 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002337 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2338 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002339 if (auto *OMPRegionInfo =
2340 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00002341 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002342 auto *Result = CGF.EmitRuntimeCall(
2343 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002344 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002345 // if (__kmpc_cancel_barrier()) {
2346 // exit from construct;
2347 // }
2348 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2349 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2350 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2351 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2352 CGF.EmitBlock(ExitBB);
2353 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002354 auto CancelDestination =
2355 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002356 CGF.EmitBranchThroughCleanup(CancelDestination);
2357 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2358 }
2359 return;
2360 }
2361 }
2362 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002363}
2364
Alexander Musmanc6388682014-12-15 07:07:06 +00002365/// \brief Map the OpenMP loop schedule to the runtime enumeration.
2366static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002367 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002368 switch (ScheduleKind) {
2369 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002370 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2371 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00002372 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002373 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002374 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002375 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002376 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002377 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2378 case OMPC_SCHEDULE_auto:
2379 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00002380 case OMPC_SCHEDULE_unknown:
2381 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002382 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00002383 }
2384 llvm_unreachable("Unexpected runtime schedule");
2385}
2386
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002387/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
2388static OpenMPSchedType
2389getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2390 // only static is allowed for dist_schedule
2391 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
2392}
2393
Alexander Musmanc6388682014-12-15 07:07:06 +00002394bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2395 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002396 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00002397 return Schedule == OMP_sch_static;
2398}
2399
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002400bool CGOpenMPRuntime::isStaticNonchunked(
2401 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2402 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2403 return Schedule == OMP_dist_sch_static;
2404}
2405
2406
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002407bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002408 auto Schedule =
2409 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002410 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2411 return Schedule != OMP_sch_static;
2412}
2413
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002414static int addMonoNonMonoModifier(OpenMPSchedType Schedule,
2415 OpenMPScheduleClauseModifier M1,
2416 OpenMPScheduleClauseModifier M2) {
Alexey Bataev6cff6242016-05-30 13:05:14 +00002417 int Modifier = 0;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002418 switch (M1) {
2419 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002420 Modifier = OMP_sch_modifier_monotonic;
2421 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002422 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002423 Modifier = OMP_sch_modifier_nonmonotonic;
2424 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002425 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002426 if (Schedule == OMP_sch_static_chunked)
2427 Schedule = OMP_sch_static_balanced_chunked;
2428 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002429 case OMPC_SCHEDULE_MODIFIER_last:
2430 case OMPC_SCHEDULE_MODIFIER_unknown:
2431 break;
2432 }
2433 switch (M2) {
2434 case OMPC_SCHEDULE_MODIFIER_monotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002435 Modifier = OMP_sch_modifier_monotonic;
2436 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002437 case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002438 Modifier = OMP_sch_modifier_nonmonotonic;
2439 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002440 case OMPC_SCHEDULE_MODIFIER_simd:
Alexey Bataev6cff6242016-05-30 13:05:14 +00002441 if (Schedule == OMP_sch_static_chunked)
2442 Schedule = OMP_sch_static_balanced_chunked;
2443 break;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002444 case OMPC_SCHEDULE_MODIFIER_last:
2445 case OMPC_SCHEDULE_MODIFIER_unknown:
2446 break;
2447 }
Alexey Bataev6cff6242016-05-30 13:05:14 +00002448 return Schedule | Modifier;
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002449}
2450
John McCall7f416cc2015-09-08 08:05:57 +00002451void CGOpenMPRuntime::emitForDispatchInit(CodeGenFunction &CGF,
2452 SourceLocation Loc,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002453 const OpenMPScheduleTy &ScheduleKind,
John McCall7f416cc2015-09-08 08:05:57 +00002454 unsigned IVSize, bool IVSigned,
2455 bool Ordered, llvm::Value *UB,
2456 llvm::Value *Chunk) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002457 if (!CGF.HaveInsertPoint())
2458 return;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002459 OpenMPSchedType Schedule =
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002460 getRuntimeSchedule(ScheduleKind.Schedule, Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00002461 assert(Ordered ||
2462 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
Alexey Bataev6cff6242016-05-30 13:05:14 +00002463 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
2464 Schedule != OMP_sch_static_balanced_chunked));
John McCall7f416cc2015-09-08 08:05:57 +00002465 // Call __kmpc_dispatch_init(
2466 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2467 // kmp_int[32|64] lower, kmp_int[32|64] upper,
2468 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002469
John McCall7f416cc2015-09-08 08:05:57 +00002470 // If the Chunk was not specified in the clause - use default value 1.
2471 if (Chunk == nullptr)
2472 Chunk = CGF.Builder.getIntN(IVSize, 1);
2473 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002474 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2475 CGF.Builder.getInt32(addMonoNonMonoModifier(
2476 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
2477 CGF.Builder.getIntN(IVSize, 0), // Lower
2478 UB, // Upper
2479 CGF.Builder.getIntN(IVSize, 1), // Stride
2480 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00002481 };
2482 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2483}
2484
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002485static void emitForStaticInitCall(
2486 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
2487 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule,
2488 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
2489 unsigned IVSize, bool Ordered, Address IL, Address LB, Address UB,
2490 Address ST, llvm::Value *Chunk) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002491 if (!CGF.HaveInsertPoint())
2492 return;
2493
2494 assert(!Ordered);
2495 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
Alexey Bataev6cff6242016-05-30 13:05:14 +00002496 Schedule == OMP_sch_static_balanced_chunked ||
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002497 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
2498 Schedule == OMP_dist_sch_static ||
2499 Schedule == OMP_dist_sch_static_chunked);
2500
2501 // Call __kmpc_for_static_init(
2502 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2503 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2504 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2505 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
2506 if (Chunk == nullptr) {
2507 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
2508 Schedule == OMP_dist_sch_static) &&
2509 "expected static non-chunked schedule");
2510 // If the Chunk was not specified in the clause - use default value 1.
2511 Chunk = CGF.Builder.getIntN(IVSize, 1);
2512 } else {
2513 assert((Schedule == OMP_sch_static_chunked ||
Alexey Bataev6cff6242016-05-30 13:05:14 +00002514 Schedule == OMP_sch_static_balanced_chunked ||
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002515 Schedule == OMP_ord_static_chunked ||
2516 Schedule == OMP_dist_sch_static_chunked) &&
2517 "expected static chunked schedule");
2518 }
2519 llvm::Value *Args[] = {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002520 UpdateLocation, ThreadId, CGF.Builder.getInt32(addMonoNonMonoModifier(
2521 Schedule, M1, M2)), // Schedule type
2522 IL.getPointer(), // &isLastIter
2523 LB.getPointer(), // &LB
2524 UB.getPointer(), // &UB
2525 ST.getPointer(), // &Stride
2526 CGF.Builder.getIntN(IVSize, 1), // Incr
2527 Chunk // Chunk
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002528 };
2529 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
2530}
2531
John McCall7f416cc2015-09-08 08:05:57 +00002532void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
2533 SourceLocation Loc,
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002534 const OpenMPScheduleTy &ScheduleKind,
John McCall7f416cc2015-09-08 08:05:57 +00002535 unsigned IVSize, bool IVSigned,
2536 bool Ordered, Address IL, Address LB,
2537 Address UB, Address ST,
2538 llvm::Value *Chunk) {
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002539 OpenMPSchedType ScheduleNum =
2540 getRuntimeSchedule(ScheduleKind.Schedule, Chunk != nullptr, Ordered);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002541 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2542 auto *ThreadId = getThreadID(CGF, Loc);
2543 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002544 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
2545 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, IVSize,
2546 Ordered, IL, LB, UB, ST, Chunk);
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002547}
John McCall7f416cc2015-09-08 08:05:57 +00002548
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002549void CGOpenMPRuntime::emitDistributeStaticInit(
2550 CodeGenFunction &CGF, SourceLocation Loc,
2551 OpenMPDistScheduleClauseKind SchedKind, unsigned IVSize, bool IVSigned,
2552 bool Ordered, Address IL, Address LB, Address UB, Address ST,
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002553 llvm::Value *Chunk) {
2554 OpenMPSchedType ScheduleNum = getRuntimeSchedule(SchedKind, Chunk != nullptr);
2555 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2556 auto *ThreadId = getThreadID(CGF, Loc);
2557 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
Alexey Bataev9ebd7422016-05-10 09:57:36 +00002558 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
2559 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
2560 OMPC_SCHEDULE_MODIFIER_unknown, IVSize, Ordered, IL, LB,
2561 UB, ST, Chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002562}
2563
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002564void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
2565 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002566 if (!CGF.HaveInsertPoint())
2567 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00002568 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002569 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002570 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
2571 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00002572}
2573
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002574void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
2575 SourceLocation Loc,
2576 unsigned IVSize,
2577 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002578 if (!CGF.HaveInsertPoint())
2579 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002580 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002581 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002582 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
2583}
2584
Alexander Musman92bdaab2015-03-12 13:37:50 +00002585llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
2586 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00002587 bool IVSigned, Address IL,
2588 Address LB, Address UB,
2589 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00002590 // Call __kmpc_dispatch_next(
2591 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
2592 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
2593 // kmp_int[32|64] *p_stride);
2594 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00002595 emitUpdateLocation(CGF, Loc),
2596 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002597 IL.getPointer(), // &isLastIter
2598 LB.getPointer(), // &Lower
2599 UB.getPointer(), // &Upper
2600 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00002601 };
2602 llvm::Value *Call =
2603 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
2604 return CGF.EmitScalarConversion(
2605 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002606 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002607}
2608
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002609void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
2610 llvm::Value *NumThreads,
2611 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002612 if (!CGF.HaveInsertPoint())
2613 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00002614 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
2615 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002616 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00002617 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002618 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
2619 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00002620}
2621
Alexey Bataev7f210c62015-06-18 13:40:03 +00002622void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
2623 OpenMPProcBindClauseKind ProcBind,
2624 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002625 if (!CGF.HaveInsertPoint())
2626 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00002627 // Constants for proc bind value accepted by the runtime.
2628 enum ProcBindTy {
2629 ProcBindFalse = 0,
2630 ProcBindTrue,
2631 ProcBindMaster,
2632 ProcBindClose,
2633 ProcBindSpread,
2634 ProcBindIntel,
2635 ProcBindDefault
2636 } RuntimeProcBind;
2637 switch (ProcBind) {
2638 case OMPC_PROC_BIND_master:
2639 RuntimeProcBind = ProcBindMaster;
2640 break;
2641 case OMPC_PROC_BIND_close:
2642 RuntimeProcBind = ProcBindClose;
2643 break;
2644 case OMPC_PROC_BIND_spread:
2645 RuntimeProcBind = ProcBindSpread;
2646 break;
2647 case OMPC_PROC_BIND_unknown:
2648 llvm_unreachable("Unsupported proc_bind value.");
2649 }
2650 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
2651 llvm::Value *Args[] = {
2652 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2653 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
2654 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
2655}
2656
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002657void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
2658 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002659 if (!CGF.HaveInsertPoint())
2660 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00002661 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002662 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
2663 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002664}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002665
Alexey Bataev62b63b12015-03-10 07:28:44 +00002666namespace {
2667/// \brief Indexes of fields for type kmp_task_t.
2668enum KmpTaskTFields {
2669 /// \brief List of shared variables.
2670 KmpTaskTShareds,
2671 /// \brief Task routine.
2672 KmpTaskTRoutine,
2673 /// \brief Partition id for the untied tasks.
2674 KmpTaskTPartId,
Alexey Bataevad537bb2016-05-30 09:06:50 +00002675 /// Function with call of destructors for private variables.
2676 Data1,
2677 /// Task priority.
2678 Data2,
Alexey Bataev7292c292016-04-25 12:22:29 +00002679 /// (Taskloops only) Lower bound.
2680 KmpTaskTLowerBound,
2681 /// (Taskloops only) Upper bound.
2682 KmpTaskTUpperBound,
2683 /// (Taskloops only) Stride.
2684 KmpTaskTStride,
2685 /// (Taskloops only) Is last iteration flag.
2686 KmpTaskTLastIter,
Alexey Bataev62b63b12015-03-10 07:28:44 +00002687};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002688} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00002689
Samuel Antaoee8fb302016-01-06 13:42:12 +00002690bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
2691 // FIXME: Add other entries type when they become supported.
2692 return OffloadEntriesTargetRegion.empty();
2693}
2694
2695/// \brief Initialize target region entry.
2696void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2697 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2698 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00002699 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002700 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
2701 "only required for the device "
2702 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00002703 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002704 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr);
2705 ++OffloadingEntriesNum;
2706}
2707
2708void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2709 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2710 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00002711 llvm::Constant *Addr, llvm::Constant *ID) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002712 // If we are emitting code for a target, the entry is already initialized,
2713 // only has to be registered.
2714 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00002715 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00002716 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00002717 auto &Entry =
2718 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00002719 assert(Entry.isValid() && "Entry not initialized!");
2720 Entry.setAddress(Addr);
2721 Entry.setID(ID);
2722 return;
2723 } else {
2724 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID);
Samuel Antao2de62b02016-02-13 23:35:10 +00002725 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002726 }
2727}
2728
2729bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00002730 unsigned DeviceID, unsigned FileID, StringRef ParentName,
2731 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002732 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
2733 if (PerDevice == OffloadEntriesTargetRegion.end())
2734 return false;
2735 auto PerFile = PerDevice->second.find(FileID);
2736 if (PerFile == PerDevice->second.end())
2737 return false;
2738 auto PerParentName = PerFile->second.find(ParentName);
2739 if (PerParentName == PerFile->second.end())
2740 return false;
2741 auto PerLine = PerParentName->second.find(LineNum);
2742 if (PerLine == PerParentName->second.end())
2743 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002744 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00002745 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00002746 return false;
2747 return true;
2748}
2749
2750void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
2751 const OffloadTargetRegionEntryInfoActTy &Action) {
2752 // Scan all target region entries and perform the provided action.
2753 for (auto &D : OffloadEntriesTargetRegion)
2754 for (auto &F : D.second)
2755 for (auto &P : F.second)
2756 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00002757 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002758}
2759
2760/// \brief Create a Ctor/Dtor-like function whose body is emitted through
2761/// \a Codegen. This is used to emit the two functions that register and
2762/// unregister the descriptor of the current compilation unit.
2763static llvm::Function *
2764createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
2765 const RegionCodeGenTy &Codegen) {
2766 auto &C = CGM.getContext();
2767 FunctionArgList Args;
2768 ImplicitParamDecl DummyPtr(C, /*DC=*/nullptr, SourceLocation(),
2769 /*Id=*/nullptr, C.VoidPtrTy);
2770 Args.push_back(&DummyPtr);
2771
2772 CodeGenFunction CGF(CGM);
John McCallc56a8b32016-03-11 04:30:31 +00002773 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002774 auto FTy = CGM.getTypes().GetFunctionType(FI);
2775 auto *Fn =
2776 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
2777 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
2778 Codegen(CGF);
2779 CGF.FinishFunction();
2780 return Fn;
2781}
2782
2783llvm::Function *
2784CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
2785
2786 // If we don't have entries or if we are emitting code for the device, we
2787 // don't need to do anything.
2788 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
2789 return nullptr;
2790
2791 auto &M = CGM.getModule();
2792 auto &C = CGM.getContext();
2793
2794 // Get list of devices we care about
2795 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
2796
2797 // We should be creating an offloading descriptor only if there are devices
2798 // specified.
2799 assert(!Devices.empty() && "No OpenMP offloading devices??");
2800
2801 // Create the external variables that will point to the begin and end of the
2802 // host entries section. These will be defined by the linker.
2803 auto *OffloadEntryTy =
2804 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
2805 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
2806 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002807 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002808 ".omp_offloading.entries_begin");
2809 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
2810 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002811 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002812 ".omp_offloading.entries_end");
2813
2814 // Create all device images
Samuel Antaoee8fb302016-01-06 13:42:12 +00002815 auto *DeviceImageTy = cast<llvm::StructType>(
2816 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00002817 ConstantInitBuilder DeviceImagesBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002818 auto DeviceImagesEntries = DeviceImagesBuilder.beginArray(DeviceImageTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002819
2820 for (unsigned i = 0; i < Devices.size(); ++i) {
2821 StringRef T = Devices[i].getTriple();
2822 auto *ImgBegin = new llvm::GlobalVariable(
2823 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002824 /*Initializer=*/nullptr,
2825 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002826 auto *ImgEnd = new llvm::GlobalVariable(
2827 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002828 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002829
John McCall6c9f1fdb2016-11-19 08:17:24 +00002830 auto Dev = DeviceImagesEntries.beginStruct(DeviceImageTy);
2831 Dev.add(ImgBegin);
2832 Dev.add(ImgEnd);
2833 Dev.add(HostEntriesBegin);
2834 Dev.add(HostEntriesEnd);
John McCallf1788632016-11-28 22:18:30 +00002835 Dev.finishAndAddTo(DeviceImagesEntries);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002836 }
2837
2838 // Create device images global array.
John McCall6c9f1fdb2016-11-19 08:17:24 +00002839 llvm::GlobalVariable *DeviceImages =
2840 DeviceImagesEntries.finishAndCreateGlobal(".omp_offloading.device_images",
2841 CGM.getPointerAlign(),
2842 /*isConstant=*/true);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002843 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002844
2845 // This is a Zero array to be used in the creation of the constant expressions
2846 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
2847 llvm::Constant::getNullValue(CGM.Int32Ty)};
2848
2849 // Create the target region descriptor.
2850 auto *BinaryDescriptorTy = cast<llvm::StructType>(
2851 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
John McCall23c9dc62016-11-28 22:18:27 +00002852 ConstantInitBuilder DescBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002853 auto DescInit = DescBuilder.beginStruct(BinaryDescriptorTy);
2854 DescInit.addInt(CGM.Int32Ty, Devices.size());
2855 DescInit.add(llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(),
2856 DeviceImages,
2857 Index));
2858 DescInit.add(HostEntriesBegin);
2859 DescInit.add(HostEntriesEnd);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002860
John McCall6c9f1fdb2016-11-19 08:17:24 +00002861 auto *Desc = DescInit.finishAndCreateGlobal(".omp_offloading.descriptor",
2862 CGM.getPointerAlign(),
2863 /*isConstant=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002864
2865 // Emit code to register or unregister the descriptor at execution
2866 // startup or closing, respectively.
2867
2868 // Create a variable to drive the registration and unregistration of the
2869 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
2870 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
2871 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
2872 IdentInfo, C.CharTy);
2873
2874 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002875 CGM, ".omp_offloading.descriptor_unreg",
2876 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002877 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
2878 Desc);
2879 });
2880 auto *RegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002881 CGM, ".omp_offloading.descriptor_reg",
2882 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002883 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_register_lib),
2884 Desc);
2885 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
2886 });
2887 return RegFn;
2888}
2889
Samuel Antao2de62b02016-02-13 23:35:10 +00002890void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
2891 llvm::Constant *Addr, uint64_t Size) {
2892 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00002893 auto *TgtOffloadEntryType = cast<llvm::StructType>(
2894 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
2895 llvm::LLVMContext &C = CGM.getModule().getContext();
2896 llvm::Module &M = CGM.getModule();
2897
2898 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00002899 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002900
2901 // Create constant string with the name.
2902 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
2903
2904 llvm::GlobalVariable *Str =
2905 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
2906 llvm::GlobalValue::InternalLinkage, StrPtrInit,
2907 ".omp_offloading.entry_name");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002908 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002909 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
2910
John McCall6c9f1fdb2016-11-19 08:17:24 +00002911 // We can't have any padding between symbols, so we need to have 1-byte
2912 // alignment.
2913 auto Align = CharUnits::fromQuantity(1);
2914
Samuel Antaoee8fb302016-01-06 13:42:12 +00002915 // Create the entry struct.
John McCall23c9dc62016-11-28 22:18:27 +00002916 ConstantInitBuilder EntryBuilder(CGM);
John McCall6c9f1fdb2016-11-19 08:17:24 +00002917 auto EntryInit = EntryBuilder.beginStruct(TgtOffloadEntryType);
2918 EntryInit.add(AddrPtr);
2919 EntryInit.add(StrPtr);
2920 EntryInit.addInt(CGM.SizeTy, Size);
2921 llvm::GlobalVariable *Entry =
2922 EntryInit.finishAndCreateGlobal(".omp_offloading.entry",
2923 Align,
2924 /*constant*/ true,
2925 llvm::GlobalValue::ExternalLinkage);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002926
2927 // The entry has to be created in the section the linker expects it to be.
2928 Entry->setSection(".omp_offloading.entries");
Samuel Antaoee8fb302016-01-06 13:42:12 +00002929}
2930
2931void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
2932 // Emit the offloading entries and metadata so that the device codegen side
Samuel Antao4c8035b2016-12-12 18:00:20 +00002933 // can easily figure out what to emit. The produced metadata looks like
2934 // this:
Samuel Antaoee8fb302016-01-06 13:42:12 +00002935 //
2936 // !omp_offload.info = !{!1, ...}
2937 //
2938 // Right now we only generate metadata for function that contain target
2939 // regions.
2940
2941 // If we do not have entries, we dont need to do anything.
2942 if (OffloadEntriesInfoManager.empty())
2943 return;
2944
2945 llvm::Module &M = CGM.getModule();
2946 llvm::LLVMContext &C = M.getContext();
2947 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
2948 OrderedEntries(OffloadEntriesInfoManager.size());
2949
2950 // Create the offloading info metadata node.
2951 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
2952
2953 // Auxiliar methods to create metadata values and strings.
2954 auto getMDInt = [&](unsigned v) {
2955 return llvm::ConstantAsMetadata::get(
2956 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
2957 };
2958
2959 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
2960
2961 // Create function that emits metadata for each target region entry;
2962 auto &&TargetRegionMetadataEmitter = [&](
2963 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002964 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
2965 llvm::SmallVector<llvm::Metadata *, 32> Ops;
2966 // Generate metadata for target regions. Each entry of this metadata
2967 // contains:
2968 // - Entry 0 -> Kind of this type of metadata (0).
2969 // - Entry 1 -> Device ID of the file where the entry was identified.
2970 // - Entry 2 -> File ID of the file where the entry was identified.
2971 // - Entry 3 -> Mangled name of the function where the entry was identified.
2972 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00002973 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00002974 // The first element of the metadata node is the kind.
2975 Ops.push_back(getMDInt(E.getKind()));
2976 Ops.push_back(getMDInt(DeviceID));
2977 Ops.push_back(getMDInt(FileID));
2978 Ops.push_back(getMDString(ParentName));
2979 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002980 Ops.push_back(getMDInt(E.getOrder()));
2981
2982 // Save this entry in the right position of the ordered entries array.
2983 OrderedEntries[E.getOrder()] = &E;
2984
2985 // Add metadata to the named metadata node.
2986 MD->addOperand(llvm::MDNode::get(C, Ops));
2987 };
2988
2989 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
2990 TargetRegionMetadataEmitter);
2991
2992 for (auto *E : OrderedEntries) {
2993 assert(E && "All ordered entries must exist!");
2994 if (auto *CE =
2995 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
2996 E)) {
2997 assert(CE->getID() && CE->getAddress() &&
2998 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00002999 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00003000 } else
3001 llvm_unreachable("Unsupported entry kind.");
3002 }
3003}
3004
3005/// \brief Loads all the offload entries information from the host IR
3006/// metadata.
3007void CGOpenMPRuntime::loadOffloadInfoMetadata() {
3008 // If we are in target mode, load the metadata from the host IR. This code has
3009 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
3010
3011 if (!CGM.getLangOpts().OpenMPIsDevice)
3012 return;
3013
3014 if (CGM.getLangOpts().OMPHostIRFile.empty())
3015 return;
3016
3017 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
3018 if (Buf.getError())
3019 return;
3020
3021 llvm::LLVMContext C;
Peter Collingbourned9445c42016-11-13 07:00:17 +00003022 auto ME = expectedToErrorOrAndEmitErrors(
3023 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003024
3025 if (ME.getError())
3026 return;
3027
3028 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
3029 if (!MD)
3030 return;
3031
3032 for (auto I : MD->operands()) {
3033 llvm::MDNode *MN = cast<llvm::MDNode>(I);
3034
3035 auto getMDInt = [&](unsigned Idx) {
3036 llvm::ConstantAsMetadata *V =
3037 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
3038 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
3039 };
3040
3041 auto getMDString = [&](unsigned Idx) {
3042 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
3043 return V->getString();
3044 };
3045
3046 switch (getMDInt(0)) {
3047 default:
3048 llvm_unreachable("Unexpected metadata!");
3049 break;
3050 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3051 OFFLOAD_ENTRY_INFO_TARGET_REGION:
3052 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
3053 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
3054 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00003055 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00003056 break;
3057 }
3058 }
3059}
3060
Alexey Bataev62b63b12015-03-10 07:28:44 +00003061void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
3062 if (!KmpRoutineEntryPtrTy) {
3063 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
3064 auto &C = CGM.getContext();
3065 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
3066 FunctionProtoType::ExtProtoInfo EPI;
3067 KmpRoutineEntryPtrQTy = C.getPointerType(
3068 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
3069 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
3070 }
3071}
3072
Alexey Bataevc71a4092015-09-11 10:29:41 +00003073static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
3074 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003075 auto *Field = FieldDecl::Create(
3076 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
3077 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
3078 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
3079 Field->setAccess(AS_public);
3080 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003081 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003082}
3083
Samuel Antaoee8fb302016-01-06 13:42:12 +00003084QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
3085
3086 // Make sure the type of the entry is already created. This is the type we
3087 // have to create:
3088 // struct __tgt_offload_entry{
3089 // void *addr; // Pointer to the offload entry info.
3090 // // (function or global)
3091 // char *name; // Name of the function or global.
3092 // size_t size; // Size of the entry info (0 if it a function).
3093 // };
3094 if (TgtOffloadEntryQTy.isNull()) {
3095 ASTContext &C = CGM.getContext();
3096 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
3097 RD->startDefinition();
3098 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3099 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
3100 addFieldToRecordDecl(C, RD, C.getSizeType());
3101 RD->completeDefinition();
3102 TgtOffloadEntryQTy = C.getRecordType(RD);
3103 }
3104 return TgtOffloadEntryQTy;
3105}
3106
3107QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
3108 // These are the types we need to build:
3109 // struct __tgt_device_image{
3110 // void *ImageStart; // Pointer to the target code start.
3111 // void *ImageEnd; // Pointer to the target code end.
3112 // // We also add the host entries to the device image, as it may be useful
3113 // // for the target runtime to have access to that information.
3114 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
3115 // // the entries.
3116 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3117 // // entries (non inclusive).
3118 // };
3119 if (TgtDeviceImageQTy.isNull()) {
3120 ASTContext &C = CGM.getContext();
3121 auto *RD = C.buildImplicitRecord("__tgt_device_image");
3122 RD->startDefinition();
3123 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3124 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3125 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3126 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3127 RD->completeDefinition();
3128 TgtDeviceImageQTy = C.getRecordType(RD);
3129 }
3130 return TgtDeviceImageQTy;
3131}
3132
3133QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
3134 // struct __tgt_bin_desc{
3135 // int32_t NumDevices; // Number of devices supported.
3136 // __tgt_device_image *DeviceImages; // Arrays of device images
3137 // // (one per device).
3138 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
3139 // // entries.
3140 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
3141 // // entries (non inclusive).
3142 // };
3143 if (TgtBinaryDescriptorQTy.isNull()) {
3144 ASTContext &C = CGM.getContext();
3145 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
3146 RD->startDefinition();
3147 addFieldToRecordDecl(
3148 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3149 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
3150 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3151 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
3152 RD->completeDefinition();
3153 TgtBinaryDescriptorQTy = C.getRecordType(RD);
3154 }
3155 return TgtBinaryDescriptorQTy;
3156}
3157
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003158namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00003159struct PrivateHelpersTy {
3160 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
3161 const VarDecl *PrivateElemInit)
3162 : Original(Original), PrivateCopy(PrivateCopy),
3163 PrivateElemInit(PrivateElemInit) {}
3164 const VarDecl *Original;
3165 const VarDecl *PrivateCopy;
3166 const VarDecl *PrivateElemInit;
3167};
3168typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00003169} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003170
Alexey Bataev9e034042015-05-05 04:05:12 +00003171static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00003172createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003173 if (!Privates.empty()) {
3174 auto &C = CGM.getContext();
3175 // Build struct .kmp_privates_t. {
3176 // /* private vars */
3177 // };
3178 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
3179 RD->startDefinition();
3180 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00003181 auto *VD = Pair.second.Original;
3182 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003183 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00003184 auto *FD = addFieldToRecordDecl(C, RD, Type);
3185 if (VD->hasAttrs()) {
3186 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
3187 E(VD->getAttrs().end());
3188 I != E; ++I)
3189 FD->addAttr(*I);
3190 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003191 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003192 RD->completeDefinition();
3193 return RD;
3194 }
3195 return nullptr;
3196}
3197
Alexey Bataev9e034042015-05-05 04:05:12 +00003198static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00003199createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
3200 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003201 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003202 auto &C = CGM.getContext();
3203 // Build struct kmp_task_t {
3204 // void * shareds;
3205 // kmp_routine_entry_t routine;
3206 // kmp_int32 part_id;
Alexey Bataevad537bb2016-05-30 09:06:50 +00003207 // kmp_cmplrdata_t data1;
3208 // kmp_cmplrdata_t data2;
Alexey Bataev7292c292016-04-25 12:22:29 +00003209 // For taskloops additional fields:
3210 // kmp_uint64 lb;
3211 // kmp_uint64 ub;
3212 // kmp_int64 st;
3213 // kmp_int32 liter;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003214 // };
Alexey Bataevad537bb2016-05-30 09:06:50 +00003215 auto *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
3216 UD->startDefinition();
3217 addFieldToRecordDecl(C, UD, KmpInt32Ty);
3218 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
3219 UD->completeDefinition();
3220 QualType KmpCmplrdataTy = C.getRecordType(UD);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003221 auto *RD = C.buildImplicitRecord("kmp_task_t");
3222 RD->startDefinition();
3223 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3224 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
3225 addFieldToRecordDecl(C, RD, KmpInt32Ty);
Alexey Bataevad537bb2016-05-30 09:06:50 +00003226 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3227 addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003228 if (isOpenMPTaskLoopDirective(Kind)) {
3229 QualType KmpUInt64Ty =
3230 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3231 QualType KmpInt64Ty =
3232 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3233 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3234 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3235 addFieldToRecordDecl(C, RD, KmpInt64Ty);
3236 addFieldToRecordDecl(C, RD, KmpInt32Ty);
3237 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003238 RD->completeDefinition();
3239 return RD;
3240}
3241
3242static RecordDecl *
3243createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003244 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003245 auto &C = CGM.getContext();
3246 // Build struct kmp_task_t_with_privates {
3247 // kmp_task_t task_data;
3248 // .kmp_privates_t. privates;
3249 // };
3250 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
3251 RD->startDefinition();
3252 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003253 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
3254 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
3255 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003256 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003257 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003258}
3259
3260/// \brief Emit a proxy function which accepts kmp_task_t as the second
3261/// argument.
3262/// \code
3263/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003264/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00003265/// For taskloops:
3266/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003267/// tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003268/// return 0;
3269/// }
3270/// \endcode
3271static llvm::Value *
3272emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00003273 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
3274 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003275 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003276 QualType SharedsPtrTy, llvm::Value *TaskFunction,
3277 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003278 auto &C = CGM.getContext();
3279 FunctionArgList Args;
3280 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
3281 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00003282 /*Id=*/nullptr,
3283 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003284 Args.push_back(&GtidArg);
3285 Args.push_back(&TaskTypeArg);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003286 auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003287 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003288 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
3289 auto *TaskEntry =
3290 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
3291 ".omp_task_entry.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003292 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003293 CodeGenFunction CGF(CGM);
3294 CGF.disableDebugInfo();
3295 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
3296
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003297 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00003298 // tt,
3299 // For taskloops:
3300 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3301 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003302 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00003303 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003304 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3305 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3306 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003307 auto *KmpTaskTWithPrivatesQTyRD =
3308 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003309 LValue Base =
3310 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003311 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3312 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3313 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003314 auto *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003315
3316 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3317 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003318 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003319 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003320 CGF.ConvertTypeForMem(SharedsPtrTy));
3321
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003322 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3323 llvm::Value *PrivatesParam;
3324 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3325 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3326 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003327 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003328 } else
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003329 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003330
Alexey Bataev7292c292016-04-25 12:22:29 +00003331 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
3332 TaskPrivatesMap,
3333 CGF.Builder
3334 .CreatePointerBitCastOrAddrSpaceCast(
3335 TDBase.getAddress(), CGF.VoidPtrTy)
3336 .getPointer()};
3337 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
3338 std::end(CommonArgs));
3339 if (isOpenMPTaskLoopDirective(Kind)) {
3340 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
3341 auto LBLVal = CGF.EmitLValueForField(Base, *LBFI);
3342 auto *LBParam = CGF.EmitLoadOfLValue(LBLVal, Loc).getScalarVal();
3343 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
3344 auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
3345 auto *UBParam = CGF.EmitLoadOfLValue(UBLVal, Loc).getScalarVal();
3346 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
3347 auto StLVal = CGF.EmitLValueForField(Base, *StFI);
3348 auto *StParam = CGF.EmitLoadOfLValue(StLVal, Loc).getScalarVal();
3349 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3350 auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
3351 auto *LIParam = CGF.EmitLoadOfLValue(LILVal, Loc).getScalarVal();
3352 CallArgs.push_back(LBParam);
3353 CallArgs.push_back(UBParam);
3354 CallArgs.push_back(StParam);
3355 CallArgs.push_back(LIParam);
3356 }
3357 CallArgs.push_back(SharedsParam);
3358
Alexey Bataev62b63b12015-03-10 07:28:44 +00003359 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
3360 CGF.EmitStoreThroughLValue(
3361 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00003362 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00003363 CGF.FinishFunction();
3364 return TaskEntry;
3365}
3366
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003367static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
3368 SourceLocation Loc,
3369 QualType KmpInt32Ty,
3370 QualType KmpTaskTWithPrivatesPtrQTy,
3371 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003372 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003373 FunctionArgList Args;
3374 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
3375 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00003376 /*Id=*/nullptr,
3377 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003378 Args.push_back(&GtidArg);
3379 Args.push_back(&TaskTypeArg);
3380 FunctionType::ExtInfo Info;
3381 auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003382 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003383 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
3384 auto *DestructorFn =
3385 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
3386 ".omp_task_destructor.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003387 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
3388 DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003389 CodeGenFunction CGF(CGM);
3390 CGF.disableDebugInfo();
3391 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
3392 Args);
3393
Alexey Bataev31300ed2016-02-04 11:27:03 +00003394 LValue Base = CGF.EmitLoadOfPointerLValue(
3395 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3396 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003397 auto *KmpTaskTWithPrivatesQTyRD =
3398 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3399 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003400 Base = CGF.EmitLValueForField(Base, *FI);
3401 for (auto *Field :
3402 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
3403 if (auto DtorKind = Field->getType().isDestructedType()) {
3404 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
3405 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
3406 }
3407 }
3408 CGF.FinishFunction();
3409 return DestructorFn;
3410}
3411
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003412/// \brief Emit a privates mapping function for correct handling of private and
3413/// firstprivate variables.
3414/// \code
3415/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
3416/// **noalias priv1,..., <tyn> **noalias privn) {
3417/// *priv1 = &.privates.priv1;
3418/// ...;
3419/// *privn = &.privates.privn;
3420/// }
3421/// \endcode
3422static llvm::Value *
3423emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00003424 ArrayRef<const Expr *> PrivateVars,
3425 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataevf93095a2016-05-05 08:46:22 +00003426 ArrayRef<const Expr *> LastprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003427 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003428 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003429 auto &C = CGM.getContext();
3430 FunctionArgList Args;
3431 ImplicitParamDecl TaskPrivatesArg(
3432 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3433 C.getPointerType(PrivatesQTy).withConst().withRestrict());
3434 Args.push_back(&TaskPrivatesArg);
3435 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
3436 unsigned Counter = 1;
3437 for (auto *E: PrivateVars) {
3438 Args.push_back(ImplicitParamDecl::Create(
3439 C, /*DC=*/nullptr, Loc,
3440 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3441 .withConst()
3442 .withRestrict()));
3443 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3444 PrivateVarsPos[VD] = Counter;
3445 ++Counter;
3446 }
3447 for (auto *E : FirstprivateVars) {
3448 Args.push_back(ImplicitParamDecl::Create(
3449 C, /*DC=*/nullptr, Loc,
3450 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3451 .withConst()
3452 .withRestrict()));
3453 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3454 PrivateVarsPos[VD] = Counter;
3455 ++Counter;
3456 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003457 for (auto *E: LastprivateVars) {
3458 Args.push_back(ImplicitParamDecl::Create(
3459 C, /*DC=*/nullptr, Loc,
3460 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3461 .withConst()
3462 .withRestrict()));
3463 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3464 PrivateVarsPos[VD] = Counter;
3465 ++Counter;
3466 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003467 auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003468 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003469 auto *TaskPrivatesMapTy =
3470 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
3471 auto *TaskPrivatesMap = llvm::Function::Create(
3472 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
3473 ".omp_task_privates_map.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003474 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
3475 TaskPrivatesMapFnInfo);
Chandler Carruthfcd33142016-12-23 01:24:49 +00003476 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00003477 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003478 CodeGenFunction CGF(CGM);
3479 CGF.disableDebugInfo();
3480 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
3481 TaskPrivatesMapFnInfo, Args);
3482
3483 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003484 LValue Base = CGF.EmitLoadOfPointerLValue(
3485 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
3486 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003487 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
3488 Counter = 0;
3489 for (auto *Field : PrivatesQTyRD->fields()) {
3490 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
3491 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00003492 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00003493 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
3494 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00003495 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003496 ++Counter;
3497 }
3498 CGF.FinishFunction();
3499 return TaskPrivatesMap;
3500}
3501
Alexey Bataev9e034042015-05-05 04:05:12 +00003502static int array_pod_sort_comparator(const PrivateDataTy *P1,
3503 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003504 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
3505}
3506
Alexey Bataevf93095a2016-05-05 08:46:22 +00003507/// Emit initialization for private variables in task-based directives.
Alexey Bataev8a831592016-05-10 10:36:51 +00003508static void emitPrivatesInit(CodeGenFunction &CGF,
Alexey Bataevf93095a2016-05-05 08:46:22 +00003509 const OMPExecutableDirective &D,
3510 Address KmpTaskSharedsPtr, LValue TDBase,
3511 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
3512 QualType SharedsTy, QualType SharedsPtrTy,
3513 const OMPTaskDataTy &Data,
3514 ArrayRef<PrivateDataTy> Privates, bool ForDup) {
3515 auto &C = CGF.getContext();
Alexey Bataevf93095a2016-05-05 08:46:22 +00003516 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3517 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
3518 LValue SrcBase;
3519 if (!Data.FirstprivateVars.empty()) {
3520 SrcBase = CGF.MakeAddrLValue(
3521 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3522 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
3523 SharedsTy);
3524 }
3525 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
3526 cast<CapturedStmt>(*D.getAssociatedStmt()));
3527 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
3528 for (auto &&Pair : Privates) {
3529 auto *VD = Pair.second.PrivateCopy;
3530 auto *Init = VD->getAnyInitializer();
Alexey Bataevf93095a2016-05-05 08:46:22 +00003531 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) &&
3532 !CGF.isTrivialInitializer(Init)))) {
Alexey Bataev8a831592016-05-10 10:36:51 +00003533 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003534 if (auto *Elem = Pair.second.PrivateElemInit) {
3535 auto *OriginalVD = Pair.second.Original;
3536 auto *SharedField = CapturesInfo.lookup(OriginalVD);
3537 auto SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
3538 SharedRefLValue = CGF.MakeAddrLValue(
3539 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
3540 SharedRefLValue.getType(), AlignmentSource::Decl);
3541 QualType Type = OriginalVD->getType();
3542 if (Type->isArrayType()) {
3543 // Initialize firstprivate array.
3544 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) {
3545 // Perform simple memcpy.
3546 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
3547 SharedRefLValue.getAddress(), Type);
3548 } else {
3549 // Initialize firstprivate array using element-by-element
3550 // intialization.
3551 CGF.EmitOMPAggregateAssign(
3552 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type,
3553 [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
3554 Address SrcElement) {
3555 // Clean up any temporaries needed by the initialization.
3556 CodeGenFunction::OMPPrivateScope InitScope(CGF);
3557 InitScope.addPrivate(
3558 Elem, [SrcElement]() -> Address { return SrcElement; });
3559 (void)InitScope.Privatize();
3560 // Emit initialization for single element.
3561 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
3562 CGF, &CapturesInfo);
3563 CGF.EmitAnyExprToMem(Init, DestElement,
3564 Init->getType().getQualifiers(),
3565 /*IsInitializer=*/false);
3566 });
3567 }
3568 } else {
3569 CodeGenFunction::OMPPrivateScope InitScope(CGF);
3570 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
3571 return SharedRefLValue.getAddress();
3572 });
3573 (void)InitScope.Privatize();
3574 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
3575 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
3576 /*capturedByInit=*/false);
3577 }
3578 } else
3579 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
3580 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003581 ++FI;
3582 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003583}
3584
3585/// Check if duplication function is required for taskloops.
3586static bool checkInitIsRequired(CodeGenFunction &CGF,
3587 ArrayRef<PrivateDataTy> Privates) {
3588 bool InitRequired = false;
3589 for (auto &&Pair : Privates) {
3590 auto *VD = Pair.second.PrivateCopy;
3591 auto *Init = VD->getAnyInitializer();
3592 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) &&
3593 !CGF.isTrivialInitializer(Init));
3594 }
3595 return InitRequired;
3596}
3597
3598
3599/// Emit task_dup function (for initialization of
3600/// private/firstprivate/lastprivate vars and last_iter flag)
3601/// \code
3602/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
3603/// lastpriv) {
3604/// // setup lastprivate flag
3605/// task_dst->last = lastpriv;
3606/// // could be constructor calls here...
3607/// }
3608/// \endcode
3609static llvm::Value *
3610emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
3611 const OMPExecutableDirective &D,
3612 QualType KmpTaskTWithPrivatesPtrQTy,
3613 const RecordDecl *KmpTaskTWithPrivatesQTyRD,
3614 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
3615 QualType SharedsPtrTy, const OMPTaskDataTy &Data,
3616 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
3617 auto &C = CGM.getContext();
3618 FunctionArgList Args;
3619 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc,
3620 /*Id=*/nullptr, KmpTaskTWithPrivatesPtrQTy);
3621 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc,
3622 /*Id=*/nullptr, KmpTaskTWithPrivatesPtrQTy);
3623 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc,
3624 /*Id=*/nullptr, C.IntTy);
3625 Args.push_back(&DstArg);
3626 Args.push_back(&SrcArg);
3627 Args.push_back(&LastprivArg);
3628 auto &TaskDupFnInfo =
3629 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3630 auto *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
3631 auto *TaskDup =
3632 llvm::Function::Create(TaskDupTy, llvm::GlobalValue::InternalLinkage,
3633 ".omp_task_dup.", &CGM.getModule());
3634 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskDup, TaskDupFnInfo);
3635 CodeGenFunction CGF(CGM);
3636 CGF.disableDebugInfo();
3637 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args);
3638
3639 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3640 CGF.GetAddrOfLocalVar(&DstArg),
3641 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3642 // task_dst->liter = lastpriv;
3643 if (WithLastIter) {
3644 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3645 LValue Base = CGF.EmitLValueForField(
3646 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
3647 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
3648 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
3649 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
3650 CGF.EmitStoreOfScalar(Lastpriv, LILVal);
3651 }
3652
3653 // Emit initial values for private copies (if any).
3654 assert(!Privates.empty());
3655 Address KmpTaskSharedsPtr = Address::invalid();
3656 if (!Data.FirstprivateVars.empty()) {
3657 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3658 CGF.GetAddrOfLocalVar(&SrcArg),
3659 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3660 LValue Base = CGF.EmitLValueForField(
3661 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
3662 KmpTaskSharedsPtr = Address(
3663 CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
3664 Base, *std::next(KmpTaskTQTyRD->field_begin(),
3665 KmpTaskTShareds)),
3666 Loc),
3667 CGF.getNaturalTypeAlignment(SharedsTy));
3668 }
Alexey Bataev8a831592016-05-10 10:36:51 +00003669 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
3670 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003671 CGF.FinishFunction();
3672 return TaskDup;
3673}
3674
Alexey Bataev8a831592016-05-10 10:36:51 +00003675/// Checks if destructor function is required to be generated.
3676/// \return true if cleanups are required, false otherwise.
3677static bool
3678checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) {
3679 bool NeedsCleanup = false;
3680 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3681 auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl());
3682 for (auto *FD : PrivateRD->fields()) {
3683 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType();
3684 if (NeedsCleanup)
3685 break;
3686 }
3687 return NeedsCleanup;
3688}
3689
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003690CGOpenMPRuntime::TaskResultTy
3691CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
3692 const OMPExecutableDirective &D,
3693 llvm::Value *TaskFunction, QualType SharedsTy,
3694 Address Shareds, const OMPTaskDataTy &Data) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003695 auto &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00003696 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003697 // Aggregate privates and sort them by the alignment.
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003698 auto I = Data.PrivateCopies.begin();
3699 for (auto *E : Data.PrivateVars) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003700 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3701 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00003702 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00003703 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3704 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003705 ++I;
3706 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003707 I = Data.FirstprivateCopies.begin();
3708 auto IElemInitRef = Data.FirstprivateInits.begin();
3709 for (auto *E : Data.FirstprivateVars) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003710 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3711 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00003712 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00003713 PrivateHelpersTy(
3714 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3715 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
Richard Trieucc3949d2016-02-18 22:34:54 +00003716 ++I;
3717 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00003718 }
Alexey Bataevf93095a2016-05-05 08:46:22 +00003719 I = Data.LastprivateCopies.begin();
3720 for (auto *E : Data.LastprivateVars) {
3721 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3722 Privates.push_back(std::make_pair(
3723 C.getDeclAlign(VD),
3724 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3725 /*PrivateElemInit=*/nullptr)));
3726 ++I;
3727 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003728 llvm::array_pod_sort(Privates.begin(), Privates.end(),
3729 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003730 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
3731 // Build type kmp_routine_entry_t (if not built yet).
3732 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003733 // Build type kmp_task_t (if not built yet).
3734 if (KmpTaskTQTy.isNull()) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003735 KmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
3736 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003737 }
3738 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003739 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003740 auto *KmpTaskTWithPrivatesQTyRD =
3741 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
3742 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
3743 QualType KmpTaskTWithPrivatesPtrQTy =
3744 C.getPointerType(KmpTaskTWithPrivatesQTy);
3745 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
3746 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00003747 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003748 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
3749
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003750 // Emit initial values for private copies (if any).
3751 llvm::Value *TaskPrivatesMap = nullptr;
3752 auto *TaskPrivatesMapTy =
3753 std::next(cast<llvm::Function>(TaskFunction)->getArgumentList().begin(),
3754 3)
3755 ->getType();
3756 if (!Privates.empty()) {
3757 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataevf93095a2016-05-05 08:46:22 +00003758 TaskPrivatesMap = emitTaskPrivateMappingFunction(
3759 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars,
3760 FI->getType(), Privates);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003761 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3762 TaskPrivatesMap, TaskPrivatesMapTy);
3763 } else {
3764 TaskPrivatesMap = llvm::ConstantPointerNull::get(
3765 cast<llvm::PointerType>(TaskPrivatesMapTy));
3766 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003767 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
3768 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003769 auto *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00003770 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
3771 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
3772 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003773
3774 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
3775 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
3776 // kmp_routine_entry_t *task_entry);
3777 // Task flags. Format is taken from
3778 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
3779 // description of kmp_tasking_flags struct.
Alexey Bataev1e1e2862016-05-10 12:21:02 +00003780 enum {
3781 TiedFlag = 0x1,
3782 FinalFlag = 0x2,
3783 DestructorsFlag = 0x8,
3784 PriorityFlag = 0x20
3785 };
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003786 unsigned Flags = Data.Tied ? TiedFlag : 0;
Alexey Bataev8a831592016-05-10 10:36:51 +00003787 bool NeedsCleanup = false;
3788 if (!Privates.empty()) {
3789 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD);
3790 if (NeedsCleanup)
3791 Flags = Flags | DestructorsFlag;
3792 }
Alexey Bataev1e1e2862016-05-10 12:21:02 +00003793 if (Data.Priority.getInt())
3794 Flags = Flags | PriorityFlag;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003795 auto *TaskFlags =
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003796 Data.Final.getPointer()
3797 ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
Alexey Bataev62b63b12015-03-10 07:28:44 +00003798 CGF.Builder.getInt32(FinalFlag),
3799 CGF.Builder.getInt32(/*C=*/0))
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003800 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003801 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00003802 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003803 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
3804 getThreadID(CGF, Loc), TaskFlags,
3805 KmpTaskTWithPrivatesTySize, SharedsSize,
3806 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3807 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00003808 auto *NewTask = CGF.EmitRuntimeCall(
3809 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003810 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3811 NewTask, KmpTaskTWithPrivatesPtrTy);
3812 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
3813 KmpTaskTWithPrivatesQTy);
3814 LValue TDBase =
3815 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003816 // Fill the data in the resulting kmp_task_t record.
3817 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00003818 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003819 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00003820 KmpTaskSharedsPtr =
3821 Address(CGF.EmitLoadOfScalar(
3822 CGF.EmitLValueForField(
3823 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
3824 KmpTaskTShareds)),
3825 Loc),
3826 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003827 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003828 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003829 // Emit initial values for private copies (if any).
Alexey Bataevf93095a2016-05-05 08:46:22 +00003830 TaskResultTy Result;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003831 if (!Privates.empty()) {
Alexey Bataev8a831592016-05-10 10:36:51 +00003832 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
3833 SharedsTy, SharedsPtrTy, Data, Privates,
3834 /*ForDup=*/false);
Alexey Bataevf93095a2016-05-05 08:46:22 +00003835 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
3836 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) {
3837 Result.TaskDupFn = emitTaskDupFunction(
3838 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
3839 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
3840 /*WithLastIter=*/!Data.LastprivateVars.empty());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003841 }
3842 }
Alexey Bataevad537bb2016-05-30 09:06:50 +00003843 // Fields of union "kmp_cmplrdata_t" for destructors and priority.
3844 enum { Priority = 0, Destructors = 1 };
Alexey Bataev62b63b12015-03-10 07:28:44 +00003845 // Provide pointer to function with destructors for privates.
Alexey Bataevad537bb2016-05-30 09:06:50 +00003846 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
3847 auto *KmpCmplrdataUD = (*FI)->getType()->getAsUnionType()->getDecl();
3848 if (NeedsCleanup) {
3849 llvm::Value *DestructorFn = emitDestructorsFunction(
3850 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
3851 KmpTaskTWithPrivatesQTy);
3852 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
3853 LValue DestructorsLV = CGF.EmitLValueForField(
3854 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
3855 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3856 DestructorFn, KmpRoutineEntryPtrTy),
3857 DestructorsLV);
3858 }
3859 // Set priority.
3860 if (Data.Priority.getInt()) {
3861 LValue Data2LV = CGF.EmitLValueForField(
3862 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
3863 LValue PriorityLV = CGF.EmitLValueForField(
3864 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
3865 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
3866 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003867 Result.NewTask = NewTask;
3868 Result.TaskEntry = TaskEntry;
3869 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
3870 Result.TDBase = TDBase;
3871 Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
3872 return Result;
Alexey Bataev7292c292016-04-25 12:22:29 +00003873}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003874
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003875void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc,
3876 const OMPExecutableDirective &D,
3877 llvm::Value *TaskFunction,
3878 QualType SharedsTy, Address Shareds,
3879 const Expr *IfCond,
3880 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003881 if (!CGF.HaveInsertPoint())
3882 return;
3883
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003884 TaskResultTy Result =
3885 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
3886 llvm::Value *NewTask = Result.NewTask;
3887 llvm::Value *TaskEntry = Result.TaskEntry;
3888 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy;
3889 LValue TDBase = Result.TDBase;
3890 RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD;
Alexey Bataev7292c292016-04-25 12:22:29 +00003891 auto &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003892 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00003893 Address DependenciesArray = Address::invalid();
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003894 unsigned NumDependencies = Data.Dependences.size();
John McCall7f416cc2015-09-08 08:05:57 +00003895 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003896 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00003897 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003898 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
3899 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003900 QualType FlagsTy =
3901 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003902 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
3903 if (KmpDependInfoTy.isNull()) {
3904 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
3905 KmpDependInfoRD->startDefinition();
3906 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
3907 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
3908 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
3909 KmpDependInfoRD->completeDefinition();
3910 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003911 } else
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003912 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
John McCall7f416cc2015-09-08 08:05:57 +00003913 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003914 // Define type kmp_depend_info[<Dependences.size()>];
3915 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00003916 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003917 ArrayType::Normal, /*IndexTypeQuals=*/0);
3918 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00003919 DependenciesArray =
3920 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
John McCall7f416cc2015-09-08 08:05:57 +00003921 for (unsigned i = 0; i < NumDependencies; ++i) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003922 const Expr *E = Data.Dependences[i].second;
John McCall7f416cc2015-09-08 08:05:57 +00003923 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003924 llvm::Value *Size;
3925 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003926 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
3927 LValue UpAddrLVal =
3928 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
3929 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00003930 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003931 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00003932 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003933 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
3934 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003935 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00003936 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003937 auto Base = CGF.MakeAddrLValue(
3938 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003939 KmpDependInfoTy);
3940 // deps[i].base_addr = &<Dependences[i].second>;
3941 auto BaseAddrLVal = CGF.EmitLValueForField(
3942 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00003943 CGF.EmitStoreOfScalar(
3944 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
3945 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003946 // deps[i].len = sizeof(<Dependences[i].second>);
3947 auto LenLVal = CGF.EmitLValueForField(
3948 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
3949 CGF.EmitStoreOfScalar(Size, LenLVal);
3950 // deps[i].flags = <Dependences[i].first>;
3951 RTLDependenceKindTy DepKind;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003952 switch (Data.Dependences[i].first) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003953 case OMPC_DEPEND_in:
3954 DepKind = DepIn;
3955 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00003956 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003957 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003958 case OMPC_DEPEND_inout:
3959 DepKind = DepInOut;
3960 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00003961 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003962 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003963 case OMPC_DEPEND_unknown:
3964 llvm_unreachable("Unknown task dependence type");
3965 }
3966 auto FlagsLVal = CGF.EmitLValueForField(
3967 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
3968 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
3969 FlagsLVal);
3970 }
John McCall7f416cc2015-09-08 08:05:57 +00003971 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3972 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003973 CGF.VoidPtrTy);
3974 }
3975
Alexey Bataev62b63b12015-03-10 07:28:44 +00003976 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
3977 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003978 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
3979 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
3980 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
3981 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00003982 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003983 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00003984 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
3985 llvm::Value *DepTaskArgs[7];
3986 if (NumDependencies) {
3987 DepTaskArgs[0] = UpLoc;
3988 DepTaskArgs[1] = ThreadID;
3989 DepTaskArgs[2] = NewTask;
3990 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
3991 DepTaskArgs[4] = DependenciesArray.getPointer();
3992 DepTaskArgs[5] = CGF.Builder.getInt32(0);
3993 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3994 }
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003995 auto &&ThenCodeGen = [this, Loc, &Data, TDBase, KmpTaskTQTyRD,
Alexey Bataev48591dd2016-04-20 04:01:36 +00003996 NumDependencies, &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003997 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00003998 if (!Data.Tied) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003999 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
4000 auto PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
4001 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
4002 }
John McCall7f416cc2015-09-08 08:05:57 +00004003 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004004 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00004005 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00004006 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00004007 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00004008 TaskArgs);
4009 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00004010 // Check if parent region is untied and build return for untied task;
4011 if (auto *Region =
4012 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4013 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00004014 };
John McCall7f416cc2015-09-08 08:05:57 +00004015
4016 llvm::Value *DepWaitTaskArgs[6];
4017 if (NumDependencies) {
4018 DepWaitTaskArgs[0] = UpLoc;
4019 DepWaitTaskArgs[1] = ThreadID;
4020 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
4021 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
4022 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
4023 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
4024 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004025 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
4026 NumDependencies, &DepWaitTaskArgs](CodeGenFunction &CGF,
4027 PrePostActionTy &) {
4028 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004029 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
4030 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
4031 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
4032 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
4033 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00004034 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004035 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004036 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004037 // Call proxy_task_entry(gtid, new_task);
4038 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy](
4039 CodeGenFunction &CGF, PrePostActionTy &Action) {
4040 Action.Enter(CGF);
4041 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
4042 CGF.EmitCallOrInvoke(TaskEntry, OutlinedFnArgs);
4043 };
4044
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004045 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
4046 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004047 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
4048 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004049 RegionCodeGenTy RCG(CodeGen);
4050 CommonActionTy Action(
4051 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
4052 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
4053 RCG.setAction(Action);
4054 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00004055 };
John McCall7f416cc2015-09-08 08:05:57 +00004056
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004057 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00004058 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004059 else {
4060 RegionCodeGenTy ThenRCG(ThenCodeGen);
4061 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00004062 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00004063}
4064
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004065void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc,
4066 const OMPLoopDirective &D,
4067 llvm::Value *TaskFunction,
4068 QualType SharedsTy, Address Shareds,
4069 const Expr *IfCond,
4070 const OMPTaskDataTy &Data) {
Alexey Bataev7292c292016-04-25 12:22:29 +00004071 if (!CGF.HaveInsertPoint())
4072 return;
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004073 TaskResultTy Result =
4074 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data);
Alexey Bataev7292c292016-04-25 12:22:29 +00004075 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
4076 // libcall.
4077 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
4078 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
4079 // sched, kmp_uint64 grainsize, void *task_dup);
4080 llvm::Value *ThreadID = getThreadID(CGF, Loc);
4081 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
4082 llvm::Value *IfVal;
4083 if (IfCond) {
4084 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
4085 /*isSigned=*/true);
4086 } else
4087 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
4088
4089 LValue LBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004090 Result.TDBase,
4091 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004092 auto *LBVar =
4093 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
4094 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
4095 /*IsInitializer=*/true);
4096 LValue UBLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004097 Result.TDBase,
4098 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
Alexey Bataev7292c292016-04-25 12:22:29 +00004099 auto *UBVar =
4100 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
4101 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
4102 /*IsInitializer=*/true);
4103 LValue StLVal = CGF.EmitLValueForField(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004104 Result.TDBase,
4105 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
Alexey Bataev7292c292016-04-25 12:22:29 +00004106 auto *StVar =
4107 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
4108 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
4109 /*IsInitializer=*/true);
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004110 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 };
Alexey Bataev7292c292016-04-25 12:22:29 +00004111 llvm::Value *TaskArgs[] = {
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004112 UpLoc, ThreadID, Result.NewTask, IfVal, LBLVal.getPointer(),
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004113 UBLVal.getPointer(), CGF.EmitLoadOfScalar(StLVal, SourceLocation()),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004114 llvm::ConstantInt::getSigned(CGF.IntTy, Data.Nogroup ? 1 : 0),
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004115 llvm::ConstantInt::getSigned(
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004116 CGF.IntTy, Data.Schedule.getPointer()
4117 ? Data.Schedule.getInt() ? NumTasks : Grainsize
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004118 : NoSchedule),
Alexey Bataev24b5bae2016-04-28 09:23:51 +00004119 Data.Schedule.getPointer()
4120 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty,
Alexey Bataev2b19a6f2016-04-28 09:15:06 +00004121 /*isSigned=*/false)
4122 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
Alexey Bataevf93095a2016-05-05 08:46:22 +00004123 Result.TaskDupFn
4124 ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Result.TaskDupFn,
4125 CGF.VoidPtrTy)
4126 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
Alexey Bataev7292c292016-04-25 12:22:29 +00004127 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
4128}
4129
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004130/// \brief Emit reduction operation for each element of array (required for
4131/// array sections) LHS op = RHS.
4132/// \param Type Type of array.
4133/// \param LHSVar Variable on the left side of the reduction operation
4134/// (references element of array in original variable).
4135/// \param RHSVar Variable on the right side of the reduction operation
4136/// (references element of array in original variable).
4137/// \param RedOpGen Generator of reduction operation with use of LHSVar and
4138/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00004139static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004140 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
4141 const VarDecl *RHSVar,
4142 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
4143 const Expr *, const Expr *)> &RedOpGen,
4144 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
4145 const Expr *UpExpr = nullptr) {
4146 // Perform element-by-element initialization.
4147 QualType ElementTy;
4148 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
4149 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
4150
4151 // Drill down to the base element type on both arrays.
4152 auto ArrayTy = Type->getAsArrayTypeUnsafe();
4153 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
4154
4155 auto RHSBegin = RHSAddr.getPointer();
4156 auto LHSBegin = LHSAddr.getPointer();
4157 // Cast from pointer to array type to pointer to single element.
4158 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
4159 // The basic structure here is a while-do loop.
4160 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
4161 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
4162 auto IsEmpty =
4163 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
4164 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
4165
4166 // Enter the loop body, making that address the current address.
4167 auto EntryBB = CGF.Builder.GetInsertBlock();
4168 CGF.EmitBlock(BodyBB);
4169
4170 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
4171
4172 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
4173 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
4174 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
4175 Address RHSElementCurrent =
4176 Address(RHSElementPHI,
4177 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4178
4179 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
4180 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
4181 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
4182 Address LHSElementCurrent =
4183 Address(LHSElementPHI,
4184 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
4185
4186 // Emit copy.
4187 CodeGenFunction::OMPPrivateScope Scope(CGF);
4188 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
4189 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
4190 Scope.Privatize();
4191 RedOpGen(CGF, XExpr, EExpr, UpExpr);
4192 Scope.ForceCleanup();
4193
4194 // Shift the address forward by one element.
4195 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
4196 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
4197 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
4198 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
4199 // Check whether we've reached the end.
4200 auto Done =
4201 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
4202 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
4203 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
4204 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
4205
4206 // Done.
4207 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
4208}
4209
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004210/// Emit reduction combiner. If the combiner is a simple expression emit it as
4211/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
4212/// UDR combiner function.
4213static void emitReductionCombiner(CodeGenFunction &CGF,
4214 const Expr *ReductionOp) {
4215 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
4216 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
4217 if (auto *DRE =
4218 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
4219 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
4220 std::pair<llvm::Function *, llvm::Function *> Reduction =
4221 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
4222 RValue Func = RValue::get(Reduction.first);
4223 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
4224 CGF.EmitIgnoredExpr(ReductionOp);
4225 return;
4226 }
4227 CGF.EmitIgnoredExpr(ReductionOp);
4228}
4229
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004230static llvm::Value *emitReductionFunction(CodeGenModule &CGM,
4231 llvm::Type *ArgsType,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004232 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004233 ArrayRef<const Expr *> LHSExprs,
4234 ArrayRef<const Expr *> RHSExprs,
4235 ArrayRef<const Expr *> ReductionOps) {
4236 auto &C = CGM.getContext();
4237
4238 // void reduction_func(void *LHSArg, void *RHSArg);
4239 FunctionArgList Args;
4240 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
4241 C.VoidPtrTy);
4242 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
4243 C.VoidPtrTy);
4244 Args.push_back(&LHSArg);
4245 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00004246 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004247 auto *Fn = llvm::Function::Create(
4248 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
4249 ".omp.reduction.reduction_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00004250 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004251 CodeGenFunction CGF(CGM);
4252 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
4253
4254 // Dst = (void*[n])(LHSArg);
4255 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00004256 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4257 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
4258 ArgsType), CGF.getPointerAlign());
4259 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4260 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
4261 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004262
4263 // ...
4264 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
4265 // ...
4266 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004267 auto IPriv = Privates.begin();
4268 unsigned Idx = 0;
4269 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004270 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
4271 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004272 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004273 });
4274 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
4275 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004276 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00004277 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004278 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00004279 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004280 // Get array size and emit VLA type.
4281 ++Idx;
4282 Address Elem =
4283 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
4284 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004285 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
4286 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004287 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00004288 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004289 CGF.EmitVariablyModifiedType(PrivTy);
4290 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004291 }
4292 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004293 IPriv = Privates.begin();
4294 auto ILHS = LHSExprs.begin();
4295 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004296 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004297 if ((*IPriv)->getType()->isArrayType()) {
4298 // Emit reduction for array section.
4299 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4300 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004301 EmitOMPAggregateReduction(
4302 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4303 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4304 emitReductionCombiner(CGF, E);
4305 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004306 } else
4307 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00004308 emitReductionCombiner(CGF, E);
Richard Trieucc3949d2016-02-18 22:34:54 +00004309 ++IPriv;
4310 ++ILHS;
4311 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004312 }
4313 Scope.ForceCleanup();
4314 CGF.FinishFunction();
4315 return Fn;
4316}
4317
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004318static void emitSingleReductionCombiner(CodeGenFunction &CGF,
4319 const Expr *ReductionOp,
4320 const Expr *PrivateRef,
4321 const DeclRefExpr *LHS,
4322 const DeclRefExpr *RHS) {
4323 if (PrivateRef->getType()->isArrayType()) {
4324 // Emit reduction for array section.
4325 auto *LHSVar = cast<VarDecl>(LHS->getDecl());
4326 auto *RHSVar = cast<VarDecl>(RHS->getDecl());
4327 EmitOMPAggregateReduction(
4328 CGF, PrivateRef->getType(), LHSVar, RHSVar,
4329 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4330 emitReductionCombiner(CGF, ReductionOp);
4331 });
4332 } else
4333 // Emit reduction for array subscript or single variable.
4334 emitReductionCombiner(CGF, ReductionOp);
4335}
4336
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004337void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004338 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004339 ArrayRef<const Expr *> LHSExprs,
4340 ArrayRef<const Expr *> RHSExprs,
4341 ArrayRef<const Expr *> ReductionOps,
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004342 bool WithNowait, bool SimpleReduction) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004343 if (!CGF.HaveInsertPoint())
4344 return;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004345 // Next code should be emitted for reduction:
4346 //
4347 // static kmp_critical_name lock = { 0 };
4348 //
4349 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
4350 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
4351 // ...
4352 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
4353 // *(Type<n>-1*)rhs[<n>-1]);
4354 // }
4355 //
4356 // ...
4357 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
4358 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4359 // RedList, reduce_func, &<lock>)) {
4360 // case 1:
4361 // ...
4362 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4363 // ...
4364 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4365 // break;
4366 // case 2:
4367 // ...
4368 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4369 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00004370 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004371 // break;
4372 // default:;
4373 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004374 //
4375 // if SimpleReduction is true, only the next code is generated:
4376 // ...
4377 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4378 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004379
4380 auto &C = CGM.getContext();
4381
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004382 if (SimpleReduction) {
4383 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004384 auto IPriv = Privates.begin();
4385 auto ILHS = LHSExprs.begin();
4386 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004387 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004388 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4389 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00004390 ++IPriv;
4391 ++ILHS;
4392 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004393 }
4394 return;
4395 }
4396
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004397 // 1. Build a list of reduction variables.
4398 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004399 auto Size = RHSExprs.size();
4400 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00004401 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004402 // Reserve place for array size.
4403 ++Size;
4404 }
4405 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004406 QualType ReductionArrayTy =
4407 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4408 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00004409 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004410 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004411 auto IPriv = Privates.begin();
4412 unsigned Idx = 0;
4413 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004414 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004415 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00004416 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004417 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004418 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4419 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004420 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004421 // Store array size.
4422 ++Idx;
4423 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
4424 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00004425 llvm::Value *Size = CGF.Builder.CreateIntCast(
4426 CGF.getVLASize(
4427 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4428 .first,
4429 CGF.SizeTy, /*isSigned=*/false);
4430 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4431 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004432 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004433 }
4434
4435 // 2. Emit reduce_func().
4436 auto *ReductionFn = emitReductionFunction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004437 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
4438 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004439
4440 // 3. Create static kmp_critical_name lock = { 0 };
4441 auto *Lock = getCriticalRegionLock(".reduction");
4442
4443 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4444 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00004445 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004446 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004447 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
Samuel Antao4c8035b2016-12-12 18:00:20 +00004448 auto *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4449 ReductionList.getPointer(), CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004450 llvm::Value *Args[] = {
4451 IdentTLoc, // ident_t *<loc>
4452 ThreadId, // i32 <gtid>
4453 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
4454 ReductionArrayTySize, // size_type sizeof(RedList)
4455 RL, // void *RedList
4456 ReductionFn, // void (*) (void *, void *) <reduce_func>
4457 Lock // kmp_critical_name *&<lock>
4458 };
4459 auto Res = CGF.EmitRuntimeCall(
4460 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
4461 : OMPRTL__kmpc_reduce),
4462 Args);
4463
4464 // 5. Build switch(res)
4465 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
4466 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
4467
4468 // 6. Build case 1:
4469 // ...
4470 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4471 // ...
4472 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4473 // break;
4474 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
4475 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
4476 CGF.EmitBlock(Case1BB);
4477
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004478 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4479 llvm::Value *EndArgs[] = {
4480 IdentTLoc, // ident_t *<loc>
4481 ThreadId, // i32 <gtid>
4482 Lock // kmp_critical_name *&<lock>
4483 };
4484 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
4485 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004486 auto IPriv = Privates.begin();
4487 auto ILHS = LHSExprs.begin();
4488 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004489 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004490 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4491 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00004492 ++IPriv;
4493 ++ILHS;
4494 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004495 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004496 };
4497 RegionCodeGenTy RCG(CodeGen);
4498 CommonActionTy Action(
4499 nullptr, llvm::None,
4500 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
4501 : OMPRTL__kmpc_end_reduce),
4502 EndArgs);
4503 RCG.setAction(Action);
4504 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004505
4506 CGF.EmitBranch(DefaultBB);
4507
4508 // 7. Build case 2:
4509 // ...
4510 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4511 // ...
4512 // break;
4513 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
4514 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
4515 CGF.EmitBlock(Case2BB);
4516
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004517 auto &&AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs, &ReductionOps](
4518 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004519 auto ILHS = LHSExprs.begin();
4520 auto IRHS = RHSExprs.begin();
4521 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004522 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004523 const Expr *XExpr = nullptr;
4524 const Expr *EExpr = nullptr;
4525 const Expr *UpExpr = nullptr;
4526 BinaryOperatorKind BO = BO_Comma;
4527 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
4528 if (BO->getOpcode() == BO_Assign) {
4529 XExpr = BO->getLHS();
4530 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004531 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004532 }
4533 // Try to emit update expression as a simple atomic.
4534 auto *RHSExpr = UpExpr;
4535 if (RHSExpr) {
4536 // Analyze RHS part of the whole expression.
4537 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
4538 RHSExpr->IgnoreParenImpCasts())) {
4539 // If this is a conditional operator, analyze its condition for
4540 // min/max reduction operator.
4541 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00004542 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004543 if (auto *BORHS =
4544 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
4545 EExpr = BORHS->getRHS();
4546 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004547 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004548 }
4549 if (XExpr) {
4550 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4551 auto &&AtomicRedGen = [BO, VD, IPriv,
4552 Loc](CodeGenFunction &CGF, const Expr *XExpr,
4553 const Expr *EExpr, const Expr *UpExpr) {
4554 LValue X = CGF.EmitLValue(XExpr);
4555 RValue E;
4556 if (EExpr)
4557 E = CGF.EmitAnyExpr(EExpr);
4558 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00004559 X, E, BO, /*IsXLHSInRHSPart=*/true,
4560 llvm::AtomicOrdering::Monotonic, Loc,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004561 [&CGF, UpExpr, VD, IPriv, Loc](RValue XRValue) {
4562 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4563 PrivateScope.addPrivate(
4564 VD, [&CGF, VD, XRValue, Loc]() -> Address {
4565 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
4566 CGF.emitOMPSimpleStore(
4567 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
4568 VD->getType().getNonReferenceType(), Loc);
4569 return LHSTemp;
4570 });
4571 (void)PrivateScope.Privatize();
4572 return CGF.EmitAnyExpr(UpExpr);
4573 });
4574 };
4575 if ((*IPriv)->getType()->isArrayType()) {
4576 // Emit atomic reduction for array section.
4577 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
4578 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
4579 AtomicRedGen, XExpr, EExpr, UpExpr);
4580 } else
4581 // Emit atomic reduction for array subscript or single variable.
4582 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
4583 } else {
4584 // Emit as a critical region.
4585 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
4586 const Expr *, const Expr *) {
4587 auto &RT = CGF.CGM.getOpenMPRuntime();
4588 RT.emitCriticalRegion(
4589 CGF, ".atomic_reduction",
4590 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
4591 Action.Enter(CGF);
4592 emitReductionCombiner(CGF, E);
4593 },
4594 Loc);
4595 };
4596 if ((*IPriv)->getType()->isArrayType()) {
4597 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4598 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
4599 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4600 CritRedGen);
4601 } else
4602 CritRedGen(CGF, nullptr, nullptr, nullptr);
4603 }
Richard Trieucc3949d2016-02-18 22:34:54 +00004604 ++ILHS;
4605 ++IRHS;
4606 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004607 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004608 };
4609 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
4610 if (!WithNowait) {
4611 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
4612 llvm::Value *EndArgs[] = {
4613 IdentTLoc, // ident_t *<loc>
4614 ThreadId, // i32 <gtid>
4615 Lock // kmp_critical_name *&<lock>
4616 };
4617 CommonActionTy Action(nullptr, llvm::None,
4618 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
4619 EndArgs);
4620 AtomicRCG.setAction(Action);
4621 AtomicRCG(CGF);
4622 } else
4623 AtomicRCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004624
4625 CGF.EmitBranch(DefaultBB);
4626 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
4627}
4628
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004629void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
4630 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004631 if (!CGF.HaveInsertPoint())
4632 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004633 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
4634 // global_tid);
4635 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
4636 // Ignore return result until untied tasks are supported.
4637 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00004638 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4639 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004640}
4641
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00004642void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004643 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004644 const RegionCodeGenTy &CodeGen,
4645 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004646 if (!CGF.HaveInsertPoint())
4647 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004648 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00004649 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00004650}
4651
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004652namespace {
4653enum RTCancelKind {
4654 CancelNoreq = 0,
4655 CancelParallel = 1,
4656 CancelLoop = 2,
4657 CancelSections = 3,
4658 CancelTaskgroup = 4
4659};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00004660} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004661
4662static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
4663 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00004664 if (CancelRegion == OMPD_parallel)
4665 CancelKind = CancelParallel;
4666 else if (CancelRegion == OMPD_for)
4667 CancelKind = CancelLoop;
4668 else if (CancelRegion == OMPD_sections)
4669 CancelKind = CancelSections;
4670 else {
4671 assert(CancelRegion == OMPD_taskgroup);
4672 CancelKind = CancelTaskgroup;
4673 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004674 return CancelKind;
4675}
4676
4677void CGOpenMPRuntime::emitCancellationPointCall(
4678 CodeGenFunction &CGF, SourceLocation Loc,
4679 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004680 if (!CGF.HaveInsertPoint())
4681 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004682 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
4683 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004684 if (auto *OMPRegionInfo =
4685 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00004686 if (OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004687 llvm::Value *Args[] = {
4688 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
4689 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004690 // Ignore return result until untied tasks are supported.
4691 auto *Result = CGF.EmitRuntimeCall(
4692 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
4693 // if (__kmpc_cancellationpoint()) {
4694 // __kmpc_cancel_barrier();
4695 // exit from construct;
4696 // }
4697 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4698 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4699 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4700 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4701 CGF.EmitBlock(ExitBB);
4702 // __kmpc_cancel_barrier();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004703 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004704 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004705 auto CancelDest =
4706 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004707 CGF.EmitBranchThroughCleanup(CancelDest);
4708 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4709 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00004710 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00004711}
4712
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004713void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00004714 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004715 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004716 if (!CGF.HaveInsertPoint())
4717 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004718 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
4719 // kmp_int32 cncl_kind);
4720 if (auto *OMPRegionInfo =
4721 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004722 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
4723 PrePostActionTy &) {
4724 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00004725 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004726 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00004727 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
4728 // Ignore return result until untied tasks are supported.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004729 auto *Result = CGF.EmitRuntimeCall(
4730 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00004731 // if (__kmpc_cancel()) {
4732 // __kmpc_cancel_barrier();
4733 // exit from construct;
4734 // }
4735 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4736 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4737 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4738 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4739 CGF.EmitBlock(ExitBB);
4740 // __kmpc_cancel_barrier();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004741 RT.emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
Alexey Bataev87933c72015-09-18 08:07:34 +00004742 // exit from construct;
4743 auto CancelDest =
4744 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
4745 CGF.EmitBranchThroughCleanup(CancelDest);
4746 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4747 };
4748 if (IfCond)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004749 emitOMPIfClause(CGF, IfCond, ThenGen,
4750 [](CodeGenFunction &, PrePostActionTy &) {});
4751 else {
4752 RegionCodeGenTy ThenRCG(ThenGen);
4753 ThenRCG(CGF);
4754 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004755 }
4756}
Samuel Antaobed3c462015-10-02 16:14:20 +00004757
Samuel Antaoee8fb302016-01-06 13:42:12 +00004758/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00004759/// consists of the file and device IDs as well as line number associated with
4760/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004761static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
4762 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004763 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004764
4765 auto &SM = C.getSourceManager();
4766
4767 // The loc should be always valid and have a file ID (the user cannot use
4768 // #pragma directives in macros)
4769
4770 assert(Loc.isValid() && "Source location is expected to be always valid.");
4771 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
4772
4773 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
4774 assert(PLoc.isValid() && "Source location is expected to be always valid.");
4775
4776 llvm::sys::fs::UniqueID ID;
4777 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
4778 llvm_unreachable("Source file with target region no longer exists!");
4779
4780 DeviceID = ID.getDevice();
4781 FileID = ID.getFile();
4782 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004783}
4784
4785void CGOpenMPRuntime::emitTargetOutlinedFunction(
4786 const OMPExecutableDirective &D, StringRef ParentName,
4787 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004788 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004789 assert(!ParentName.empty() && "Invalid target region parent name!");
4790
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00004791 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
4792 IsOffloadEntry, CodeGen);
4793}
4794
4795void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
4796 const OMPExecutableDirective &D, StringRef ParentName,
4797 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
4798 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00004799 // Create a unique name for the entry function using the source location
4800 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00004801 //
Samuel Antao2de62b02016-02-13 23:35:10 +00004802 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00004803 //
4804 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00004805 // mangled name of the function that encloses the target region and BB is the
4806 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004807
4808 unsigned DeviceID;
4809 unsigned FileID;
4810 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004811 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004812 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004813 SmallString<64> EntryFnName;
4814 {
4815 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00004816 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
4817 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004818 }
4819
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00004820 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4821
Samuel Antaobed3c462015-10-02 16:14:20 +00004822 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004823 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00004824 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004825
Samuel Antao6d004262016-06-16 18:39:34 +00004826 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004827
4828 // If this target outline function is not an offload entry, we don't need to
4829 // register it.
4830 if (!IsOffloadEntry)
4831 return;
4832
4833 // The target region ID is used by the runtime library to identify the current
4834 // target region, so it only has to be unique and not necessarily point to
4835 // anything. It could be the pointer to the outlined function that implements
4836 // the target region, but we aren't using that so that the compiler doesn't
4837 // need to keep that, and could therefore inline the host function if proven
4838 // worthwhile during optimization. In the other hand, if emitting code for the
4839 // device, the ID has to be the function address so that it can retrieved from
4840 // the offloading entry and launched by the runtime library. We also mark the
4841 // outlined function to have external linkage in case we are emitting code for
4842 // the device, because these functions will be entry points to the device.
4843
4844 if (CGM.getLangOpts().OpenMPIsDevice) {
4845 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
4846 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
4847 } else
4848 OutlinedFnID = new llvm::GlobalVariable(
4849 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
4850 llvm::GlobalValue::PrivateLinkage,
4851 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
4852
4853 // Register the information for the entry associated with this target region.
4854 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00004855 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID);
Samuel Antaobed3c462015-10-02 16:14:20 +00004856}
4857
Carlo Bertolli6eee9062016-04-29 01:37:30 +00004858/// discard all CompoundStmts intervening between two constructs
4859static const Stmt *ignoreCompoundStmts(const Stmt *Body) {
4860 while (auto *CS = dyn_cast_or_null<CompoundStmt>(Body))
4861 Body = CS->body_front();
4862
4863 return Body;
4864}
4865
Samuel Antaob68e2db2016-03-03 16:20:23 +00004866/// \brief Emit the num_teams clause of an enclosed teams directive at the
4867/// target region scope. If there is no teams directive associated with the
4868/// target directive, or if there is no num_teams clause associated with the
4869/// enclosed teams directive, return nullptr.
4870static llvm::Value *
4871emitNumTeamsClauseForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4872 CodeGenFunction &CGF,
4873 const OMPExecutableDirective &D) {
4874
4875 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4876 "teams directive expected to be "
4877 "emitted only for the host!");
4878
4879 // FIXME: For the moment we do not support combined directives with target and
4880 // teams, so we do not expect to get any num_teams clause in the provided
4881 // directive. Once we support that, this assertion can be replaced by the
4882 // actual emission of the clause expression.
4883 assert(D.getSingleClause<OMPNumTeamsClause>() == nullptr &&
4884 "Not expecting clause in directive.");
4885
4886 // If the current target region has a teams region enclosed, we need to get
4887 // the number of teams to pass to the runtime function call. This is done
4888 // by generating the expression in a inlined region. This is required because
4889 // the expression is captured in the enclosing target environment when the
4890 // teams directive is not combined with target.
4891
4892 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4893
4894 // FIXME: Accommodate other combined directives with teams when they become
4895 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00004896 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
4897 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00004898 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
4899 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4900 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4901 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
4902 return CGF.Builder.CreateIntCast(NumTeams, CGF.Int32Ty,
4903 /*IsSigned=*/true);
4904 }
4905
4906 // If we have an enclosed teams directive but no num_teams clause we use
4907 // the default value 0.
4908 return CGF.Builder.getInt32(0);
4909 }
4910
4911 // No teams associated with the directive.
4912 return nullptr;
4913}
4914
4915/// \brief Emit the thread_limit clause of an enclosed teams directive at the
4916/// target region scope. If there is no teams directive associated with the
4917/// target directive, or if there is no thread_limit clause associated with the
4918/// enclosed teams directive, return nullptr.
4919static llvm::Value *
4920emitThreadLimitClauseForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4921 CodeGenFunction &CGF,
4922 const OMPExecutableDirective &D) {
4923
4924 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4925 "teams directive expected to be "
4926 "emitted only for the host!");
4927
4928 // FIXME: For the moment we do not support combined directives with target and
4929 // teams, so we do not expect to get any thread_limit clause in the provided
4930 // directive. Once we support that, this assertion can be replaced by the
4931 // actual emission of the clause expression.
4932 assert(D.getSingleClause<OMPThreadLimitClause>() == nullptr &&
4933 "Not expecting clause in directive.");
4934
4935 // If the current target region has a teams region enclosed, we need to get
4936 // the thread limit to pass to the runtime function call. This is done
4937 // by generating the expression in a inlined region. This is required because
4938 // the expression is captured in the enclosing target environment when the
4939 // teams directive is not combined with target.
4940
4941 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4942
4943 // FIXME: Accommodate other combined directives with teams when they become
4944 // available.
Carlo Bertolli6eee9062016-04-29 01:37:30 +00004945 if (auto *TeamsDir = dyn_cast_or_null<OMPTeamsDirective>(
4946 ignoreCompoundStmts(CS.getCapturedStmt()))) {
Samuel Antaob68e2db2016-03-03 16:20:23 +00004947 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
4948 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4949 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4950 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
4951 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
4952 /*IsSigned=*/true);
4953 }
4954
4955 // If we have an enclosed teams directive but no thread_limit clause we use
4956 // the default value 0.
4957 return CGF.Builder.getInt32(0);
4958 }
4959
4960 // No teams associated with the directive.
4961 return nullptr;
4962}
4963
Samuel Antao86ace552016-04-27 22:40:57 +00004964namespace {
4965// \brief Utility to handle information from clauses associated with a given
4966// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
4967// It provides a convenient interface to obtain the information and generate
4968// code for that information.
4969class MappableExprsHandler {
4970public:
4971 /// \brief Values for bit flags used to specify the mapping type for
4972 /// offloading.
4973 enum OpenMPOffloadMappingFlags {
Samuel Antao86ace552016-04-27 22:40:57 +00004974 /// \brief Allocate memory on the device and move data from host to device.
4975 OMP_MAP_TO = 0x01,
4976 /// \brief Allocate memory on the device and move data from device to host.
4977 OMP_MAP_FROM = 0x02,
4978 /// \brief Always perform the requested mapping action on the element, even
4979 /// if it was already mapped before.
4980 OMP_MAP_ALWAYS = 0x04,
Samuel Antao86ace552016-04-27 22:40:57 +00004981 /// \brief Delete the element from the device environment, ignoring the
4982 /// current reference count associated with the element.
Samuel Antao6782e942016-05-26 16:48:10 +00004983 OMP_MAP_DELETE = 0x08,
4984 /// \brief The element being mapped is a pointer, therefore the pointee
4985 /// should be mapped as well.
4986 OMP_MAP_IS_PTR = 0x10,
4987 /// \brief This flags signals that an argument is the first one relating to
4988 /// a map/private clause expression. For some cases a single
4989 /// map/privatization results in multiple arguments passed to the runtime
4990 /// library.
4991 OMP_MAP_FIRST_REF = 0x20,
Samuel Antaocc10b852016-07-28 14:23:26 +00004992 /// \brief Signal that the runtime library has to return the device pointer
4993 /// in the current position for the data being mapped.
4994 OMP_MAP_RETURN_PTR = 0x40,
Samuel Antaod486f842016-05-26 16:53:38 +00004995 /// \brief This flag signals that the reference being passed is a pointer to
4996 /// private data.
4997 OMP_MAP_PRIVATE_PTR = 0x80,
Samuel Antao86ace552016-04-27 22:40:57 +00004998 /// \brief Pass the element to the device by value.
Samuel Antao6782e942016-05-26 16:48:10 +00004999 OMP_MAP_PRIVATE_VAL = 0x100,
Samuel Antao86ace552016-04-27 22:40:57 +00005000 };
5001
Samuel Antaocc10b852016-07-28 14:23:26 +00005002 /// Class that associates information with a base pointer to be passed to the
5003 /// runtime library.
5004 class BasePointerInfo {
5005 /// The base pointer.
5006 llvm::Value *Ptr = nullptr;
5007 /// The base declaration that refers to this device pointer, or null if
5008 /// there is none.
5009 const ValueDecl *DevPtrDecl = nullptr;
5010
5011 public:
5012 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr)
5013 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {}
5014 llvm::Value *operator*() const { return Ptr; }
5015 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; }
5016 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; }
5017 };
5018
5019 typedef SmallVector<BasePointerInfo, 16> MapBaseValuesArrayTy;
Samuel Antao86ace552016-04-27 22:40:57 +00005020 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
5021 typedef SmallVector<unsigned, 16> MapFlagsArrayTy;
5022
5023private:
5024 /// \brief Directive from where the map clauses were extracted.
Samuel Antao44bcdb32016-07-28 15:31:29 +00005025 const OMPExecutableDirective &CurDir;
Samuel Antao86ace552016-04-27 22:40:57 +00005026
5027 /// \brief Function the directive is being generated for.
5028 CodeGenFunction &CGF;
5029
Samuel Antaod486f842016-05-26 16:53:38 +00005030 /// \brief Set of all first private variables in the current directive.
5031 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls;
5032
Samuel Antao6890b092016-07-28 14:25:09 +00005033 /// Map between device pointer declarations and their expression components.
5034 /// The key value for declarations in 'this' is null.
5035 llvm::DenseMap<
5036 const ValueDecl *,
5037 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>>
5038 DevPointersMap;
5039
Samuel Antao86ace552016-04-27 22:40:57 +00005040 llvm::Value *getExprTypeSize(const Expr *E) const {
5041 auto ExprTy = E->getType().getCanonicalType();
5042
5043 // Reference types are ignored for mapping purposes.
5044 if (auto *RefTy = ExprTy->getAs<ReferenceType>())
5045 ExprTy = RefTy->getPointeeType().getCanonicalType();
5046
5047 // Given that an array section is considered a built-in type, we need to
5048 // do the calculation based on the length of the section instead of relying
5049 // on CGF.getTypeSize(E->getType()).
5050 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
5051 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
5052 OAE->getBase()->IgnoreParenImpCasts())
5053 .getCanonicalType();
5054
5055 // If there is no length associated with the expression, that means we
5056 // are using the whole length of the base.
5057 if (!OAE->getLength() && OAE->getColonLoc().isValid())
5058 return CGF.getTypeSize(BaseTy);
5059
5060 llvm::Value *ElemSize;
5061 if (auto *PTy = BaseTy->getAs<PointerType>())
5062 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
5063 else {
5064 auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
5065 assert(ATy && "Expecting array type if not a pointer type.");
5066 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
5067 }
5068
5069 // If we don't have a length at this point, that is because we have an
5070 // array section with a single element.
5071 if (!OAE->getLength())
5072 return ElemSize;
5073
5074 auto *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
5075 LengthVal =
5076 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
5077 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
5078 }
5079 return CGF.getTypeSize(ExprTy);
5080 }
5081
5082 /// \brief Return the corresponding bits for a given map clause modifier. Add
5083 /// a flag marking the map as a pointer if requested. Add a flag marking the
Samuel Antao6782e942016-05-26 16:48:10 +00005084 /// map as the first one of a series of maps that relate to the same map
5085 /// expression.
Samuel Antao86ace552016-04-27 22:40:57 +00005086 unsigned getMapTypeBits(OpenMPMapClauseKind MapType,
5087 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
Samuel Antao6782e942016-05-26 16:48:10 +00005088 bool AddIsFirstFlag) const {
Samuel Antao86ace552016-04-27 22:40:57 +00005089 unsigned Bits = 0u;
5090 switch (MapType) {
5091 case OMPC_MAP_alloc:
Samuel Antao6782e942016-05-26 16:48:10 +00005092 case OMPC_MAP_release:
5093 // alloc and release is the default behavior in the runtime library, i.e.
5094 // if we don't pass any bits alloc/release that is what the runtime is
5095 // going to do. Therefore, we don't need to signal anything for these two
5096 // type modifiers.
Samuel Antao86ace552016-04-27 22:40:57 +00005097 break;
5098 case OMPC_MAP_to:
5099 Bits = OMP_MAP_TO;
5100 break;
5101 case OMPC_MAP_from:
5102 Bits = OMP_MAP_FROM;
5103 break;
5104 case OMPC_MAP_tofrom:
5105 Bits = OMP_MAP_TO | OMP_MAP_FROM;
5106 break;
5107 case OMPC_MAP_delete:
5108 Bits = OMP_MAP_DELETE;
5109 break;
Samuel Antao86ace552016-04-27 22:40:57 +00005110 default:
5111 llvm_unreachable("Unexpected map type!");
5112 break;
5113 }
5114 if (AddPtrFlag)
Samuel Antao6782e942016-05-26 16:48:10 +00005115 Bits |= OMP_MAP_IS_PTR;
5116 if (AddIsFirstFlag)
5117 Bits |= OMP_MAP_FIRST_REF;
Samuel Antao86ace552016-04-27 22:40:57 +00005118 if (MapTypeModifier == OMPC_MAP_always)
5119 Bits |= OMP_MAP_ALWAYS;
5120 return Bits;
5121 }
5122
5123 /// \brief Return true if the provided expression is a final array section. A
5124 /// final array section, is one whose length can't be proved to be one.
5125 bool isFinalArraySectionExpression(const Expr *E) const {
5126 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
5127
5128 // It is not an array section and therefore not a unity-size one.
5129 if (!OASE)
5130 return false;
5131
5132 // An array section with no colon always refer to a single element.
5133 if (OASE->getColonLoc().isInvalid())
5134 return false;
5135
5136 auto *Length = OASE->getLength();
5137
5138 // If we don't have a length we have to check if the array has size 1
5139 // for this dimension. Also, we should always expect a length if the
5140 // base type is pointer.
5141 if (!Length) {
5142 auto BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
5143 OASE->getBase()->IgnoreParenImpCasts())
5144 .getCanonicalType();
5145 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
5146 return ATy->getSize().getSExtValue() != 1;
5147 // If we don't have a constant dimension length, we have to consider
5148 // the current section as having any size, so it is not necessarily
5149 // unitary. If it happen to be unity size, that's user fault.
5150 return true;
5151 }
5152
5153 // Check if the length evaluates to 1.
5154 llvm::APSInt ConstLength;
5155 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
5156 return true; // Can have more that size 1.
5157
5158 return ConstLength.getSExtValue() != 1;
5159 }
5160
5161 /// \brief Generate the base pointers, section pointers, sizes and map type
5162 /// bits for the provided map type, map modifier, and expression components.
5163 /// \a IsFirstComponent should be set to true if the provided set of
5164 /// components is the first associated with a capture.
5165 void generateInfoForComponentList(
5166 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
5167 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
Samuel Antaocc10b852016-07-28 14:23:26 +00005168 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
Samuel Antao86ace552016-04-27 22:40:57 +00005169 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
5170 bool IsFirstComponentList) const {
5171
5172 // The following summarizes what has to be generated for each map and the
5173 // types bellow. The generated information is expressed in this order:
5174 // base pointer, section pointer, size, flags
5175 // (to add to the ones that come from the map type and modifier).
5176 //
5177 // double d;
5178 // int i[100];
5179 // float *p;
5180 //
5181 // struct S1 {
5182 // int i;
5183 // float f[50];
5184 // }
5185 // struct S2 {
5186 // int i;
5187 // float f[50];
5188 // S1 s;
5189 // double *p;
5190 // struct S2 *ps;
5191 // }
5192 // S2 s;
5193 // S2 *ps;
5194 //
5195 // map(d)
5196 // &d, &d, sizeof(double), noflags
5197 //
5198 // map(i)
5199 // &i, &i, 100*sizeof(int), noflags
5200 //
5201 // map(i[1:23])
5202 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
5203 //
5204 // map(p)
5205 // &p, &p, sizeof(float*), noflags
5206 //
5207 // map(p[1:24])
5208 // p, &p[1], 24*sizeof(float), noflags
5209 //
5210 // map(s)
5211 // &s, &s, sizeof(S2), noflags
5212 //
5213 // map(s.i)
5214 // &s, &(s.i), sizeof(int), noflags
5215 //
5216 // map(s.s.f)
5217 // &s, &(s.i.f), 50*sizeof(int), noflags
5218 //
5219 // map(s.p)
5220 // &s, &(s.p), sizeof(double*), noflags
5221 //
5222 // map(s.p[:22], s.a s.b)
5223 // &s, &(s.p), sizeof(double*), noflags
5224 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag + extra_flag
5225 //
5226 // map(s.ps)
5227 // &s, &(s.ps), sizeof(S2*), noflags
5228 //
5229 // map(s.ps->s.i)
5230 // &s, &(s.ps), sizeof(S2*), noflags
5231 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag + extra_flag
5232 //
5233 // map(s.ps->ps)
5234 // &s, &(s.ps), sizeof(S2*), noflags
5235 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5236 //
5237 // map(s.ps->ps->ps)
5238 // &s, &(s.ps), sizeof(S2*), noflags
5239 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5240 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5241 //
5242 // map(s.ps->ps->s.f[:22])
5243 // &s, &(s.ps), sizeof(S2*), noflags
5244 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
5245 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag + extra_flag
5246 //
5247 // map(ps)
5248 // &ps, &ps, sizeof(S2*), noflags
5249 //
5250 // map(ps->i)
5251 // ps, &(ps->i), sizeof(int), noflags
5252 //
5253 // map(ps->s.f)
5254 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
5255 //
5256 // map(ps->p)
5257 // ps, &(ps->p), sizeof(double*), noflags
5258 //
5259 // map(ps->p[:22])
5260 // ps, &(ps->p), sizeof(double*), noflags
5261 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag + extra_flag
5262 //
5263 // map(ps->ps)
5264 // ps, &(ps->ps), sizeof(S2*), noflags
5265 //
5266 // map(ps->ps->s.i)
5267 // ps, &(ps->ps), sizeof(S2*), noflags
5268 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag + extra_flag
5269 //
5270 // map(ps->ps->ps)
5271 // ps, &(ps->ps), sizeof(S2*), noflags
5272 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5273 //
5274 // map(ps->ps->ps->ps)
5275 // ps, &(ps->ps), sizeof(S2*), noflags
5276 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5277 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5278 //
5279 // map(ps->ps->ps->s.f[:22])
5280 // ps, &(ps->ps), sizeof(S2*), noflags
5281 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
5282 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag +
5283 // extra_flag
5284
5285 // Track if the map information being generated is the first for a capture.
5286 bool IsCaptureFirstInfo = IsFirstComponentList;
5287
5288 // Scan the components from the base to the complete expression.
5289 auto CI = Components.rbegin();
5290 auto CE = Components.rend();
5291 auto I = CI;
5292
5293 // Track if the map information being generated is the first for a list of
5294 // components.
5295 bool IsExpressionFirstInfo = true;
5296 llvm::Value *BP = nullptr;
5297
5298 if (auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
5299 // The base is the 'this' pointer. The content of the pointer is going
5300 // to be the base of the field being mapped.
5301 BP = CGF.EmitScalarExpr(ME->getBase());
5302 } else {
5303 // The base is the reference to the variable.
5304 // BP = &Var.
5305 BP = CGF.EmitLValue(cast<DeclRefExpr>(I->getAssociatedExpression()))
5306 .getPointer();
5307
5308 // If the variable is a pointer and is being dereferenced (i.e. is not
Nico Webera6916892016-06-10 18:53:04 +00005309 // the last component), the base has to be the pointer itself, not its
Samuel Antao403ffd42016-07-27 22:49:49 +00005310 // reference. References are ignored for mapping purposes.
5311 QualType Ty =
5312 I->getAssociatedDeclaration()->getType().getNonReferenceType();
5313 if (Ty->isAnyPointerType() && std::next(I) != CE) {
5314 auto PtrAddr = CGF.MakeNaturalAlignAddrLValue(BP, Ty);
Samuel Antao86ace552016-04-27 22:40:57 +00005315 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
Samuel Antao403ffd42016-07-27 22:49:49 +00005316 Ty->castAs<PointerType>())
Samuel Antao86ace552016-04-27 22:40:57 +00005317 .getPointer();
5318
5319 // We do not need to generate individual map information for the
5320 // pointer, it can be associated with the combined storage.
5321 ++I;
5322 }
5323 }
5324
5325 for (; I != CE; ++I) {
5326 auto Next = std::next(I);
5327
5328 // We need to generate the addresses and sizes if this is the last
5329 // component, if the component is a pointer or if it is an array section
5330 // whose length can't be proved to be one. If this is a pointer, it
5331 // becomes the base address for the following components.
5332
5333 // A final array section, is one whose length can't be proved to be one.
5334 bool IsFinalArraySection =
5335 isFinalArraySectionExpression(I->getAssociatedExpression());
5336
5337 // Get information on whether the element is a pointer. Have to do a
5338 // special treatment for array sections given that they are built-in
5339 // types.
5340 const auto *OASE =
5341 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
5342 bool IsPointer =
5343 (OASE &&
5344 OMPArraySectionExpr::getBaseOriginalType(OASE)
5345 .getCanonicalType()
5346 ->isAnyPointerType()) ||
5347 I->getAssociatedExpression()->getType()->isAnyPointerType();
5348
5349 if (Next == CE || IsPointer || IsFinalArraySection) {
5350
5351 // If this is not the last component, we expect the pointer to be
5352 // associated with an array expression or member expression.
5353 assert((Next == CE ||
5354 isa<MemberExpr>(Next->getAssociatedExpression()) ||
5355 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
5356 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
5357 "Unexpected expression");
5358
Samuel Antao86ace552016-04-27 22:40:57 +00005359 auto *LB = CGF.EmitLValue(I->getAssociatedExpression()).getPointer();
5360 auto *Size = getExprTypeSize(I->getAssociatedExpression());
5361
Samuel Antao03a3cec2016-07-27 22:52:16 +00005362 // If we have a member expression and the current component is a
5363 // reference, we have to map the reference too. Whenever we have a
5364 // reference, the section that reference refers to is going to be a
5365 // load instruction from the storage assigned to the reference.
5366 if (isa<MemberExpr>(I->getAssociatedExpression()) &&
5367 I->getAssociatedDeclaration()->getType()->isReferenceType()) {
5368 auto *LI = cast<llvm::LoadInst>(LB);
5369 auto *RefAddr = LI->getPointerOperand();
5370
5371 BasePointers.push_back(BP);
5372 Pointers.push_back(RefAddr);
5373 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
5374 Types.push_back(getMapTypeBits(
5375 /*MapType*/ OMPC_MAP_alloc, /*MapTypeModifier=*/OMPC_MAP_unknown,
5376 !IsExpressionFirstInfo, IsCaptureFirstInfo));
5377 IsExpressionFirstInfo = false;
5378 IsCaptureFirstInfo = false;
5379 // The reference will be the next base address.
5380 BP = RefAddr;
5381 }
5382
5383 BasePointers.push_back(BP);
Samuel Antao86ace552016-04-27 22:40:57 +00005384 Pointers.push_back(LB);
5385 Sizes.push_back(Size);
Samuel Antao03a3cec2016-07-27 22:52:16 +00005386
Samuel Antao6782e942016-05-26 16:48:10 +00005387 // We need to add a pointer flag for each map that comes from the
5388 // same expression except for the first one. We also need to signal
5389 // this map is the first one that relates with the current capture
5390 // (there is a set of entries for each capture).
Samuel Antao86ace552016-04-27 22:40:57 +00005391 Types.push_back(getMapTypeBits(MapType, MapTypeModifier,
5392 !IsExpressionFirstInfo,
Samuel Antao6782e942016-05-26 16:48:10 +00005393 IsCaptureFirstInfo));
Samuel Antao86ace552016-04-27 22:40:57 +00005394
5395 // If we have a final array section, we are done with this expression.
5396 if (IsFinalArraySection)
5397 break;
5398
5399 // The pointer becomes the base for the next element.
5400 if (Next != CE)
5401 BP = LB;
5402
5403 IsExpressionFirstInfo = false;
5404 IsCaptureFirstInfo = false;
5405 continue;
5406 }
5407 }
5408 }
5409
Samuel Antaod486f842016-05-26 16:53:38 +00005410 /// \brief Return the adjusted map modifiers if the declaration a capture
5411 /// refers to appears in a first-private clause. This is expected to be used
5412 /// only with directives that start with 'target'.
5413 unsigned adjustMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap,
5414 unsigned CurrentModifiers) {
5415 assert(Cap.capturesVariable() && "Expected capture by reference only!");
5416
5417 // A first private variable captured by reference will use only the
5418 // 'private ptr' and 'map to' flag. Return the right flags if the captured
5419 // declaration is known as first-private in this handler.
5420 if (FirstPrivateDecls.count(Cap.getCapturedVar()))
5421 return MappableExprsHandler::OMP_MAP_PRIVATE_PTR |
5422 MappableExprsHandler::OMP_MAP_TO;
5423
5424 // We didn't modify anything.
5425 return CurrentModifiers;
5426 }
5427
Samuel Antao86ace552016-04-27 22:40:57 +00005428public:
5429 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
Samuel Antao44bcdb32016-07-28 15:31:29 +00005430 : CurDir(Dir), CGF(CGF) {
Samuel Antaod486f842016-05-26 16:53:38 +00005431 // Extract firstprivate clause information.
5432 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>())
5433 for (const auto *D : C->varlists())
5434 FirstPrivateDecls.insert(
5435 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl());
Samuel Antao6890b092016-07-28 14:25:09 +00005436 // Extract device pointer clause information.
5437 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>())
5438 for (auto L : C->component_lists())
5439 DevPointersMap[L.first].push_back(L.second);
Samuel Antaod486f842016-05-26 16:53:38 +00005440 }
Samuel Antao86ace552016-04-27 22:40:57 +00005441
5442 /// \brief Generate all the base pointers, section pointers, sizes and map
Samuel Antaocc10b852016-07-28 14:23:26 +00005443 /// types for the extracted mappable expressions. Also, for each item that
5444 /// relates with a device pointer, a pair of the relevant declaration and
5445 /// index where it occurs is appended to the device pointers info array.
5446 void generateAllInfo(MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00005447 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
5448 MapFlagsArrayTy &Types) const {
5449 BasePointers.clear();
5450 Pointers.clear();
5451 Sizes.clear();
5452 Types.clear();
5453
5454 struct MapInfo {
Samuel Antaocc10b852016-07-28 14:23:26 +00005455 /// Kind that defines how a device pointer has to be returned.
5456 enum ReturnPointerKind {
5457 // Don't have to return any pointer.
5458 RPK_None,
5459 // Pointer is the base of the declaration.
5460 RPK_Base,
5461 // Pointer is a member of the base declaration - 'this'
5462 RPK_Member,
5463 // Pointer is a reference and a member of the base declaration - 'this'
5464 RPK_MemberReference,
5465 };
Samuel Antao86ace552016-04-27 22:40:57 +00005466 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
Hans Wennborgbc1b58d2016-07-30 00:41:37 +00005467 OpenMPMapClauseKind MapType;
5468 OpenMPMapClauseKind MapTypeModifier;
5469 ReturnPointerKind ReturnDevicePointer;
5470
5471 MapInfo()
5472 : MapType(OMPC_MAP_unknown), MapTypeModifier(OMPC_MAP_unknown),
5473 ReturnDevicePointer(RPK_None) {}
Samuel Antaocc10b852016-07-28 14:23:26 +00005474 MapInfo(
5475 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
5476 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
5477 ReturnPointerKind ReturnDevicePointer)
5478 : Components(Components), MapType(MapType),
5479 MapTypeModifier(MapTypeModifier),
5480 ReturnDevicePointer(ReturnDevicePointer) {}
Samuel Antao86ace552016-04-27 22:40:57 +00005481 };
5482
5483 // We have to process the component lists that relate with the same
5484 // declaration in a single chunk so that we can generate the map flags
5485 // correctly. Therefore, we organize all lists in a map.
5486 llvm::DenseMap<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
Samuel Antao8d2d7302016-05-26 18:30:22 +00005487
5488 // Helper function to fill the information map for the different supported
5489 // clauses.
Samuel Antaocc10b852016-07-28 14:23:26 +00005490 auto &&InfoGen = [&Info](
5491 const ValueDecl *D,
5492 OMPClauseMappableExprCommon::MappableExprComponentListRef L,
5493 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier,
Samuel Antaocf3f83e2016-07-28 14:47:35 +00005494 MapInfo::ReturnPointerKind ReturnDevicePointer) {
Samuel Antaocc10b852016-07-28 14:23:26 +00005495 const ValueDecl *VD =
5496 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr;
5497 Info[VD].push_back({L, MapType, MapModifier, ReturnDevicePointer});
5498 };
Samuel Antao8d2d7302016-05-26 18:30:22 +00005499
Paul Robinson78fb1322016-08-01 22:12:46 +00005500 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00005501 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005502 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00005503 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(),
5504 MapInfo::RPK_None);
Paul Robinson15c84002016-07-29 20:46:16 +00005505 for (auto *C : this->CurDir.getClausesOfKind<OMPToClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005506 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00005507 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown,
5508 MapInfo::RPK_None);
Paul Robinson15c84002016-07-29 20:46:16 +00005509 for (auto *C : this->CurDir.getClausesOfKind<OMPFromClause>())
Samuel Antao8d2d7302016-05-26 18:30:22 +00005510 for (auto L : C->component_lists())
Samuel Antaocf3f83e2016-07-28 14:47:35 +00005511 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown,
5512 MapInfo::RPK_None);
Samuel Antao86ace552016-04-27 22:40:57 +00005513
Samuel Antaocc10b852016-07-28 14:23:26 +00005514 // Look at the use_device_ptr clause information and mark the existing map
5515 // entries as such. If there is no map information for an entry in the
5516 // use_device_ptr list, we create one with map type 'alloc' and zero size
5517 // section. It is the user fault if that was not mapped before.
Paul Robinson78fb1322016-08-01 22:12:46 +00005518 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00005519 for (auto *C : this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>())
Samuel Antaocc10b852016-07-28 14:23:26 +00005520 for (auto L : C->component_lists()) {
5521 assert(!L.second.empty() && "Not expecting empty list of components!");
5522 const ValueDecl *VD = L.second.back().getAssociatedDeclaration();
5523 VD = cast<ValueDecl>(VD->getCanonicalDecl());
5524 auto *IE = L.second.back().getAssociatedExpression();
5525 // If the first component is a member expression, we have to look into
5526 // 'this', which maps to null in the map of map information. Otherwise
5527 // look directly for the information.
5528 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD);
5529
5530 // We potentially have map information for this declaration already.
5531 // Look for the first set of components that refer to it.
5532 if (It != Info.end()) {
5533 auto CI = std::find_if(
5534 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) {
5535 return MI.Components.back().getAssociatedDeclaration() == VD;
5536 });
5537 // If we found a map entry, signal that the pointer has to be returned
5538 // and move on to the next declaration.
5539 if (CI != It->second.end()) {
5540 CI->ReturnDevicePointer = isa<MemberExpr>(IE)
5541 ? (VD->getType()->isReferenceType()
5542 ? MapInfo::RPK_MemberReference
5543 : MapInfo::RPK_Member)
5544 : MapInfo::RPK_Base;
5545 continue;
5546 }
5547 }
5548
5549 // We didn't find any match in our map information - generate a zero
5550 // size array section.
Paul Robinson78fb1322016-08-01 22:12:46 +00005551 // FIXME: MSVC 2013 seems to require this-> to find member CGF.
Samuel Antaocc10b852016-07-28 14:23:26 +00005552 llvm::Value *Ptr =
Paul Robinson15c84002016-07-29 20:46:16 +00005553 this->CGF
5554 .EmitLoadOfLValue(this->CGF.EmitLValue(IE), SourceLocation())
Samuel Antaocc10b852016-07-28 14:23:26 +00005555 .getScalarVal();
5556 BasePointers.push_back({Ptr, VD});
5557 Pointers.push_back(Ptr);
Paul Robinson15c84002016-07-29 20:46:16 +00005558 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy));
Samuel Antaocc10b852016-07-28 14:23:26 +00005559 Types.push_back(OMP_MAP_RETURN_PTR | OMP_MAP_FIRST_REF);
5560 }
5561
Samuel Antao86ace552016-04-27 22:40:57 +00005562 for (auto &M : Info) {
5563 // We need to know when we generate information for the first component
5564 // associated with a capture, because the mapping flags depend on it.
5565 bool IsFirstComponentList = true;
5566 for (MapInfo &L : M.second) {
5567 assert(!L.Components.empty() &&
5568 "Not expecting declaration with no component lists.");
Samuel Antaocc10b852016-07-28 14:23:26 +00005569
5570 // Remember the current base pointer index.
5571 unsigned CurrentBasePointersIdx = BasePointers.size();
Paul Robinson78fb1322016-08-01 22:12:46 +00005572 // FIXME: MSVC 2013 seems to require this-> to find the member method.
Paul Robinson15c84002016-07-29 20:46:16 +00005573 this->generateInfoForComponentList(L.MapType, L.MapTypeModifier,
5574 L.Components, BasePointers, Pointers,
5575 Sizes, Types, IsFirstComponentList);
Samuel Antaocc10b852016-07-28 14:23:26 +00005576
5577 // If this entry relates with a device pointer, set the relevant
5578 // declaration and add the 'return pointer' flag.
5579 if (IsFirstComponentList &&
5580 L.ReturnDevicePointer != MapInfo::RPK_None) {
5581 // If the pointer is not the base of the map, we need to skip the
5582 // base. If it is a reference in a member field, we also need to skip
5583 // the map of the reference.
5584 if (L.ReturnDevicePointer != MapInfo::RPK_Base) {
5585 ++CurrentBasePointersIdx;
5586 if (L.ReturnDevicePointer == MapInfo::RPK_MemberReference)
5587 ++CurrentBasePointersIdx;
5588 }
5589 assert(BasePointers.size() > CurrentBasePointersIdx &&
5590 "Unexpected number of mapped base pointers.");
5591
5592 auto *RelevantVD = L.Components.back().getAssociatedDeclaration();
5593 assert(RelevantVD &&
5594 "No relevant declaration related with device pointer??");
5595
5596 BasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD);
5597 Types[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PTR;
5598 }
Samuel Antao86ace552016-04-27 22:40:57 +00005599 IsFirstComponentList = false;
5600 }
5601 }
5602 }
5603
5604 /// \brief Generate the base pointers, section pointers, sizes and map types
5605 /// associated to a given capture.
5606 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
Samuel Antao6890b092016-07-28 14:25:09 +00005607 llvm::Value *Arg,
Samuel Antaocc10b852016-07-28 14:23:26 +00005608 MapBaseValuesArrayTy &BasePointers,
Samuel Antao86ace552016-04-27 22:40:57 +00005609 MapValuesArrayTy &Pointers,
5610 MapValuesArrayTy &Sizes,
5611 MapFlagsArrayTy &Types) const {
5612 assert(!Cap->capturesVariableArrayType() &&
5613 "Not expecting to generate map info for a variable array type!");
5614
5615 BasePointers.clear();
5616 Pointers.clear();
5617 Sizes.clear();
5618 Types.clear();
5619
Samuel Antao6890b092016-07-28 14:25:09 +00005620 // We need to know when we generating information for the first component
5621 // associated with a capture, because the mapping flags depend on it.
5622 bool IsFirstComponentList = true;
5623
Samuel Antao86ace552016-04-27 22:40:57 +00005624 const ValueDecl *VD =
5625 Cap->capturesThis()
5626 ? nullptr
5627 : cast<ValueDecl>(Cap->getCapturedVar()->getCanonicalDecl());
5628
Samuel Antao6890b092016-07-28 14:25:09 +00005629 // If this declaration appears in a is_device_ptr clause we just have to
5630 // pass the pointer by value. If it is a reference to a declaration, we just
5631 // pass its value, otherwise, if it is a member expression, we need to map
5632 // 'to' the field.
5633 if (!VD) {
5634 auto It = DevPointersMap.find(VD);
5635 if (It != DevPointersMap.end()) {
5636 for (auto L : It->second) {
5637 generateInfoForComponentList(
5638 /*MapType=*/OMPC_MAP_to, /*MapTypeModifier=*/OMPC_MAP_unknown, L,
5639 BasePointers, Pointers, Sizes, Types, IsFirstComponentList);
5640 IsFirstComponentList = false;
5641 }
5642 return;
5643 }
5644 } else if (DevPointersMap.count(VD)) {
5645 BasePointers.push_back({Arg, VD});
5646 Pointers.push_back(Arg);
5647 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy));
5648 Types.push_back(OMP_MAP_PRIVATE_VAL | OMP_MAP_FIRST_REF);
5649 return;
5650 }
5651
Paul Robinson78fb1322016-08-01 22:12:46 +00005652 // FIXME: MSVC 2013 seems to require this-> to find member CurDir.
Paul Robinson15c84002016-07-29 20:46:16 +00005653 for (auto *C : this->CurDir.getClausesOfKind<OMPMapClause>())
Samuel Antao86ace552016-04-27 22:40:57 +00005654 for (auto L : C->decl_component_lists(VD)) {
5655 assert(L.first == VD &&
5656 "We got information for the wrong declaration??");
5657 assert(!L.second.empty() &&
5658 "Not expecting declaration with no component lists.");
5659 generateInfoForComponentList(C->getMapType(), C->getMapTypeModifier(),
5660 L.second, BasePointers, Pointers, Sizes,
5661 Types, IsFirstComponentList);
5662 IsFirstComponentList = false;
5663 }
5664
5665 return;
5666 }
Samuel Antaod486f842016-05-26 16:53:38 +00005667
5668 /// \brief Generate the default map information for a given capture \a CI,
5669 /// record field declaration \a RI and captured value \a CV.
Samuel Antaocc10b852016-07-28 14:23:26 +00005670 void generateDefaultMapInfo(const CapturedStmt::Capture &CI,
5671 const FieldDecl &RI, llvm::Value *CV,
5672 MapBaseValuesArrayTy &CurBasePointers,
5673 MapValuesArrayTy &CurPointers,
5674 MapValuesArrayTy &CurSizes,
5675 MapFlagsArrayTy &CurMapTypes) {
Samuel Antaod486f842016-05-26 16:53:38 +00005676
5677 // Do the default mapping.
5678 if (CI.capturesThis()) {
5679 CurBasePointers.push_back(CV);
5680 CurPointers.push_back(CV);
5681 const PointerType *PtrTy = cast<PointerType>(RI.getType().getTypePtr());
5682 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
5683 // Default map type.
Samuel Antaocc10b852016-07-28 14:23:26 +00005684 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM);
Samuel Antaod486f842016-05-26 16:53:38 +00005685 } else if (CI.capturesVariableByCopy()) {
Samuel Antao6d004262016-06-16 18:39:34 +00005686 CurBasePointers.push_back(CV);
5687 CurPointers.push_back(CV);
Samuel Antaod486f842016-05-26 16:53:38 +00005688 if (!RI.getType()->isAnyPointerType()) {
Samuel Antao6d004262016-06-16 18:39:34 +00005689 // We have to signal to the runtime captures passed by value that are
5690 // not pointers.
Samuel Antaocc10b852016-07-28 14:23:26 +00005691 CurMapTypes.push_back(OMP_MAP_PRIVATE_VAL);
Samuel Antaod486f842016-05-26 16:53:38 +00005692 CurSizes.push_back(CGF.getTypeSize(RI.getType()));
5693 } else {
5694 // Pointers are implicitly mapped with a zero size and no flags
5695 // (other than first map that is added for all implicit maps).
5696 CurMapTypes.push_back(0u);
Samuel Antaod486f842016-05-26 16:53:38 +00005697 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy));
5698 }
5699 } else {
5700 assert(CI.capturesVariable() && "Expected captured reference.");
5701 CurBasePointers.push_back(CV);
5702 CurPointers.push_back(CV);
5703
5704 const ReferenceType *PtrTy =
5705 cast<ReferenceType>(RI.getType().getTypePtr());
5706 QualType ElementType = PtrTy->getPointeeType();
5707 CurSizes.push_back(CGF.getTypeSize(ElementType));
5708 // The default map type for a scalar/complex type is 'to' because by
5709 // default the value doesn't have to be retrieved. For an aggregate
5710 // type, the default is 'tofrom'.
5711 CurMapTypes.push_back(ElementType->isAggregateType()
Samuel Antaocc10b852016-07-28 14:23:26 +00005712 ? (OMP_MAP_TO | OMP_MAP_FROM)
5713 : OMP_MAP_TO);
Samuel Antaod486f842016-05-26 16:53:38 +00005714
5715 // If we have a capture by reference we may need to add the private
5716 // pointer flag if the base declaration shows in some first-private
5717 // clause.
5718 CurMapTypes.back() =
5719 adjustMapModifiersForPrivateClauses(CI, CurMapTypes.back());
5720 }
5721 // Every default map produces a single argument, so, it is always the
5722 // first one.
Samuel Antaocc10b852016-07-28 14:23:26 +00005723 CurMapTypes.back() |= OMP_MAP_FIRST_REF;
Samuel Antaod486f842016-05-26 16:53:38 +00005724 }
Samuel Antao86ace552016-04-27 22:40:57 +00005725};
Samuel Antaodf158d52016-04-27 22:58:19 +00005726
5727enum OpenMPOffloadingReservedDeviceIDs {
5728 /// \brief Device ID if the device was not defined, runtime should get it
5729 /// from environment variables in the spec.
5730 OMP_DEVICEID_UNDEF = -1,
5731};
5732} // anonymous namespace
5733
5734/// \brief Emit the arrays used to pass the captures and map information to the
5735/// offloading runtime library. If there is no map or capture information,
5736/// return nullptr by reference.
5737static void
Samuel Antaocc10b852016-07-28 14:23:26 +00005738emitOffloadingArrays(CodeGenFunction &CGF,
5739 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers,
Samuel Antaodf158d52016-04-27 22:58:19 +00005740 MappableExprsHandler::MapValuesArrayTy &Pointers,
5741 MappableExprsHandler::MapValuesArrayTy &Sizes,
Samuel Antaocc10b852016-07-28 14:23:26 +00005742 MappableExprsHandler::MapFlagsArrayTy &MapTypes,
5743 CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00005744 auto &CGM = CGF.CGM;
5745 auto &Ctx = CGF.getContext();
5746
Samuel Antaocc10b852016-07-28 14:23:26 +00005747 // Reset the array information.
5748 Info.clearArrayInfo();
5749 Info.NumberOfPtrs = BasePointers.size();
Samuel Antaodf158d52016-04-27 22:58:19 +00005750
Samuel Antaocc10b852016-07-28 14:23:26 +00005751 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00005752 // Detect if we have any capture size requiring runtime evaluation of the
5753 // size so that a constant array could be eventually used.
5754 bool hasRuntimeEvaluationCaptureSize = false;
5755 for (auto *S : Sizes)
5756 if (!isa<llvm::Constant>(S)) {
5757 hasRuntimeEvaluationCaptureSize = true;
5758 break;
5759 }
5760
Samuel Antaocc10b852016-07-28 14:23:26 +00005761 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true);
Samuel Antaodf158d52016-04-27 22:58:19 +00005762 QualType PointerArrayType =
5763 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
5764 /*IndexTypeQuals=*/0);
5765
Samuel Antaocc10b852016-07-28 14:23:26 +00005766 Info.BasePointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00005767 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
Samuel Antaocc10b852016-07-28 14:23:26 +00005768 Info.PointersArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00005769 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
5770
5771 // If we don't have any VLA types or other types that require runtime
5772 // evaluation, we can use a constant array for the map sizes, otherwise we
5773 // need to fill up the arrays as we do for the pointers.
5774 if (hasRuntimeEvaluationCaptureSize) {
5775 QualType SizeArrayType = Ctx.getConstantArrayType(
5776 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
5777 /*IndexTypeQuals=*/0);
Samuel Antaocc10b852016-07-28 14:23:26 +00005778 Info.SizesArray =
Samuel Antaodf158d52016-04-27 22:58:19 +00005779 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
5780 } else {
5781 // We expect all the sizes to be constant, so we collect them to create
5782 // a constant array.
5783 SmallVector<llvm::Constant *, 16> ConstSizes;
5784 for (auto S : Sizes)
5785 ConstSizes.push_back(cast<llvm::Constant>(S));
5786
5787 auto *SizesArrayInit = llvm::ConstantArray::get(
5788 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes);
5789 auto *SizesArrayGbl = new llvm::GlobalVariable(
5790 CGM.getModule(), SizesArrayInit->getType(),
5791 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
5792 SizesArrayInit, ".offload_sizes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00005793 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00005794 Info.SizesArray = SizesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00005795 }
5796
5797 // The map types are always constant so we don't need to generate code to
5798 // fill arrays. Instead, we create an array constant.
5799 llvm::Constant *MapTypesArrayInit =
5800 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
5801 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
5802 CGM.getModule(), MapTypesArrayInit->getType(),
5803 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
5804 MapTypesArrayInit, ".offload_maptypes");
Peter Collingbournebcf909d2016-06-14 21:02:05 +00005805 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Samuel Antaocc10b852016-07-28 14:23:26 +00005806 Info.MapTypesArray = MapTypesArrayGbl;
Samuel Antaodf158d52016-04-27 22:58:19 +00005807
Samuel Antaocc10b852016-07-28 14:23:26 +00005808 for (unsigned i = 0; i < Info.NumberOfPtrs; ++i) {
5809 llvm::Value *BPVal = *BasePointers[i];
Samuel Antaodf158d52016-04-27 22:58:19 +00005810 if (BPVal->getType()->isPointerTy())
5811 BPVal = CGF.Builder.CreateBitCast(BPVal, CGM.VoidPtrTy);
5812 else {
5813 assert(BPVal->getType()->isIntegerTy() &&
5814 "If not a pointer, the value type must be an integer.");
5815 BPVal = CGF.Builder.CreateIntToPtr(BPVal, CGM.VoidPtrTy);
5816 }
5817 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005818 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5819 Info.BasePointersArray, 0, i);
Samuel Antaodf158d52016-04-27 22:58:19 +00005820 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
5821 CGF.Builder.CreateStore(BPVal, BPAddr);
5822
Samuel Antaocc10b852016-07-28 14:23:26 +00005823 if (Info.requiresDevicePointerInfo())
5824 if (auto *DevVD = BasePointers[i].getDevicePtrDecl())
5825 Info.CaptureDeviceAddrMap.insert(std::make_pair(DevVD, BPAddr));
5826
Samuel Antaodf158d52016-04-27 22:58:19 +00005827 llvm::Value *PVal = Pointers[i];
5828 if (PVal->getType()->isPointerTy())
5829 PVal = CGF.Builder.CreateBitCast(PVal, CGM.VoidPtrTy);
5830 else {
5831 assert(PVal->getType()->isIntegerTy() &&
5832 "If not a pointer, the value type must be an integer.");
5833 PVal = CGF.Builder.CreateIntToPtr(PVal, CGM.VoidPtrTy);
5834 }
5835 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005836 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5837 Info.PointersArray, 0, i);
Samuel Antaodf158d52016-04-27 22:58:19 +00005838 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
5839 CGF.Builder.CreateStore(PVal, PAddr);
5840
5841 if (hasRuntimeEvaluationCaptureSize) {
5842 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005843 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs),
5844 Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005845 /*Idx0=*/0,
5846 /*Idx1=*/i);
5847 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
5848 CGF.Builder.CreateStore(
5849 CGF.Builder.CreateIntCast(Sizes[i], CGM.SizeTy, /*isSigned=*/true),
5850 SAddr);
5851 }
5852 }
5853 }
5854}
5855/// \brief Emit the arguments to be passed to the runtime library based on the
5856/// arrays of pointers, sizes and map types.
5857static void emitOffloadingArraysArgument(
5858 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg,
5859 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00005860 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00005861 auto &CGM = CGF.CGM;
Samuel Antaocc10b852016-07-28 14:23:26 +00005862 if (Info.NumberOfPtrs) {
Samuel Antaodf158d52016-04-27 22:58:19 +00005863 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005864 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5865 Info.BasePointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005866 /*Idx0=*/0, /*Idx1=*/0);
5867 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005868 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs),
5869 Info.PointersArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005870 /*Idx0=*/0,
5871 /*Idx1=*/0);
5872 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005873 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005874 /*Idx0=*/0, /*Idx1=*/0);
5875 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32(
Samuel Antaocc10b852016-07-28 14:23:26 +00005876 llvm::ArrayType::get(CGM.Int32Ty, Info.NumberOfPtrs),
5877 Info.MapTypesArray,
Samuel Antaodf158d52016-04-27 22:58:19 +00005878 /*Idx0=*/0,
5879 /*Idx1=*/0);
5880 } else {
5881 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
5882 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy);
5883 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo());
5884 MapTypesArrayArg =
5885 llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo());
5886 }
Samuel Antao86ace552016-04-27 22:40:57 +00005887}
5888
Samuel Antaobed3c462015-10-02 16:14:20 +00005889void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
5890 const OMPExecutableDirective &D,
5891 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00005892 llvm::Value *OutlinedFnID,
Samuel Antaobed3c462015-10-02 16:14:20 +00005893 const Expr *IfCond, const Expr *Device,
5894 ArrayRef<llvm::Value *> CapturedVars) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005895 if (!CGF.HaveInsertPoint())
5896 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00005897
Samuel Antaoee8fb302016-01-06 13:42:12 +00005898 assert(OutlinedFn && "Invalid outlined function!");
5899
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005900 auto &Ctx = CGF.getContext();
5901
Samuel Antao86ace552016-04-27 22:40:57 +00005902 // Fill up the arrays with all the captured variables.
5903 MappableExprsHandler::MapValuesArrayTy KernelArgs;
Samuel Antaocc10b852016-07-28 14:23:26 +00005904 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00005905 MappableExprsHandler::MapValuesArrayTy Pointers;
5906 MappableExprsHandler::MapValuesArrayTy Sizes;
5907 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobed3c462015-10-02 16:14:20 +00005908
Samuel Antaocc10b852016-07-28 14:23:26 +00005909 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers;
Samuel Antao86ace552016-04-27 22:40:57 +00005910 MappableExprsHandler::MapValuesArrayTy CurPointers;
5911 MappableExprsHandler::MapValuesArrayTy CurSizes;
5912 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
5913
Samuel Antaod486f842016-05-26 16:53:38 +00005914 // Get mappable expression information.
5915 MappableExprsHandler MEHandler(D, CGF);
Samuel Antaobed3c462015-10-02 16:14:20 +00005916
5917 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5918 auto RI = CS.getCapturedRecordDecl()->field_begin();
Samuel Antaobed3c462015-10-02 16:14:20 +00005919 auto CV = CapturedVars.begin();
5920 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
5921 CE = CS.capture_end();
5922 CI != CE; ++CI, ++RI, ++CV) {
5923 StringRef Name;
5924 QualType Ty;
Samuel Antaobed3c462015-10-02 16:14:20 +00005925
Samuel Antao86ace552016-04-27 22:40:57 +00005926 CurBasePointers.clear();
5927 CurPointers.clear();
5928 CurSizes.clear();
5929 CurMapTypes.clear();
5930
5931 // VLA sizes are passed to the outlined region by copy and do not have map
5932 // information associated.
Samuel Antaobed3c462015-10-02 16:14:20 +00005933 if (CI->capturesVariableArrayType()) {
Samuel Antao86ace552016-04-27 22:40:57 +00005934 CurBasePointers.push_back(*CV);
5935 CurPointers.push_back(*CV);
5936 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005937 // Copy to the device as an argument. No need to retrieve it.
Samuel Antao6782e942016-05-26 16:48:10 +00005938 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_PRIVATE_VAL |
5939 MappableExprsHandler::OMP_MAP_FIRST_REF);
Samuel Antaobed3c462015-10-02 16:14:20 +00005940 } else {
Samuel Antao86ace552016-04-27 22:40:57 +00005941 // If we have any information in the map clause, we use it, otherwise we
5942 // just do a default mapping.
Samuel Antao6890b092016-07-28 14:25:09 +00005943 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers,
Samuel Antao86ace552016-04-27 22:40:57 +00005944 CurSizes, CurMapTypes);
Samuel Antaod486f842016-05-26 16:53:38 +00005945 if (CurBasePointers.empty())
5946 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers,
5947 CurPointers, CurSizes, CurMapTypes);
Samuel Antaobed3c462015-10-02 16:14:20 +00005948 }
Samuel Antao86ace552016-04-27 22:40:57 +00005949 // We expect to have at least an element of information for this capture.
5950 assert(!CurBasePointers.empty() && "Non-existing map pointer for capture!");
5951 assert(CurBasePointers.size() == CurPointers.size() &&
5952 CurBasePointers.size() == CurSizes.size() &&
5953 CurBasePointers.size() == CurMapTypes.size() &&
5954 "Inconsistent map information sizes!");
Samuel Antaobed3c462015-10-02 16:14:20 +00005955
Samuel Antao86ace552016-04-27 22:40:57 +00005956 // The kernel args are always the first elements of the base pointers
5957 // associated with a capture.
Samuel Antaocc10b852016-07-28 14:23:26 +00005958 KernelArgs.push_back(*CurBasePointers.front());
Samuel Antao86ace552016-04-27 22:40:57 +00005959 // We need to append the results of this capture to what we already have.
5960 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
5961 Pointers.append(CurPointers.begin(), CurPointers.end());
5962 Sizes.append(CurSizes.begin(), CurSizes.end());
5963 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
Samuel Antaobed3c462015-10-02 16:14:20 +00005964 }
5965
5966 // Keep track on whether the host function has to be executed.
5967 auto OffloadErrorQType =
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005968 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00005969 auto OffloadError = CGF.MakeAddrLValue(
5970 CGF.CreateMemTemp(OffloadErrorQType, ".run_host_version"),
5971 OffloadErrorQType);
5972 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty),
5973 OffloadError);
5974
5975 // Fill up the pointer arrays and transfer execution to the device.
Samuel Antaodf158d52016-04-27 22:58:19 +00005976 auto &&ThenGen = [&Ctx, &BasePointers, &Pointers, &Sizes, &MapTypes, Device,
5977 OutlinedFnID, OffloadError, OffloadErrorQType,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005978 &D](CodeGenFunction &CGF, PrePostActionTy &) {
5979 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antaodf158d52016-04-27 22:58:19 +00005980 // Emit the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00005981 TargetDataInfo Info;
5982 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
5983 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
5984 Info.PointersArray, Info.SizesArray,
5985 Info.MapTypesArray, Info);
Samuel Antaobed3c462015-10-02 16:14:20 +00005986
5987 // On top of the arrays that were filled up, the target offloading call
5988 // takes as arguments the device id as well as the host pointer. The host
5989 // pointer is used by the runtime library to identify the current target
5990 // region, so it only has to be unique and not necessarily point to
5991 // anything. It could be the pointer to the outlined function that
5992 // implements the target region, but we aren't using that so that the
5993 // compiler doesn't need to keep that, and could therefore inline the host
5994 // function if proven worthwhile during optimization.
5995
Samuel Antaoee8fb302016-01-06 13:42:12 +00005996 // From this point on, we need to have an ID of the target region defined.
5997 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00005998
5999 // Emit device ID if any.
6000 llvm::Value *DeviceID;
6001 if (Device)
6002 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006003 CGF.Int32Ty, /*isSigned=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006004 else
6005 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6006
Samuel Antaodf158d52016-04-27 22:58:19 +00006007 // Emit the number of elements in the offloading arrays.
6008 llvm::Value *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6009
Samuel Antaob68e2db2016-03-03 16:20:23 +00006010 // Return value of the runtime offloading call.
6011 llvm::Value *Return;
6012
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006013 auto *NumTeams = emitNumTeamsClauseForTargetDirective(RT, CGF, D);
6014 auto *ThreadLimit = emitThreadLimitClauseForTargetDirective(RT, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006015
6016 // If we have NumTeams defined this means that we have an enclosed teams
6017 // region. Therefore we also expect to have ThreadLimit defined. These two
6018 // values should be defined in the presence of a teams directive, regardless
6019 // of having any clauses associated. If the user is using teams but no
6020 // clauses, these two values will be the default that should be passed to
6021 // the runtime library - a 32-bit integer with the value zero.
6022 if (NumTeams) {
6023 assert(ThreadLimit && "Thread limit expression should be available along "
6024 "with number of teams.");
6025 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00006026 DeviceID, OutlinedFnID,
6027 PointerNum, Info.BasePointersArray,
6028 Info.PointersArray, Info.SizesArray,
6029 Info.MapTypesArray, NumTeams,
6030 ThreadLimit};
Samuel Antaob68e2db2016-03-03 16:20:23 +00006031 Return = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006032 RT.createRuntimeFunction(OMPRTL__tgt_target_teams), OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00006033 } else {
6034 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00006035 DeviceID, OutlinedFnID,
6036 PointerNum, Info.BasePointersArray,
6037 Info.PointersArray, Info.SizesArray,
6038 Info.MapTypesArray};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006039 Return = CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target),
Samuel Antaob68e2db2016-03-03 16:20:23 +00006040 OffloadingArgs);
6041 }
Samuel Antaobed3c462015-10-02 16:14:20 +00006042
6043 CGF.EmitStoreOfScalar(Return, OffloadError);
6044 };
6045
Samuel Antaoee8fb302016-01-06 13:42:12 +00006046 // Notify that the host version must be executed.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006047 auto &&ElseGen = [OffloadError](CodeGenFunction &CGF, PrePostActionTy &) {
6048 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/-1u),
Samuel Antaoee8fb302016-01-06 13:42:12 +00006049 OffloadError);
6050 };
6051
6052 // If we have a target function ID it means that we need to support
6053 // offloading, otherwise, just execute on the host. We need to execute on host
6054 // regardless of the conditional in the if clause if, e.g., the user do not
6055 // specify target triples.
6056 if (OutlinedFnID) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006057 if (IfCond)
Samuel Antaoee8fb302016-01-06 13:42:12 +00006058 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006059 else {
6060 RegionCodeGenTy ThenRCG(ThenGen);
6061 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00006062 }
6063 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006064 RegionCodeGenTy ElseRCG(ElseGen);
6065 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00006066 }
Samuel Antaobed3c462015-10-02 16:14:20 +00006067
6068 // Check the error code and execute the host version if required.
6069 auto OffloadFailedBlock = CGF.createBasicBlock("omp_offload.failed");
6070 auto OffloadContBlock = CGF.createBasicBlock("omp_offload.cont");
6071 auto OffloadErrorVal = CGF.EmitLoadOfScalar(OffloadError, SourceLocation());
6072 auto Failed = CGF.Builder.CreateIsNotNull(OffloadErrorVal);
6073 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
6074
6075 CGF.EmitBlock(OffloadFailedBlock);
Samuel Antao86ace552016-04-27 22:40:57 +00006076 CGF.Builder.CreateCall(OutlinedFn, KernelArgs);
Samuel Antaobed3c462015-10-02 16:14:20 +00006077 CGF.EmitBranch(OffloadContBlock);
6078
6079 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00006080}
Samuel Antaoee8fb302016-01-06 13:42:12 +00006081
6082void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
6083 StringRef ParentName) {
6084 if (!S)
6085 return;
6086
6087 // If we find a OMP target directive, codegen the outline function and
6088 // register the result.
6089 // FIXME: Add other directives with target when they become supported.
6090 bool isTargetDirective = isa<OMPTargetDirective>(S);
6091
6092 if (isTargetDirective) {
6093 auto *E = cast<OMPExecutableDirective>(S);
6094 unsigned DeviceID;
6095 unsigned FileID;
6096 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00006097 getTargetEntryUniqueInfo(CGM.getContext(), E->getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00006098 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006099
6100 // Is this a target region that should not be emitted as an entry point? If
6101 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00006102 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
6103 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00006104 return;
6105
6106 llvm::Function *Fn;
6107 llvm::Constant *Addr;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00006108 std::tie(Fn, Addr) =
6109 CodeGenFunction::EmitOMPTargetDirectiveOutlinedFunction(
6110 CGM, cast<OMPTargetDirective>(*E), ParentName,
6111 /*isOffloadEntry=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006112 assert(Fn && Addr && "Target region emission failed.");
6113 return;
6114 }
6115
6116 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
Samuel Antaoe49645c2016-05-08 06:43:56 +00006117 if (!E->hasAssociatedStmt())
Samuel Antaoee8fb302016-01-06 13:42:12 +00006118 return;
6119
6120 scanForTargetRegionsFunctions(
6121 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
6122 ParentName);
6123 return;
6124 }
6125
6126 // If this is a lambda function, look into its body.
6127 if (auto *L = dyn_cast<LambdaExpr>(S))
6128 S = L->getBody();
6129
6130 // Keep looking for target regions recursively.
6131 for (auto *II : S->children())
6132 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00006133}
6134
6135bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
6136 auto &FD = *cast<FunctionDecl>(GD.getDecl());
6137
6138 // If emitting code for the host, we do not process FD here. Instead we do
6139 // the normal code generation.
6140 if (!CGM.getLangOpts().OpenMPIsDevice)
6141 return false;
6142
6143 // Try to detect target regions in the function.
6144 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
6145
Samuel Antao4b75b872016-12-12 19:26:31 +00006146 // We should not emit any function other that the ones created during the
Samuel Antaoee8fb302016-01-06 13:42:12 +00006147 // scanning. Therefore, we signal that this function is completely dealt
6148 // with.
6149 return true;
6150}
6151
6152bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
6153 if (!CGM.getLangOpts().OpenMPIsDevice)
6154 return false;
6155
6156 // Check if there are Ctors/Dtors in this declaration and look for target
6157 // regions in it. We use the complete variant to produce the kernel name
6158 // mangling.
6159 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
6160 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
6161 for (auto *Ctor : RD->ctors()) {
6162 StringRef ParentName =
6163 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
6164 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
6165 }
6166 auto *Dtor = RD->getDestructor();
6167 if (Dtor) {
6168 StringRef ParentName =
6169 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
6170 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
6171 }
6172 }
6173
6174 // If we are in target mode we do not emit any global (declare target is not
6175 // implemented yet). Therefore we signal that GD was processed in this case.
6176 return true;
6177}
6178
6179bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
6180 auto *VD = GD.getDecl();
6181 if (isa<FunctionDecl>(VD))
6182 return emitTargetFunctions(GD);
6183
6184 return emitTargetGlobalVariable(GD);
6185}
6186
6187llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
6188 // If we have offloading in the current module, we need to emit the entries
6189 // now and register the offloading descriptor.
6190 createOffloadEntriesAndInfoMetadata();
6191
6192 // Create and register the offloading binary descriptors. This is the main
6193 // entity that captures all the information about offloading in the current
6194 // compilation unit.
6195 return createOffloadingBinaryDescriptorRegistration();
6196}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006197
6198void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
6199 const OMPExecutableDirective &D,
6200 SourceLocation Loc,
6201 llvm::Value *OutlinedFn,
6202 ArrayRef<llvm::Value *> CapturedVars) {
6203 if (!CGF.HaveInsertPoint())
6204 return;
6205
6206 auto *RTLoc = emitUpdateLocation(CGF, Loc);
6207 CodeGenFunction::RunCleanupsScope Scope(CGF);
6208
6209 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
6210 llvm::Value *Args[] = {
6211 RTLoc,
6212 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
6213 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
6214 llvm::SmallVector<llvm::Value *, 16> RealArgs;
6215 RealArgs.append(std::begin(Args), std::end(Args));
6216 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
6217
6218 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
6219 CGF.EmitRuntimeCall(RTLFn, RealArgs);
6220}
6221
6222void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00006223 const Expr *NumTeams,
6224 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006225 SourceLocation Loc) {
6226 if (!CGF.HaveInsertPoint())
6227 return;
6228
6229 auto *RTLoc = emitUpdateLocation(CGF, Loc);
6230
Carlo Bertollic6872252016-04-04 15:55:02 +00006231 llvm::Value *NumTeamsVal =
6232 (NumTeams)
6233 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
6234 CGF.CGM.Int32Ty, /* isSigned = */ true)
6235 : CGF.Builder.getInt32(0);
6236
6237 llvm::Value *ThreadLimitVal =
6238 (ThreadLimit)
6239 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
6240 CGF.CGM.Int32Ty, /* isSigned = */ true)
6241 : CGF.Builder.getInt32(0);
6242
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006243 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00006244 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
6245 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00006246 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
6247 PushNumTeamsArgs);
6248}
Samuel Antaodf158d52016-04-27 22:58:19 +00006249
Samuel Antaocc10b852016-07-28 14:23:26 +00006250void CGOpenMPRuntime::emitTargetDataCalls(
6251 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
6252 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006253 if (!CGF.HaveInsertPoint())
6254 return;
6255
Samuel Antaocc10b852016-07-28 14:23:26 +00006256 // Action used to replace the default codegen action and turn privatization
6257 // off.
6258 PrePostActionTy NoPrivAction;
Samuel Antaodf158d52016-04-27 22:58:19 +00006259
6260 // Generate the code for the opening of the data environment. Capture all the
6261 // arguments of the runtime call by reference because they are used in the
6262 // closing of the region.
Samuel Antaocc10b852016-07-28 14:23:26 +00006263 auto &&BeginThenGen = [&D, &CGF, Device, &Info, &CodeGen, &NoPrivAction](
6264 CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaodf158d52016-04-27 22:58:19 +00006265 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00006266 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaodf158d52016-04-27 22:58:19 +00006267 MappableExprsHandler::MapValuesArrayTy Pointers;
6268 MappableExprsHandler::MapValuesArrayTy Sizes;
6269 MappableExprsHandler::MapFlagsArrayTy MapTypes;
6270
6271 // Get map clause information.
6272 MappableExprsHandler MCHandler(D, CGF);
6273 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaodf158d52016-04-27 22:58:19 +00006274
6275 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00006276 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00006277
6278 llvm::Value *BasePointersArrayArg = nullptr;
6279 llvm::Value *PointersArrayArg = nullptr;
6280 llvm::Value *SizesArrayArg = nullptr;
6281 llvm::Value *MapTypesArrayArg = nullptr;
6282 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006283 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00006284
6285 // Emit device ID if any.
6286 llvm::Value *DeviceID = nullptr;
6287 if (Device)
6288 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6289 CGF.Int32Ty, /*isSigned=*/true);
6290 else
6291 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6292
6293 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00006294 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00006295
6296 llvm::Value *OffloadingArgs[] = {
6297 DeviceID, PointerNum, BasePointersArrayArg,
6298 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
6299 auto &RT = CGF.CGM.getOpenMPRuntime();
6300 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_begin),
6301 OffloadingArgs);
Samuel Antaocc10b852016-07-28 14:23:26 +00006302
6303 // If device pointer privatization is required, emit the body of the region
6304 // here. It will have to be duplicated: with and without privatization.
6305 if (!Info.CaptureDeviceAddrMap.empty())
6306 CodeGen(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00006307 };
6308
6309 // Generate code for the closing of the data region.
Samuel Antaocc10b852016-07-28 14:23:26 +00006310 auto &&EndThenGen = [&CGF, Device, &Info](CodeGenFunction &CGF,
6311 PrePostActionTy &) {
6312 assert(Info.isValid() && "Invalid data environment closing arguments.");
Samuel Antaodf158d52016-04-27 22:58:19 +00006313
6314 llvm::Value *BasePointersArrayArg = nullptr;
6315 llvm::Value *PointersArrayArg = nullptr;
6316 llvm::Value *SizesArrayArg = nullptr;
6317 llvm::Value *MapTypesArrayArg = nullptr;
6318 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg,
Samuel Antaocc10b852016-07-28 14:23:26 +00006319 SizesArrayArg, MapTypesArrayArg, Info);
Samuel Antaodf158d52016-04-27 22:58:19 +00006320
6321 // Emit device ID if any.
6322 llvm::Value *DeviceID = nullptr;
6323 if (Device)
6324 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6325 CGF.Int32Ty, /*isSigned=*/true);
6326 else
6327 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6328
6329 // Emit the number of elements in the offloading arrays.
Samuel Antaocc10b852016-07-28 14:23:26 +00006330 auto *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs);
Samuel Antaodf158d52016-04-27 22:58:19 +00006331
6332 llvm::Value *OffloadingArgs[] = {
6333 DeviceID, PointerNum, BasePointersArrayArg,
6334 PointersArrayArg, SizesArrayArg, MapTypesArrayArg};
6335 auto &RT = CGF.CGM.getOpenMPRuntime();
6336 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target_data_end),
6337 OffloadingArgs);
6338 };
6339
Samuel Antaocc10b852016-07-28 14:23:26 +00006340 // If we need device pointer privatization, we need to emit the body of the
6341 // region with no privatization in the 'else' branch of the conditional.
6342 // Otherwise, we don't have to do anything.
6343 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF,
6344 PrePostActionTy &) {
6345 if (!Info.CaptureDeviceAddrMap.empty()) {
6346 CodeGen.setAction(NoPrivAction);
6347 CodeGen(CGF);
6348 }
6349 };
6350
6351 // We don't have to do anything to close the region if the if clause evaluates
6352 // to false.
6353 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
Samuel Antaodf158d52016-04-27 22:58:19 +00006354
6355 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006356 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00006357 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00006358 RegionCodeGenTy RCG(BeginThenGen);
6359 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00006360 }
6361
Samuel Antaocc10b852016-07-28 14:23:26 +00006362 // If we don't require privatization of device pointers, we emit the body in
6363 // between the runtime calls. This avoids duplicating the body code.
6364 if (Info.CaptureDeviceAddrMap.empty()) {
6365 CodeGen.setAction(NoPrivAction);
6366 CodeGen(CGF);
6367 }
Samuel Antaodf158d52016-04-27 22:58:19 +00006368
6369 if (IfCond) {
Samuel Antaocc10b852016-07-28 14:23:26 +00006370 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen);
Samuel Antaodf158d52016-04-27 22:58:19 +00006371 } else {
Samuel Antaocc10b852016-07-28 14:23:26 +00006372 RegionCodeGenTy RCG(EndThenGen);
6373 RCG(CGF);
Samuel Antaodf158d52016-04-27 22:58:19 +00006374 }
6375}
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006376
Samuel Antao8d2d7302016-05-26 18:30:22 +00006377void CGOpenMPRuntime::emitTargetDataStandAloneCall(
Samuel Antao8dd66282016-04-27 23:14:30 +00006378 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond,
6379 const Expr *Device) {
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006380 if (!CGF.HaveInsertPoint())
6381 return;
6382
Samuel Antao8dd66282016-04-27 23:14:30 +00006383 assert((isa<OMPTargetEnterDataDirective>(D) ||
Samuel Antao8d2d7302016-05-26 18:30:22 +00006384 isa<OMPTargetExitDataDirective>(D) ||
6385 isa<OMPTargetUpdateDirective>(D)) &&
6386 "Expecting either target enter, exit data, or update directives.");
Samuel Antao8dd66282016-04-27 23:14:30 +00006387
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006388 // Generate the code for the opening of the data environment.
6389 auto &&ThenGen = [&D, &CGF, Device](CodeGenFunction &CGF, PrePostActionTy &) {
6390 // Fill up the arrays with all the mapped variables.
Samuel Antaocc10b852016-07-28 14:23:26 +00006391 MappableExprsHandler::MapBaseValuesArrayTy BasePointers;
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006392 MappableExprsHandler::MapValuesArrayTy Pointers;
6393 MappableExprsHandler::MapValuesArrayTy Sizes;
6394 MappableExprsHandler::MapFlagsArrayTy MapTypes;
6395
6396 // Get map clause information.
Samuel Antao8d2d7302016-05-26 18:30:22 +00006397 MappableExprsHandler MEHandler(D, CGF);
6398 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006399
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006400 // Fill up the arrays and create the arguments.
Samuel Antaocc10b852016-07-28 14:23:26 +00006401 TargetDataInfo Info;
6402 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info);
6403 emitOffloadingArraysArgument(CGF, Info.BasePointersArray,
6404 Info.PointersArray, Info.SizesArray,
6405 Info.MapTypesArray, Info);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006406
6407 // Emit device ID if any.
6408 llvm::Value *DeviceID = nullptr;
6409 if (Device)
6410 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
6411 CGF.Int32Ty, /*isSigned=*/true);
6412 else
6413 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
6414
6415 // Emit the number of elements in the offloading arrays.
6416 auto *PointerNum = CGF.Builder.getInt32(BasePointers.size());
6417
6418 llvm::Value *OffloadingArgs[] = {
Samuel Antaocc10b852016-07-28 14:23:26 +00006419 DeviceID, PointerNum, Info.BasePointersArray,
6420 Info.PointersArray, Info.SizesArray, Info.MapTypesArray};
Samuel Antao8d2d7302016-05-26 18:30:22 +00006421
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006422 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antao8d2d7302016-05-26 18:30:22 +00006423 // Select the right runtime function call for each expected standalone
6424 // directive.
6425 OpenMPRTLFunction RTLFn;
6426 switch (D.getDirectiveKind()) {
6427 default:
6428 llvm_unreachable("Unexpected standalone target data directive.");
6429 break;
6430 case OMPD_target_enter_data:
6431 RTLFn = OMPRTL__tgt_target_data_begin;
6432 break;
6433 case OMPD_target_exit_data:
6434 RTLFn = OMPRTL__tgt_target_data_end;
6435 break;
6436 case OMPD_target_update:
6437 RTLFn = OMPRTL__tgt_target_data_update;
6438 break;
6439 }
6440 CGF.EmitRuntimeCall(RT.createRuntimeFunction(RTLFn), OffloadingArgs);
Samuel Antaobd0ae2e2016-04-27 23:07:29 +00006441 };
6442
6443 // In the event we get an if clause, we don't have to take any action on the
6444 // else side.
6445 auto &&ElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {};
6446
6447 if (IfCond) {
6448 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
6449 } else {
6450 RegionCodeGenTy ThenGenRCG(ThenGen);
6451 ThenGenRCG(CGF);
6452 }
6453}
Alexey Bataevc7a82b42016-05-06 09:40:08 +00006454
6455namespace {
6456 /// Kind of parameter in a function with 'declare simd' directive.
6457 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector };
6458 /// Attribute set of the parameter.
6459 struct ParamAttrTy {
6460 ParamKindTy Kind = Vector;
6461 llvm::APSInt StrideOrArg;
6462 llvm::APSInt Alignment;
6463 };
6464} // namespace
6465
6466static unsigned evaluateCDTSize(const FunctionDecl *FD,
6467 ArrayRef<ParamAttrTy> ParamAttrs) {
6468 // Every vector variant of a SIMD-enabled function has a vector length (VLEN).
6469 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument
6470 // of that clause. The VLEN value must be power of 2.
6471 // In other case the notion of the function`s "characteristic data type" (CDT)
6472 // is used to compute the vector length.
6473 // CDT is defined in the following order:
6474 // a) For non-void function, the CDT is the return type.
6475 // b) If the function has any non-uniform, non-linear parameters, then the
6476 // CDT is the type of the first such parameter.
6477 // c) If the CDT determined by a) or b) above is struct, union, or class
6478 // type which is pass-by-value (except for the type that maps to the
6479 // built-in complex data type), the characteristic data type is int.
6480 // d) If none of the above three cases is applicable, the CDT is int.
6481 // The VLEN is then determined based on the CDT and the size of vector
6482 // register of that ISA for which current vector version is generated. The
6483 // VLEN is computed using the formula below:
6484 // VLEN = sizeof(vector_register) / sizeof(CDT),
6485 // where vector register size specified in section 3.2.1 Registers and the
6486 // Stack Frame of original AMD64 ABI document.
6487 QualType RetType = FD->getReturnType();
6488 if (RetType.isNull())
6489 return 0;
6490 ASTContext &C = FD->getASTContext();
6491 QualType CDT;
6492 if (!RetType.isNull() && !RetType->isVoidType())
6493 CDT = RetType;
6494 else {
6495 unsigned Offset = 0;
6496 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6497 if (ParamAttrs[Offset].Kind == Vector)
6498 CDT = C.getPointerType(C.getRecordType(MD->getParent()));
6499 ++Offset;
6500 }
6501 if (CDT.isNull()) {
6502 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) {
6503 if (ParamAttrs[I + Offset].Kind == Vector) {
6504 CDT = FD->getParamDecl(I)->getType();
6505 break;
6506 }
6507 }
6508 }
6509 }
6510 if (CDT.isNull())
6511 CDT = C.IntTy;
6512 CDT = CDT->getCanonicalTypeUnqualified();
6513 if (CDT->isRecordType() || CDT->isUnionType())
6514 CDT = C.IntTy;
6515 return C.getTypeSize(CDT);
6516}
6517
6518static void
6519emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn,
Benjamin Kramer81cb4b72016-11-24 16:01:20 +00006520 const llvm::APSInt &VLENVal,
Alexey Bataevc7a82b42016-05-06 09:40:08 +00006521 ArrayRef<ParamAttrTy> ParamAttrs,
6522 OMPDeclareSimdDeclAttr::BranchStateTy State) {
6523 struct ISADataTy {
6524 char ISA;
6525 unsigned VecRegSize;
6526 };
6527 ISADataTy ISAData[] = {
6528 {
6529 'b', 128
6530 }, // SSE
6531 {
6532 'c', 256
6533 }, // AVX
6534 {
6535 'd', 256
6536 }, // AVX2
6537 {
6538 'e', 512
6539 }, // AVX512
6540 };
6541 llvm::SmallVector<char, 2> Masked;
6542 switch (State) {
6543 case OMPDeclareSimdDeclAttr::BS_Undefined:
6544 Masked.push_back('N');
6545 Masked.push_back('M');
6546 break;
6547 case OMPDeclareSimdDeclAttr::BS_Notinbranch:
6548 Masked.push_back('N');
6549 break;
6550 case OMPDeclareSimdDeclAttr::BS_Inbranch:
6551 Masked.push_back('M');
6552 break;
6553 }
6554 for (auto Mask : Masked) {
6555 for (auto &Data : ISAData) {
6556 SmallString<256> Buffer;
6557 llvm::raw_svector_ostream Out(Buffer);
6558 Out << "_ZGV" << Data.ISA << Mask;
6559 if (!VLENVal) {
6560 Out << llvm::APSInt::getUnsigned(Data.VecRegSize /
6561 evaluateCDTSize(FD, ParamAttrs));
6562 } else
6563 Out << VLENVal;
6564 for (auto &ParamAttr : ParamAttrs) {
6565 switch (ParamAttr.Kind){
6566 case LinearWithVarStride:
6567 Out << 's' << ParamAttr.StrideOrArg;
6568 break;
6569 case Linear:
6570 Out << 'l';
6571 if (!!ParamAttr.StrideOrArg)
6572 Out << ParamAttr.StrideOrArg;
6573 break;
6574 case Uniform:
6575 Out << 'u';
6576 break;
6577 case Vector:
6578 Out << 'v';
6579 break;
6580 }
6581 if (!!ParamAttr.Alignment)
6582 Out << 'a' << ParamAttr.Alignment;
6583 }
6584 Out << '_' << Fn->getName();
6585 Fn->addFnAttr(Out.str());
6586 }
6587 }
6588}
6589
6590void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD,
6591 llvm::Function *Fn) {
6592 ASTContext &C = CGM.getContext();
6593 FD = FD->getCanonicalDecl();
6594 // Map params to their positions in function decl.
6595 llvm::DenseMap<const Decl *, unsigned> ParamPositions;
6596 if (isa<CXXMethodDecl>(FD))
6597 ParamPositions.insert({FD, 0});
6598 unsigned ParamPos = ParamPositions.size();
David Majnemer59f77922016-06-24 04:05:48 +00006599 for (auto *P : FD->parameters()) {
Alexey Bataevc7a82b42016-05-06 09:40:08 +00006600 ParamPositions.insert({P->getCanonicalDecl(), ParamPos});
6601 ++ParamPos;
6602 }
6603 for (auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) {
6604 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size());
6605 // Mark uniform parameters.
6606 for (auto *E : Attr->uniforms()) {
6607 E = E->IgnoreParenImpCasts();
6608 unsigned Pos;
6609 if (isa<CXXThisExpr>(E))
6610 Pos = ParamPositions[FD];
6611 else {
6612 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
6613 ->getCanonicalDecl();
6614 Pos = ParamPositions[PVD];
6615 }
6616 ParamAttrs[Pos].Kind = Uniform;
6617 }
6618 // Get alignment info.
6619 auto NI = Attr->alignments_begin();
6620 for (auto *E : Attr->aligneds()) {
6621 E = E->IgnoreParenImpCasts();
6622 unsigned Pos;
6623 QualType ParmTy;
6624 if (isa<CXXThisExpr>(E)) {
6625 Pos = ParamPositions[FD];
6626 ParmTy = E->getType();
6627 } else {
6628 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
6629 ->getCanonicalDecl();
6630 Pos = ParamPositions[PVD];
6631 ParmTy = PVD->getType();
6632 }
6633 ParamAttrs[Pos].Alignment =
6634 (*NI) ? (*NI)->EvaluateKnownConstInt(C)
6635 : llvm::APSInt::getUnsigned(
6636 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy))
6637 .getQuantity());
6638 ++NI;
6639 }
6640 // Mark linear parameters.
6641 auto SI = Attr->steps_begin();
6642 auto MI = Attr->modifiers_begin();
6643 for (auto *E : Attr->linears()) {
6644 E = E->IgnoreParenImpCasts();
6645 unsigned Pos;
6646 if (isa<CXXThisExpr>(E))
6647 Pos = ParamPositions[FD];
6648 else {
6649 auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl())
6650 ->getCanonicalDecl();
6651 Pos = ParamPositions[PVD];
6652 }
6653 auto &ParamAttr = ParamAttrs[Pos];
6654 ParamAttr.Kind = Linear;
6655 if (*SI) {
6656 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C,
6657 Expr::SE_AllowSideEffects)) {
6658 if (auto *DRE = cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) {
6659 if (auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) {
6660 ParamAttr.Kind = LinearWithVarStride;
6661 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned(
6662 ParamPositions[StridePVD->getCanonicalDecl()]);
6663 }
6664 }
6665 }
6666 }
6667 ++SI;
6668 ++MI;
6669 }
6670 llvm::APSInt VLENVal;
6671 if (const Expr *VLEN = Attr->getSimdlen())
6672 VLENVal = VLEN->EvaluateKnownConstInt(C);
6673 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState();
6674 if (CGM.getTriple().getArch() == llvm::Triple::x86 ||
6675 CGM.getTriple().getArch() == llvm::Triple::x86_64)
6676 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State);
6677 }
6678}
Alexey Bataev8b427062016-05-25 12:36:08 +00006679
6680namespace {
6681/// Cleanup action for doacross support.
6682class DoacrossCleanupTy final : public EHScopeStack::Cleanup {
6683public:
6684 static const int DoacrossFinArgs = 2;
6685
6686private:
6687 llvm::Value *RTLFn;
6688 llvm::Value *Args[DoacrossFinArgs];
6689
6690public:
6691 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs)
6692 : RTLFn(RTLFn) {
6693 assert(CallArgs.size() == DoacrossFinArgs);
6694 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args));
6695 }
6696 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
6697 if (!CGF.HaveInsertPoint())
6698 return;
6699 CGF.EmitRuntimeCall(RTLFn, Args);
6700 }
6701};
6702} // namespace
6703
6704void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF,
6705 const OMPLoopDirective &D) {
6706 if (!CGF.HaveInsertPoint())
6707 return;
6708
6709 ASTContext &C = CGM.getContext();
6710 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true);
6711 RecordDecl *RD;
6712 if (KmpDimTy.isNull()) {
6713 // Build struct kmp_dim { // loop bounds info casted to kmp_int64
6714 // kmp_int64 lo; // lower
6715 // kmp_int64 up; // upper
6716 // kmp_int64 st; // stride
6717 // };
6718 RD = C.buildImplicitRecord("kmp_dim");
6719 RD->startDefinition();
6720 addFieldToRecordDecl(C, RD, Int64Ty);
6721 addFieldToRecordDecl(C, RD, Int64Ty);
6722 addFieldToRecordDecl(C, RD, Int64Ty);
6723 RD->completeDefinition();
6724 KmpDimTy = C.getRecordType(RD);
6725 } else
6726 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl());
6727
6728 Address DimsAddr = CGF.CreateMemTemp(KmpDimTy, "dims");
6729 CGF.EmitNullInitialization(DimsAddr, KmpDimTy);
6730 enum { LowerFD = 0, UpperFD, StrideFD };
6731 // Fill dims with data.
6732 LValue DimsLVal = CGF.MakeAddrLValue(DimsAddr, KmpDimTy);
6733 // dims.upper = num_iterations;
6734 LValue UpperLVal =
6735 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), UpperFD));
6736 llvm::Value *NumIterVal = CGF.EmitScalarConversion(
6737 CGF.EmitScalarExpr(D.getNumIterations()), D.getNumIterations()->getType(),
6738 Int64Ty, D.getNumIterations()->getExprLoc());
6739 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal);
6740 // dims.stride = 1;
6741 LValue StrideLVal =
6742 CGF.EmitLValueForField(DimsLVal, *std::next(RD->field_begin(), StrideFD));
6743 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1),
6744 StrideLVal);
6745
6746 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid,
6747 // kmp_int32 num_dims, struct kmp_dim * dims);
6748 llvm::Value *Args[] = {emitUpdateLocation(CGF, D.getLocStart()),
6749 getThreadID(CGF, D.getLocStart()),
6750 llvm::ConstantInt::getSigned(CGM.Int32Ty, 1),
6751 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
6752 DimsAddr.getPointer(), CGM.VoidPtrTy)};
6753
6754 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init);
6755 CGF.EmitRuntimeCall(RTLFn, Args);
6756 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = {
6757 emitUpdateLocation(CGF, D.getLocEnd()), getThreadID(CGF, D.getLocEnd())};
6758 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini);
6759 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn,
6760 llvm::makeArrayRef(FiniArgs));
6761}
6762
6763void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF,
6764 const OMPDependClause *C) {
6765 QualType Int64Ty =
6766 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
6767 const Expr *CounterVal = C->getCounterValue();
6768 assert(CounterVal);
6769 llvm::Value *CntVal = CGF.EmitScalarConversion(CGF.EmitScalarExpr(CounterVal),
6770 CounterVal->getType(), Int64Ty,
6771 CounterVal->getExprLoc());
6772 Address CntAddr = CGF.CreateMemTemp(Int64Ty, ".cnt.addr");
6773 CGF.EmitStoreOfScalar(CntVal, CntAddr, /*Volatile=*/false, Int64Ty);
6774 llvm::Value *Args[] = {emitUpdateLocation(CGF, C->getLocStart()),
6775 getThreadID(CGF, C->getLocStart()),
6776 CntAddr.getPointer()};
6777 llvm::Value *RTLFn;
6778 if (C->getDependencyKind() == OMPC_DEPEND_source)
6779 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post);
6780 else {
6781 assert(C->getDependencyKind() == OMPC_DEPEND_sink);
6782 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait);
6783 }
6784 CGF.EmitRuntimeCall(RTLFn, Args);
6785}
6786