blob: 442d64ba38e0aa3497b73066da377d6eed9f0a51 [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"
18#include "clang/AST/Decl.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000019#include "clang/AST/StmtOpenMP.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000020#include "llvm/ADT/ArrayRef.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000021#include "llvm/Bitcode/ReaderWriter.h"
Alexey Bataevd74d0602014-10-13 06:02:40 +000022#include "llvm/IR/CallSite.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000023#include "llvm/IR/DerivedTypes.h"
24#include "llvm/IR/GlobalValue.h"
25#include "llvm/IR/Value.h"
Samuel Antaoee8fb302016-01-06 13:42:12 +000026#include "llvm/Support/Format.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000027#include "llvm/Support/raw_ostream.h"
Alexey Bataev23b69422014-06-18 07:08:49 +000028#include <cassert>
Alexey Bataev9959db52014-05-06 10:08:46 +000029
30using namespace clang;
31using namespace CodeGen;
32
Benjamin Kramerc52193f2014-10-10 13:57:57 +000033namespace {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000034/// \brief Base class for handling code generation inside OpenMP regions.
Alexey Bataev18095712014-10-10 12:19:54 +000035class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
36public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000037 /// \brief Kinds of OpenMP regions used in codegen.
38 enum CGOpenMPRegionKind {
39 /// \brief Region with outlined function for standalone 'parallel'
40 /// directive.
41 ParallelOutlinedRegion,
42 /// \brief Region with outlined function for standalone 'task' directive.
43 TaskOutlinedRegion,
44 /// \brief Region for constructs that do not require function outlining,
45 /// like 'for', 'sections', 'atomic' etc. directives.
46 InlinedRegion,
Samuel Antaobed3c462015-10-02 16:14:20 +000047 /// \brief Region with outlined function for standalone 'target' directive.
48 TargetRegion,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000049 };
Alexey Bataev18095712014-10-10 12:19:54 +000050
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000051 CGOpenMPRegionInfo(const CapturedStmt &CS,
52 const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000053 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
54 bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000055 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
Alexey Bataev25e5b442015-09-15 12:52:43 +000056 CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000057
58 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +000059 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
60 bool HasCancel)
Alexey Bataev81c7ea02015-07-03 09:56:58 +000061 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
Alexey Bataev25e5b442015-09-15 12:52:43 +000062 Kind(Kind), HasCancel(HasCancel) {}
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000063
64 /// \brief Get a variable or parameter for storing global thread id
Alexey Bataev18095712014-10-10 12:19:54 +000065 /// inside OpenMP construct.
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000066 virtual const VarDecl *getThreadIDVariable() const = 0;
Alexey Bataev18095712014-10-10 12:19:54 +000067
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000068 /// \brief Emit the captured statement body.
Hans Wennborg7eb54642015-09-10 17:07:54 +000069 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000070
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000071 /// \brief Get an LValue for the current ThreadID variable.
Alexey Bataev62b63b12015-03-10 07:28:44 +000072 /// \return LValue for thread id variable. This LValue always has type int32*.
73 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
Alexey Bataev18095712014-10-10 12:19:54 +000074
Alexey Bataev48591dd2016-04-20 04:01:36 +000075 virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {}
76
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000077 CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000078
Alexey Bataev81c7ea02015-07-03 09:56:58 +000079 OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
80
Alexey Bataev25e5b442015-09-15 12:52:43 +000081 bool hasCancel() const { return HasCancel; }
82
Alexey Bataev18095712014-10-10 12:19:54 +000083 static bool classof(const CGCapturedStmtInfo *Info) {
84 return Info->getKind() == CR_OpenMP;
85 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000086
Alexey Bataev48591dd2016-04-20 04:01:36 +000087 ~CGOpenMPRegionInfo() override = default;
88
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000089protected:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000090 CGOpenMPRegionKind RegionKind;
Hans Wennborg45c74392016-01-12 20:54:36 +000091 RegionCodeGenTy CodeGen;
Alexey Bataev81c7ea02015-07-03 09:56:58 +000092 OpenMPDirectiveKind Kind;
Alexey Bataev25e5b442015-09-15 12:52:43 +000093 bool HasCancel;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000094};
Alexey Bataev18095712014-10-10 12:19:54 +000095
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000096/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +000097class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +000098public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +000099 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000100 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000101 OpenMPDirectiveKind Kind, bool HasCancel)
102 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
103 HasCancel),
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000104 ThreadIDVar(ThreadIDVar) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000105 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
106 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000107
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000108 /// \brief Get a variable or parameter for storing global thread id
109 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000110 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000111
Alexey Bataev18095712014-10-10 12:19:54 +0000112 /// \brief Get the name of the capture helper.
Benjamin Kramerc52193f2014-10-10 13:57:57 +0000113 StringRef getHelperName() const override { return ".omp_outlined."; }
Alexey Bataev18095712014-10-10 12:19:54 +0000114
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000115 static bool classof(const CGCapturedStmtInfo *Info) {
116 return CGOpenMPRegionInfo::classof(Info) &&
117 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
118 ParallelOutlinedRegion;
119 }
120
Alexey Bataev18095712014-10-10 12:19:54 +0000121private:
122 /// \brief A variable or parameter storing global thread id for OpenMP
123 /// constructs.
124 const VarDecl *ThreadIDVar;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000125};
126
Alexey Bataev62b63b12015-03-10 07:28:44 +0000127/// \brief API for captured statement code generation in OpenMP constructs.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000128class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000129public:
Alexey Bataev48591dd2016-04-20 04:01:36 +0000130 class UntiedTaskActionTy final : public PrePostActionTy {
131 bool Untied;
132 const VarDecl *PartIDVar;
133 const RegionCodeGenTy UntiedCodeGen;
134 llvm::SwitchInst *UntiedSwitch = nullptr;
135
136 public:
137 UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
138 const RegionCodeGenTy &UntiedCodeGen)
139 : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
140 void Enter(CodeGenFunction &CGF) override {
141 if (Untied) {
142 // Emit task switching point.
143 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
144 CGF.GetAddrOfLocalVar(PartIDVar),
145 PartIDVar->getType()->castAs<PointerType>());
146 auto *Res = CGF.EmitLoadOfScalar(PartIdLVal, SourceLocation());
147 auto *DoneBB = CGF.createBasicBlock(".untied.done.");
148 UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
149 CGF.EmitBlock(DoneBB);
150 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
151 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
152 UntiedSwitch->addCase(CGF.Builder.getInt32(0),
153 CGF.Builder.GetInsertBlock());
154 emitUntiedSwitch(CGF);
155 }
156 }
157 void emitUntiedSwitch(CodeGenFunction &CGF) const {
158 if (Untied) {
159 auto PartIdLVal = CGF.EmitLoadOfPointerLValue(
160 CGF.GetAddrOfLocalVar(PartIDVar),
161 PartIDVar->getType()->castAs<PointerType>());
162 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
163 PartIdLVal);
164 UntiedCodeGen(CGF);
165 CodeGenFunction::JumpDest CurPoint =
166 CGF.getJumpDestInCurrentScope(".untied.next.");
167 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
168 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
169 UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
170 CGF.Builder.GetInsertBlock());
171 CGF.EmitBranchThroughCleanup(CurPoint);
172 CGF.EmitBlock(CurPoint.getBlock());
173 }
174 }
175 unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
176 };
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000177 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
Alexey Bataev62b63b12015-03-10 07:28:44 +0000178 const VarDecl *ThreadIDVar,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000179 const RegionCodeGenTy &CodeGen,
Alexey Bataev48591dd2016-04-20 04:01:36 +0000180 OpenMPDirectiveKind Kind, bool HasCancel,
181 const UntiedTaskActionTy &Action)
Alexey Bataev25e5b442015-09-15 12:52:43 +0000182 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
Alexey Bataev48591dd2016-04-20 04:01:36 +0000183 ThreadIDVar(ThreadIDVar), Action(Action) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000184 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
185 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000186
Alexey Bataev62b63b12015-03-10 07:28:44 +0000187 /// \brief Get a variable or parameter for storing global thread id
188 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000189 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000190
191 /// \brief Get an LValue for the current ThreadID variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000192 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000193
Alexey Bataev62b63b12015-03-10 07:28:44 +0000194 /// \brief Get the name of the capture helper.
195 StringRef getHelperName() const override { return ".omp_outlined."; }
196
Alexey Bataev48591dd2016-04-20 04:01:36 +0000197 void emitUntiedSwitch(CodeGenFunction &CGF) override {
198 Action.emitUntiedSwitch(CGF);
199 }
200
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000201 static bool classof(const CGCapturedStmtInfo *Info) {
202 return CGOpenMPRegionInfo::classof(Info) &&
203 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
204 TaskOutlinedRegion;
205 }
206
Alexey Bataev62b63b12015-03-10 07:28:44 +0000207private:
208 /// \brief A variable or parameter storing global thread id for OpenMP
209 /// constructs.
210 const VarDecl *ThreadIDVar;
Alexey Bataev48591dd2016-04-20 04:01:36 +0000211 /// Action for emitting code for untied tasks.
212 const UntiedTaskActionTy &Action;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000213};
214
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000215/// \brief API for inlined captured statement code generation in OpenMP
216/// constructs.
217class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
218public:
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000219 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000220 const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000221 OpenMPDirectiveKind Kind, bool HasCancel)
222 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
223 OldCSI(OldCSI),
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000224 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000225
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000226 // \brief Retrieve the value of the context parameter.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000227 llvm::Value *getContextValue() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000228 if (OuterRegionInfo)
229 return OuterRegionInfo->getContextValue();
230 llvm_unreachable("No context value for inlined OpenMP region");
231 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000232
Hans Wennborg7eb54642015-09-10 17:07:54 +0000233 void setContextValue(llvm::Value *V) override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000234 if (OuterRegionInfo) {
235 OuterRegionInfo->setContextValue(V);
236 return;
237 }
238 llvm_unreachable("No context value for inlined OpenMP region");
239 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000240
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000241 /// \brief Lookup the captured field decl for a variable.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000242 const FieldDecl *lookup(const VarDecl *VD) const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000243 if (OuterRegionInfo)
244 return OuterRegionInfo->lookup(VD);
Alexey Bataev69c62a92015-04-15 04:52:20 +0000245 // If there is no outer outlined region,no need to lookup in a list of
246 // captured variables, we can use the original one.
247 return nullptr;
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000248 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000249
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000250 FieldDecl *getThisFieldDecl() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000251 if (OuterRegionInfo)
252 return OuterRegionInfo->getThisFieldDecl();
253 return nullptr;
254 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000255
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000256 /// \brief Get a variable or parameter for storing global thread id
257 /// inside OpenMP construct.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000258 const VarDecl *getThreadIDVariable() const override {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000259 if (OuterRegionInfo)
260 return OuterRegionInfo->getThreadIDVariable();
261 return nullptr;
262 }
Alexey Bataev62b63b12015-03-10 07:28:44 +0000263
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000264 /// \brief Get the name of the capture helper.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000265 StringRef getHelperName() const override {
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000266 if (auto *OuterRegionInfo = getOldCSI())
267 return OuterRegionInfo->getHelperName();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000268 llvm_unreachable("No helper name for inlined OpenMP construct");
269 }
270
Alexey Bataev48591dd2016-04-20 04:01:36 +0000271 void emitUntiedSwitch(CodeGenFunction &CGF) override {
272 if (OuterRegionInfo)
273 OuterRegionInfo->emitUntiedSwitch(CGF);
274 }
275
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000276 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
277
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000278 static bool classof(const CGCapturedStmtInfo *Info) {
279 return CGOpenMPRegionInfo::classof(Info) &&
280 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
281 }
282
Alexey Bataev48591dd2016-04-20 04:01:36 +0000283 ~CGOpenMPInlinedRegionInfo() override = default;
284
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000285private:
286 /// \brief CodeGen info about outer OpenMP region.
287 CodeGenFunction::CGCapturedStmtInfo *OldCSI;
288 CGOpenMPRegionInfo *OuterRegionInfo;
Alexey Bataev18095712014-10-10 12:19:54 +0000289};
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000290
Samuel Antaobed3c462015-10-02 16:14:20 +0000291/// \brief API for captured statement code generation in OpenMP target
292/// constructs. For this captures, implicit parameters are used instead of the
Samuel Antaoee8fb302016-01-06 13:42:12 +0000293/// captured fields. The name of the target region has to be unique in a given
294/// application so it is provided by the client, because only the client has
295/// the information to generate that.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000296class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
Samuel Antaobed3c462015-10-02 16:14:20 +0000297public:
298 CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000299 const RegionCodeGenTy &CodeGen, StringRef HelperName)
Samuel Antaobed3c462015-10-02 16:14:20 +0000300 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
Samuel Antaoee8fb302016-01-06 13:42:12 +0000301 /*HasCancel=*/false),
302 HelperName(HelperName) {}
Samuel Antaobed3c462015-10-02 16:14:20 +0000303
304 /// \brief This is unused for target regions because each starts executing
305 /// with a single thread.
306 const VarDecl *getThreadIDVariable() const override { return nullptr; }
307
308 /// \brief Get the name of the capture helper.
Samuel Antaoee8fb302016-01-06 13:42:12 +0000309 StringRef getHelperName() const override { return HelperName; }
Samuel Antaobed3c462015-10-02 16:14:20 +0000310
311 static bool classof(const CGCapturedStmtInfo *Info) {
312 return CGOpenMPRegionInfo::classof(Info) &&
313 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
314 }
Samuel Antaoee8fb302016-01-06 13:42:12 +0000315
316private:
317 StringRef HelperName;
Samuel Antaobed3c462015-10-02 16:14:20 +0000318};
319
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000320static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000321 llvm_unreachable("No codegen for expressions");
322}
323/// \brief API for generation of expressions captured in a innermost OpenMP
324/// region.
Alexey Bataev48591dd2016-04-20 04:01:36 +0000325class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
Samuel Antaob68e2db2016-03-03 16:20:23 +0000326public:
327 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
328 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
329 OMPD_unknown,
330 /*HasCancel=*/false),
331 PrivScope(CGF) {
332 // Make sure the globals captured in the provided statement are local by
333 // using the privatization logic. We assume the same variable is not
334 // captured more than once.
335 for (auto &C : CS.captures()) {
336 if (!C.capturesVariable() && !C.capturesVariableByCopy())
337 continue;
338
339 const VarDecl *VD = C.getCapturedVar();
340 if (VD->isLocalVarDeclOrParm())
341 continue;
342
343 DeclRefExpr DRE(const_cast<VarDecl *>(VD),
344 /*RefersToEnclosingVariableOrCapture=*/false,
345 VD->getType().getNonReferenceType(), VK_LValue,
346 SourceLocation());
347 PrivScope.addPrivate(VD, [&CGF, &DRE]() -> Address {
348 return CGF.EmitLValue(&DRE).getAddress();
349 });
350 }
351 (void)PrivScope.Privatize();
352 }
353
354 /// \brief Lookup the captured field decl for a variable.
355 const FieldDecl *lookup(const VarDecl *VD) const override {
356 if (auto *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
357 return FD;
358 return nullptr;
359 }
360
361 /// \brief Emit the captured statement body.
362 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
363 llvm_unreachable("No body for expressions");
364 }
365
366 /// \brief Get a variable or parameter for storing global thread id
367 /// inside OpenMP construct.
368 const VarDecl *getThreadIDVariable() const override {
369 llvm_unreachable("No thread id for expressions");
370 }
371
372 /// \brief Get the name of the capture helper.
373 StringRef getHelperName() const override {
374 llvm_unreachable("No helper name for expressions");
375 }
376
377 static bool classof(const CGCapturedStmtInfo *Info) { return false; }
378
379private:
380 /// Private scope to capture global variables.
381 CodeGenFunction::OMPPrivateScope PrivScope;
382};
383
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000384/// \brief RAII for emitting code of OpenMP constructs.
385class InlinedOpenMPRegionRAII {
386 CodeGenFunction &CGF;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000387 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
388 FieldDecl *LambdaThisCaptureField = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000389
390public:
391 /// \brief Constructs region for combined constructs.
392 /// \param CodeGen Code generation sequence for combined directives. Includes
393 /// a list of functions used for code generation of implicitly inlined
394 /// regions.
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000395 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
Alexey Bataev25e5b442015-09-15 12:52:43 +0000396 OpenMPDirectiveKind Kind, bool HasCancel)
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000397 : CGF(CGF) {
398 // Start emission for the construct.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000399 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
400 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000401 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
402 LambdaThisCaptureField = CGF.LambdaThisCaptureField;
403 CGF.LambdaThisCaptureField = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000404 }
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000405
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000406 ~InlinedOpenMPRegionRAII() {
407 // Restore original CapturedStmtInfo only if we're done with code emission.
408 auto *OldCSI =
409 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
410 delete CGF.CapturedStmtInfo;
411 CGF.CapturedStmtInfo = OldCSI;
Alexey Bataev4ba78a42016-04-27 07:56:03 +0000412 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
413 CGF.LambdaThisCaptureField = LambdaThisCaptureField;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000414 }
415};
416
Alexey Bataev50b3c952016-02-19 10:38:26 +0000417/// \brief Values for bit flags used in the ident_t to describe the fields.
418/// All enumeric elements are named and described in accordance with the code
419/// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
420enum OpenMPLocationFlags {
421 /// \brief Use trampoline for internal microtask.
422 OMP_IDENT_IMD = 0x01,
423 /// \brief Use c-style ident structure.
424 OMP_IDENT_KMPC = 0x02,
425 /// \brief Atomic reduction option for kmpc_reduce.
426 OMP_ATOMIC_REDUCE = 0x10,
427 /// \brief Explicit 'barrier' directive.
428 OMP_IDENT_BARRIER_EXPL = 0x20,
429 /// \brief Implicit barrier in code.
430 OMP_IDENT_BARRIER_IMPL = 0x40,
431 /// \brief Implicit barrier in 'for' directive.
432 OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
433 /// \brief Implicit barrier in 'sections' directive.
434 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
435 /// \brief Implicit barrier in 'single' directive.
436 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140
437};
438
439/// \brief Describes ident structure that describes a source location.
440/// All descriptions are taken from
441/// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h
442/// Original structure:
443/// typedef struct ident {
444/// kmp_int32 reserved_1; /**< might be used in Fortran;
445/// see above */
446/// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags;
447/// KMP_IDENT_KMPC identifies this union
448/// member */
449/// kmp_int32 reserved_2; /**< not really used in Fortran any more;
450/// see above */
451///#if USE_ITT_BUILD
452/// /* but currently used for storing
453/// region-specific ITT */
454/// /* contextual information. */
455///#endif /* USE_ITT_BUILD */
456/// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for
457/// C++ */
458/// char const *psource; /**< String describing the source location.
459/// The string is composed of semi-colon separated
460// fields which describe the source file,
461/// the function and a pair of line numbers that
462/// delimit the construct.
463/// */
464/// } ident_t;
465enum IdentFieldIndex {
466 /// \brief might be used in Fortran
467 IdentField_Reserved_1,
468 /// \brief OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
469 IdentField_Flags,
470 /// \brief Not really used in Fortran any more
471 IdentField_Reserved_2,
472 /// \brief Source[4] in Fortran, do not use for C++
473 IdentField_Reserved_3,
474 /// \brief String describing the source location. The string is composed of
475 /// semi-colon separated fields which describe the source file, the function
476 /// and a pair of line numbers that delimit the construct.
477 IdentField_PSource
478};
479
480/// \brief Schedule types for 'omp for' loops (these enumerators are taken from
481/// the enum sched_type in kmp.h).
482enum OpenMPSchedType {
483 /// \brief Lower bound for default (unordered) versions.
484 OMP_sch_lower = 32,
485 OMP_sch_static_chunked = 33,
486 OMP_sch_static = 34,
487 OMP_sch_dynamic_chunked = 35,
488 OMP_sch_guided_chunked = 36,
489 OMP_sch_runtime = 37,
490 OMP_sch_auto = 38,
491 /// \brief Lower bound for 'ordered' versions.
492 OMP_ord_lower = 64,
493 OMP_ord_static_chunked = 65,
494 OMP_ord_static = 66,
495 OMP_ord_dynamic_chunked = 67,
496 OMP_ord_guided_chunked = 68,
497 OMP_ord_runtime = 69,
498 OMP_ord_auto = 70,
499 OMP_sch_default = OMP_sch_static,
Carlo Bertollifc35ad22016-03-07 16:04:49 +0000500 /// \brief dist_schedule types
501 OMP_dist_sch_static_chunked = 91,
502 OMP_dist_sch_static = 92,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000503};
504
505enum OpenMPRTLFunction {
506 /// \brief Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc,
507 /// kmpc_micro microtask, ...);
508 OMPRTL__kmpc_fork_call,
509 /// \brief Call to void *__kmpc_threadprivate_cached(ident_t *loc,
510 /// kmp_int32 global_tid, void *data, size_t size, void ***cache);
511 OMPRTL__kmpc_threadprivate_cached,
512 /// \brief Call to void __kmpc_threadprivate_register( ident_t *,
513 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
514 OMPRTL__kmpc_threadprivate_register,
515 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc);
516 OMPRTL__kmpc_global_thread_num,
517 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
518 // kmp_critical_name *crit);
519 OMPRTL__kmpc_critical,
520 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32
521 // global_tid, kmp_critical_name *crit, uintptr_t hint);
522 OMPRTL__kmpc_critical_with_hint,
523 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
524 // kmp_critical_name *crit);
525 OMPRTL__kmpc_end_critical,
526 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
527 // global_tid);
528 OMPRTL__kmpc_cancel_barrier,
529 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
530 OMPRTL__kmpc_barrier,
531 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
532 OMPRTL__kmpc_for_static_fini,
533 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
534 // global_tid);
535 OMPRTL__kmpc_serialized_parallel,
536 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
537 // global_tid);
538 OMPRTL__kmpc_end_serialized_parallel,
539 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
540 // kmp_int32 num_threads);
541 OMPRTL__kmpc_push_num_threads,
542 // Call to void __kmpc_flush(ident_t *loc);
543 OMPRTL__kmpc_flush,
544 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid);
545 OMPRTL__kmpc_master,
546 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid);
547 OMPRTL__kmpc_end_master,
548 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
549 // int end_part);
550 OMPRTL__kmpc_omp_taskyield,
551 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid);
552 OMPRTL__kmpc_single,
553 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid);
554 OMPRTL__kmpc_end_single,
555 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
556 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
557 // kmp_routine_entry_t *task_entry);
558 OMPRTL__kmpc_omp_task_alloc,
559 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t *
560 // new_task);
561 OMPRTL__kmpc_omp_task,
562 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
563 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
564 // kmp_int32 didit);
565 OMPRTL__kmpc_copyprivate,
566 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
567 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
568 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
569 OMPRTL__kmpc_reduce,
570 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
571 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
572 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
573 // *lck);
574 OMPRTL__kmpc_reduce_nowait,
575 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
576 // kmp_critical_name *lck);
577 OMPRTL__kmpc_end_reduce,
578 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
579 // kmp_critical_name *lck);
580 OMPRTL__kmpc_end_reduce_nowait,
581 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
582 // kmp_task_t * new_task);
583 OMPRTL__kmpc_omp_task_begin_if0,
584 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
585 // kmp_task_t * new_task);
586 OMPRTL__kmpc_omp_task_complete_if0,
587 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
588 OMPRTL__kmpc_ordered,
589 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
590 OMPRTL__kmpc_end_ordered,
591 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
592 // global_tid);
593 OMPRTL__kmpc_omp_taskwait,
594 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
595 OMPRTL__kmpc_taskgroup,
596 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
597 OMPRTL__kmpc_end_taskgroup,
598 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
599 // int proc_bind);
600 OMPRTL__kmpc_push_proc_bind,
601 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32
602 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t
603 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
604 OMPRTL__kmpc_omp_task_with_deps,
605 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32
606 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
607 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
608 OMPRTL__kmpc_omp_wait_deps,
609 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
610 // global_tid, kmp_int32 cncl_kind);
611 OMPRTL__kmpc_cancellationpoint,
612 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
613 // kmp_int32 cncl_kind);
614 OMPRTL__kmpc_cancel,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000615 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid,
616 // kmp_int32 num_teams, kmp_int32 thread_limit);
617 OMPRTL__kmpc_push_num_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000618 // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
619 // microtask, ...);
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000620 OMPRTL__kmpc_fork_teams,
Alexey Bataev7292c292016-04-25 12:22:29 +0000621 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
622 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
623 // sched, kmp_uint64 grainsize, void *task_dup);
624 OMPRTL__kmpc_taskloop,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000625
626 //
627 // Offloading related calls
628 //
629 // Call to int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
630 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
631 // *arg_types);
632 OMPRTL__tgt_target,
Samuel Antaob68e2db2016-03-03 16:20:23 +0000633 // Call to int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
634 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
635 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
636 OMPRTL__tgt_target_teams,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000637 // Call to void __tgt_register_lib(__tgt_bin_desc *desc);
638 OMPRTL__tgt_register_lib,
639 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc);
640 OMPRTL__tgt_unregister_lib,
641};
642
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000643/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
644/// region.
645class CleanupTy final : public EHScopeStack::Cleanup {
646 PrePostActionTy *Action;
647
648public:
649 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
650 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
651 if (!CGF.HaveInsertPoint())
652 return;
653 Action->Exit(CGF);
654 }
655};
656
Hans Wennborg7eb54642015-09-10 17:07:54 +0000657} // anonymous namespace
Alexey Bataev18095712014-10-10 12:19:54 +0000658
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000659void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
660 CodeGenFunction::RunCleanupsScope Scope(CGF);
661 if (PrePostAction) {
662 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
663 Callback(CodeGen, CGF, *PrePostAction);
664 } else {
665 PrePostActionTy Action;
666 Callback(CodeGen, CGF, Action);
667 }
668}
669
Alexey Bataev18095712014-10-10 12:19:54 +0000670LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
Alexey Bataev31300ed2016-02-04 11:27:03 +0000671 return CGF.EmitLoadOfPointerLValue(
672 CGF.GetAddrOfLocalVar(getThreadIDVariable()),
673 getThreadIDVariable()->getType()->castAs<PointerType>());
Alexey Bataev18095712014-10-10 12:19:54 +0000674}
675
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000676void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) {
Alexey Bataev8ef31412015-12-18 07:58:25 +0000677 if (!CGF.HaveInsertPoint())
678 return;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000679 // 1.2.2 OpenMP Language Terminology
680 // Structured block - An executable statement with a single entry at the
681 // top and a single exit at the bottom.
682 // The point of exit cannot be a branch out of the structured block.
683 // longjmp() and throw() must not violate the entry/exit criteria.
684 CGF.EHStack.pushTerminate();
Alexey Bataev14fa1c62016-03-29 05:34:15 +0000685 CodeGen(CGF);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +0000686 CGF.EHStack.popTerminate();
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000687}
688
Alexey Bataev62b63b12015-03-10 07:28:44 +0000689LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
690 CodeGenFunction &CGF) {
Alexey Bataev2377fe92015-09-10 08:12:02 +0000691 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
692 getThreadIDVariable()->getType(),
693 AlignmentSource::Decl);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000694}
695
Alexey Bataev9959db52014-05-06 10:08:46 +0000696CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM)
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000697 : CGM(CGM), OffloadEntriesInfoManager(CGM) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000698 IdentTy = llvm::StructType::create(
699 "ident_t", CGM.Int32Ty /* reserved_1 */, CGM.Int32Ty /* flags */,
700 CGM.Int32Ty /* reserved_2 */, CGM.Int32Ty /* reserved_3 */,
Alexander Musmanfdfa8552014-09-11 08:10:57 +0000701 CGM.Int8PtrTy /* psource */, nullptr);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +0000702 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
Samuel Antaoee8fb302016-01-06 13:42:12 +0000703
704 loadOffloadInfoMetadata();
Alexey Bataev9959db52014-05-06 10:08:46 +0000705}
706
Alexey Bataev91797552015-03-18 04:13:55 +0000707void CGOpenMPRuntime::clear() {
708 InternalVars.clear();
709}
710
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000711static llvm::Function *
712emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
713 const Expr *CombinerInitializer, const VarDecl *In,
714 const VarDecl *Out, bool IsCombiner) {
715 // void .omp_combiner.(Ty *in, Ty *out);
716 auto &C = CGM.getContext();
717 QualType PtrTy = C.getPointerType(Ty).withRestrict();
718 FunctionArgList Args;
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000719 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
720 /*Id=*/nullptr, PtrTy);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000721 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
722 /*Id=*/nullptr, PtrTy);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000723 Args.push_back(&OmpOutParm);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000724 Args.push_back(&OmpInParm);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000725 auto &FnInfo =
John McCallc56a8b32016-03-11 04:30:31 +0000726 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000727 auto *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
728 auto *Fn = llvm::Function::Create(
729 FnTy, llvm::GlobalValue::InternalLinkage,
730 IsCombiner ? ".omp_combiner." : ".omp_initializer.", &CGM.getModule());
731 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, FnInfo);
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000732 Fn->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataevc5b1d322016-03-04 09:22:22 +0000733 CodeGenFunction CGF(CGM);
734 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
735 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
736 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args);
737 CodeGenFunction::OMPPrivateScope Scope(CGF);
738 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
739 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() -> Address {
740 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
741 .getAddress();
742 });
743 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
744 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() -> Address {
745 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
746 .getAddress();
747 });
748 (void)Scope.Privatize();
749 CGF.EmitIgnoredExpr(CombinerInitializer);
750 Scope.ForceCleanup();
751 CGF.FinishFunction();
752 return Fn;
753}
754
755void CGOpenMPRuntime::emitUserDefinedReduction(
756 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
757 if (UDRMap.count(D) > 0)
758 return;
759 auto &C = CGM.getContext();
760 if (!In || !Out) {
761 In = &C.Idents.get("omp_in");
762 Out = &C.Idents.get("omp_out");
763 }
764 llvm::Function *Combiner = emitCombinerOrInitializer(
765 CGM, D->getType(), D->getCombiner(), cast<VarDecl>(D->lookup(In).front()),
766 cast<VarDecl>(D->lookup(Out).front()),
767 /*IsCombiner=*/true);
768 llvm::Function *Initializer = nullptr;
769 if (auto *Init = D->getInitializer()) {
770 if (!Priv || !Orig) {
771 Priv = &C.Idents.get("omp_priv");
772 Orig = &C.Idents.get("omp_orig");
773 }
774 Initializer = emitCombinerOrInitializer(
775 CGM, D->getType(), Init, cast<VarDecl>(D->lookup(Orig).front()),
776 cast<VarDecl>(D->lookup(Priv).front()),
777 /*IsCombiner=*/false);
778 }
779 UDRMap.insert(std::make_pair(D, std::make_pair(Combiner, Initializer)));
780 if (CGF) {
781 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
782 Decls.second.push_back(D);
783 }
784}
785
Alexey Bataeva839ddd2016-03-17 10:19:46 +0000786std::pair<llvm::Function *, llvm::Function *>
787CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
788 auto I = UDRMap.find(D);
789 if (I != UDRMap.end())
790 return I->second;
791 emitUserDefinedReduction(/*CGF=*/nullptr, D);
792 return UDRMap.lookup(D);
793}
794
John McCall7f416cc2015-09-08 08:05:57 +0000795// Layout information for ident_t.
796static CharUnits getIdentAlign(CodeGenModule &CGM) {
797 return CGM.getPointerAlign();
798}
799static CharUnits getIdentSize(CodeGenModule &CGM) {
800 assert((4 * CGM.getPointerSize()).isMultipleOf(CGM.getPointerAlign()));
801 return CharUnits::fromQuantity(16) + CGM.getPointerSize();
802}
Alexey Bataev50b3c952016-02-19 10:38:26 +0000803static CharUnits getOffsetOfIdentField(IdentFieldIndex Field) {
John McCall7f416cc2015-09-08 08:05:57 +0000804 // All the fields except the last are i32, so this works beautifully.
805 return unsigned(Field) * CharUnits::fromQuantity(4);
806}
807static Address createIdentFieldGEP(CodeGenFunction &CGF, Address Addr,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000808 IdentFieldIndex Field,
John McCall7f416cc2015-09-08 08:05:57 +0000809 const llvm::Twine &Name = "") {
810 auto Offset = getOffsetOfIdentField(Field);
811 return CGF.Builder.CreateStructGEP(Addr, Field, Offset, Name);
812}
813
Carlo Bertolli430d8ec2016-03-03 20:34:23 +0000814llvm::Value *CGOpenMPRuntime::emitParallelOrTeamsOutlinedFunction(
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000815 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
816 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000817 assert(ThreadIDVar->getType()->isPointerType() &&
818 "thread id variable must be of type kmp_int32 *");
Alexey Bataev18095712014-10-10 12:19:54 +0000819 const CapturedStmt *CS = cast<CapturedStmt>(D.getAssociatedStmt());
820 CodeGenFunction CGF(CGM, true);
Alexey Bataev25e5b442015-09-15 12:52:43 +0000821 bool HasCancel = false;
822 if (auto *OPD = dyn_cast<OMPParallelDirective>(&D))
823 HasCancel = OPD->hasCancel();
824 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
825 HasCancel = OPSD->hasCancel();
826 else if (auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
827 HasCancel = OPFD->hasCancel();
828 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
829 HasCancel);
Alexey Bataevd157d472015-06-24 03:35:38 +0000830 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev2377fe92015-09-10 08:12:02 +0000831 return CGF.GenerateOpenMPCapturedStmtFunction(*CS);
Alexey Bataev18095712014-10-10 12:19:54 +0000832}
833
Alexey Bataev81c7ea02015-07-03 09:56:58 +0000834llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction(
835 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
Alexey Bataev48591dd2016-04-20 04:01:36 +0000836 const VarDecl *PartIDVar, const VarDecl *TaskTVar,
837 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
838 bool Tied, unsigned &NumberOfParts) {
839 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
840 PrePostActionTy &) {
841 auto *ThreadID = getThreadID(CGF, D.getLocStart());
842 auto *UpLoc = emitUpdateLocation(CGF, D.getLocStart());
843 llvm::Value *TaskArgs[] = {
844 UpLoc, ThreadID,
845 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
846 TaskTVar->getType()->castAs<PointerType>())
847 .getPointer()};
848 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs);
849 };
850 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
851 UntiedCodeGen);
852 CodeGen.setAction(Action);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000853 assert(!ThreadIDVar->getType()->isPointerType() &&
854 "thread id variable must be of type kmp_int32 for tasks");
855 auto *CS = cast<CapturedStmt>(D.getAssociatedStmt());
Alexey Bataev7292c292016-04-25 12:22:29 +0000856 auto *TD = dyn_cast<OMPTaskDirective>(&D);
Alexey Bataev62b63b12015-03-10 07:28:44 +0000857 CodeGenFunction CGF(CGM, true);
Alexey Bataev7292c292016-04-25 12:22:29 +0000858 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
859 InnermostKind,
860 TD ? TD->hasCancel() : false, Action);
Alexey Bataevd157d472015-06-24 03:35:38 +0000861 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Alexey Bataev48591dd2016-04-20 04:01:36 +0000862 auto *Res = CGF.GenerateCapturedStmtFunction(*CS);
863 if (!Tied)
864 NumberOfParts = Action.getNumberOfParts();
865 return Res;
Alexey Bataev62b63b12015-03-10 07:28:44 +0000866}
867
Alexey Bataev50b3c952016-02-19 10:38:26 +0000868Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) {
John McCall7f416cc2015-09-08 08:05:57 +0000869 CharUnits Align = getIdentAlign(CGM);
Alexey Bataev15007ba2014-05-07 06:18:01 +0000870 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags);
Alexey Bataev9959db52014-05-06 10:08:46 +0000871 if (!Entry) {
872 if (!DefaultOpenMPPSource) {
873 // Initialize default location for psource field of ident_t structure of
874 // all ident_t objects. Format is ";file;function;line;column;;".
875 // Taken from
876 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c
877 DefaultOpenMPPSource =
John McCall7f416cc2015-09-08 08:05:57 +0000878 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000879 DefaultOpenMPPSource =
880 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy);
881 }
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000882 auto DefaultOpenMPLocation = new llvm::GlobalVariable(
883 CGM.getModule(), IdentTy, /*isConstant*/ true,
884 llvm::GlobalValue::PrivateLinkage, /*Initializer*/ nullptr);
Alexey Bataev9959db52014-05-06 10:08:46 +0000885 DefaultOpenMPLocation->setUnnamedAddr(true);
John McCall7f416cc2015-09-08 08:05:57 +0000886 DefaultOpenMPLocation->setAlignment(Align.getQuantity());
Alexey Bataev9959db52014-05-06 10:08:46 +0000887
888 llvm::Constant *Zero = llvm::ConstantInt::get(CGM.Int32Ty, 0, true);
Alexey Bataev23b69422014-06-18 07:08:49 +0000889 llvm::Constant *Values[] = {Zero,
890 llvm::ConstantInt::get(CGM.Int32Ty, Flags),
891 Zero, Zero, DefaultOpenMPPSource};
Alexey Bataev9959db52014-05-06 10:08:46 +0000892 llvm::Constant *Init = llvm::ConstantStruct::get(IdentTy, Values);
893 DefaultOpenMPLocation->setInitializer(Init);
John McCall7f416cc2015-09-08 08:05:57 +0000894 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation;
Alexey Bataev9959db52014-05-06 10:08:46 +0000895 }
John McCall7f416cc2015-09-08 08:05:57 +0000896 return Address(Entry, Align);
Alexey Bataev9959db52014-05-06 10:08:46 +0000897}
898
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000899llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
900 SourceLocation Loc,
Alexey Bataev50b3c952016-02-19 10:38:26 +0000901 unsigned Flags) {
902 Flags |= OMP_IDENT_KMPC;
Alexey Bataev9959db52014-05-06 10:08:46 +0000903 // If no debug info is generated - return global default location.
Benjamin Kramer8c305922016-02-02 11:06:51 +0000904 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
Alexey Bataev9959db52014-05-06 10:08:46 +0000905 Loc.isInvalid())
John McCall7f416cc2015-09-08 08:05:57 +0000906 return getOrCreateDefaultLocation(Flags).getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000907
908 assert(CGF.CurFn && "No function in current CodeGenFunction.");
909
John McCall7f416cc2015-09-08 08:05:57 +0000910 Address LocValue = Address::invalid();
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000911 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
912 if (I != OpenMPLocThreadIDMap.end())
John McCall7f416cc2015-09-08 08:05:57 +0000913 LocValue = Address(I->second.DebugLoc, getIdentAlign(CGF.CGM));
914
Alexander Musmanc6388682014-12-15 07:07:06 +0000915 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if
916 // GetOpenMPThreadID was called before this routine.
John McCall7f416cc2015-09-08 08:05:57 +0000917 if (!LocValue.isValid()) {
Alexey Bataev15007ba2014-05-07 06:18:01 +0000918 // Generate "ident_t .kmpc_loc.addr;"
John McCall7f416cc2015-09-08 08:05:57 +0000919 Address AI = CGF.CreateTempAlloca(IdentTy, getIdentAlign(CGF.CGM),
920 ".kmpc_loc.addr");
Alexey Bataev18095712014-10-10 12:19:54 +0000921 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
John McCall7f416cc2015-09-08 08:05:57 +0000922 Elem.second.DebugLoc = AI.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000923 LocValue = AI;
924
925 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
926 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000927 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags),
John McCall7f416cc2015-09-08 08:05:57 +0000928 CGM.getSize(getIdentSize(CGF.CGM)));
Alexey Bataev9959db52014-05-06 10:08:46 +0000929 }
930
931 // char **psource = &.kmpc_loc_<flags>.addr.psource;
John McCall7f416cc2015-09-08 08:05:57 +0000932 Address PSource = createIdentFieldGEP(CGF, LocValue, IdentField_PSource);
Alexey Bataev9959db52014-05-06 10:08:46 +0000933
Alexey Bataevf002aca2014-05-30 05:48:40 +0000934 auto OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding());
935 if (OMPDebugLoc == nullptr) {
936 SmallString<128> Buffer2;
937 llvm::raw_svector_ostream OS2(Buffer2);
938 // Build debug location
939 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
940 OS2 << ";" << PLoc.getFilename() << ";";
941 if (const FunctionDecl *FD =
942 dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) {
943 OS2 << FD->getQualifiedNameAsString();
944 }
945 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
946 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str());
947 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc;
Alexey Bataev9959db52014-05-06 10:08:46 +0000948 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000949 // *psource = ";<File>;<Function>;<Line>;<Column>;;";
Alexey Bataevf002aca2014-05-30 05:48:40 +0000950 CGF.Builder.CreateStore(OMPDebugLoc, PSource);
951
John McCall7f416cc2015-09-08 08:05:57 +0000952 // Our callers always pass this to a runtime function, so for
953 // convenience, go ahead and return a naked pointer.
954 return LocValue.getPointer();
Alexey Bataev9959db52014-05-06 10:08:46 +0000955}
956
Alexey Bataev3eff5f42015-02-25 08:32:46 +0000957llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
958 SourceLocation Loc) {
Alexey Bataev9959db52014-05-06 10:08:46 +0000959 assert(CGF.CurFn && "No function in current CodeGenFunction.");
960
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000961 llvm::Value *ThreadID = nullptr;
Alexey Bataev18095712014-10-10 12:19:54 +0000962 // Check whether we've already cached a load of the thread id in this
963 // function.
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000964 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
Alexey Bataev18095712014-10-10 12:19:54 +0000965 if (I != OpenMPLocThreadIDMap.end()) {
966 ThreadID = I->second.ThreadID;
Alexey Bataev03b340a2014-10-21 03:16:40 +0000967 if (ThreadID != nullptr)
968 return ThreadID;
969 }
Alexey Bataev3015bcc2016-01-22 08:56:50 +0000970 if (auto *OMPRegionInfo =
Alexey Bataev1e4b7132014-12-03 12:11:24 +0000971 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev62b63b12015-03-10 07:28:44 +0000972 if (OMPRegionInfo->getThreadIDVariable()) {
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000973 // Check if this an outlined function with thread id passed as argument.
974 auto LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000975 ThreadID = CGF.EmitLoadOfLValue(LVal, Loc).getScalarVal();
976 // If value loaded in entry block, cache it and use it everywhere in
977 // function.
978 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) {
979 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
980 Elem.second.ThreadID = ThreadID;
981 }
982 return ThreadID;
Alexey Bataevd6c57552014-07-25 07:55:17 +0000983 }
Alexey Bataev9959db52014-05-06 10:08:46 +0000984 }
Alexey Bataev8cbe0a62015-02-26 10:27:34 +0000985
986 // This is not an outlined function region - need to call __kmpc_int32
987 // kmpc_global_thread_num(ident_t *loc).
988 // Generate thread id value and cache this value for use across the
989 // function.
990 CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
991 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt);
992 ThreadID =
993 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
994 emitUpdateLocation(CGF, Loc));
995 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
996 Elem.second.ThreadID = ThreadID;
Alexey Bataev4a5bb772014-10-08 14:01:46 +0000997 return ThreadID;
Alexey Bataev9959db52014-05-06 10:08:46 +0000998}
999
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001000void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001001 assert(CGF.CurFn && "No function in current CodeGenFunction.");
Alexey Bataev03b340a2014-10-21 03:16:40 +00001002 if (OpenMPLocThreadIDMap.count(CGF.CurFn))
1003 OpenMPLocThreadIDMap.erase(CGF.CurFn);
Alexey Bataevc5b1d322016-03-04 09:22:22 +00001004 if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1005 for(auto *D : FunctionUDRMap[CGF.CurFn]) {
1006 UDRMap.erase(D);
1007 }
1008 FunctionUDRMap.erase(CGF.CurFn);
1009 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001010}
1011
1012llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001013 if (!IdentTy) {
1014 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001015 return llvm::PointerType::getUnqual(IdentTy);
1016}
1017
1018llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001019 if (!Kmpc_MicroTy) {
1020 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1021 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1022 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1023 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1024 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001025 return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1026}
1027
1028llvm::Constant *
Alexey Bataev50b3c952016-02-19 10:38:26 +00001029CGOpenMPRuntime::createRuntimeFunction(unsigned Function) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001030 llvm::Constant *RTLFn = nullptr;
Alexey Bataev50b3c952016-02-19 10:38:26 +00001031 switch (static_cast<OpenMPRTLFunction>(Function)) {
Alexey Bataev9959db52014-05-06 10:08:46 +00001032 case OMPRTL__kmpc_fork_call: {
1033 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro
1034 // microtask, ...);
Alexey Bataev23b69422014-06-18 07:08:49 +00001035 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1036 getKmpc_MicroPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001037 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001038 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
Alexey Bataev9959db52014-05-06 10:08:46 +00001039 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call");
1040 break;
1041 }
1042 case OMPRTL__kmpc_global_thread_num: {
1043 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc);
Alexey Bataev23b69422014-06-18 07:08:49 +00001044 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
Alexey Bataev9959db52014-05-06 10:08:46 +00001045 llvm::FunctionType *FnTy =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001046 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
Alexey Bataev9959db52014-05-06 10:08:46 +00001047 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num");
1048 break;
1049 }
Alexey Bataev97720002014-11-11 04:05:39 +00001050 case OMPRTL__kmpc_threadprivate_cached: {
1051 // Build void *__kmpc_threadprivate_cached(ident_t *loc,
1052 // kmp_int32 global_tid, void *data, size_t size, void ***cache);
1053 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1054 CGM.VoidPtrTy, CGM.SizeTy,
1055 CGM.VoidPtrTy->getPointerTo()->getPointerTo()};
1056 llvm::FunctionType *FnTy =
1057 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false);
1058 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached");
1059 break;
1060 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001061 case OMPRTL__kmpc_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001062 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid,
1063 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001064 llvm::Type *TypeParams[] = {
1065 getIdentTyPointerTy(), CGM.Int32Ty,
1066 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1067 llvm::FunctionType *FnTy =
1068 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1069 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical");
1070 break;
1071 }
Alexey Bataevfc57d162015-12-15 10:55:09 +00001072 case OMPRTL__kmpc_critical_with_hint: {
1073 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid,
1074 // kmp_critical_name *crit, uintptr_t hint);
1075 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1076 llvm::PointerType::getUnqual(KmpCriticalNameTy),
1077 CGM.IntPtrTy};
1078 llvm::FunctionType *FnTy =
1079 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1080 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint");
1081 break;
1082 }
Alexey Bataev97720002014-11-11 04:05:39 +00001083 case OMPRTL__kmpc_threadprivate_register: {
1084 // Build void __kmpc_threadprivate_register(ident_t *, void *data,
1085 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor);
1086 // typedef void *(*kmpc_ctor)(void *);
1087 auto KmpcCtorTy =
1088 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1089 /*isVarArg*/ false)->getPointerTo();
1090 // typedef void *(*kmpc_cctor)(void *, void *);
1091 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1092 auto KmpcCopyCtorTy =
1093 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs,
1094 /*isVarArg*/ false)->getPointerTo();
1095 // typedef void (*kmpc_dtor)(void *);
1096 auto KmpcDtorTy =
1097 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false)
1098 ->getPointerTo();
1099 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy,
1100 KmpcCopyCtorTy, KmpcDtorTy};
1101 auto FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs,
1102 /*isVarArg*/ false);
1103 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register");
1104 break;
1105 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001106 case OMPRTL__kmpc_end_critical: {
Alexey Bataevf9472182014-09-22 12:32:31 +00001107 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid,
1108 // kmp_critical_name *crit);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001109 llvm::Type *TypeParams[] = {
1110 getIdentTyPointerTy(), CGM.Int32Ty,
1111 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1112 llvm::FunctionType *FnTy =
1113 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1114 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical");
1115 break;
1116 }
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001117 case OMPRTL__kmpc_cancel_barrier: {
1118 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32
1119 // global_tid);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001120 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1121 llvm::FunctionType *FnTy =
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00001122 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1123 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier");
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001124 break;
1125 }
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001126 case OMPRTL__kmpc_barrier: {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001127 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00001128 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1129 llvm::FunctionType *FnTy =
1130 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1131 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier");
1132 break;
1133 }
Alexander Musmanc6388682014-12-15 07:07:06 +00001134 case OMPRTL__kmpc_for_static_fini: {
1135 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid);
1136 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1137 llvm::FunctionType *FnTy =
1138 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1139 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini");
1140 break;
1141 }
Alexey Bataevb2059782014-10-13 08:23:51 +00001142 case OMPRTL__kmpc_push_num_threads: {
1143 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid,
1144 // kmp_int32 num_threads)
1145 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1146 CGM.Int32Ty};
1147 llvm::FunctionType *FnTy =
1148 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1149 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads");
1150 break;
1151 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001152 case OMPRTL__kmpc_serialized_parallel: {
1153 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32
1154 // global_tid);
1155 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1156 llvm::FunctionType *FnTy =
1157 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1158 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel");
1159 break;
1160 }
1161 case OMPRTL__kmpc_end_serialized_parallel: {
1162 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32
1163 // global_tid);
1164 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1165 llvm::FunctionType *FnTy =
1166 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1167 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel");
1168 break;
1169 }
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001170 case OMPRTL__kmpc_flush: {
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001171 // Build void __kmpc_flush(ident_t *loc);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001172 llvm::Type *TypeParams[] = {getIdentTyPointerTy()};
1173 llvm::FunctionType *FnTy =
Alexey Bataevd76df6d2015-02-24 12:55:09 +00001174 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
Alexey Bataevcc37cc12014-11-20 04:34:54 +00001175 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush");
1176 break;
1177 }
Alexey Bataev8d690652014-12-04 07:23:53 +00001178 case OMPRTL__kmpc_master: {
1179 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid);
1180 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1181 llvm::FunctionType *FnTy =
1182 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1183 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master");
1184 break;
1185 }
1186 case OMPRTL__kmpc_end_master: {
1187 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid);
1188 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1189 llvm::FunctionType *FnTy =
1190 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1191 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master");
1192 break;
1193 }
Alexey Bataev9f797f32015-02-05 05:57:51 +00001194 case OMPRTL__kmpc_omp_taskyield: {
1195 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid,
1196 // int end_part);
1197 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1198 llvm::FunctionType *FnTy =
1199 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1200 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield");
1201 break;
1202 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00001203 case OMPRTL__kmpc_single: {
1204 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid);
1205 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1206 llvm::FunctionType *FnTy =
1207 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1208 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single");
1209 break;
1210 }
1211 case OMPRTL__kmpc_end_single: {
1212 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid);
1213 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1214 llvm::FunctionType *FnTy =
1215 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1216 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single");
1217 break;
1218 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00001219 case OMPRTL__kmpc_omp_task_alloc: {
1220 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
1221 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
1222 // kmp_routine_entry_t *task_entry);
1223 assert(KmpRoutineEntryPtrTy != nullptr &&
1224 "Type kmp_routine_entry_t must be created.");
1225 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1226 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy};
1227 // Return void * and then cast to particular kmp_task_t type.
1228 llvm::FunctionType *FnTy =
1229 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false);
1230 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc");
1231 break;
1232 }
1233 case OMPRTL__kmpc_omp_task: {
1234 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1235 // *new_task);
1236 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1237 CGM.VoidPtrTy};
1238 llvm::FunctionType *FnTy =
1239 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1240 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task");
1241 break;
1242 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00001243 case OMPRTL__kmpc_copyprivate: {
1244 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid,
Alexey Bataev66beaa92015-04-30 03:47:32 +00001245 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *),
Alexey Bataeva63048e2015-03-23 06:18:07 +00001246 // kmp_int32 didit);
1247 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1248 auto *CpyFnTy =
1249 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false);
Alexey Bataev66beaa92015-04-30 03:47:32 +00001250 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy,
Alexey Bataeva63048e2015-03-23 06:18:07 +00001251 CGM.VoidPtrTy, CpyFnTy->getPointerTo(),
1252 CGM.Int32Ty};
1253 llvm::FunctionType *FnTy =
1254 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1255 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate");
1256 break;
1257 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00001258 case OMPRTL__kmpc_reduce: {
1259 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid,
1260 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void
1261 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck);
1262 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1263 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1264 /*isVarArg=*/false);
1265 llvm::Type *TypeParams[] = {
1266 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1267 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1268 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1269 llvm::FunctionType *FnTy =
1270 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1271 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce");
1272 break;
1273 }
1274 case OMPRTL__kmpc_reduce_nowait: {
1275 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32
1276 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data,
1277 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name
1278 // *lck);
1279 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1280 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams,
1281 /*isVarArg=*/false);
1282 llvm::Type *TypeParams[] = {
1283 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy,
1284 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(),
1285 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1286 llvm::FunctionType *FnTy =
1287 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1288 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait");
1289 break;
1290 }
1291 case OMPRTL__kmpc_end_reduce: {
1292 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid,
1293 // kmp_critical_name *lck);
1294 llvm::Type *TypeParams[] = {
1295 getIdentTyPointerTy(), CGM.Int32Ty,
1296 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1297 llvm::FunctionType *FnTy =
1298 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1299 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce");
1300 break;
1301 }
1302 case OMPRTL__kmpc_end_reduce_nowait: {
1303 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid,
1304 // kmp_critical_name *lck);
1305 llvm::Type *TypeParams[] = {
1306 getIdentTyPointerTy(), CGM.Int32Ty,
1307 llvm::PointerType::getUnqual(KmpCriticalNameTy)};
1308 llvm::FunctionType *FnTy =
1309 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1310 RTLFn =
1311 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait");
1312 break;
1313 }
Alexey Bataev1d677132015-04-22 13:57:31 +00001314 case OMPRTL__kmpc_omp_task_begin_if0: {
1315 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1316 // *new_task);
1317 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1318 CGM.VoidPtrTy};
1319 llvm::FunctionType *FnTy =
1320 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1321 RTLFn =
1322 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0");
1323 break;
1324 }
1325 case OMPRTL__kmpc_omp_task_complete_if0: {
1326 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t
1327 // *new_task);
1328 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1329 CGM.VoidPtrTy};
1330 llvm::FunctionType *FnTy =
1331 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1332 RTLFn = CGM.CreateRuntimeFunction(FnTy,
1333 /*Name=*/"__kmpc_omp_task_complete_if0");
1334 break;
1335 }
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001336 case OMPRTL__kmpc_ordered: {
1337 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid);
1338 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1339 llvm::FunctionType *FnTy =
1340 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1341 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered");
1342 break;
1343 }
1344 case OMPRTL__kmpc_end_ordered: {
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001345 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001346 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1347 llvm::FunctionType *FnTy =
1348 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1349 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered");
1350 break;
1351 }
Alexey Bataev8b8e2022015-04-27 05:22:09 +00001352 case OMPRTL__kmpc_omp_taskwait: {
1353 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid);
1354 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1355 llvm::FunctionType *FnTy =
1356 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1357 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait");
1358 break;
1359 }
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00001360 case OMPRTL__kmpc_taskgroup: {
1361 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid);
1362 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1363 llvm::FunctionType *FnTy =
1364 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1365 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup");
1366 break;
1367 }
1368 case OMPRTL__kmpc_end_taskgroup: {
1369 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid);
1370 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty};
1371 llvm::FunctionType *FnTy =
1372 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1373 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup");
1374 break;
1375 }
Alexey Bataev7f210c62015-06-18 13:40:03 +00001376 case OMPRTL__kmpc_push_proc_bind: {
1377 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid,
1378 // int proc_bind)
1379 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1380 llvm::FunctionType *FnTy =
1381 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1382 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind");
1383 break;
1384 }
Alexey Bataev1d2353d2015-06-24 11:01:36 +00001385 case OMPRTL__kmpc_omp_task_with_deps: {
1386 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
1387 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
1388 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list);
1389 llvm::Type *TypeParams[] = {
1390 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty,
1391 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy};
1392 llvm::FunctionType *FnTy =
1393 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false);
1394 RTLFn =
1395 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps");
1396 break;
1397 }
1398 case OMPRTL__kmpc_omp_wait_deps: {
1399 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
1400 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias,
1401 // kmp_depend_info_t *noalias_dep_list);
1402 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1403 CGM.Int32Ty, CGM.VoidPtrTy,
1404 CGM.Int32Ty, CGM.VoidPtrTy};
1405 llvm::FunctionType *FnTy =
1406 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1407 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps");
1408 break;
1409 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00001410 case OMPRTL__kmpc_cancellationpoint: {
1411 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
1412 // global_tid, kmp_int32 cncl_kind)
1413 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1414 llvm::FunctionType *FnTy =
1415 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1416 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint");
1417 break;
1418 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00001419 case OMPRTL__kmpc_cancel: {
1420 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
1421 // kmp_int32 cncl_kind)
1422 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy};
1423 llvm::FunctionType *FnTy =
1424 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1425 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel");
1426 break;
1427 }
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00001428 case OMPRTL__kmpc_push_num_teams: {
1429 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid,
1430 // kmp_int32 num_teams, kmp_int32 num_threads)
1431 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty,
1432 CGM.Int32Ty};
1433 llvm::FunctionType *FnTy =
1434 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1435 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams");
1436 break;
1437 }
1438 case OMPRTL__kmpc_fork_teams: {
1439 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro
1440 // microtask, ...);
1441 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty,
1442 getKmpc_MicroPointerTy()};
1443 llvm::FunctionType *FnTy =
1444 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true);
1445 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams");
1446 break;
1447 }
Alexey Bataev7292c292016-04-25 12:22:29 +00001448 case OMPRTL__kmpc_taskloop: {
1449 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
1450 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
1451 // sched, kmp_uint64 grainsize, void *task_dup);
1452 llvm::Type *TypeParams[] = {getIdentTyPointerTy(),
1453 CGM.IntTy,
1454 CGM.VoidPtrTy,
1455 CGM.IntTy,
1456 CGM.Int64Ty->getPointerTo(),
1457 CGM.Int64Ty->getPointerTo(),
1458 CGM.Int64Ty,
1459 CGM.IntTy,
1460 CGM.IntTy,
1461 CGM.Int64Ty,
1462 CGM.VoidPtrTy};
1463 llvm::FunctionType *FnTy =
1464 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1465 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop");
1466 break;
1467 }
Samuel Antaobed3c462015-10-02 16:14:20 +00001468 case OMPRTL__tgt_target: {
1469 // Build int32_t __tgt_target(int32_t device_id, void *host_ptr, int32_t
1470 // arg_num, void** args_base, void **args, size_t *arg_sizes, int32_t
1471 // *arg_types);
1472 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1473 CGM.VoidPtrTy,
1474 CGM.Int32Ty,
1475 CGM.VoidPtrPtrTy,
1476 CGM.VoidPtrPtrTy,
1477 CGM.SizeTy->getPointerTo(),
1478 CGM.Int32Ty->getPointerTo()};
1479 llvm::FunctionType *FnTy =
1480 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1481 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target");
1482 break;
1483 }
Samuel Antaob68e2db2016-03-03 16:20:23 +00001484 case OMPRTL__tgt_target_teams: {
1485 // Build int32_t __tgt_target_teams(int32_t device_id, void *host_ptr,
1486 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes,
1487 // int32_t *arg_types, int32_t num_teams, int32_t thread_limit);
1488 llvm::Type *TypeParams[] = {CGM.Int32Ty,
1489 CGM.VoidPtrTy,
1490 CGM.Int32Ty,
1491 CGM.VoidPtrPtrTy,
1492 CGM.VoidPtrPtrTy,
1493 CGM.SizeTy->getPointerTo(),
1494 CGM.Int32Ty->getPointerTo(),
1495 CGM.Int32Ty,
1496 CGM.Int32Ty};
1497 llvm::FunctionType *FnTy =
1498 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1499 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams");
1500 break;
1501 }
Samuel Antaoee8fb302016-01-06 13:42:12 +00001502 case OMPRTL__tgt_register_lib: {
1503 // Build void __tgt_register_lib(__tgt_bin_desc *desc);
1504 QualType ParamTy =
1505 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1506 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1507 llvm::FunctionType *FnTy =
1508 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1509 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib");
1510 break;
1511 }
1512 case OMPRTL__tgt_unregister_lib: {
1513 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc);
1514 QualType ParamTy =
1515 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy());
1516 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)};
1517 llvm::FunctionType *FnTy =
1518 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1519 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib");
1520 break;
1521 }
Alexey Bataev9959db52014-05-06 10:08:46 +00001522 }
Alexey Bataev50b3c952016-02-19 10:38:26 +00001523 assert(RTLFn && "Unable to find OpenMP runtime function");
Alexey Bataev9959db52014-05-06 10:08:46 +00001524 return RTLFn;
1525}
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001526
Alexander Musman21212e42015-03-13 10:38:23 +00001527llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize,
1528 bool IVSigned) {
1529 assert((IVSize == 32 || IVSize == 64) &&
1530 "IV size is not compatible with the omp runtime");
1531 auto Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4"
1532 : "__kmpc_for_static_init_4u")
1533 : (IVSigned ? "__kmpc_for_static_init_8"
1534 : "__kmpc_for_static_init_8u");
1535 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1536 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1537 llvm::Type *TypeParams[] = {
1538 getIdentTyPointerTy(), // loc
1539 CGM.Int32Ty, // tid
1540 CGM.Int32Ty, // schedtype
1541 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1542 PtrTy, // p_lower
1543 PtrTy, // p_upper
1544 PtrTy, // p_stride
1545 ITy, // incr
1546 ITy // chunk
1547 };
1548 llvm::FunctionType *FnTy =
1549 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1550 return CGM.CreateRuntimeFunction(FnTy, Name);
1551}
1552
Alexander Musman92bdaab2015-03-12 13:37:50 +00001553llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize,
1554 bool IVSigned) {
1555 assert((IVSize == 32 || IVSize == 64) &&
1556 "IV size is not compatible with the omp runtime");
1557 auto Name =
1558 IVSize == 32
1559 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u")
1560 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u");
1561 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1562 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
1563 CGM.Int32Ty, // tid
1564 CGM.Int32Ty, // schedtype
1565 ITy, // lower
1566 ITy, // upper
1567 ITy, // stride
1568 ITy // chunk
1569 };
1570 llvm::FunctionType *FnTy =
1571 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1572 return CGM.CreateRuntimeFunction(FnTy, Name);
1573}
1574
Alexey Bataev98eb6e32015-04-22 11:15:40 +00001575llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize,
1576 bool IVSigned) {
1577 assert((IVSize == 32 || IVSize == 64) &&
1578 "IV size is not compatible with the omp runtime");
1579 auto Name =
1580 IVSize == 32
1581 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u")
1582 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u");
1583 llvm::Type *TypeParams[] = {
1584 getIdentTyPointerTy(), // loc
1585 CGM.Int32Ty, // tid
1586 };
1587 llvm::FunctionType *FnTy =
1588 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1589 return CGM.CreateRuntimeFunction(FnTy, Name);
1590}
1591
Alexander Musman92bdaab2015-03-12 13:37:50 +00001592llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize,
1593 bool IVSigned) {
1594 assert((IVSize == 32 || IVSize == 64) &&
1595 "IV size is not compatible with the omp runtime");
1596 auto Name =
1597 IVSize == 32
1598 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u")
1599 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u");
1600 auto ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty;
1601 auto PtrTy = llvm::PointerType::getUnqual(ITy);
1602 llvm::Type *TypeParams[] = {
1603 getIdentTyPointerTy(), // loc
1604 CGM.Int32Ty, // tid
1605 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1606 PtrTy, // p_lower
1607 PtrTy, // p_upper
1608 PtrTy // p_stride
1609 };
1610 llvm::FunctionType *FnTy =
1611 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1612 return CGM.CreateRuntimeFunction(FnTy, Name);
1613}
1614
Alexey Bataev97720002014-11-11 04:05:39 +00001615llvm::Constant *
1616CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001617 assert(!CGM.getLangOpts().OpenMPUseTLS ||
1618 !CGM.getContext().getTargetInfo().isTLSSupported());
Alexey Bataev97720002014-11-11 04:05:39 +00001619 // Lookup the entry, lazily creating it if necessary.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001620 return getOrCreateInternalVariable(CGM.Int8PtrPtrTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001621 Twine(CGM.getMangledName(VD)) + ".cache.");
1622}
1623
John McCall7f416cc2015-09-08 08:05:57 +00001624Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
1625 const VarDecl *VD,
1626 Address VDAddr,
1627 SourceLocation Loc) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001628 if (CGM.getLangOpts().OpenMPUseTLS &&
1629 CGM.getContext().getTargetInfo().isTLSSupported())
1630 return VDAddr;
1631
John McCall7f416cc2015-09-08 08:05:57 +00001632 auto VarTy = VDAddr.getElementType();
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001633 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00001634 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1635 CGM.Int8PtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001636 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
1637 getOrCreateThreadPrivateCache(VD)};
John McCall7f416cc2015-09-08 08:05:57 +00001638 return Address(CGF.EmitRuntimeCall(
1639 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args),
1640 VDAddr.getAlignment());
Alexey Bataev97720002014-11-11 04:05:39 +00001641}
1642
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001643void CGOpenMPRuntime::emitThreadPrivateVarInit(
John McCall7f416cc2015-09-08 08:05:57 +00001644 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
Alexey Bataev97720002014-11-11 04:05:39 +00001645 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
1646 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
1647 // library.
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001648 auto OMPLoc = emitUpdateLocation(CGF, Loc);
1649 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num),
Alexey Bataev97720002014-11-11 04:05:39 +00001650 OMPLoc);
1651 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
1652 // to register constructor/destructor for variable.
1653 llvm::Value *Args[] = {OMPLoc,
John McCall7f416cc2015-09-08 08:05:57 +00001654 CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1655 CGM.VoidPtrTy),
Alexey Bataev97720002014-11-11 04:05:39 +00001656 Ctor, CopyCtor, Dtor};
Alexey Bataev1e4b7132014-12-03 12:11:24 +00001657 CGF.EmitRuntimeCall(
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001658 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001659}
1660
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001661llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
John McCall7f416cc2015-09-08 08:05:57 +00001662 const VarDecl *VD, Address VDAddr, SourceLocation Loc,
Alexey Bataev97720002014-11-11 04:05:39 +00001663 bool PerformInit, CodeGenFunction *CGF) {
Samuel Antaof8b50122015-07-13 22:54:53 +00001664 if (CGM.getLangOpts().OpenMPUseTLS &&
1665 CGM.getContext().getTargetInfo().isTLSSupported())
1666 return nullptr;
1667
Alexey Bataev97720002014-11-11 04:05:39 +00001668 VD = VD->getDefinition(CGM.getContext());
1669 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) {
1670 ThreadPrivateWithDefinition.insert(VD);
1671 QualType ASTTy = VD->getType();
1672
1673 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
1674 auto Init = VD->getAnyInitializer();
1675 if (CGM.getLangOpts().CPlusPlus && PerformInit) {
1676 // Generate function that re-emits the declaration's initializer into the
1677 // threadprivate copy of the variable VD
1678 CodeGenFunction CtorCGF(CGM);
1679 FunctionArgList Args;
1680 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1681 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1682 Args.push_back(&Dst);
1683
John McCallc56a8b32016-03-11 04:30:31 +00001684 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1685 CGM.getContext().VoidPtrTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001686 auto FTy = CGM.getTypes().GetFunctionType(FI);
1687 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001688 FTy, ".__kmpc_global_ctor_.", FI, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001689 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
1690 Args, SourceLocation());
1691 auto ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001692 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001693 CGM.getContext().VoidPtrTy, Dst.getLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001694 Address Arg = Address(ArgVal, VDAddr.getAlignment());
1695 Arg = CtorCGF.Builder.CreateElementBitCast(Arg,
1696 CtorCGF.ConvertTypeForMem(ASTTy));
Alexey Bataev97720002014-11-11 04:05:39 +00001697 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
1698 /*IsInitializer=*/true);
1699 ArgVal = CtorCGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00001700 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
Alexey Bataev97720002014-11-11 04:05:39 +00001701 CGM.getContext().VoidPtrTy, Dst.getLocation());
1702 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
1703 CtorCGF.FinishFunction();
1704 Ctor = Fn;
1705 }
1706 if (VD->getType().isDestructedType() != QualType::DK_none) {
1707 // Generate function that emits destructor call for the threadprivate copy
1708 // of the variable VD
1709 CodeGenFunction DtorCGF(CGM);
1710 FunctionArgList Args;
1711 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, SourceLocation(),
1712 /*Id=*/nullptr, CGM.getContext().VoidPtrTy);
1713 Args.push_back(&Dst);
1714
John McCallc56a8b32016-03-11 04:30:31 +00001715 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1716 CGM.getContext().VoidTy, Args);
Alexey Bataev97720002014-11-11 04:05:39 +00001717 auto FTy = CGM.getTypes().GetFunctionType(FI);
1718 auto Fn = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001719 FTy, ".__kmpc_global_dtor_.", FI, Loc);
Adrian Prantl1858c662016-04-24 22:22:29 +00001720 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00001721 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
1722 SourceLocation());
Adrian Prantl1858c662016-04-24 22:22:29 +00001723 // Create a scope with an artificial location for the body of this function.
1724 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
Alexey Bataev97720002014-11-11 04:05:39 +00001725 auto ArgVal = DtorCGF.EmitLoadOfScalar(
1726 DtorCGF.GetAddrOfLocalVar(&Dst),
John McCall7f416cc2015-09-08 08:05:57 +00001727 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
1728 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001729 DtorCGF.getDestroyer(ASTTy.isDestructedType()),
1730 DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
1731 DtorCGF.FinishFunction();
1732 Dtor = Fn;
1733 }
1734 // Do not emit init function if it is not required.
1735 if (!Ctor && !Dtor)
1736 return nullptr;
1737
1738 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1739 auto CopyCtorTy =
1740 llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
1741 /*isVarArg=*/false)->getPointerTo();
1742 // Copying constructor for the threadprivate variable.
1743 // Must be NULL - reserved by runtime, but currently it requires that this
1744 // parameter is always NULL. Otherwise it fires assertion.
1745 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
1746 if (Ctor == nullptr) {
1747 auto CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1748 /*isVarArg=*/false)->getPointerTo();
1749 Ctor = llvm::Constant::getNullValue(CtorTy);
1750 }
1751 if (Dtor == nullptr) {
1752 auto DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
1753 /*isVarArg=*/false)->getPointerTo();
1754 Dtor = llvm::Constant::getNullValue(DtorTy);
1755 }
1756 if (!CGF) {
1757 auto InitFunctionTy =
1758 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
1759 auto InitFunction = CGM.CreateGlobalInitOrDestructFunction(
Akira Hatanaka7791f1a42015-10-31 01:28:07 +00001760 InitFunctionTy, ".__omp_threadprivate_init_.",
1761 CGM.getTypes().arrangeNullaryFunction());
Alexey Bataev97720002014-11-11 04:05:39 +00001762 CodeGenFunction InitCGF(CGM);
1763 FunctionArgList ArgList;
1764 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
1765 CGM.getTypes().arrangeNullaryFunction(), ArgList,
1766 Loc);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001767 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001768 InitCGF.FinishFunction();
1769 return InitFunction;
1770 }
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001771 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
Alexey Bataev97720002014-11-11 04:05:39 +00001772 }
1773 return nullptr;
1774}
1775
Alexey Bataev1d677132015-04-22 13:57:31 +00001776/// \brief Emits code for OpenMP 'if' clause using specified \a CodeGen
1777/// function. Here is the logic:
1778/// if (Cond) {
1779/// ThenGen();
1780/// } else {
1781/// ElseGen();
1782/// }
1783static void emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond,
1784 const RegionCodeGenTy &ThenGen,
1785 const RegionCodeGenTy &ElseGen) {
1786 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
1787
1788 // If the condition constant folds and can be elided, try to avoid emitting
1789 // the condition and the dead arm of the if/else.
1790 bool CondConstant;
1791 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001792 if (CondConstant)
Alexey Bataev1d677132015-04-22 13:57:31 +00001793 ThenGen(CGF);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001794 else
Alexey Bataev1d677132015-04-22 13:57:31 +00001795 ElseGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001796 return;
1797 }
1798
1799 // Otherwise, the condition did not fold, or we couldn't elide it. Just
1800 // emit the conditional branch.
1801 auto ThenBlock = CGF.createBasicBlock("omp_if.then");
1802 auto ElseBlock = CGF.createBasicBlock("omp_if.else");
1803 auto ContBlock = CGF.createBasicBlock("omp_if.end");
1804 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
1805
1806 // Emit the 'then' code.
1807 CGF.EmitBlock(ThenBlock);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001808 ThenGen(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00001809 CGF.EmitBranch(ContBlock);
1810 // Emit the 'else' code if present.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001811 // There is no need to emit line number for unconditional branch.
1812 (void)ApplyDebugLocation::CreateEmpty(CGF);
1813 CGF.EmitBlock(ElseBlock);
1814 ElseGen(CGF);
1815 // There is no need to emit line number for unconditional branch.
1816 (void)ApplyDebugLocation::CreateEmpty(CGF);
1817 CGF.EmitBranch(ContBlock);
Alexey Bataev1d677132015-04-22 13:57:31 +00001818 // Emit the continuation block for code after the if.
1819 CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001820}
1821
Alexey Bataev1d677132015-04-22 13:57:31 +00001822void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
1823 llvm::Value *OutlinedFn,
Alexey Bataev2377fe92015-09-10 08:12:02 +00001824 ArrayRef<llvm::Value *> CapturedVars,
Alexey Bataev1d677132015-04-22 13:57:31 +00001825 const Expr *IfCond) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001826 if (!CGF.HaveInsertPoint())
1827 return;
Alexey Bataev1d677132015-04-22 13:57:31 +00001828 auto *RTLoc = emitUpdateLocation(CGF, Loc);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001829 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF,
1830 PrePostActionTy &) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00001831 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001832 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev2377fe92015-09-10 08:12:02 +00001833 llvm::Value *Args[] = {
1834 RTLoc,
1835 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001836 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
Alexey Bataev2377fe92015-09-10 08:12:02 +00001837 llvm::SmallVector<llvm::Value *, 16> RealArgs;
1838 RealArgs.append(std::begin(Args), std::end(Args));
1839 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
1840
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001841 auto RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call);
Alexey Bataev2377fe92015-09-10 08:12:02 +00001842 CGF.EmitRuntimeCall(RTLFn, RealArgs);
1843 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001844 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF,
1845 PrePostActionTy &) {
1846 auto &RT = CGF.CGM.getOpenMPRuntime();
1847 auto ThreadID = RT.getThreadID(CGF, Loc);
Alexey Bataev1d677132015-04-22 13:57:31 +00001848 // Build calls:
1849 // __kmpc_serialized_parallel(&Loc, GTid);
1850 llvm::Value *Args[] = {RTLoc, ThreadID};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001851 CGF.EmitRuntimeCall(
1852 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001853
Alexey Bataev1d677132015-04-22 13:57:31 +00001854 // OutlinedFn(&GTid, &zero, CapturedStruct);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001855 auto ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00001856 Address ZeroAddr =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001857 CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4),
1858 /*Name*/ ".zero.addr");
Alexey Bataev1d677132015-04-22 13:57:31 +00001859 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0));
Alexey Bataev2377fe92015-09-10 08:12:02 +00001860 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
1861 OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
1862 OutlinedFnArgs.push_back(ZeroAddr.getPointer());
1863 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
Alexey Bataev1d677132015-04-22 13:57:31 +00001864 CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001865
Alexey Bataev1d677132015-04-22 13:57:31 +00001866 // __kmpc_end_serialized_parallel(&Loc, GTid);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001867 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
Alexey Bataev1d677132015-04-22 13:57:31 +00001868 CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001869 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel),
1870 EndArgs);
Alexey Bataev1d677132015-04-22 13:57:31 +00001871 };
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001872 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00001873 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001874 else {
1875 RegionCodeGenTy ThenRCG(ThenGen);
1876 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00001877 }
Alexey Bataevd74d0602014-10-13 06:02:40 +00001878}
1879
NAKAMURA Takumi59c74b222014-10-27 08:08:18 +00001880// If we're inside an (outlined) parallel region, use the region info's
Alexey Bataevd74d0602014-10-13 06:02:40 +00001881// thread-ID variable (it is passed in a first argument of the outlined function
1882// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
1883// regular serial code region, get thread ID by calling kmp_int32
1884// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
1885// return the address of that temp.
John McCall7f416cc2015-09-08 08:05:57 +00001886Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
1887 SourceLocation Loc) {
Alexey Bataev3015bcc2016-01-22 08:56:50 +00001888 if (auto *OMPRegionInfo =
Alexey Bataevd74d0602014-10-13 06:02:40 +00001889 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001890 if (OMPRegionInfo->getThreadIDVariable())
Alexey Bataev62b63b12015-03-10 07:28:44 +00001891 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress();
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00001892
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001893 auto ThreadID = getThreadID(CGF, Loc);
Alexey Bataevd74d0602014-10-13 06:02:40 +00001894 auto Int32Ty =
1895 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
1896 auto ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
1897 CGF.EmitStoreOfScalar(ThreadID,
John McCall7f416cc2015-09-08 08:05:57 +00001898 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
Alexey Bataevd74d0602014-10-13 06:02:40 +00001899
1900 return ThreadIDTemp;
1901}
1902
Alexey Bataev97720002014-11-11 04:05:39 +00001903llvm::Constant *
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001904CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty,
Alexey Bataev97720002014-11-11 04:05:39 +00001905 const llvm::Twine &Name) {
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001906 SmallString<256> Buffer;
1907 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev97720002014-11-11 04:05:39 +00001908 Out << Name;
1909 auto RuntimeName = Out.str();
David Blaikie13156b62014-11-19 03:06:06 +00001910 auto &Elem = *InternalVars.insert(std::make_pair(RuntimeName, nullptr)).first;
1911 if (Elem.second) {
1912 assert(Elem.second->getType()->getPointerElementType() == Ty &&
Alexey Bataev97720002014-11-11 04:05:39 +00001913 "OMP internal variable has different type than requested");
David Blaikie13156b62014-11-19 03:06:06 +00001914 return &*Elem.second;
Alexey Bataev97720002014-11-11 04:05:39 +00001915 }
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001916
David Blaikie13156b62014-11-19 03:06:06 +00001917 return Elem.second = new llvm::GlobalVariable(
1918 CGM.getModule(), Ty, /*IsConstant*/ false,
1919 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
1920 Elem.first());
Alexey Bataev97720002014-11-11 04:05:39 +00001921}
1922
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001923llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
Alexey Bataev97720002014-11-11 04:05:39 +00001924 llvm::Twine Name(".gomp_critical_user_", CriticalName);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001925 return getOrCreateInternalVariable(KmpCriticalNameTy, Name.concat(".var"));
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001926}
1927
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001928namespace {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001929/// Common pre(post)-action for different OpenMP constructs.
1930class CommonActionTy final : public PrePostActionTy {
1931 llvm::Value *EnterCallee;
1932 ArrayRef<llvm::Value *> EnterArgs;
1933 llvm::Value *ExitCallee;
1934 ArrayRef<llvm::Value *> ExitArgs;
1935 bool Conditional;
1936 llvm::BasicBlock *ContBlock = nullptr;
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001937
1938public:
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001939 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs,
1940 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs,
1941 bool Conditional = false)
1942 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
1943 ExitArgs(ExitArgs), Conditional(Conditional) {}
1944 void Enter(CodeGenFunction &CGF) override {
1945 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
1946 if (Conditional) {
1947 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
1948 auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
1949 ContBlock = CGF.createBasicBlock("omp_if.end");
1950 // Generate the branch (If-stmt)
1951 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
1952 CGF.EmitBlock(ThenBlock);
1953 }
Alexey Bataeva744ff52015-05-05 09:24:37 +00001954 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001955 void Done(CodeGenFunction &CGF) {
1956 // Emit the rest of blocks/branches
1957 CGF.EmitBranch(ContBlock);
1958 CGF.EmitBlock(ContBlock, true);
1959 }
1960 void Exit(CodeGenFunction &CGF) override {
1961 CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
Alexey Bataev3e6124b2015-04-10 07:48:12 +00001962 }
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001963};
Hans Wennborg7eb54642015-09-10 17:07:54 +00001964} // anonymous namespace
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001965
1966void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
1967 StringRef CriticalName,
1968 const RegionCodeGenTy &CriticalOpGen,
Alexey Bataevfc57d162015-12-15 10:55:09 +00001969 SourceLocation Loc, const Expr *Hint) {
1970 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
Alexey Bataev75ddfab2014-12-01 11:32:38 +00001971 // CriticalOpGen();
1972 // __kmpc_end_critical(ident_t *, gtid, Lock);
1973 // Prepare arguments and build a call to __kmpc_critical
Alexey Bataev8ef31412015-12-18 07:58:25 +00001974 if (!CGF.HaveInsertPoint())
1975 return;
Alexey Bataevfc57d162015-12-15 10:55:09 +00001976 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1977 getCriticalRegionLock(CriticalName)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001978 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
1979 std::end(Args));
Alexey Bataevfc57d162015-12-15 10:55:09 +00001980 if (Hint) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00001981 EnterArgs.push_back(CGF.Builder.CreateIntCast(
1982 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false));
1983 }
1984 CommonActionTy Action(
1985 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint
1986 : OMPRTL__kmpc_critical),
1987 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args);
1988 CriticalOpGen.setAction(Action);
Alexey Bataevfc57d162015-12-15 10:55:09 +00001989 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
Alexey Bataev3a3bf0b2014-09-22 10:01:53 +00001990}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00001991
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001992void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00001993 const RegionCodeGenTy &MasterOpGen,
Alexey Bataev3eff5f42015-02-25 08:32:46 +00001994 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00001995 if (!CGF.HaveInsertPoint())
1996 return;
Alexey Bataev8d690652014-12-04 07:23:53 +00001997 // if(__kmpc_master(ident_t *, gtid)) {
1998 // MasterOpGen();
1999 // __kmpc_end_master(ident_t *, gtid);
2000 // }
2001 // Prepare arguments and build a call to __kmpc_master
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002002 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002003 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args,
2004 createRuntimeFunction(OMPRTL__kmpc_end_master), Args,
2005 /*Conditional=*/true);
2006 MasterOpGen.setAction(Action);
2007 emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2008 Action.Done(CGF);
Alexey Bataev8d690652014-12-04 07:23:53 +00002009}
2010
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002011void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2012 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002013 if (!CGF.HaveInsertPoint())
2014 return;
Alexey Bataev9f797f32015-02-05 05:57:51 +00002015 // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2016 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002017 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataev9f797f32015-02-05 05:57:51 +00002018 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002019 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00002020 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2021 Region->emitUntiedSwitch(CGF);
Alexey Bataev9f797f32015-02-05 05:57:51 +00002022}
2023
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002024void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2025 const RegionCodeGenTy &TaskgroupOpGen,
2026 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002027 if (!CGF.HaveInsertPoint())
2028 return;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002029 // __kmpc_taskgroup(ident_t *, gtid);
2030 // TaskgroupOpGen();
2031 // __kmpc_end_taskgroup(ident_t *, gtid);
2032 // Prepare arguments and build a call to __kmpc_taskgroup
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002033 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2034 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args,
2035 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup),
2036 Args);
2037 TaskgroupOpGen.setAction(Action);
2038 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00002039}
2040
John McCall7f416cc2015-09-08 08:05:57 +00002041/// Given an array of pointers to variables, project the address of a
2042/// given variable.
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002043static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2044 unsigned Index, const VarDecl *Var) {
John McCall7f416cc2015-09-08 08:05:57 +00002045 // Pull out the pointer to the variable.
2046 Address PtrAddr =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002047 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00002048 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2049
2050 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00002051 Addr = CGF.Builder.CreateElementBitCast(
2052 Addr, CGF.ConvertTypeForMem(Var->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00002053 return Addr;
2054}
2055
Alexey Bataeva63048e2015-03-23 06:18:07 +00002056static llvm::Value *emitCopyprivateCopyFunction(
Alexey Bataev420d45b2015-04-14 05:11:24 +00002057 CodeGenModule &CGM, llvm::Type *ArgsType,
2058 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
2059 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002060 auto &C = CGM.getContext();
2061 // void copy_func(void *LHSArg, void *RHSArg);
2062 FunctionArgList Args;
2063 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2064 C.VoidPtrTy);
2065 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
2066 C.VoidPtrTy);
2067 Args.push_back(&LHSArg);
2068 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00002069 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002070 auto *Fn = llvm::Function::Create(
2071 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
2072 ".omp.copyprivate.copy_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00002073 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002074 CodeGenFunction CGF(CGM);
2075 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
Alexey Bataev420d45b2015-04-14 05:11:24 +00002076 // Dest = (void*[n])(LHSArg);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002077 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00002078 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2079 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2080 ArgsType), CGF.getPointerAlign());
2081 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2082 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2083 ArgsType), CGF.getPointerAlign());
Alexey Bataeva63048e2015-03-23 06:18:07 +00002084 // *(Type0*)Dst[0] = *(Type0*)Src[0];
2085 // *(Type1*)Dst[1] = *(Type1*)Src[1];
2086 // ...
2087 // *(Typen*)Dst[n] = *(Typen*)Src[n];
Alexey Bataeva63048e2015-03-23 06:18:07 +00002088 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002089 auto DestVar = cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2090 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2091
2092 auto SrcVar = cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2093 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2094
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00002095 auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2096 QualType Type = VD->getType();
John McCall7f416cc2015-09-08 08:05:57 +00002097 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002098 }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002099 CGF.FinishFunction();
2100 return Fn;
2101}
2102
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002103void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00002104 const RegionCodeGenTy &SingleOpGen,
Alexey Bataeva63048e2015-03-23 06:18:07 +00002105 SourceLocation Loc,
2106 ArrayRef<const Expr *> CopyprivateVars,
2107 ArrayRef<const Expr *> SrcExprs,
2108 ArrayRef<const Expr *> DstExprs,
2109 ArrayRef<const Expr *> AssignmentOps) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002110 if (!CGF.HaveInsertPoint())
2111 return;
Alexey Bataeva63048e2015-03-23 06:18:07 +00002112 assert(CopyprivateVars.size() == SrcExprs.size() &&
2113 CopyprivateVars.size() == DstExprs.size() &&
2114 CopyprivateVars.size() == AssignmentOps.size());
2115 auto &C = CGM.getContext();
2116 // int32 did_it = 0;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002117 // if(__kmpc_single(ident_t *, gtid)) {
2118 // SingleOpGen();
2119 // __kmpc_end_single(ident_t *, gtid);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002120 // did_it = 1;
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002121 // }
Alexey Bataeva63048e2015-03-23 06:18:07 +00002122 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2123 // <copy_func>, did_it);
2124
John McCall7f416cc2015-09-08 08:05:57 +00002125 Address DidIt = Address::invalid();
Alexey Bataeva63048e2015-03-23 06:18:07 +00002126 if (!CopyprivateVars.empty()) {
2127 // int32 did_it = 0;
2128 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2129 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
John McCall7f416cc2015-09-08 08:05:57 +00002130 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002131 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002132 // Prepare arguments and build a call to __kmpc_single
Alexey Bataevd7614fb2015-04-10 06:33:45 +00002133 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002134 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args,
2135 createRuntimeFunction(OMPRTL__kmpc_end_single), Args,
2136 /*Conditional=*/true);
2137 SingleOpGen.setAction(Action);
2138 emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2139 if (DidIt.isValid()) {
2140 // did_it = 1;
2141 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2142 }
2143 Action.Done(CGF);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002144 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2145 // <copy_func>, did_it);
John McCall7f416cc2015-09-08 08:05:57 +00002146 if (DidIt.isValid()) {
Alexey Bataeva63048e2015-03-23 06:18:07 +00002147 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2148 auto CopyprivateArrayTy =
2149 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
2150 /*IndexTypeQuals=*/0);
2151 // Create a list of all private variables for copyprivate.
John McCall7f416cc2015-09-08 08:05:57 +00002152 Address CopyprivateList =
Alexey Bataeva63048e2015-03-23 06:18:07 +00002153 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2154 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) {
John McCall7f416cc2015-09-08 08:05:57 +00002155 Address Elem = CGF.Builder.CreateConstArrayGEP(
2156 CopyprivateList, I, CGF.getPointerSize());
2157 CGF.Builder.CreateStore(
Alexey Bataeva63048e2015-03-23 06:18:07 +00002158 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00002159 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy),
2160 Elem);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002161 }
2162 // Build function that copies private values from single region to all other
2163 // threads in the corresponding parallel region.
2164 auto *CpyFn = emitCopyprivateCopyFunction(
2165 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
Alexey Bataev420d45b2015-04-14 05:11:24 +00002166 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataev1189bd02016-01-26 12:20:39 +00002167 auto *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00002168 Address CL =
2169 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2170 CGF.VoidPtrTy);
2171 auto *DidItVal = CGF.Builder.CreateLoad(DidIt);
Alexey Bataeva63048e2015-03-23 06:18:07 +00002172 llvm::Value *Args[] = {
2173 emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2174 getThreadID(CGF, Loc), // i32 <gtid>
Alexey Bataev66beaa92015-04-30 03:47:32 +00002175 BufSize, // size_t <buf_size>
John McCall7f416cc2015-09-08 08:05:57 +00002176 CL.getPointer(), // void *<copyprivate list>
Alexey Bataeva63048e2015-03-23 06:18:07 +00002177 CpyFn, // void (*) (void *, void *) <copy_func>
2178 DidItVal // i32 did_it
2179 };
2180 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args);
2181 }
Alexey Bataev6956e2e2015-02-05 06:35:41 +00002182}
2183
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002184void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2185 const RegionCodeGenTy &OrderedOpGen,
Alexey Bataev5f600d62015-09-29 03:48:57 +00002186 SourceLocation Loc, bool IsThreads) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002187 if (!CGF.HaveInsertPoint())
2188 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002189 // __kmpc_ordered(ident_t *, gtid);
2190 // OrderedOpGen();
2191 // __kmpc_end_ordered(ident_t *, gtid);
2192 // Prepare arguments and build a call to __kmpc_ordered
Alexey Bataev5f600d62015-09-29 03:48:57 +00002193 if (IsThreads) {
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002194 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002195 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args,
2196 createRuntimeFunction(OMPRTL__kmpc_end_ordered),
2197 Args);
2198 OrderedOpGen.setAction(Action);
2199 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2200 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002201 }
Alexey Bataev5f600d62015-09-29 03:48:57 +00002202 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002203}
2204
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002205void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00002206 OpenMPDirectiveKind Kind, bool EmitChecks,
2207 bool ForceSimpleCall) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002208 if (!CGF.HaveInsertPoint())
2209 return;
Alexey Bataev8f7c1b02014-12-05 04:09:23 +00002210 // Build call __kmpc_cancel_barrier(loc, thread_id);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002211 // Build call __kmpc_barrier(loc, thread_id);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002212 unsigned Flags;
2213 if (Kind == OMPD_for)
2214 Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2215 else if (Kind == OMPD_sections)
2216 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2217 else if (Kind == OMPD_single)
2218 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2219 else if (Kind == OMPD_barrier)
2220 Flags = OMP_IDENT_BARRIER_EXPL;
2221 else
2222 Flags = OMP_IDENT_BARRIER_IMPL;
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002223 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2224 // thread_id);
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002225 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2226 getThreadID(CGF, Loc)};
Alexey Bataev3015bcc2016-01-22 08:56:50 +00002227 if (auto *OMPRegionInfo =
2228 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00002229 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002230 auto *Result = CGF.EmitRuntimeCall(
2231 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args);
Alexey Bataev25e5b442015-09-15 12:52:43 +00002232 if (EmitChecks) {
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002233 // if (__kmpc_cancel_barrier()) {
2234 // exit from construct;
2235 // }
2236 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
2237 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
2238 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
2239 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2240 CGF.EmitBlock(ExitBB);
2241 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00002242 auto CancelDestination =
2243 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00002244 CGF.EmitBranchThroughCleanup(CancelDestination);
2245 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2246 }
2247 return;
2248 }
2249 }
2250 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00002251}
2252
Alexander Musmanc6388682014-12-15 07:07:06 +00002253/// \brief Map the OpenMP loop schedule to the runtime enumeration.
2254static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002255 bool Chunked, bool Ordered) {
Alexander Musmanc6388682014-12-15 07:07:06 +00002256 switch (ScheduleKind) {
2257 case OMPC_SCHEDULE_static:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002258 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked)
2259 : (Ordered ? OMP_ord_static : OMP_sch_static);
Alexander Musmanc6388682014-12-15 07:07:06 +00002260 case OMPC_SCHEDULE_dynamic:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002261 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002262 case OMPC_SCHEDULE_guided:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002263 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked;
Alexander Musmanc6388682014-12-15 07:07:06 +00002264 case OMPC_SCHEDULE_runtime:
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002265 return Ordered ? OMP_ord_runtime : OMP_sch_runtime;
2266 case OMPC_SCHEDULE_auto:
2267 return Ordered ? OMP_ord_auto : OMP_sch_auto;
Alexander Musmanc6388682014-12-15 07:07:06 +00002268 case OMPC_SCHEDULE_unknown:
2269 assert(!Chunked && "chunk was specified but schedule kind not known");
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002270 return Ordered ? OMP_ord_static : OMP_sch_static;
Alexander Musmanc6388682014-12-15 07:07:06 +00002271 }
2272 llvm_unreachable("Unexpected runtime schedule");
2273}
2274
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002275/// \brief Map the OpenMP distribute schedule to the runtime enumeration.
2276static OpenMPSchedType
2277getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2278 // only static is allowed for dist_schedule
2279 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static;
2280}
2281
Alexander Musmanc6388682014-12-15 07:07:06 +00002282bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2283 bool Chunked) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002284 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
Alexander Musmanc6388682014-12-15 07:07:06 +00002285 return Schedule == OMP_sch_static;
2286}
2287
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002288bool CGOpenMPRuntime::isStaticNonchunked(
2289 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2290 auto Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2291 return Schedule == OMP_dist_sch_static;
2292}
2293
2294
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002295bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002296 auto Schedule =
2297 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
Alexander Musmandf7a8e22015-01-22 08:49:35 +00002298 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2299 return Schedule != OMP_sch_static;
2300}
2301
John McCall7f416cc2015-09-08 08:05:57 +00002302void CGOpenMPRuntime::emitForDispatchInit(CodeGenFunction &CGF,
2303 SourceLocation Loc,
2304 OpenMPScheduleClauseKind ScheduleKind,
2305 unsigned IVSize, bool IVSigned,
2306 bool Ordered, llvm::Value *UB,
2307 llvm::Value *Chunk) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002308 if (!CGF.HaveInsertPoint())
2309 return;
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002310 OpenMPSchedType Schedule =
2311 getRuntimeSchedule(ScheduleKind, Chunk != nullptr, Ordered);
John McCall7f416cc2015-09-08 08:05:57 +00002312 assert(Ordered ||
2313 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
2314 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked));
2315 // Call __kmpc_dispatch_init(
2316 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2317 // kmp_int[32|64] lower, kmp_int[32|64] upper,
2318 // kmp_int[32|64] stride, kmp_int[32|64] chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002319
John McCall7f416cc2015-09-08 08:05:57 +00002320 // If the Chunk was not specified in the clause - use default value 1.
2321 if (Chunk == nullptr)
2322 Chunk = CGF.Builder.getIntN(IVSize, 1);
2323 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00002324 emitUpdateLocation(CGF, Loc),
2325 getThreadID(CGF, Loc),
2326 CGF.Builder.getInt32(Schedule), // Schedule type
2327 CGF.Builder.getIntN(IVSize, 0), // Lower
2328 UB, // Upper
2329 CGF.Builder.getIntN(IVSize, 1), // Stride
2330 Chunk // Chunk
John McCall7f416cc2015-09-08 08:05:57 +00002331 };
2332 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2333}
2334
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002335static void emitForStaticInitCall(CodeGenFunction &CGF,
2336 SourceLocation Loc,
2337 llvm::Value * UpdateLocation,
2338 llvm::Value * ThreadId,
2339 llvm::Constant * ForStaticInitFunction,
2340 OpenMPSchedType Schedule,
2341 unsigned IVSize, bool IVSigned, bool Ordered,
2342 Address IL, Address LB, Address UB,
2343 Address ST, llvm::Value *Chunk) {
2344 if (!CGF.HaveInsertPoint())
2345 return;
2346
2347 assert(!Ordered);
2348 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
2349 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
2350 Schedule == OMP_dist_sch_static ||
2351 Schedule == OMP_dist_sch_static_chunked);
2352
2353 // Call __kmpc_for_static_init(
2354 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2355 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2356 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2357 // kmp_int[32|64] incr, kmp_int[32|64] chunk);
2358 if (Chunk == nullptr) {
2359 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
2360 Schedule == OMP_dist_sch_static) &&
2361 "expected static non-chunked schedule");
2362 // If the Chunk was not specified in the clause - use default value 1.
2363 Chunk = CGF.Builder.getIntN(IVSize, 1);
2364 } else {
2365 assert((Schedule == OMP_sch_static_chunked ||
2366 Schedule == OMP_ord_static_chunked ||
2367 Schedule == OMP_dist_sch_static_chunked) &&
2368 "expected static chunked schedule");
2369 }
2370 llvm::Value *Args[] = {
2371 UpdateLocation,
2372 ThreadId,
2373 CGF.Builder.getInt32(Schedule), // Schedule type
2374 IL.getPointer(), // &isLastIter
2375 LB.getPointer(), // &LB
2376 UB.getPointer(), // &UB
2377 ST.getPointer(), // &Stride
2378 CGF.Builder.getIntN(IVSize, 1), // Incr
2379 Chunk // Chunk
2380 };
2381 CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
2382}
2383
John McCall7f416cc2015-09-08 08:05:57 +00002384void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
2385 SourceLocation Loc,
2386 OpenMPScheduleClauseKind ScheduleKind,
2387 unsigned IVSize, bool IVSigned,
2388 bool Ordered, Address IL, Address LB,
2389 Address UB, Address ST,
2390 llvm::Value *Chunk) {
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002391 OpenMPSchedType ScheduleNum = getRuntimeSchedule(ScheduleKind, Chunk != nullptr,
2392 Ordered);
2393 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2394 auto *ThreadId = getThreadID(CGF, Loc);
2395 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
2396 emitForStaticInitCall(CGF, Loc, UpdatedLocation, ThreadId, StaticInitFunction,
2397 ScheduleNum, IVSize, IVSigned, Ordered, IL, LB, UB, ST, Chunk);
2398}
John McCall7f416cc2015-09-08 08:05:57 +00002399
Carlo Bertollifc35ad22016-03-07 16:04:49 +00002400void CGOpenMPRuntime::emitDistributeStaticInit(CodeGenFunction &CGF,
2401 SourceLocation Loc, OpenMPDistScheduleClauseKind SchedKind,
2402 unsigned IVSize, bool IVSigned,
2403 bool Ordered, Address IL, Address LB,
2404 Address UB, Address ST,
2405 llvm::Value *Chunk) {
2406 OpenMPSchedType ScheduleNum = getRuntimeSchedule(SchedKind, Chunk != nullptr);
2407 auto *UpdatedLocation = emitUpdateLocation(CGF, Loc);
2408 auto *ThreadId = getThreadID(CGF, Loc);
2409 auto *StaticInitFunction = createForStaticInitFunction(IVSize, IVSigned);
2410 emitForStaticInitCall(CGF, Loc, UpdatedLocation, ThreadId, StaticInitFunction,
2411 ScheduleNum, IVSize, IVSigned, Ordered, IL, LB, UB, ST, Chunk);
Alexander Musmanc6388682014-12-15 07:07:06 +00002412}
2413
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002414void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
2415 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002416 if (!CGF.HaveInsertPoint())
2417 return;
Alexander Musmanc6388682014-12-15 07:07:06 +00002418 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002419 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002420 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini),
2421 Args);
Alexander Musmanc6388682014-12-15 07:07:06 +00002422}
2423
Alexey Bataevd7589ffe2015-05-20 13:12:48 +00002424void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
2425 SourceLocation Loc,
2426 unsigned IVSize,
2427 bool IVSigned) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002428 if (!CGF.HaveInsertPoint())
2429 return;
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002430 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
Alexey Bataev50b3c952016-02-19 10:38:26 +00002431 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
Alexey Bataev98eb6e32015-04-22 11:15:40 +00002432 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
2433}
2434
Alexander Musman92bdaab2015-03-12 13:37:50 +00002435llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
2436 SourceLocation Loc, unsigned IVSize,
John McCall7f416cc2015-09-08 08:05:57 +00002437 bool IVSigned, Address IL,
2438 Address LB, Address UB,
2439 Address ST) {
Alexander Musman92bdaab2015-03-12 13:37:50 +00002440 // Call __kmpc_dispatch_next(
2441 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
2442 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
2443 // kmp_int[32|64] *p_stride);
2444 llvm::Value *Args[] = {
Alexey Bataev50b3c952016-02-19 10:38:26 +00002445 emitUpdateLocation(CGF, Loc),
2446 getThreadID(CGF, Loc),
John McCall7f416cc2015-09-08 08:05:57 +00002447 IL.getPointer(), // &isLastIter
2448 LB.getPointer(), // &Lower
2449 UB.getPointer(), // &Upper
2450 ST.getPointer() // &Stride
Alexander Musman92bdaab2015-03-12 13:37:50 +00002451 };
2452 llvm::Value *Call =
2453 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
2454 return CGF.EmitScalarConversion(
2455 Call, CGF.getContext().getIntTypeForBitwidth(32, /* Signed */ true),
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002456 CGF.getContext().BoolTy, Loc);
Alexander Musman92bdaab2015-03-12 13:37:50 +00002457}
2458
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002459void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
2460 llvm::Value *NumThreads,
2461 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002462 if (!CGF.HaveInsertPoint())
2463 return;
Alexey Bataevb2059782014-10-13 08:23:51 +00002464 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
2465 llvm::Value *Args[] = {
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002466 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
Alexey Bataevb2059782014-10-13 08:23:51 +00002467 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002468 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads),
2469 Args);
Alexey Bataevb2059782014-10-13 08:23:51 +00002470}
2471
Alexey Bataev7f210c62015-06-18 13:40:03 +00002472void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
2473 OpenMPProcBindClauseKind ProcBind,
2474 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002475 if (!CGF.HaveInsertPoint())
2476 return;
Alexey Bataev7f210c62015-06-18 13:40:03 +00002477 // Constants for proc bind value accepted by the runtime.
2478 enum ProcBindTy {
2479 ProcBindFalse = 0,
2480 ProcBindTrue,
2481 ProcBindMaster,
2482 ProcBindClose,
2483 ProcBindSpread,
2484 ProcBindIntel,
2485 ProcBindDefault
2486 } RuntimeProcBind;
2487 switch (ProcBind) {
2488 case OMPC_PROC_BIND_master:
2489 RuntimeProcBind = ProcBindMaster;
2490 break;
2491 case OMPC_PROC_BIND_close:
2492 RuntimeProcBind = ProcBindClose;
2493 break;
2494 case OMPC_PROC_BIND_spread:
2495 RuntimeProcBind = ProcBindSpread;
2496 break;
2497 case OMPC_PROC_BIND_unknown:
2498 llvm_unreachable("Unsupported proc_bind value.");
2499 }
2500 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
2501 llvm::Value *Args[] = {
2502 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2503 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)};
2504 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args);
2505}
2506
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002507void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
2508 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00002509 if (!CGF.HaveInsertPoint())
2510 return;
Alexey Bataevd76df6d2015-02-24 12:55:09 +00002511 // Build call void __kmpc_flush(ident_t *loc)
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002512 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush),
2513 emitUpdateLocation(CGF, Loc));
Alexey Bataevcc37cc12014-11-20 04:34:54 +00002514}
Alexey Bataev3eff5f42015-02-25 08:32:46 +00002515
Alexey Bataev62b63b12015-03-10 07:28:44 +00002516namespace {
2517/// \brief Indexes of fields for type kmp_task_t.
2518enum KmpTaskTFields {
2519 /// \brief List of shared variables.
2520 KmpTaskTShareds,
2521 /// \brief Task routine.
2522 KmpTaskTRoutine,
2523 /// \brief Partition id for the untied tasks.
2524 KmpTaskTPartId,
2525 /// \brief Function with call of destructors for private variables.
2526 KmpTaskTDestructors,
Alexey Bataev7292c292016-04-25 12:22:29 +00002527 /// (Taskloops only) Lower bound.
2528 KmpTaskTLowerBound,
2529 /// (Taskloops only) Upper bound.
2530 KmpTaskTUpperBound,
2531 /// (Taskloops only) Stride.
2532 KmpTaskTStride,
2533 /// (Taskloops only) Is last iteration flag.
2534 KmpTaskTLastIter,
Alexey Bataev62b63b12015-03-10 07:28:44 +00002535};
Hans Wennborg7eb54642015-09-10 17:07:54 +00002536} // anonymous namespace
Alexey Bataev62b63b12015-03-10 07:28:44 +00002537
Samuel Antaoee8fb302016-01-06 13:42:12 +00002538bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
2539 // FIXME: Add other entries type when they become supported.
2540 return OffloadEntriesTargetRegion.empty();
2541}
2542
2543/// \brief Initialize target region entry.
2544void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2545 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2546 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00002547 unsigned Order) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002548 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
2549 "only required for the device "
2550 "code generation.");
Samuel Antao2de62b02016-02-13 23:35:10 +00002551 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
Samuel Antaoee8fb302016-01-06 13:42:12 +00002552 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr);
2553 ++OffloadingEntriesNum;
2554}
2555
2556void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2557 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2558 StringRef ParentName, unsigned LineNum,
Samuel Antao2de62b02016-02-13 23:35:10 +00002559 llvm::Constant *Addr, llvm::Constant *ID) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002560 // If we are emitting code for a target, the entry is already initialized,
2561 // only has to be registered.
2562 if (CGM.getLangOpts().OpenMPIsDevice) {
Samuel Antao2de62b02016-02-13 23:35:10 +00002563 assert(hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
Samuel Antaoee8fb302016-01-06 13:42:12 +00002564 "Entry must exist.");
Samuel Antao2de62b02016-02-13 23:35:10 +00002565 auto &Entry =
2566 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
Samuel Antaoee8fb302016-01-06 13:42:12 +00002567 assert(Entry.isValid() && "Entry not initialized!");
2568 Entry.setAddress(Addr);
2569 Entry.setID(ID);
2570 return;
2571 } else {
2572 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum++, Addr, ID);
Samuel Antao2de62b02016-02-13 23:35:10 +00002573 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002574 }
2575}
2576
2577bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00002578 unsigned DeviceID, unsigned FileID, StringRef ParentName,
2579 unsigned LineNum) const {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002580 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
2581 if (PerDevice == OffloadEntriesTargetRegion.end())
2582 return false;
2583 auto PerFile = PerDevice->second.find(FileID);
2584 if (PerFile == PerDevice->second.end())
2585 return false;
2586 auto PerParentName = PerFile->second.find(ParentName);
2587 if (PerParentName == PerFile->second.end())
2588 return false;
2589 auto PerLine = PerParentName->second.find(LineNum);
2590 if (PerLine == PerParentName->second.end())
2591 return false;
Samuel Antaoee8fb302016-01-06 13:42:12 +00002592 // Fail if this entry is already registered.
Samuel Antao2de62b02016-02-13 23:35:10 +00002593 if (PerLine->second.getAddress() || PerLine->second.getID())
Samuel Antaoee8fb302016-01-06 13:42:12 +00002594 return false;
2595 return true;
2596}
2597
2598void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
2599 const OffloadTargetRegionEntryInfoActTy &Action) {
2600 // Scan all target region entries and perform the provided action.
2601 for (auto &D : OffloadEntriesTargetRegion)
2602 for (auto &F : D.second)
2603 for (auto &P : F.second)
2604 for (auto &L : P.second)
Samuel Antao2de62b02016-02-13 23:35:10 +00002605 Action(D.first, F.first, P.first(), L.first, L.second);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002606}
2607
2608/// \brief Create a Ctor/Dtor-like function whose body is emitted through
2609/// \a Codegen. This is used to emit the two functions that register and
2610/// unregister the descriptor of the current compilation unit.
2611static llvm::Function *
2612createOffloadingBinaryDescriptorFunction(CodeGenModule &CGM, StringRef Name,
2613 const RegionCodeGenTy &Codegen) {
2614 auto &C = CGM.getContext();
2615 FunctionArgList Args;
2616 ImplicitParamDecl DummyPtr(C, /*DC=*/nullptr, SourceLocation(),
2617 /*Id=*/nullptr, C.VoidPtrTy);
2618 Args.push_back(&DummyPtr);
2619
2620 CodeGenFunction CGF(CGM);
2621 GlobalDecl();
John McCallc56a8b32016-03-11 04:30:31 +00002622 auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002623 auto FTy = CGM.getTypes().GetFunctionType(FI);
2624 auto *Fn =
2625 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, SourceLocation());
2626 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FI, Args, SourceLocation());
2627 Codegen(CGF);
2628 CGF.FinishFunction();
2629 return Fn;
2630}
2631
2632llvm::Function *
2633CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() {
2634
2635 // If we don't have entries or if we are emitting code for the device, we
2636 // don't need to do anything.
2637 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty())
2638 return nullptr;
2639
2640 auto &M = CGM.getModule();
2641 auto &C = CGM.getContext();
2642
2643 // Get list of devices we care about
2644 auto &Devices = CGM.getLangOpts().OMPTargetTriples;
2645
2646 // We should be creating an offloading descriptor only if there are devices
2647 // specified.
2648 assert(!Devices.empty() && "No OpenMP offloading devices??");
2649
2650 // Create the external variables that will point to the begin and end of the
2651 // host entries section. These will be defined by the linker.
2652 auto *OffloadEntryTy =
2653 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy());
2654 llvm::GlobalVariable *HostEntriesBegin = new llvm::GlobalVariable(
2655 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002656 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002657 ".omp_offloading.entries_begin");
2658 llvm::GlobalVariable *HostEntriesEnd = new llvm::GlobalVariable(
2659 M, OffloadEntryTy, /*isConstant=*/true,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002660 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002661 ".omp_offloading.entries_end");
2662
2663 // Create all device images
2664 llvm::SmallVector<llvm::Constant *, 4> DeviceImagesEntires;
2665 auto *DeviceImageTy = cast<llvm::StructType>(
2666 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy()));
2667
2668 for (unsigned i = 0; i < Devices.size(); ++i) {
2669 StringRef T = Devices[i].getTriple();
2670 auto *ImgBegin = new llvm::GlobalVariable(
2671 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002672 /*Initializer=*/nullptr,
2673 Twine(".omp_offloading.img_start.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002674 auto *ImgEnd = new llvm::GlobalVariable(
2675 M, CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage,
Eugene Zelenko1660a5d2016-01-26 19:01:06 +00002676 /*Initializer=*/nullptr, Twine(".omp_offloading.img_end.") + Twine(T));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002677
2678 llvm::Constant *Dev =
2679 llvm::ConstantStruct::get(DeviceImageTy, ImgBegin, ImgEnd,
2680 HostEntriesBegin, HostEntriesEnd, nullptr);
2681 DeviceImagesEntires.push_back(Dev);
2682 }
2683
2684 // Create device images global array.
2685 llvm::ArrayType *DeviceImagesInitTy =
2686 llvm::ArrayType::get(DeviceImageTy, DeviceImagesEntires.size());
2687 llvm::Constant *DeviceImagesInit =
2688 llvm::ConstantArray::get(DeviceImagesInitTy, DeviceImagesEntires);
2689
2690 llvm::GlobalVariable *DeviceImages = new llvm::GlobalVariable(
2691 M, DeviceImagesInitTy, /*isConstant=*/true,
2692 llvm::GlobalValue::InternalLinkage, DeviceImagesInit,
2693 ".omp_offloading.device_images");
2694 DeviceImages->setUnnamedAddr(true);
2695
2696 // This is a Zero array to be used in the creation of the constant expressions
2697 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty),
2698 llvm::Constant::getNullValue(CGM.Int32Ty)};
2699
2700 // Create the target region descriptor.
2701 auto *BinaryDescriptorTy = cast<llvm::StructType>(
2702 CGM.getTypes().ConvertTypeForMem(getTgtBinaryDescriptorQTy()));
2703 llvm::Constant *TargetRegionsDescriptorInit = llvm::ConstantStruct::get(
2704 BinaryDescriptorTy, llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()),
2705 llvm::ConstantExpr::getGetElementPtr(DeviceImagesInitTy, DeviceImages,
2706 Index),
2707 HostEntriesBegin, HostEntriesEnd, nullptr);
2708
2709 auto *Desc = new llvm::GlobalVariable(
2710 M, BinaryDescriptorTy, /*isConstant=*/true,
2711 llvm::GlobalValue::InternalLinkage, TargetRegionsDescriptorInit,
2712 ".omp_offloading.descriptor");
2713
2714 // Emit code to register or unregister the descriptor at execution
2715 // startup or closing, respectively.
2716
2717 // Create a variable to drive the registration and unregistration of the
2718 // descriptor, so we can reuse the logic that emits Ctors and Dtors.
2719 auto *IdentInfo = &C.Idents.get(".omp_offloading.reg_unreg_var");
2720 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), SourceLocation(),
2721 IdentInfo, C.CharTy);
2722
2723 auto *UnRegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002724 CGM, ".omp_offloading.descriptor_unreg",
2725 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002726 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_unregister_lib),
2727 Desc);
2728 });
2729 auto *RegFn = createOffloadingBinaryDescriptorFunction(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00002730 CGM, ".omp_offloading.descriptor_reg",
2731 [&](CodeGenFunction &CGF, PrePostActionTy &) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00002732 CGF.EmitCallOrInvoke(createRuntimeFunction(OMPRTL__tgt_register_lib),
2733 Desc);
2734 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc);
2735 });
2736 return RegFn;
2737}
2738
Samuel Antao2de62b02016-02-13 23:35:10 +00002739void CGOpenMPRuntime::createOffloadEntry(llvm::Constant *ID,
2740 llvm::Constant *Addr, uint64_t Size) {
2741 StringRef Name = Addr->getName();
Samuel Antaoee8fb302016-01-06 13:42:12 +00002742 auto *TgtOffloadEntryType = cast<llvm::StructType>(
2743 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()));
2744 llvm::LLVMContext &C = CGM.getModule().getContext();
2745 llvm::Module &M = CGM.getModule();
2746
2747 // Make sure the address has the right type.
Samuel Antao2de62b02016-02-13 23:35:10 +00002748 llvm::Constant *AddrPtr = llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002749
2750 // Create constant string with the name.
2751 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
2752
2753 llvm::GlobalVariable *Str =
2754 new llvm::GlobalVariable(M, StrPtrInit->getType(), /*isConstant=*/true,
2755 llvm::GlobalValue::InternalLinkage, StrPtrInit,
2756 ".omp_offloading.entry_name");
2757 Str->setUnnamedAddr(true);
2758 llvm::Constant *StrPtr = llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy);
2759
2760 // Create the entry struct.
2761 llvm::Constant *EntryInit = llvm::ConstantStruct::get(
2762 TgtOffloadEntryType, AddrPtr, StrPtr,
2763 llvm::ConstantInt::get(CGM.SizeTy, Size), nullptr);
2764 llvm::GlobalVariable *Entry = new llvm::GlobalVariable(
2765 M, TgtOffloadEntryType, true, llvm::GlobalValue::ExternalLinkage,
2766 EntryInit, ".omp_offloading.entry");
2767
2768 // The entry has to be created in the section the linker expects it to be.
2769 Entry->setSection(".omp_offloading.entries");
2770 // We can't have any padding between symbols, so we need to have 1-byte
2771 // alignment.
2772 Entry->setAlignment(1);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002773}
2774
2775void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
2776 // Emit the offloading entries and metadata so that the device codegen side
2777 // can
2778 // easily figure out what to emit. The produced metadata looks like this:
2779 //
2780 // !omp_offload.info = !{!1, ...}
2781 //
2782 // Right now we only generate metadata for function that contain target
2783 // regions.
2784
2785 // If we do not have entries, we dont need to do anything.
2786 if (OffloadEntriesInfoManager.empty())
2787 return;
2788
2789 llvm::Module &M = CGM.getModule();
2790 llvm::LLVMContext &C = M.getContext();
2791 SmallVector<OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16>
2792 OrderedEntries(OffloadEntriesInfoManager.size());
2793
2794 // Create the offloading info metadata node.
2795 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
2796
2797 // Auxiliar methods to create metadata values and strings.
2798 auto getMDInt = [&](unsigned v) {
2799 return llvm::ConstantAsMetadata::get(
2800 llvm::ConstantInt::get(llvm::Type::getInt32Ty(C), v));
2801 };
2802
2803 auto getMDString = [&](StringRef v) { return llvm::MDString::get(C, v); };
2804
2805 // Create function that emits metadata for each target region entry;
2806 auto &&TargetRegionMetadataEmitter = [&](
2807 unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned Line,
Samuel Antaoee8fb302016-01-06 13:42:12 +00002808 OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
2809 llvm::SmallVector<llvm::Metadata *, 32> Ops;
2810 // Generate metadata for target regions. Each entry of this metadata
2811 // contains:
2812 // - Entry 0 -> Kind of this type of metadata (0).
2813 // - Entry 1 -> Device ID of the file where the entry was identified.
2814 // - Entry 2 -> File ID of the file where the entry was identified.
2815 // - Entry 3 -> Mangled name of the function where the entry was identified.
2816 // - Entry 4 -> Line in the file where the entry was identified.
Samuel Antao2de62b02016-02-13 23:35:10 +00002817 // - Entry 5 -> Order the entry was created.
Samuel Antaoee8fb302016-01-06 13:42:12 +00002818 // The first element of the metadata node is the kind.
2819 Ops.push_back(getMDInt(E.getKind()));
2820 Ops.push_back(getMDInt(DeviceID));
2821 Ops.push_back(getMDInt(FileID));
2822 Ops.push_back(getMDString(ParentName));
2823 Ops.push_back(getMDInt(Line));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002824 Ops.push_back(getMDInt(E.getOrder()));
2825
2826 // Save this entry in the right position of the ordered entries array.
2827 OrderedEntries[E.getOrder()] = &E;
2828
2829 // Add metadata to the named metadata node.
2830 MD->addOperand(llvm::MDNode::get(C, Ops));
2831 };
2832
2833 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
2834 TargetRegionMetadataEmitter);
2835
2836 for (auto *E : OrderedEntries) {
2837 assert(E && "All ordered entries must exist!");
2838 if (auto *CE =
2839 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
2840 E)) {
2841 assert(CE->getID() && CE->getAddress() &&
2842 "Entry ID and Addr are invalid!");
Samuel Antao2de62b02016-02-13 23:35:10 +00002843 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0);
Samuel Antaoee8fb302016-01-06 13:42:12 +00002844 } else
2845 llvm_unreachable("Unsupported entry kind.");
2846 }
2847}
2848
2849/// \brief Loads all the offload entries information from the host IR
2850/// metadata.
2851void CGOpenMPRuntime::loadOffloadInfoMetadata() {
2852 // If we are in target mode, load the metadata from the host IR. This code has
2853 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
2854
2855 if (!CGM.getLangOpts().OpenMPIsDevice)
2856 return;
2857
2858 if (CGM.getLangOpts().OMPHostIRFile.empty())
2859 return;
2860
2861 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
2862 if (Buf.getError())
2863 return;
2864
2865 llvm::LLVMContext C;
2866 auto ME = llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C);
2867
2868 if (ME.getError())
2869 return;
2870
2871 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
2872 if (!MD)
2873 return;
2874
2875 for (auto I : MD->operands()) {
2876 llvm::MDNode *MN = cast<llvm::MDNode>(I);
2877
2878 auto getMDInt = [&](unsigned Idx) {
2879 llvm::ConstantAsMetadata *V =
2880 cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
2881 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
2882 };
2883
2884 auto getMDString = [&](unsigned Idx) {
2885 llvm::MDString *V = cast<llvm::MDString>(MN->getOperand(Idx));
2886 return V->getString();
2887 };
2888
2889 switch (getMDInt(0)) {
2890 default:
2891 llvm_unreachable("Unexpected metadata!");
2892 break;
2893 case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
2894 OFFLOAD_ENTRY_INFO_TARGET_REGION:
2895 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
2896 /*DeviceID=*/getMDInt(1), /*FileID=*/getMDInt(2),
2897 /*ParentName=*/getMDString(3), /*Line=*/getMDInt(4),
Samuel Antao2de62b02016-02-13 23:35:10 +00002898 /*Order=*/getMDInt(5));
Samuel Antaoee8fb302016-01-06 13:42:12 +00002899 break;
2900 }
2901 }
2902}
2903
Alexey Bataev62b63b12015-03-10 07:28:44 +00002904void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
2905 if (!KmpRoutineEntryPtrTy) {
2906 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
2907 auto &C = CGM.getContext();
2908 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
2909 FunctionProtoType::ExtProtoInfo EPI;
2910 KmpRoutineEntryPtrQTy = C.getPointerType(
2911 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
2912 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
2913 }
2914}
2915
Alexey Bataevc71a4092015-09-11 10:29:41 +00002916static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
2917 QualType FieldTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002918 auto *Field = FieldDecl::Create(
2919 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
2920 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
2921 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
2922 Field->setAccess(AS_public);
2923 DC->addDecl(Field);
Alexey Bataevc71a4092015-09-11 10:29:41 +00002924 return Field;
Alexey Bataev62b63b12015-03-10 07:28:44 +00002925}
2926
Samuel Antaoee8fb302016-01-06 13:42:12 +00002927QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
2928
2929 // Make sure the type of the entry is already created. This is the type we
2930 // have to create:
2931 // struct __tgt_offload_entry{
2932 // void *addr; // Pointer to the offload entry info.
2933 // // (function or global)
2934 // char *name; // Name of the function or global.
2935 // size_t size; // Size of the entry info (0 if it a function).
2936 // };
2937 if (TgtOffloadEntryQTy.isNull()) {
2938 ASTContext &C = CGM.getContext();
2939 auto *RD = C.buildImplicitRecord("__tgt_offload_entry");
2940 RD->startDefinition();
2941 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2942 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
2943 addFieldToRecordDecl(C, RD, C.getSizeType());
2944 RD->completeDefinition();
2945 TgtOffloadEntryQTy = C.getRecordType(RD);
2946 }
2947 return TgtOffloadEntryQTy;
2948}
2949
2950QualType CGOpenMPRuntime::getTgtDeviceImageQTy() {
2951 // These are the types we need to build:
2952 // struct __tgt_device_image{
2953 // void *ImageStart; // Pointer to the target code start.
2954 // void *ImageEnd; // Pointer to the target code end.
2955 // // We also add the host entries to the device image, as it may be useful
2956 // // for the target runtime to have access to that information.
2957 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all
2958 // // the entries.
2959 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
2960 // // entries (non inclusive).
2961 // };
2962 if (TgtDeviceImageQTy.isNull()) {
2963 ASTContext &C = CGM.getContext();
2964 auto *RD = C.buildImplicitRecord("__tgt_device_image");
2965 RD->startDefinition();
2966 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2967 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
2968 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2969 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2970 RD->completeDefinition();
2971 TgtDeviceImageQTy = C.getRecordType(RD);
2972 }
2973 return TgtDeviceImageQTy;
2974}
2975
2976QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() {
2977 // struct __tgt_bin_desc{
2978 // int32_t NumDevices; // Number of devices supported.
2979 // __tgt_device_image *DeviceImages; // Arrays of device images
2980 // // (one per device).
2981 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the
2982 // // entries.
2983 // __tgt_offload_entry *EntriesEnd; // End of the table with all the
2984 // // entries (non inclusive).
2985 // };
2986 if (TgtBinaryDescriptorQTy.isNull()) {
2987 ASTContext &C = CGM.getContext();
2988 auto *RD = C.buildImplicitRecord("__tgt_bin_desc");
2989 RD->startDefinition();
2990 addFieldToRecordDecl(
2991 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
2992 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy()));
2993 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2994 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy()));
2995 RD->completeDefinition();
2996 TgtBinaryDescriptorQTy = C.getRecordType(RD);
2997 }
2998 return TgtBinaryDescriptorQTy;
2999}
3000
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003001namespace {
Alexey Bataev9e034042015-05-05 04:05:12 +00003002struct PrivateHelpersTy {
3003 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy,
3004 const VarDecl *PrivateElemInit)
3005 : Original(Original), PrivateCopy(PrivateCopy),
3006 PrivateElemInit(PrivateElemInit) {}
3007 const VarDecl *Original;
3008 const VarDecl *PrivateCopy;
3009 const VarDecl *PrivateElemInit;
3010};
3011typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
Hans Wennborg7eb54642015-09-10 17:07:54 +00003012} // anonymous namespace
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003013
Alexey Bataev9e034042015-05-05 04:05:12 +00003014static RecordDecl *
Craig Topper8674c5c2015-09-29 04:30:07 +00003015createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003016 if (!Privates.empty()) {
3017 auto &C = CGM.getContext();
3018 // Build struct .kmp_privates_t. {
3019 // /* private vars */
3020 // };
3021 auto *RD = C.buildImplicitRecord(".kmp_privates.t");
3022 RD->startDefinition();
3023 for (auto &&Pair : Privates) {
Alexey Bataevc71a4092015-09-11 10:29:41 +00003024 auto *VD = Pair.second.Original;
3025 auto Type = VD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003026 Type = Type.getNonReferenceType();
Alexey Bataevc71a4092015-09-11 10:29:41 +00003027 auto *FD = addFieldToRecordDecl(C, RD, Type);
3028 if (VD->hasAttrs()) {
3029 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
3030 E(VD->getAttrs().end());
3031 I != E; ++I)
3032 FD->addAttr(*I);
3033 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003034 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003035 RD->completeDefinition();
3036 return RD;
3037 }
3038 return nullptr;
3039}
3040
Alexey Bataev9e034042015-05-05 04:05:12 +00003041static RecordDecl *
Alexey Bataev7292c292016-04-25 12:22:29 +00003042createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
3043 QualType KmpInt32Ty,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003044 QualType KmpRoutineEntryPointerQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003045 auto &C = CGM.getContext();
3046 // Build struct kmp_task_t {
3047 // void * shareds;
3048 // kmp_routine_entry_t routine;
3049 // kmp_int32 part_id;
3050 // kmp_routine_entry_t destructors;
Alexey Bataev7292c292016-04-25 12:22:29 +00003051 // For taskloops additional fields:
3052 // kmp_uint64 lb;
3053 // kmp_uint64 ub;
3054 // kmp_int64 st;
3055 // kmp_int32 liter;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003056 // };
3057 auto *RD = C.buildImplicitRecord("kmp_task_t");
3058 RD->startDefinition();
3059 addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3060 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
3061 addFieldToRecordDecl(C, RD, KmpInt32Ty);
3062 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003063 if (isOpenMPTaskLoopDirective(Kind)) {
3064 QualType KmpUInt64Ty =
3065 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3066 QualType KmpInt64Ty =
3067 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3068 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3069 addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3070 addFieldToRecordDecl(C, RD, KmpInt64Ty);
3071 addFieldToRecordDecl(C, RD, KmpInt32Ty);
3072 }
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003073 RD->completeDefinition();
3074 return RD;
3075}
3076
3077static RecordDecl *
3078createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003079 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003080 auto &C = CGM.getContext();
3081 // Build struct kmp_task_t_with_privates {
3082 // kmp_task_t task_data;
3083 // .kmp_privates_t. privates;
3084 // };
3085 auto *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
3086 RD->startDefinition();
3087 addFieldToRecordDecl(C, RD, KmpTaskTQTy);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003088 if (auto *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) {
3089 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
3090 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003091 RD->completeDefinition();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003092 return RD;
Alexey Bataev62b63b12015-03-10 07:28:44 +00003093}
3094
3095/// \brief Emit a proxy function which accepts kmp_task_t as the second
3096/// argument.
3097/// \code
3098/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003099/// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
Alexey Bataev7292c292016-04-25 12:22:29 +00003100/// For taskloops:
3101/// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003102/// tt->shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003103/// return 0;
3104/// }
3105/// \endcode
3106static llvm::Value *
3107emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
Alexey Bataev7292c292016-04-25 12:22:29 +00003108 OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
3109 QualType KmpTaskTWithPrivatesPtrQTy,
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003110 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003111 QualType SharedsPtrTy, llvm::Value *TaskFunction,
3112 llvm::Value *TaskPrivatesMap) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003113 auto &C = CGM.getContext();
3114 FunctionArgList Args;
3115 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
3116 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00003117 /*Id=*/nullptr,
3118 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003119 Args.push_back(&GtidArg);
3120 Args.push_back(&TaskTypeArg);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003121 auto &TaskEntryFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003122 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003123 auto *TaskEntryTy = CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
3124 auto *TaskEntry =
3125 llvm::Function::Create(TaskEntryTy, llvm::GlobalValue::InternalLinkage,
3126 ".omp_task_entry.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003127 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskEntry, TaskEntryFnInfo);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003128 CodeGenFunction CGF(CGM);
3129 CGF.disableDebugInfo();
3130 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args);
3131
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003132 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
Alexey Bataev7292c292016-04-25 12:22:29 +00003133 // tt,
3134 // For taskloops:
3135 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3136 // tt->task_data.shareds);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003137 auto *GtidParam = CGF.EmitLoadOfScalar(
John McCall7f416cc2015-09-08 08:05:57 +00003138 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003139 LValue TDBase = CGF.EmitLoadOfPointerLValue(
3140 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3141 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003142 auto *KmpTaskTWithPrivatesQTyRD =
3143 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003144 LValue Base =
3145 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003146 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3147 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3148 auto PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
Alexey Bataev48591dd2016-04-20 04:01:36 +00003149 auto *PartidParam = PartIdLVal.getPointer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003150
3151 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3152 auto SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003153 auto *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003154 CGF.EmitLoadOfLValue(SharedsLVal, Loc).getScalarVal(),
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003155 CGF.ConvertTypeForMem(SharedsPtrTy));
3156
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003157 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3158 llvm::Value *PrivatesParam;
3159 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3160 auto PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3161 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00003162 PrivatesLVal.getPointer(), CGF.VoidPtrTy);
Alexey Bataev7292c292016-04-25 12:22:29 +00003163 } else
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003164 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003165
Alexey Bataev7292c292016-04-25 12:22:29 +00003166 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
3167 TaskPrivatesMap,
3168 CGF.Builder
3169 .CreatePointerBitCastOrAddrSpaceCast(
3170 TDBase.getAddress(), CGF.VoidPtrTy)
3171 .getPointer()};
3172 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
3173 std::end(CommonArgs));
3174 if (isOpenMPTaskLoopDirective(Kind)) {
3175 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
3176 auto LBLVal = CGF.EmitLValueForField(Base, *LBFI);
3177 auto *LBParam = CGF.EmitLoadOfLValue(LBLVal, Loc).getScalarVal();
3178 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
3179 auto UBLVal = CGF.EmitLValueForField(Base, *UBFI);
3180 auto *UBParam = CGF.EmitLoadOfLValue(UBLVal, Loc).getScalarVal();
3181 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
3182 auto StLVal = CGF.EmitLValueForField(Base, *StFI);
3183 auto *StParam = CGF.EmitLoadOfLValue(StLVal, Loc).getScalarVal();
3184 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3185 auto LILVal = CGF.EmitLValueForField(Base, *LIFI);
3186 auto *LIParam = CGF.EmitLoadOfLValue(LILVal, Loc).getScalarVal();
3187 CallArgs.push_back(LBParam);
3188 CallArgs.push_back(UBParam);
3189 CallArgs.push_back(StParam);
3190 CallArgs.push_back(LIParam);
3191 }
3192 CallArgs.push_back(SharedsParam);
3193
Alexey Bataev62b63b12015-03-10 07:28:44 +00003194 CGF.EmitCallOrInvoke(TaskFunction, CallArgs);
3195 CGF.EmitStoreThroughLValue(
3196 RValue::get(CGF.Builder.getInt32(/*C=*/0)),
John McCall7f416cc2015-09-08 08:05:57 +00003197 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
Alexey Bataev62b63b12015-03-10 07:28:44 +00003198 CGF.FinishFunction();
3199 return TaskEntry;
3200}
3201
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003202static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
3203 SourceLocation Loc,
3204 QualType KmpInt32Ty,
3205 QualType KmpTaskTWithPrivatesPtrQTy,
3206 QualType KmpTaskTWithPrivatesQTy) {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003207 auto &C = CGM.getContext();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003208 FunctionArgList Args;
3209 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty);
3210 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc,
Alexey Bataev2377fe92015-09-10 08:12:02 +00003211 /*Id=*/nullptr,
3212 KmpTaskTWithPrivatesPtrQTy.withRestrict());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003213 Args.push_back(&GtidArg);
3214 Args.push_back(&TaskTypeArg);
3215 FunctionType::ExtInfo Info;
3216 auto &DestructorFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003217 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003218 auto *DestructorFnTy = CGM.getTypes().GetFunctionType(DestructorFnInfo);
3219 auto *DestructorFn =
3220 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
3221 ".omp_task_destructor.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003222 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, DestructorFn,
3223 DestructorFnInfo);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003224 CodeGenFunction CGF(CGM);
3225 CGF.disableDebugInfo();
3226 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
3227 Args);
3228
Alexey Bataev31300ed2016-02-04 11:27:03 +00003229 LValue Base = CGF.EmitLoadOfPointerLValue(
3230 CGF.GetAddrOfLocalVar(&TaskTypeArg),
3231 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003232 auto *KmpTaskTWithPrivatesQTyRD =
3233 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3234 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003235 Base = CGF.EmitLValueForField(Base, *FI);
3236 for (auto *Field :
3237 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
3238 if (auto DtorKind = Field->getType().isDestructedType()) {
3239 auto FieldLValue = CGF.EmitLValueForField(Base, Field);
3240 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType());
3241 }
3242 }
3243 CGF.FinishFunction();
3244 return DestructorFn;
3245}
3246
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003247/// \brief Emit a privates mapping function for correct handling of private and
3248/// firstprivate variables.
3249/// \code
3250/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
3251/// **noalias priv1,..., <tyn> **noalias privn) {
3252/// *priv1 = &.privates.priv1;
3253/// ...;
3254/// *privn = &.privates.privn;
3255/// }
3256/// \endcode
3257static llvm::Value *
3258emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
Craig Topper8674c5c2015-09-29 04:30:07 +00003259 ArrayRef<const Expr *> PrivateVars,
3260 ArrayRef<const Expr *> FirstprivateVars,
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003261 QualType PrivatesQTy,
Craig Topper8674c5c2015-09-29 04:30:07 +00003262 ArrayRef<PrivateDataTy> Privates) {
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003263 auto &C = CGM.getContext();
3264 FunctionArgList Args;
3265 ImplicitParamDecl TaskPrivatesArg(
3266 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3267 C.getPointerType(PrivatesQTy).withConst().withRestrict());
3268 Args.push_back(&TaskPrivatesArg);
3269 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos;
3270 unsigned Counter = 1;
3271 for (auto *E: PrivateVars) {
3272 Args.push_back(ImplicitParamDecl::Create(
3273 C, /*DC=*/nullptr, Loc,
3274 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3275 .withConst()
3276 .withRestrict()));
3277 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3278 PrivateVarsPos[VD] = Counter;
3279 ++Counter;
3280 }
3281 for (auto *E : FirstprivateVars) {
3282 Args.push_back(ImplicitParamDecl::Create(
3283 C, /*DC=*/nullptr, Loc,
3284 /*Id=*/nullptr, C.getPointerType(C.getPointerType(E->getType()))
3285 .withConst()
3286 .withRestrict()));
3287 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3288 PrivateVarsPos[VD] = Counter;
3289 ++Counter;
3290 }
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003291 auto &TaskPrivatesMapFnInfo =
John McCallc56a8b32016-03-11 04:30:31 +00003292 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003293 auto *TaskPrivatesMapTy =
3294 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
3295 auto *TaskPrivatesMap = llvm::Function::Create(
3296 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage,
3297 ".omp_task_privates_map.", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003298 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, TaskPrivatesMap,
3299 TaskPrivatesMapFnInfo);
Evgeniy Stepanov6b2a61d2015-09-14 21:35:16 +00003300 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003301 CodeGenFunction CGF(CGM);
3302 CGF.disableDebugInfo();
3303 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
3304 TaskPrivatesMapFnInfo, Args);
3305
3306 // *privi = &.privates.privi;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003307 LValue Base = CGF.EmitLoadOfPointerLValue(
3308 CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
3309 TaskPrivatesArg.getType()->castAs<PointerType>());
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003310 auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
3311 Counter = 0;
3312 for (auto *Field : PrivatesQTyRD->fields()) {
3313 auto FieldLVal = CGF.EmitLValueForField(Base, Field);
3314 auto *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
John McCall7f416cc2015-09-08 08:05:57 +00003315 auto RefLVal = CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
Alexey Bataev31300ed2016-02-04 11:27:03 +00003316 auto RefLoadLVal = CGF.EmitLoadOfPointerLValue(
3317 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>());
Alexey Bataev2377fe92015-09-10 08:12:02 +00003318 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003319 ++Counter;
3320 }
3321 CGF.FinishFunction();
3322 return TaskPrivatesMap;
3323}
3324
Alexey Bataev9e034042015-05-05 04:05:12 +00003325static int array_pod_sort_comparator(const PrivateDataTy *P1,
3326 const PrivateDataTy *P2) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003327 return P1->first < P2->first ? 1 : (P2->first < P1->first ? -1 : 0);
3328}
3329
Alexey Bataev7292c292016-04-25 12:22:29 +00003330CGOpenMPRuntime::TaskDataTy CGOpenMPRuntime::emitTaskInit(
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003331 CodeGenFunction &CGF, SourceLocation Loc, const OMPExecutableDirective &D,
3332 bool Tied, llvm::PointerIntPair<llvm::Value *, 1, bool> Final,
Alexey Bataev48591dd2016-04-20 04:01:36 +00003333 unsigned NumberOfParts, llvm::Value *TaskFunction, QualType SharedsTy,
Alexey Bataev7292c292016-04-25 12:22:29 +00003334 Address Shareds, ArrayRef<const Expr *> PrivateVars,
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003335 ArrayRef<const Expr *> PrivateCopies,
3336 ArrayRef<const Expr *> FirstprivateVars,
3337 ArrayRef<const Expr *> FirstprivateCopies,
Alexey Bataev7292c292016-04-25 12:22:29 +00003338 ArrayRef<const Expr *> FirstprivateInits) {
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003339 auto &C = CGM.getContext();
Alexey Bataev7292c292016-04-25 12:22:29 +00003340 llvm::SmallVector<PrivateDataTy, 4> Privates;
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003341 // Aggregate privates and sort them by the alignment.
Alexey Bataev9e034042015-05-05 04:05:12 +00003342 auto I = PrivateCopies.begin();
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003343 for (auto *E : PrivateVars) {
3344 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3345 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00003346 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00003347 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3348 /*PrivateElemInit=*/nullptr)));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003349 ++I;
3350 }
Alexey Bataev9e034042015-05-05 04:05:12 +00003351 I = FirstprivateCopies.begin();
3352 auto IElemInitRef = FirstprivateInits.begin();
3353 for (auto *E : FirstprivateVars) {
3354 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3355 Privates.push_back(std::make_pair(
Alexey Bataevc71a4092015-09-11 10:29:41 +00003356 C.getDeclAlign(VD),
Alexey Bataev9e034042015-05-05 04:05:12 +00003357 PrivateHelpersTy(
3358 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
3359 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))));
Richard Trieucc3949d2016-02-18 22:34:54 +00003360 ++I;
3361 ++IElemInitRef;
Alexey Bataev9e034042015-05-05 04:05:12 +00003362 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003363 llvm::array_pod_sort(Privates.begin(), Privates.end(),
3364 array_pod_sort_comparator);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003365 auto KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
3366 // Build type kmp_routine_entry_t (if not built yet).
3367 emitKmpRoutineEntryT(KmpInt32Ty);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003368 // Build type kmp_task_t (if not built yet).
3369 if (KmpTaskTQTy.isNull()) {
Alexey Bataev7292c292016-04-25 12:22:29 +00003370 KmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
3371 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003372 }
3373 auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003374 // Build particular struct kmp_task_t for the given task.
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003375 auto *KmpTaskTWithPrivatesQTyRD =
3376 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
3377 auto KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
3378 QualType KmpTaskTWithPrivatesPtrQTy =
3379 C.getPointerType(KmpTaskTWithPrivatesQTy);
3380 auto *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
3381 auto *KmpTaskTWithPrivatesPtrTy = KmpTaskTWithPrivatesTy->getPointerTo();
Alexey Bataev1189bd02016-01-26 12:20:39 +00003382 auto *KmpTaskTWithPrivatesTySize = CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003383 QualType SharedsPtrTy = C.getPointerType(SharedsTy);
3384
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003385 // Emit initial values for private copies (if any).
3386 llvm::Value *TaskPrivatesMap = nullptr;
3387 auto *TaskPrivatesMapTy =
3388 std::next(cast<llvm::Function>(TaskFunction)->getArgumentList().begin(),
3389 3)
3390 ->getType();
3391 if (!Privates.empty()) {
3392 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3393 TaskPrivatesMap = emitTaskPrivateMappingFunction(
3394 CGM, Loc, PrivateVars, FirstprivateVars, FI->getType(), Privates);
3395 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3396 TaskPrivatesMap, TaskPrivatesMapTy);
3397 } else {
3398 TaskPrivatesMap = llvm::ConstantPointerNull::get(
3399 cast<llvm::PointerType>(TaskPrivatesMapTy));
3400 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003401 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
3402 // kmp_task_t *tt);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003403 auto *TaskEntry = emitProxyTaskFunction(
Alexey Bataev7292c292016-04-25 12:22:29 +00003404 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
3405 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
3406 TaskPrivatesMap);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003407
3408 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
3409 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
3410 // kmp_routine_entry_t *task_entry);
3411 // Task flags. Format is taken from
3412 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h,
3413 // description of kmp_tasking_flags struct.
3414 const unsigned TiedFlag = 0x1;
3415 const unsigned FinalFlag = 0x2;
3416 unsigned Flags = Tied ? TiedFlag : 0;
3417 auto *TaskFlags =
3418 Final.getPointer()
3419 ? CGF.Builder.CreateSelect(Final.getPointer(),
3420 CGF.Builder.getInt32(FinalFlag),
3421 CGF.Builder.getInt32(/*C=*/0))
3422 : CGF.Builder.getInt32(Final.getInt() ? FinalFlag : 0);
3423 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
Alexey Bataev40e36f12015-11-24 13:01:44 +00003424 auto *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003425 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc),
3426 getThreadID(CGF, Loc), TaskFlags,
3427 KmpTaskTWithPrivatesTySize, SharedsSize,
3428 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3429 TaskEntry, KmpRoutineEntryPtrTy)};
Alexey Bataev62b63b12015-03-10 07:28:44 +00003430 auto *NewTask = CGF.EmitRuntimeCall(
3431 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003432 auto *NewTaskNewTaskTTy = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3433 NewTask, KmpTaskTWithPrivatesPtrTy);
3434 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
3435 KmpTaskTWithPrivatesQTy);
3436 LValue TDBase =
3437 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
Alexey Bataev62b63b12015-03-10 07:28:44 +00003438 // Fill the data in the resulting kmp_task_t record.
3439 // Copy shareds if there are any.
John McCall7f416cc2015-09-08 08:05:57 +00003440 Address KmpTaskSharedsPtr = Address::invalid();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003441 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
Alexey Bataev2377fe92015-09-10 08:12:02 +00003442 KmpTaskSharedsPtr =
3443 Address(CGF.EmitLoadOfScalar(
3444 CGF.EmitLValueForField(
3445 TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
3446 KmpTaskTShareds)),
3447 Loc),
3448 CGF.getNaturalTypeAlignment(SharedsTy));
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003449 CGF.EmitAggregateCopy(KmpTaskSharedsPtr, Shareds, SharedsTy);
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003450 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003451 // Emit initial values for private copies (if any).
3452 bool NeedsCleanup = false;
3453 if (!Privates.empty()) {
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003454 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3455 auto PrivatesBase = CGF.EmitLValueForField(Base, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003456 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003457 LValue SharedsBase;
3458 if (!FirstprivateVars.empty()) {
John McCall7f416cc2015-09-08 08:05:57 +00003459 SharedsBase = CGF.MakeAddrLValue(
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003460 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3461 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
3462 SharedsTy);
3463 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003464 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(
3465 cast<CapturedStmt>(*D.getAssociatedStmt()));
3466 for (auto &&Pair : Privates) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003467 auto *VD = Pair.second.PrivateCopy;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003468 auto *Init = VD->getAnyInitializer();
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003469 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003470 if (Init) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003471 if (auto *Elem = Pair.second.PrivateElemInit) {
3472 auto *OriginalVD = Pair.second.Original;
3473 auto *SharedField = CapturesInfo.lookup(OriginalVD);
3474 auto SharedRefLValue =
3475 CGF.EmitLValueForField(SharedsBase, SharedField);
Alexey Bataevc71a4092015-09-11 10:29:41 +00003476 SharedRefLValue = CGF.MakeAddrLValue(
3477 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)),
3478 SharedRefLValue.getType(), AlignmentSource::Decl);
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003479 QualType Type = OriginalVD->getType();
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003480 if (Type->isArrayType()) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003481 // Initialize firstprivate array.
3482 if (!isa<CXXConstructExpr>(Init) ||
3483 CGF.isTrivialInitializer(Init)) {
3484 // Perform simple memcpy.
3485 CGF.EmitAggregateAssign(PrivateLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003486 SharedRefLValue.getAddress(), Type);
Alexey Bataev9e034042015-05-05 04:05:12 +00003487 } else {
3488 // Initialize firstprivate array using element-by-element
3489 // intialization.
3490 CGF.EmitOMPAggregateAssign(
3491 PrivateLValue.getAddress(), SharedRefLValue.getAddress(),
Alexey Bataev1d9c15c2015-05-19 12:31:28 +00003492 Type, [&CGF, Elem, Init, &CapturesInfo](
John McCall7f416cc2015-09-08 08:05:57 +00003493 Address DestElement, Address SrcElement) {
Alexey Bataev9e034042015-05-05 04:05:12 +00003494 // Clean up any temporaries needed by the initialization.
3495 CodeGenFunction::OMPPrivateScope InitScope(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00003496 InitScope.addPrivate(Elem, [SrcElement]() -> Address {
Alexey Bataev9e034042015-05-05 04:05:12 +00003497 return SrcElement;
3498 });
3499 (void)InitScope.Privatize();
3500 // Emit initialization for single element.
Alexey Bataevd157d472015-06-24 03:35:38 +00003501 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
3502 CGF, &CapturesInfo);
Alexey Bataev9e034042015-05-05 04:05:12 +00003503 CGF.EmitAnyExprToMem(Init, DestElement,
3504 Init->getType().getQualifiers(),
3505 /*IsInitializer=*/false);
Alexey Bataev9e034042015-05-05 04:05:12 +00003506 });
3507 }
3508 } else {
3509 CodeGenFunction::OMPPrivateScope InitScope(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00003510 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address {
Alexey Bataev9e034042015-05-05 04:05:12 +00003511 return SharedRefLValue.getAddress();
3512 });
3513 (void)InitScope.Privatize();
Alexey Bataevd157d472015-06-24 03:35:38 +00003514 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
Alexey Bataev9e034042015-05-05 04:05:12 +00003515 CGF.EmitExprAsInit(Init, VD, PrivateLValue,
3516 /*capturedByInit=*/false);
Alexey Bataev9e034042015-05-05 04:05:12 +00003517 }
3518 } else {
3519 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
3520 }
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003521 }
3522 NeedsCleanup = NeedsCleanup || FI->getType().isDestructedType();
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003523 ++FI;
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003524 }
3525 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003526 // Provide pointer to function with destructors for privates.
Alexey Bataev36c1eb92015-04-30 06:51:57 +00003527 llvm::Value *DestructorFn =
Alexey Bataev8fc69dc2015-05-18 07:54:53 +00003528 NeedsCleanup ? emitDestructorsFunction(CGM, Loc, KmpInt32Ty,
3529 KmpTaskTWithPrivatesPtrQTy,
3530 KmpTaskTWithPrivatesQTy)
3531 : llvm::ConstantPointerNull::get(
3532 cast<llvm::PointerType>(KmpRoutineEntryPtrTy));
3533 LValue Destructor = CGF.EmitLValueForField(
3534 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTDestructors));
3535 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3536 DestructorFn, KmpRoutineEntryPtrTy),
3537 Destructor);
Alexey Bataev7292c292016-04-25 12:22:29 +00003538 TaskDataTy Data;
3539 Data.NewTask = NewTask;
3540 Data.TaskEntry = TaskEntry;
3541 Data.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
3542 Data.TDBase = TDBase;
3543 Data.KmpTaskTQTyRD = KmpTaskTQTyRD;
3544 return Data;
3545}
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003546
Alexey Bataev7292c292016-04-25 12:22:29 +00003547void CGOpenMPRuntime::emitTaskCall(
3548 CodeGenFunction &CGF, SourceLocation Loc, const OMPExecutableDirective &D,
3549 bool Tied, llvm::PointerIntPair<llvm::Value *, 1, bool> Final,
3550 unsigned NumberOfParts, llvm::Value *TaskFunction, QualType SharedsTy,
3551 Address Shareds, const Expr *IfCond, ArrayRef<const Expr *> PrivateVars,
3552 ArrayRef<const Expr *> PrivateCopies,
3553 ArrayRef<const Expr *> FirstprivateVars,
3554 ArrayRef<const Expr *> FirstprivateCopies,
3555 ArrayRef<const Expr *> FirstprivateInits,
3556 ArrayRef<std::pair<OpenMPDependClauseKind, const Expr *>> Dependences) {
3557 if (!CGF.HaveInsertPoint())
3558 return;
3559
3560 TaskDataTy Data =
3561 emitTaskInit(CGF, Loc, D, Tied, Final, NumberOfParts, TaskFunction,
3562 SharedsTy, Shareds, PrivateVars, PrivateCopies,
3563 FirstprivateVars, FirstprivateCopies, FirstprivateInits);
3564 llvm::Value *NewTask = Data.NewTask;
3565 llvm::Value *TaskEntry = Data.TaskEntry;
3566 llvm::Value *NewTaskNewTaskTTy = Data.NewTaskNewTaskTTy;
3567 LValue TDBase = Data.TDBase;
3568 RecordDecl *KmpTaskTQTyRD = Data.KmpTaskTQTyRD;
3569 auto &C = CGM.getContext();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003570 // Process list of dependences.
John McCall7f416cc2015-09-08 08:05:57 +00003571 Address DependenciesArray = Address::invalid();
3572 unsigned NumDependencies = Dependences.size();
3573 if (NumDependencies) {
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003574 // Dependence kind for RTL.
Alexey Bataev92e82f92015-11-23 13:33:42 +00003575 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 };
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003576 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
3577 RecordDecl *KmpDependInfoRD;
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003578 QualType FlagsTy =
3579 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003580 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
3581 if (KmpDependInfoTy.isNull()) {
3582 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
3583 KmpDependInfoRD->startDefinition();
3584 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
3585 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
3586 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
3587 KmpDependInfoRD->completeDefinition();
3588 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
3589 } else {
3590 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
3591 }
John McCall7f416cc2015-09-08 08:05:57 +00003592 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003593 // Define type kmp_depend_info[<Dependences.size()>];
3594 QualType KmpDependInfoArrayTy = C.getConstantArrayType(
John McCall7f416cc2015-09-08 08:05:57 +00003595 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003596 ArrayType::Normal, /*IndexTypeQuals=*/0);
3597 // kmp_depend_info[<Dependences.size()>] deps;
Alexey Bataev48591dd2016-04-20 04:01:36 +00003598 DependenciesArray =
3599 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
John McCall7f416cc2015-09-08 08:05:57 +00003600 for (unsigned i = 0; i < NumDependencies; ++i) {
3601 const Expr *E = Dependences[i].second;
3602 auto Addr = CGF.EmitLValue(E);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003603 llvm::Value *Size;
3604 QualType Ty = E->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003605 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
3606 LValue UpAddrLVal =
3607 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false);
3608 llvm::Value *UpAddr =
John McCall7f416cc2015-09-08 08:05:57 +00003609 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003610 llvm::Value *LowIntPtr =
John McCall7f416cc2015-09-08 08:05:57 +00003611 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003612 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy);
3613 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003614 } else
Alexey Bataev1189bd02016-01-26 12:20:39 +00003615 Size = CGF.getTypeSize(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003616 auto Base = CGF.MakeAddrLValue(
3617 CGF.Builder.CreateConstArrayGEP(DependenciesArray, i, DependencySize),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003618 KmpDependInfoTy);
3619 // deps[i].base_addr = &<Dependences[i].second>;
3620 auto BaseAddrLVal = CGF.EmitLValueForField(
3621 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
John McCall7f416cc2015-09-08 08:05:57 +00003622 CGF.EmitStoreOfScalar(
3623 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy),
3624 BaseAddrLVal);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003625 // deps[i].len = sizeof(<Dependences[i].second>);
3626 auto LenLVal = CGF.EmitLValueForField(
3627 Base, *std::next(KmpDependInfoRD->field_begin(), Len));
3628 CGF.EmitStoreOfScalar(Size, LenLVal);
3629 // deps[i].flags = <Dependences[i].first>;
3630 RTLDependenceKindTy DepKind;
3631 switch (Dependences[i].first) {
3632 case OMPC_DEPEND_in:
3633 DepKind = DepIn;
3634 break;
Alexey Bataev92e82f92015-11-23 13:33:42 +00003635 // Out and InOut dependencies must use the same code.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003636 case OMPC_DEPEND_out:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003637 case OMPC_DEPEND_inout:
3638 DepKind = DepInOut;
3639 break;
Alexey Bataeveb482352015-12-18 05:05:56 +00003640 case OMPC_DEPEND_source:
Alexey Bataeva636c7f2015-12-23 10:27:45 +00003641 case OMPC_DEPEND_sink:
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003642 case OMPC_DEPEND_unknown:
3643 llvm_unreachable("Unknown task dependence type");
3644 }
3645 auto FlagsLVal = CGF.EmitLValueForField(
3646 Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
3647 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
3648 FlagsLVal);
3649 }
John McCall7f416cc2015-09-08 08:05:57 +00003650 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3651 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003652 CGF.VoidPtrTy);
3653 }
3654
Alexey Bataev62b63b12015-03-10 07:28:44 +00003655 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
3656 // libcall.
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003657 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid,
3658 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list,
3659 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence
3660 // list is not empty
Alexey Bataev1d677132015-04-22 13:57:31 +00003661 auto *ThreadID = getThreadID(CGF, Loc);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003662 auto *UpLoc = emitUpdateLocation(CGF, Loc);
John McCall7f416cc2015-09-08 08:05:57 +00003663 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask };
3664 llvm::Value *DepTaskArgs[7];
3665 if (NumDependencies) {
3666 DepTaskArgs[0] = UpLoc;
3667 DepTaskArgs[1] = ThreadID;
3668 DepTaskArgs[2] = NewTask;
3669 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies);
3670 DepTaskArgs[4] = DependenciesArray.getPointer();
3671 DepTaskArgs[5] = CGF.Builder.getInt32(0);
3672 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3673 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00003674 auto &&ThenCodeGen = [this, Tied, Loc, NumberOfParts, TDBase, KmpTaskTQTyRD,
3675 NumDependencies, &TaskArgs,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003676 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003677 if (!Tied) {
3678 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3679 auto PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI);
3680 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal);
3681 }
John McCall7f416cc2015-09-08 08:05:57 +00003682 if (NumDependencies) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003683 CGF.EmitRuntimeCall(
Alexey Bataev48591dd2016-04-20 04:01:36 +00003684 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs);
John McCall7f416cc2015-09-08 08:05:57 +00003685 } else {
Alexey Bataev48591dd2016-04-20 04:01:36 +00003686 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task),
John McCall7f416cc2015-09-08 08:05:57 +00003687 TaskArgs);
3688 }
Alexey Bataev48591dd2016-04-20 04:01:36 +00003689 // Check if parent region is untied and build return for untied task;
3690 if (auto *Region =
3691 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
3692 Region->emitUntiedSwitch(CGF);
Alexey Bataev1d677132015-04-22 13:57:31 +00003693 };
John McCall7f416cc2015-09-08 08:05:57 +00003694
3695 llvm::Value *DepWaitTaskArgs[6];
3696 if (NumDependencies) {
3697 DepWaitTaskArgs[0] = UpLoc;
3698 DepWaitTaskArgs[1] = ThreadID;
3699 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies);
3700 DepWaitTaskArgs[3] = DependenciesArray.getPointer();
3701 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0);
3702 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3703 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003704 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry,
3705 NumDependencies, &DepWaitTaskArgs](CodeGenFunction &CGF,
3706 PrePostActionTy &) {
3707 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003708 CodeGenFunction::RunCleanupsScope LocalScope(CGF);
3709 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid,
3710 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32
3711 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info
3712 // is specified.
John McCall7f416cc2015-09-08 08:05:57 +00003713 if (NumDependencies)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003714 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps),
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003715 DepWaitTaskArgs);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003716 // Call proxy_task_entry(gtid, new_task);
3717 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy](
3718 CodeGenFunction &CGF, PrePostActionTy &Action) {
3719 Action.Enter(CGF);
3720 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy};
3721 CGF.EmitCallOrInvoke(TaskEntry, OutlinedFnArgs);
3722 };
3723
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003724 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid,
3725 // kmp_task_t *new_task);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003726 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid,
3727 // kmp_task_t *new_task);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003728 RegionCodeGenTy RCG(CodeGen);
3729 CommonActionTy Action(
3730 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs,
3731 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs);
3732 RCG.setAction(Action);
3733 RCG(CGF);
Alexey Bataev1d2353d2015-06-24 11:01:36 +00003734 };
John McCall7f416cc2015-09-08 08:05:57 +00003735
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003736 if (IfCond)
Alexey Bataev1d677132015-04-22 13:57:31 +00003737 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003738 else {
3739 RegionCodeGenTy ThenRCG(ThenCodeGen);
3740 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00003741 }
Alexey Bataev62b63b12015-03-10 07:28:44 +00003742}
3743
Alexey Bataev7292c292016-04-25 12:22:29 +00003744void CGOpenMPRuntime::emitTaskLoopCall(
3745 CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D,
3746 bool Tied, llvm::PointerIntPair<llvm::Value *, 1, bool> Final, bool Nogroup,
3747 unsigned NumberOfParts, llvm::Value *TaskFunction, QualType SharedsTy,
3748 Address Shareds, const Expr *IfCond, ArrayRef<const Expr *> PrivateVars,
3749 ArrayRef<const Expr *> PrivateCopies,
3750 ArrayRef<const Expr *> FirstprivateVars,
3751 ArrayRef<const Expr *> FirstprivateCopies,
3752 ArrayRef<const Expr *> FirstprivateInits) {
3753 if (!CGF.HaveInsertPoint())
3754 return;
3755 TaskDataTy Data =
3756 emitTaskInit(CGF, Loc, D, Tied, Final, NumberOfParts, TaskFunction,
3757 SharedsTy, Shareds, PrivateVars, PrivateCopies,
3758 FirstprivateVars, FirstprivateCopies, FirstprivateInits);
3759 // NOTE: routine and part_id fields are intialized by __kmpc_omp_task_alloc()
3760 // libcall.
3761 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int
3762 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int
3763 // sched, kmp_uint64 grainsize, void *task_dup);
3764 llvm::Value *ThreadID = getThreadID(CGF, Loc);
3765 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc);
3766 llvm::Value *IfVal;
3767 if (IfCond) {
3768 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy,
3769 /*isSigned=*/true);
3770 } else
3771 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1);
3772
3773 LValue LBLVal = CGF.EmitLValueForField(
3774 Data.TDBase,
3775 *std::next(Data.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound));
3776 auto *LBVar =
3777 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl());
3778 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(),
3779 /*IsInitializer=*/true);
3780 LValue UBLVal = CGF.EmitLValueForField(
3781 Data.TDBase,
3782 *std::next(Data.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound));
3783 auto *UBVar =
3784 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl());
3785 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(),
3786 /*IsInitializer=*/true);
3787 LValue StLVal = CGF.EmitLValueForField(
3788 Data.TDBase,
3789 *std::next(Data.KmpTaskTQTyRD->field_begin(), KmpTaskTStride));
3790 auto *StVar =
3791 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl());
3792 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(),
3793 /*IsInitializer=*/true);
3794 llvm::Value *TaskArgs[] = {
3795 UpLoc,
3796 ThreadID,
3797 Data.NewTask,
3798 IfVal,
3799 LBLVal.getPointer(),
3800 UBLVal.getPointer(),
3801 CGF.EmitLoadOfScalar(StLVal, SourceLocation()),
3802 llvm::ConstantInt::getSigned(CGF.IntTy, Nogroup ? 1 : 0),
3803 llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/0),
3804 llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0),
3805 llvm::ConstantPointerNull::get(CGF.VoidPtrTy)};
3806 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs);
3807}
3808
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003809/// \brief Emit reduction operation for each element of array (required for
3810/// array sections) LHS op = RHS.
3811/// \param Type Type of array.
3812/// \param LHSVar Variable on the left side of the reduction operation
3813/// (references element of array in original variable).
3814/// \param RHSVar Variable on the right side of the reduction operation
3815/// (references element of array in original variable).
3816/// \param RedOpGen Generator of reduction operation with use of LHSVar and
3817/// RHSVar.
Benjamin Kramere003ca22015-10-28 13:54:16 +00003818static void EmitOMPAggregateReduction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003819 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar,
3820 const VarDecl *RHSVar,
3821 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *,
3822 const Expr *, const Expr *)> &RedOpGen,
3823 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr,
3824 const Expr *UpExpr = nullptr) {
3825 // Perform element-by-element initialization.
3826 QualType ElementTy;
3827 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar);
3828 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar);
3829
3830 // Drill down to the base element type on both arrays.
3831 auto ArrayTy = Type->getAsArrayTypeUnsafe();
3832 auto NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr);
3833
3834 auto RHSBegin = RHSAddr.getPointer();
3835 auto LHSBegin = LHSAddr.getPointer();
3836 // Cast from pointer to array type to pointer to single element.
3837 auto LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements);
3838 // The basic structure here is a while-do loop.
3839 auto BodyBB = CGF.createBasicBlock("omp.arraycpy.body");
3840 auto DoneBB = CGF.createBasicBlock("omp.arraycpy.done");
3841 auto IsEmpty =
3842 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty");
3843 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
3844
3845 // Enter the loop body, making that address the current address.
3846 auto EntryBB = CGF.Builder.GetInsertBlock();
3847 CGF.EmitBlock(BodyBB);
3848
3849 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
3850
3851 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI(
3852 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast");
3853 RHSElementPHI->addIncoming(RHSBegin, EntryBB);
3854 Address RHSElementCurrent =
3855 Address(RHSElementPHI,
3856 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
3857
3858 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI(
3859 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast");
3860 LHSElementPHI->addIncoming(LHSBegin, EntryBB);
3861 Address LHSElementCurrent =
3862 Address(LHSElementPHI,
3863 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize));
3864
3865 // Emit copy.
3866 CodeGenFunction::OMPPrivateScope Scope(CGF);
3867 Scope.addPrivate(LHSVar, [=]() -> Address { return LHSElementCurrent; });
3868 Scope.addPrivate(RHSVar, [=]() -> Address { return RHSElementCurrent; });
3869 Scope.Privatize();
3870 RedOpGen(CGF, XExpr, EExpr, UpExpr);
3871 Scope.ForceCleanup();
3872
3873 // Shift the address forward by one element.
3874 auto LHSElementNext = CGF.Builder.CreateConstGEP1_32(
3875 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element");
3876 auto RHSElementNext = CGF.Builder.CreateConstGEP1_32(
3877 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element");
3878 // Check whether we've reached the end.
3879 auto Done =
3880 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done");
3881 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
3882 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock());
3883 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock());
3884
3885 // Done.
3886 CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
3887}
3888
Alexey Bataeva839ddd2016-03-17 10:19:46 +00003889/// Emit reduction combiner. If the combiner is a simple expression emit it as
3890/// is, otherwise consider it as combiner of UDR decl and emit it as a call of
3891/// UDR combiner function.
3892static void emitReductionCombiner(CodeGenFunction &CGF,
3893 const Expr *ReductionOp) {
3894 if (auto *CE = dyn_cast<CallExpr>(ReductionOp))
3895 if (auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
3896 if (auto *DRE =
3897 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
3898 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) {
3899 std::pair<llvm::Function *, llvm::Function *> Reduction =
3900 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
3901 RValue Func = RValue::get(Reduction.first);
3902 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
3903 CGF.EmitIgnoredExpr(ReductionOp);
3904 return;
3905 }
3906 CGF.EmitIgnoredExpr(ReductionOp);
3907}
3908
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003909static llvm::Value *emitReductionFunction(CodeGenModule &CGM,
3910 llvm::Type *ArgsType,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003911 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003912 ArrayRef<const Expr *> LHSExprs,
3913 ArrayRef<const Expr *> RHSExprs,
3914 ArrayRef<const Expr *> ReductionOps) {
3915 auto &C = CGM.getContext();
3916
3917 // void reduction_func(void *LHSArg, void *RHSArg);
3918 FunctionArgList Args;
3919 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
3920 C.VoidPtrTy);
3921 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, SourceLocation(), /*Id=*/nullptr,
3922 C.VoidPtrTy);
3923 Args.push_back(&LHSArg);
3924 Args.push_back(&RHSArg);
John McCallc56a8b32016-03-11 04:30:31 +00003925 auto &CGFI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003926 auto *Fn = llvm::Function::Create(
3927 CGM.getTypes().GetFunctionType(CGFI), llvm::GlobalValue::InternalLinkage,
3928 ".omp.reduction.reduction_func", &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003929 CGM.SetInternalFunctionAttributes(/*D=*/nullptr, Fn, CGFI);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003930 CodeGenFunction CGF(CGM);
3931 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args);
3932
3933 // Dst = (void*[n])(LHSArg);
3934 // Src = (void*[n])(RHSArg);
John McCall7f416cc2015-09-08 08:05:57 +00003935 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3936 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
3937 ArgsType), CGF.getPointerAlign());
3938 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3939 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
3940 ArgsType), CGF.getPointerAlign());
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003941
3942 // ...
3943 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]);
3944 // ...
3945 CodeGenFunction::OMPPrivateScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003946 auto IPriv = Privates.begin();
3947 unsigned Idx = 0;
3948 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00003949 auto RHSVar = cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl());
3950 Scope.addPrivate(RHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003951 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00003952 });
3953 auto LHSVar = cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl());
3954 Scope.addPrivate(LHSVar, [&]() -> Address {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003955 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar);
John McCall7f416cc2015-09-08 08:05:57 +00003956 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003957 QualType PrivTy = (*IPriv)->getType();
Alexey Bataev1189bd02016-01-26 12:20:39 +00003958 if (PrivTy->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003959 // Get array size and emit VLA type.
3960 ++Idx;
3961 Address Elem =
3962 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize());
3963 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00003964 auto *VLA = CGF.getContext().getAsVariableArrayType(PrivTy);
3965 auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003966 CodeGenFunction::OpaqueValueMapping OpaqueMap(
Alexey Bataev1189bd02016-01-26 12:20:39 +00003967 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy)));
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003968 CGF.EmitVariablyModifiedType(PrivTy);
3969 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003970 }
3971 Scope.Privatize();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003972 IPriv = Privates.begin();
3973 auto ILHS = LHSExprs.begin();
3974 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003975 for (auto *E : ReductionOps) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003976 if ((*IPriv)->getType()->isArrayType()) {
3977 // Emit reduction for array section.
3978 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
3979 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
Alexey Bataeva839ddd2016-03-17 10:19:46 +00003980 EmitOMPAggregateReduction(
3981 CGF, (*IPriv)->getType(), LHSVar, RHSVar,
3982 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
3983 emitReductionCombiner(CGF, E);
3984 });
Alexey Bataevf24e7b12015-10-08 09:10:53 +00003985 } else
3986 // Emit reduction for array subscript or single variable.
Alexey Bataeva839ddd2016-03-17 10:19:46 +00003987 emitReductionCombiner(CGF, E);
Richard Trieucc3949d2016-02-18 22:34:54 +00003988 ++IPriv;
3989 ++ILHS;
3990 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00003991 }
3992 Scope.ForceCleanup();
3993 CGF.FinishFunction();
3994 return Fn;
3995}
3996
Alexey Bataev14fa1c62016-03-29 05:34:15 +00003997static void emitSingleReductionCombiner(CodeGenFunction &CGF,
3998 const Expr *ReductionOp,
3999 const Expr *PrivateRef,
4000 const DeclRefExpr *LHS,
4001 const DeclRefExpr *RHS) {
4002 if (PrivateRef->getType()->isArrayType()) {
4003 // Emit reduction for array section.
4004 auto *LHSVar = cast<VarDecl>(LHS->getDecl());
4005 auto *RHSVar = cast<VarDecl>(RHS->getDecl());
4006 EmitOMPAggregateReduction(
4007 CGF, PrivateRef->getType(), LHSVar, RHSVar,
4008 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) {
4009 emitReductionCombiner(CGF, ReductionOp);
4010 });
4011 } else
4012 // Emit reduction for array subscript or single variable.
4013 emitReductionCombiner(CGF, ReductionOp);
4014}
4015
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004016void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004017 ArrayRef<const Expr *> Privates,
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004018 ArrayRef<const Expr *> LHSExprs,
4019 ArrayRef<const Expr *> RHSExprs,
4020 ArrayRef<const Expr *> ReductionOps,
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004021 bool WithNowait, bool SimpleReduction) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004022 if (!CGF.HaveInsertPoint())
4023 return;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004024 // Next code should be emitted for reduction:
4025 //
4026 // static kmp_critical_name lock = { 0 };
4027 //
4028 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) {
4029 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]);
4030 // ...
4031 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1],
4032 // *(Type<n>-1*)rhs[<n>-1]);
4033 // }
4034 //
4035 // ...
4036 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]};
4037 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4038 // RedList, reduce_func, &<lock>)) {
4039 // case 1:
4040 // ...
4041 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4042 // ...
4043 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4044 // break;
4045 // case 2:
4046 // ...
4047 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4048 // ...
Alexey Bataev69a47792015-05-07 03:54:03 +00004049 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);]
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004050 // break;
4051 // default:;
4052 // }
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004053 //
4054 // if SimpleReduction is true, only the next code is generated:
4055 // ...
4056 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4057 // ...
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004058
4059 auto &C = CGM.getContext();
4060
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004061 if (SimpleReduction) {
4062 CodeGenFunction::RunCleanupsScope Scope(CGF);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004063 auto IPriv = Privates.begin();
4064 auto ILHS = LHSExprs.begin();
4065 auto IRHS = RHSExprs.begin();
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004066 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004067 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4068 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00004069 ++IPriv;
4070 ++ILHS;
4071 ++IRHS;
Alexey Bataev89e7e8e2015-06-17 06:21:39 +00004072 }
4073 return;
4074 }
4075
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004076 // 1. Build a list of reduction variables.
4077 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]};
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004078 auto Size = RHSExprs.size();
4079 for (auto *E : Privates) {
Alexey Bataev1189bd02016-01-26 12:20:39 +00004080 if (E->getType()->isVariablyModifiedType())
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004081 // Reserve place for array size.
4082 ++Size;
4083 }
4084 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004085 QualType ReductionArrayTy =
4086 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal,
4087 /*IndexTypeQuals=*/0);
John McCall7f416cc2015-09-08 08:05:57 +00004088 Address ReductionList =
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004089 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list");
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004090 auto IPriv = Privates.begin();
4091 unsigned Idx = 0;
4092 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) {
John McCall7f416cc2015-09-08 08:05:57 +00004093 Address Elem =
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004094 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize());
John McCall7f416cc2015-09-08 08:05:57 +00004095 CGF.Builder.CreateStore(
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004096 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
John McCall7f416cc2015-09-08 08:05:57 +00004097 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy),
4098 Elem);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004099 if ((*IPriv)->getType()->isVariablyModifiedType()) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004100 // Store array size.
4101 ++Idx;
4102 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx,
4103 CGF.getPointerSize());
Alexey Bataev1189bd02016-01-26 12:20:39 +00004104 llvm::Value *Size = CGF.Builder.CreateIntCast(
4105 CGF.getVLASize(
4106 CGF.getContext().getAsVariableArrayType((*IPriv)->getType()))
4107 .first,
4108 CGF.SizeTy, /*isSigned=*/false);
4109 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy),
4110 Elem);
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004111 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004112 }
4113
4114 // 2. Emit reduce_func().
4115 auto *ReductionFn = emitReductionFunction(
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004116 CGM, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), Privates,
4117 LHSExprs, RHSExprs, ReductionOps);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004118
4119 // 3. Create static kmp_critical_name lock = { 0 };
4120 auto *Lock = getCriticalRegionLock(".reduction");
4121
4122 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList),
4123 // RedList, reduce_func, &<lock>);
Alexey Bataev50b3c952016-02-19 10:38:26 +00004124 auto *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004125 auto *ThreadId = getThreadID(CGF, Loc);
Alexey Bataev1189bd02016-01-26 12:20:39 +00004126 auto *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy);
John McCall7f416cc2015-09-08 08:05:57 +00004127 auto *RL =
4128 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(ReductionList.getPointer(),
4129 CGF.VoidPtrTy);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004130 llvm::Value *Args[] = {
4131 IdentTLoc, // ident_t *<loc>
4132 ThreadId, // i32 <gtid>
4133 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n>
4134 ReductionArrayTySize, // size_type sizeof(RedList)
4135 RL, // void *RedList
4136 ReductionFn, // void (*) (void *, void *) <reduce_func>
4137 Lock // kmp_critical_name *&<lock>
4138 };
4139 auto Res = CGF.EmitRuntimeCall(
4140 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait
4141 : OMPRTL__kmpc_reduce),
4142 Args);
4143
4144 // 5. Build switch(res)
4145 auto *DefaultBB = CGF.createBasicBlock(".omp.reduction.default");
4146 auto *SwInst = CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2);
4147
4148 // 6. Build case 1:
4149 // ...
4150 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]);
4151 // ...
4152 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4153 // break;
4154 auto *Case1BB = CGF.createBasicBlock(".omp.reduction.case1");
4155 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB);
4156 CGF.EmitBlock(Case1BB);
4157
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004158 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>);
4159 llvm::Value *EndArgs[] = {
4160 IdentTLoc, // ident_t *<loc>
4161 ThreadId, // i32 <gtid>
4162 Lock // kmp_critical_name *&<lock>
4163 };
4164 auto &&CodeGen = [&Privates, &LHSExprs, &RHSExprs, &ReductionOps](
4165 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004166 auto IPriv = Privates.begin();
4167 auto ILHS = LHSExprs.begin();
4168 auto IRHS = RHSExprs.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004169 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004170 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS),
4171 cast<DeclRefExpr>(*IRHS));
Richard Trieucc3949d2016-02-18 22:34:54 +00004172 ++IPriv;
4173 ++ILHS;
4174 ++IRHS;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004175 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004176 };
4177 RegionCodeGenTy RCG(CodeGen);
4178 CommonActionTy Action(
4179 nullptr, llvm::None,
4180 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait
4181 : OMPRTL__kmpc_end_reduce),
4182 EndArgs);
4183 RCG.setAction(Action);
4184 RCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004185
4186 CGF.EmitBranch(DefaultBB);
4187
4188 // 7. Build case 2:
4189 // ...
4190 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]));
4191 // ...
4192 // break;
4193 auto *Case2BB = CGF.createBasicBlock(".omp.reduction.case2");
4194 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB);
4195 CGF.EmitBlock(Case2BB);
4196
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004197 auto &&AtomicCodeGen = [Loc, &Privates, &LHSExprs, &RHSExprs, &ReductionOps](
4198 CodeGenFunction &CGF, PrePostActionTy &Action) {
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004199 auto ILHS = LHSExprs.begin();
4200 auto IRHS = RHSExprs.begin();
4201 auto IPriv = Privates.begin();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004202 for (auto *E : ReductionOps) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004203 const Expr *XExpr = nullptr;
4204 const Expr *EExpr = nullptr;
4205 const Expr *UpExpr = nullptr;
4206 BinaryOperatorKind BO = BO_Comma;
4207 if (auto *BO = dyn_cast<BinaryOperator>(E)) {
4208 if (BO->getOpcode() == BO_Assign) {
4209 XExpr = BO->getLHS();
4210 UpExpr = BO->getRHS();
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004211 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004212 }
4213 // Try to emit update expression as a simple atomic.
4214 auto *RHSExpr = UpExpr;
4215 if (RHSExpr) {
4216 // Analyze RHS part of the whole expression.
4217 if (auto *ACO = dyn_cast<AbstractConditionalOperator>(
4218 RHSExpr->IgnoreParenImpCasts())) {
4219 // If this is a conditional operator, analyze its condition for
4220 // min/max reduction operator.
4221 RHSExpr = ACO->getCond();
Alexey Bataev69a47792015-05-07 03:54:03 +00004222 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004223 if (auto *BORHS =
4224 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) {
4225 EExpr = BORHS->getRHS();
4226 BO = BORHS->getOpcode();
Alexey Bataevf24e7b12015-10-08 09:10:53 +00004227 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004228 }
4229 if (XExpr) {
4230 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4231 auto &&AtomicRedGen = [BO, VD, IPriv,
4232 Loc](CodeGenFunction &CGF, const Expr *XExpr,
4233 const Expr *EExpr, const Expr *UpExpr) {
4234 LValue X = CGF.EmitLValue(XExpr);
4235 RValue E;
4236 if (EExpr)
4237 E = CGF.EmitAnyExpr(EExpr);
4238 CGF.EmitOMPAtomicSimpleUpdateExpr(
JF Bastien92f4ef12016-04-06 17:26:42 +00004239 X, E, BO, /*IsXLHSInRHSPart=*/true,
4240 llvm::AtomicOrdering::Monotonic, Loc,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004241 [&CGF, UpExpr, VD, IPriv, Loc](RValue XRValue) {
4242 CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
4243 PrivateScope.addPrivate(
4244 VD, [&CGF, VD, XRValue, Loc]() -> Address {
4245 Address LHSTemp = CGF.CreateMemTemp(VD->getType());
4246 CGF.emitOMPSimpleStore(
4247 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue,
4248 VD->getType().getNonReferenceType(), Loc);
4249 return LHSTemp;
4250 });
4251 (void)PrivateScope.Privatize();
4252 return CGF.EmitAnyExpr(UpExpr);
4253 });
4254 };
4255 if ((*IPriv)->getType()->isArrayType()) {
4256 // Emit atomic reduction for array section.
4257 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
4258 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar,
4259 AtomicRedGen, XExpr, EExpr, UpExpr);
4260 } else
4261 // Emit atomic reduction for array subscript or single variable.
4262 AtomicRedGen(CGF, XExpr, EExpr, UpExpr);
4263 } else {
4264 // Emit as a critical region.
4265 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *,
4266 const Expr *, const Expr *) {
4267 auto &RT = CGF.CGM.getOpenMPRuntime();
4268 RT.emitCriticalRegion(
4269 CGF, ".atomic_reduction",
4270 [=](CodeGenFunction &CGF, PrePostActionTy &Action) {
4271 Action.Enter(CGF);
4272 emitReductionCombiner(CGF, E);
4273 },
4274 Loc);
4275 };
4276 if ((*IPriv)->getType()->isArrayType()) {
4277 auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl());
4278 auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl());
4279 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar,
4280 CritRedGen);
4281 } else
4282 CritRedGen(CGF, nullptr, nullptr, nullptr);
4283 }
Richard Trieucc3949d2016-02-18 22:34:54 +00004284 ++ILHS;
4285 ++IRHS;
4286 ++IPriv;
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004287 }
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004288 };
4289 RegionCodeGenTy AtomicRCG(AtomicCodeGen);
4290 if (!WithNowait) {
4291 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>);
4292 llvm::Value *EndArgs[] = {
4293 IdentTLoc, // ident_t *<loc>
4294 ThreadId, // i32 <gtid>
4295 Lock // kmp_critical_name *&<lock>
4296 };
4297 CommonActionTy Action(nullptr, llvm::None,
4298 createRuntimeFunction(OMPRTL__kmpc_end_reduce),
4299 EndArgs);
4300 AtomicRCG.setAction(Action);
4301 AtomicRCG(CGF);
4302 } else
4303 AtomicRCG(CGF);
Alexey Bataev794ba0d2015-04-10 10:43:45 +00004304
4305 CGF.EmitBranch(DefaultBB);
4306 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true);
4307}
4308
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004309void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF,
4310 SourceLocation Loc) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004311 if (!CGF.HaveInsertPoint())
4312 return;
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004313 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32
4314 // global_tid);
4315 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
4316 // Ignore return result until untied tasks are supported.
4317 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args);
Alexey Bataev48591dd2016-04-20 04:01:36 +00004318 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
4319 Region->emitUntiedSwitch(CGF);
Alexey Bataev8b8e2022015-04-27 05:22:09 +00004320}
4321
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00004322void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF,
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004323 OpenMPDirectiveKind InnerKind,
Alexey Bataev25e5b442015-09-15 12:52:43 +00004324 const RegionCodeGenTy &CodeGen,
4325 bool HasCancel) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004326 if (!CGF.HaveInsertPoint())
4327 return;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004328 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel);
Alexey Bataev6f1ffc02015-04-10 04:50:10 +00004329 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr);
Alexey Bataev8cbe0a62015-02-26 10:27:34 +00004330}
4331
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004332namespace {
4333enum RTCancelKind {
4334 CancelNoreq = 0,
4335 CancelParallel = 1,
4336 CancelLoop = 2,
4337 CancelSections = 3,
4338 CancelTaskgroup = 4
4339};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00004340} // anonymous namespace
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004341
4342static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) {
4343 RTCancelKind CancelKind = CancelNoreq;
Alexey Bataev0f34da12015-07-02 04:17:07 +00004344 if (CancelRegion == OMPD_parallel)
4345 CancelKind = CancelParallel;
4346 else if (CancelRegion == OMPD_for)
4347 CancelKind = CancelLoop;
4348 else if (CancelRegion == OMPD_sections)
4349 CancelKind = CancelSections;
4350 else {
4351 assert(CancelRegion == OMPD_taskgroup);
4352 CancelKind = CancelTaskgroup;
4353 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004354 return CancelKind;
4355}
4356
4357void CGOpenMPRuntime::emitCancellationPointCall(
4358 CodeGenFunction &CGF, SourceLocation Loc,
4359 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004360 if (!CGF.HaveInsertPoint())
4361 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004362 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32
4363 // global_tid, kmp_int32 cncl_kind);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004364 if (auto *OMPRegionInfo =
4365 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev25e5b442015-09-15 12:52:43 +00004366 if (OMPRegionInfo->hasCancel()) {
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004367 llvm::Value *Args[] = {
4368 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
4369 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004370 // Ignore return result until untied tasks are supported.
4371 auto *Result = CGF.EmitRuntimeCall(
4372 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args);
4373 // if (__kmpc_cancellationpoint()) {
4374 // __kmpc_cancel_barrier();
4375 // exit from construct;
4376 // }
4377 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4378 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4379 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4380 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4381 CGF.EmitBlock(ExitBB);
4382 // __kmpc_cancel_barrier();
Alexey Bataev25e5b442015-09-15 12:52:43 +00004383 emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004384 // exit from construct;
Alexey Bataev25e5b442015-09-15 12:52:43 +00004385 auto CancelDest =
4386 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
Alexey Bataev81c7ea02015-07-03 09:56:58 +00004387 CGF.EmitBranchThroughCleanup(CancelDest);
4388 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4389 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00004390 }
Alexey Bataev0f34da12015-07-02 04:17:07 +00004391}
4392
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004393void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc,
Alexey Bataev87933c72015-09-18 08:07:34 +00004394 const Expr *IfCond,
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004395 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00004396 if (!CGF.HaveInsertPoint())
4397 return;
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004398 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid,
4399 // kmp_int32 cncl_kind);
4400 if (auto *OMPRegionInfo =
4401 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004402 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF,
4403 PrePostActionTy &) {
4404 auto &RT = CGF.CGM.getOpenMPRuntime();
Alexey Bataev87933c72015-09-18 08:07:34 +00004405 llvm::Value *Args[] = {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004406 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc),
Alexey Bataev87933c72015-09-18 08:07:34 +00004407 CGF.Builder.getInt32(getCancellationKind(CancelRegion))};
4408 // Ignore return result until untied tasks are supported.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004409 auto *Result = CGF.EmitRuntimeCall(
4410 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args);
Alexey Bataev87933c72015-09-18 08:07:34 +00004411 // if (__kmpc_cancel()) {
4412 // __kmpc_cancel_barrier();
4413 // exit from construct;
4414 // }
4415 auto *ExitBB = CGF.createBasicBlock(".cancel.exit");
4416 auto *ContBB = CGF.createBasicBlock(".cancel.continue");
4417 auto *Cmp = CGF.Builder.CreateIsNotNull(Result);
4418 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
4419 CGF.EmitBlock(ExitBB);
4420 // __kmpc_cancel_barrier();
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004421 RT.emitBarrierCall(CGF, Loc, OMPD_unknown, /*EmitChecks=*/false);
Alexey Bataev87933c72015-09-18 08:07:34 +00004422 // exit from construct;
4423 auto CancelDest =
4424 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
4425 CGF.EmitBranchThroughCleanup(CancelDest);
4426 CGF.EmitBlock(ContBB, /*IsFinished=*/true);
4427 };
4428 if (IfCond)
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004429 emitOMPIfClause(CGF, IfCond, ThenGen,
4430 [](CodeGenFunction &, PrePostActionTy &) {});
4431 else {
4432 RegionCodeGenTy ThenRCG(ThenGen);
4433 ThenRCG(CGF);
4434 }
Alexey Bataev7d5d33e2015-07-06 05:50:32 +00004435 }
4436}
Samuel Antaobed3c462015-10-02 16:14:20 +00004437
Samuel Antaoee8fb302016-01-06 13:42:12 +00004438/// \brief Obtain information that uniquely identifies a target entry. This
Samuel Antao2de62b02016-02-13 23:35:10 +00004439/// consists of the file and device IDs as well as line number associated with
4440/// the relevant entry source location.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004441static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
4442 unsigned &DeviceID, unsigned &FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004443 unsigned &LineNum) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004444
4445 auto &SM = C.getSourceManager();
4446
4447 // The loc should be always valid and have a file ID (the user cannot use
4448 // #pragma directives in macros)
4449
4450 assert(Loc.isValid() && "Source location is expected to be always valid.");
4451 assert(Loc.isFileID() && "Source location is expected to refer to a file.");
4452
4453 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
4454 assert(PLoc.isValid() && "Source location is expected to be always valid.");
4455
4456 llvm::sys::fs::UniqueID ID;
4457 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
4458 llvm_unreachable("Source file with target region no longer exists!");
4459
4460 DeviceID = ID.getDevice();
4461 FileID = ID.getFile();
4462 LineNum = PLoc.getLine();
Samuel Antaoee8fb302016-01-06 13:42:12 +00004463}
4464
4465void CGOpenMPRuntime::emitTargetOutlinedFunction(
4466 const OMPExecutableDirective &D, StringRef ParentName,
4467 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00004468 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antaoee8fb302016-01-06 13:42:12 +00004469 assert(!ParentName.empty() && "Invalid target region parent name!");
4470
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00004471 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID,
4472 IsOffloadEntry, CodeGen);
4473}
4474
4475void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper(
4476 const OMPExecutableDirective &D, StringRef ParentName,
4477 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID,
4478 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) {
Samuel Antao2de62b02016-02-13 23:35:10 +00004479 // Create a unique name for the entry function using the source location
4480 // information of the current target region. The name will be something like:
Samuel Antaoee8fb302016-01-06 13:42:12 +00004481 //
Samuel Antao2de62b02016-02-13 23:35:10 +00004482 // __omp_offloading_DD_FFFF_PP_lBB
Samuel Antaoee8fb302016-01-06 13:42:12 +00004483 //
4484 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the
Samuel Antao2de62b02016-02-13 23:35:10 +00004485 // mangled name of the function that encloses the target region and BB is the
4486 // line number of the target region.
Samuel Antaoee8fb302016-01-06 13:42:12 +00004487
4488 unsigned DeviceID;
4489 unsigned FileID;
4490 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004491 getTargetEntryUniqueInfo(CGM.getContext(), D.getLocStart(), DeviceID, FileID,
Samuel Antao2de62b02016-02-13 23:35:10 +00004492 Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004493 SmallString<64> EntryFnName;
4494 {
4495 llvm::raw_svector_ostream OS(EntryFnName);
Samuel Antao2de62b02016-02-13 23:35:10 +00004496 OS << "__omp_offloading" << llvm::format("_%x", DeviceID)
4497 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00004498 }
4499
Arpith Chacko Jacob5c309e42016-03-22 01:48:56 +00004500 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4501
Samuel Antaobed3c462015-10-02 16:14:20 +00004502 CodeGenFunction CGF(CGM, true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004503 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName);
Samuel Antaobed3c462015-10-02 16:14:20 +00004504 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
Samuel Antaoee8fb302016-01-06 13:42:12 +00004505
4506 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS);
4507
4508 // If this target outline function is not an offload entry, we don't need to
4509 // register it.
4510 if (!IsOffloadEntry)
4511 return;
4512
4513 // The target region ID is used by the runtime library to identify the current
4514 // target region, so it only has to be unique and not necessarily point to
4515 // anything. It could be the pointer to the outlined function that implements
4516 // the target region, but we aren't using that so that the compiler doesn't
4517 // need to keep that, and could therefore inline the host function if proven
4518 // worthwhile during optimization. In the other hand, if emitting code for the
4519 // device, the ID has to be the function address so that it can retrieved from
4520 // the offloading entry and launched by the runtime library. We also mark the
4521 // outlined function to have external linkage in case we are emitting code for
4522 // the device, because these functions will be entry points to the device.
4523
4524 if (CGM.getLangOpts().OpenMPIsDevice) {
4525 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy);
4526 OutlinedFn->setLinkage(llvm::GlobalValue::ExternalLinkage);
4527 } else
4528 OutlinedFnID = new llvm::GlobalVariable(
4529 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
4530 llvm::GlobalValue::PrivateLinkage,
4531 llvm::Constant::getNullValue(CGM.Int8Ty), ".omp_offload.region_id");
4532
4533 // Register the information for the entry associated with this target region.
4534 OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
Samuel Antao2de62b02016-02-13 23:35:10 +00004535 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID);
Samuel Antaobed3c462015-10-02 16:14:20 +00004536}
4537
Samuel Antaob68e2db2016-03-03 16:20:23 +00004538/// \brief Emit the num_teams clause of an enclosed teams directive at the
4539/// target region scope. If there is no teams directive associated with the
4540/// target directive, or if there is no num_teams clause associated with the
4541/// enclosed teams directive, return nullptr.
4542static llvm::Value *
4543emitNumTeamsClauseForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4544 CodeGenFunction &CGF,
4545 const OMPExecutableDirective &D) {
4546
4547 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4548 "teams directive expected to be "
4549 "emitted only for the host!");
4550
4551 // FIXME: For the moment we do not support combined directives with target and
4552 // teams, so we do not expect to get any num_teams clause in the provided
4553 // directive. Once we support that, this assertion can be replaced by the
4554 // actual emission of the clause expression.
4555 assert(D.getSingleClause<OMPNumTeamsClause>() == nullptr &&
4556 "Not expecting clause in directive.");
4557
4558 // If the current target region has a teams region enclosed, we need to get
4559 // the number of teams to pass to the runtime function call. This is done
4560 // by generating the expression in a inlined region. This is required because
4561 // the expression is captured in the enclosing target environment when the
4562 // teams directive is not combined with target.
4563
4564 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4565
4566 // FIXME: Accommodate other combined directives with teams when they become
4567 // available.
4568 if (auto *TeamsDir = dyn_cast<OMPTeamsDirective>(CS.getCapturedStmt())) {
4569 if (auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) {
4570 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4571 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4572 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams());
4573 return CGF.Builder.CreateIntCast(NumTeams, CGF.Int32Ty,
4574 /*IsSigned=*/true);
4575 }
4576
4577 // If we have an enclosed teams directive but no num_teams clause we use
4578 // the default value 0.
4579 return CGF.Builder.getInt32(0);
4580 }
4581
4582 // No teams associated with the directive.
4583 return nullptr;
4584}
4585
4586/// \brief Emit the thread_limit clause of an enclosed teams directive at the
4587/// target region scope. If there is no teams directive associated with the
4588/// target directive, or if there is no thread_limit clause associated with the
4589/// enclosed teams directive, return nullptr.
4590static llvm::Value *
4591emitThreadLimitClauseForTargetDirective(CGOpenMPRuntime &OMPRuntime,
4592 CodeGenFunction &CGF,
4593 const OMPExecutableDirective &D) {
4594
4595 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the "
4596 "teams directive expected to be "
4597 "emitted only for the host!");
4598
4599 // FIXME: For the moment we do not support combined directives with target and
4600 // teams, so we do not expect to get any thread_limit clause in the provided
4601 // directive. Once we support that, this assertion can be replaced by the
4602 // actual emission of the clause expression.
4603 assert(D.getSingleClause<OMPThreadLimitClause>() == nullptr &&
4604 "Not expecting clause in directive.");
4605
4606 // If the current target region has a teams region enclosed, we need to get
4607 // the thread limit to pass to the runtime function call. This is done
4608 // by generating the expression in a inlined region. This is required because
4609 // the expression is captured in the enclosing target environment when the
4610 // teams directive is not combined with target.
4611
4612 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
4613
4614 // FIXME: Accommodate other combined directives with teams when they become
4615 // available.
4616 if (auto *TeamsDir = dyn_cast<OMPTeamsDirective>(CS.getCapturedStmt())) {
4617 if (auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) {
4618 CGOpenMPInnerExprInfo CGInfo(CGF, CS);
4619 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
4620 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit());
4621 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty,
4622 /*IsSigned=*/true);
4623 }
4624
4625 // If we have an enclosed teams directive but no thread_limit clause we use
4626 // the default value 0.
4627 return CGF.Builder.getInt32(0);
4628 }
4629
4630 // No teams associated with the directive.
4631 return nullptr;
4632}
4633
Samuel Antao86ace552016-04-27 22:40:57 +00004634namespace {
4635// \brief Utility to handle information from clauses associated with a given
4636// construct that use mappable expressions (e.g. 'map' clause, 'to' clause).
4637// It provides a convenient interface to obtain the information and generate
4638// code for that information.
4639class MappableExprsHandler {
4640public:
4641 /// \brief Values for bit flags used to specify the mapping type for
4642 /// offloading.
4643 enum OpenMPOffloadMappingFlags {
4644 /// \brief Only allocate memory on the device,
4645 OMP_MAP_ALLOC = 0x00,
4646 /// \brief Allocate memory on the device and move data from host to device.
4647 OMP_MAP_TO = 0x01,
4648 /// \brief Allocate memory on the device and move data from device to host.
4649 OMP_MAP_FROM = 0x02,
4650 /// \brief Always perform the requested mapping action on the element, even
4651 /// if it was already mapped before.
4652 OMP_MAP_ALWAYS = 0x04,
4653 /// \brief Decrement the reference count associated with the element without
4654 /// executing any other action.
4655 OMP_MAP_RELEASE = 0x08,
4656 /// \brief Delete the element from the device environment, ignoring the
4657 /// current reference count associated with the element.
4658 OMP_MAP_DELETE = 0x10,
4659 /// \brief The element passed to the device is a pointer.
4660 OMP_MAP_PTR = 0x20,
4661 /// \brief Signal the element as extra, i.e. is not argument to the target
4662 /// region kernel.
4663 OMP_MAP_EXTRA = 0x40,
4664 /// \brief Pass the element to the device by value.
4665 OMP_MAP_BYCOPY = 0x80,
4666 };
4667
4668 typedef SmallVector<llvm::Value *, 16> MapValuesArrayTy;
4669 typedef SmallVector<unsigned, 16> MapFlagsArrayTy;
4670
4671private:
4672 /// \brief Directive from where the map clauses were extracted.
4673 const OMPExecutableDirective &Directive;
4674
4675 /// \brief Function the directive is being generated for.
4676 CodeGenFunction &CGF;
4677
4678 llvm::Value *getExprTypeSize(const Expr *E) const {
4679 auto ExprTy = E->getType().getCanonicalType();
4680
4681 // Reference types are ignored for mapping purposes.
4682 if (auto *RefTy = ExprTy->getAs<ReferenceType>())
4683 ExprTy = RefTy->getPointeeType().getCanonicalType();
4684
4685 // Given that an array section is considered a built-in type, we need to
4686 // do the calculation based on the length of the section instead of relying
4687 // on CGF.getTypeSize(E->getType()).
4688 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) {
4689 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(
4690 OAE->getBase()->IgnoreParenImpCasts())
4691 .getCanonicalType();
4692
4693 // If there is no length associated with the expression, that means we
4694 // are using the whole length of the base.
4695 if (!OAE->getLength() && OAE->getColonLoc().isValid())
4696 return CGF.getTypeSize(BaseTy);
4697
4698 llvm::Value *ElemSize;
4699 if (auto *PTy = BaseTy->getAs<PointerType>())
4700 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType());
4701 else {
4702 auto *ATy = cast<ArrayType>(BaseTy.getTypePtr());
4703 assert(ATy && "Expecting array type if not a pointer type.");
4704 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType());
4705 }
4706
4707 // If we don't have a length at this point, that is because we have an
4708 // array section with a single element.
4709 if (!OAE->getLength())
4710 return ElemSize;
4711
4712 auto *LengthVal = CGF.EmitScalarExpr(OAE->getLength());
4713 LengthVal =
4714 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false);
4715 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize);
4716 }
4717 return CGF.getTypeSize(ExprTy);
4718 }
4719
4720 /// \brief Return the corresponding bits for a given map clause modifier. Add
4721 /// a flag marking the map as a pointer if requested. Add a flag marking the
4722 /// map as extra, meaning is not an argument of the kernel.
4723 unsigned getMapTypeBits(OpenMPMapClauseKind MapType,
4724 OpenMPMapClauseKind MapTypeModifier, bool AddPtrFlag,
4725 bool AddExtraFlag) const {
4726 unsigned Bits = 0u;
4727 switch (MapType) {
4728 case OMPC_MAP_alloc:
4729 Bits = OMP_MAP_ALLOC;
4730 break;
4731 case OMPC_MAP_to:
4732 Bits = OMP_MAP_TO;
4733 break;
4734 case OMPC_MAP_from:
4735 Bits = OMP_MAP_FROM;
4736 break;
4737 case OMPC_MAP_tofrom:
4738 Bits = OMP_MAP_TO | OMP_MAP_FROM;
4739 break;
4740 case OMPC_MAP_delete:
4741 Bits = OMP_MAP_DELETE;
4742 break;
4743 case OMPC_MAP_release:
4744 Bits = OMP_MAP_RELEASE;
4745 break;
4746 default:
4747 llvm_unreachable("Unexpected map type!");
4748 break;
4749 }
4750 if (AddPtrFlag)
4751 Bits |= OMP_MAP_PTR;
4752 if (AddExtraFlag)
4753 Bits |= OMP_MAP_EXTRA;
4754 if (MapTypeModifier == OMPC_MAP_always)
4755 Bits |= OMP_MAP_ALWAYS;
4756 return Bits;
4757 }
4758
4759 /// \brief Return true if the provided expression is a final array section. A
4760 /// final array section, is one whose length can't be proved to be one.
4761 bool isFinalArraySectionExpression(const Expr *E) const {
4762 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
4763
4764 // It is not an array section and therefore not a unity-size one.
4765 if (!OASE)
4766 return false;
4767
4768 // An array section with no colon always refer to a single element.
4769 if (OASE->getColonLoc().isInvalid())
4770 return false;
4771
4772 auto *Length = OASE->getLength();
4773
4774 // If we don't have a length we have to check if the array has size 1
4775 // for this dimension. Also, we should always expect a length if the
4776 // base type is pointer.
4777 if (!Length) {
4778 auto BaseQTy = OMPArraySectionExpr::getBaseOriginalType(
4779 OASE->getBase()->IgnoreParenImpCasts())
4780 .getCanonicalType();
4781 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
4782 return ATy->getSize().getSExtValue() != 1;
4783 // If we don't have a constant dimension length, we have to consider
4784 // the current section as having any size, so it is not necessarily
4785 // unitary. If it happen to be unity size, that's user fault.
4786 return true;
4787 }
4788
4789 // Check if the length evaluates to 1.
4790 llvm::APSInt ConstLength;
4791 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext()))
4792 return true; // Can have more that size 1.
4793
4794 return ConstLength.getSExtValue() != 1;
4795 }
4796
4797 /// \brief Generate the base pointers, section pointers, sizes and map type
4798 /// bits for the provided map type, map modifier, and expression components.
4799 /// \a IsFirstComponent should be set to true if the provided set of
4800 /// components is the first associated with a capture.
4801 void generateInfoForComponentList(
4802 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier,
4803 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
4804 MapValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers,
4805 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types,
4806 bool IsFirstComponentList) const {
4807
4808 // The following summarizes what has to be generated for each map and the
4809 // types bellow. The generated information is expressed in this order:
4810 // base pointer, section pointer, size, flags
4811 // (to add to the ones that come from the map type and modifier).
4812 //
4813 // double d;
4814 // int i[100];
4815 // float *p;
4816 //
4817 // struct S1 {
4818 // int i;
4819 // float f[50];
4820 // }
4821 // struct S2 {
4822 // int i;
4823 // float f[50];
4824 // S1 s;
4825 // double *p;
4826 // struct S2 *ps;
4827 // }
4828 // S2 s;
4829 // S2 *ps;
4830 //
4831 // map(d)
4832 // &d, &d, sizeof(double), noflags
4833 //
4834 // map(i)
4835 // &i, &i, 100*sizeof(int), noflags
4836 //
4837 // map(i[1:23])
4838 // &i(=&i[0]), &i[1], 23*sizeof(int), noflags
4839 //
4840 // map(p)
4841 // &p, &p, sizeof(float*), noflags
4842 //
4843 // map(p[1:24])
4844 // p, &p[1], 24*sizeof(float), noflags
4845 //
4846 // map(s)
4847 // &s, &s, sizeof(S2), noflags
4848 //
4849 // map(s.i)
4850 // &s, &(s.i), sizeof(int), noflags
4851 //
4852 // map(s.s.f)
4853 // &s, &(s.i.f), 50*sizeof(int), noflags
4854 //
4855 // map(s.p)
4856 // &s, &(s.p), sizeof(double*), noflags
4857 //
4858 // map(s.p[:22], s.a s.b)
4859 // &s, &(s.p), sizeof(double*), noflags
4860 // &(s.p), &(s.p[0]), 22*sizeof(double), ptr_flag + extra_flag
4861 //
4862 // map(s.ps)
4863 // &s, &(s.ps), sizeof(S2*), noflags
4864 //
4865 // map(s.ps->s.i)
4866 // &s, &(s.ps), sizeof(S2*), noflags
4867 // &(s.ps), &(s.ps->s.i), sizeof(int), ptr_flag + extra_flag
4868 //
4869 // map(s.ps->ps)
4870 // &s, &(s.ps), sizeof(S2*), noflags
4871 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
4872 //
4873 // map(s.ps->ps->ps)
4874 // &s, &(s.ps), sizeof(S2*), noflags
4875 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
4876 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
4877 //
4878 // map(s.ps->ps->s.f[:22])
4879 // &s, &(s.ps), sizeof(S2*), noflags
4880 // &(s.ps), &(s.ps->ps), sizeof(S2*), ptr_flag + extra_flag
4881 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), ptr_flag + extra_flag
4882 //
4883 // map(ps)
4884 // &ps, &ps, sizeof(S2*), noflags
4885 //
4886 // map(ps->i)
4887 // ps, &(ps->i), sizeof(int), noflags
4888 //
4889 // map(ps->s.f)
4890 // ps, &(ps->s.f[0]), 50*sizeof(float), noflags
4891 //
4892 // map(ps->p)
4893 // ps, &(ps->p), sizeof(double*), noflags
4894 //
4895 // map(ps->p[:22])
4896 // ps, &(ps->p), sizeof(double*), noflags
4897 // &(ps->p), &(ps->p[0]), 22*sizeof(double), ptr_flag + extra_flag
4898 //
4899 // map(ps->ps)
4900 // ps, &(ps->ps), sizeof(S2*), noflags
4901 //
4902 // map(ps->ps->s.i)
4903 // ps, &(ps->ps), sizeof(S2*), noflags
4904 // &(ps->ps), &(ps->ps->s.i), sizeof(int), ptr_flag + extra_flag
4905 //
4906 // map(ps->ps->ps)
4907 // ps, &(ps->ps), sizeof(S2*), noflags
4908 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
4909 //
4910 // map(ps->ps->ps->ps)
4911 // ps, &(ps->ps), sizeof(S2*), noflags
4912 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
4913 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
4914 //
4915 // map(ps->ps->ps->s.f[:22])
4916 // ps, &(ps->ps), sizeof(S2*), noflags
4917 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), ptr_flag + extra_flag
4918 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), ptr_flag +
4919 // extra_flag
4920
4921 // Track if the map information being generated is the first for a capture.
4922 bool IsCaptureFirstInfo = IsFirstComponentList;
4923
4924 // Scan the components from the base to the complete expression.
4925 auto CI = Components.rbegin();
4926 auto CE = Components.rend();
4927 auto I = CI;
4928
4929 // Track if the map information being generated is the first for a list of
4930 // components.
4931 bool IsExpressionFirstInfo = true;
4932 llvm::Value *BP = nullptr;
4933
4934 if (auto *ME = dyn_cast<MemberExpr>(I->getAssociatedExpression())) {
4935 // The base is the 'this' pointer. The content of the pointer is going
4936 // to be the base of the field being mapped.
4937 BP = CGF.EmitScalarExpr(ME->getBase());
4938 } else {
4939 // The base is the reference to the variable.
4940 // BP = &Var.
4941 BP = CGF.EmitLValue(cast<DeclRefExpr>(I->getAssociatedExpression()))
4942 .getPointer();
4943
4944 // If the variable is a pointer and is being dereferenced (i.e. is not
4945 // the last component), the base has to be the pointer itself, not his
4946 // reference.
4947 if (I->getAssociatedDeclaration()->getType()->isAnyPointerType() &&
4948 std::next(I) != CE) {
4949 auto PtrAddr = CGF.MakeNaturalAlignAddrLValue(
4950 BP, I->getAssociatedDeclaration()->getType());
4951 BP = CGF.EmitLoadOfPointerLValue(PtrAddr.getAddress(),
4952 I->getAssociatedDeclaration()
4953 ->getType()
4954 ->getAs<PointerType>())
4955 .getPointer();
4956
4957 // We do not need to generate individual map information for the
4958 // pointer, it can be associated with the combined storage.
4959 ++I;
4960 }
4961 }
4962
4963 for (; I != CE; ++I) {
4964 auto Next = std::next(I);
4965
4966 // We need to generate the addresses and sizes if this is the last
4967 // component, if the component is a pointer or if it is an array section
4968 // whose length can't be proved to be one. If this is a pointer, it
4969 // becomes the base address for the following components.
4970
4971 // A final array section, is one whose length can't be proved to be one.
4972 bool IsFinalArraySection =
4973 isFinalArraySectionExpression(I->getAssociatedExpression());
4974
4975 // Get information on whether the element is a pointer. Have to do a
4976 // special treatment for array sections given that they are built-in
4977 // types.
4978 const auto *OASE =
4979 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression());
4980 bool IsPointer =
4981 (OASE &&
4982 OMPArraySectionExpr::getBaseOriginalType(OASE)
4983 .getCanonicalType()
4984 ->isAnyPointerType()) ||
4985 I->getAssociatedExpression()->getType()->isAnyPointerType();
4986
4987 if (Next == CE || IsPointer || IsFinalArraySection) {
4988
4989 // If this is not the last component, we expect the pointer to be
4990 // associated with an array expression or member expression.
4991 assert((Next == CE ||
4992 isa<MemberExpr>(Next->getAssociatedExpression()) ||
4993 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) ||
4994 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) &&
4995 "Unexpected expression");
4996
4997 // Save the base we are currently using.
4998 BasePointers.push_back(BP);
4999
5000 auto *LB = CGF.EmitLValue(I->getAssociatedExpression()).getPointer();
5001 auto *Size = getExprTypeSize(I->getAssociatedExpression());
5002
5003 Pointers.push_back(LB);
5004 Sizes.push_back(Size);
5005 // We need to add a pointer flag for each map that comes from the the
5006 // same expression except for the first one. We need to add the extra
5007 // flag for each map that relates with the current capture, except for
5008 // the first one (there is a set of entries for each capture).
5009 Types.push_back(getMapTypeBits(MapType, MapTypeModifier,
5010 !IsExpressionFirstInfo,
5011 !IsCaptureFirstInfo));
5012
5013 // If we have a final array section, we are done with this expression.
5014 if (IsFinalArraySection)
5015 break;
5016
5017 // The pointer becomes the base for the next element.
5018 if (Next != CE)
5019 BP = LB;
5020
5021 IsExpressionFirstInfo = false;
5022 IsCaptureFirstInfo = false;
5023 continue;
5024 }
5025 }
5026 }
5027
5028public:
5029 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF)
5030 : Directive(Dir), CGF(CGF) {}
5031
5032 /// \brief Generate all the base pointers, section pointers, sizes and map
5033 /// types for the extracted mappable expressions.
5034 void generateAllInfo(MapValuesArrayTy &BasePointers,
5035 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes,
5036 MapFlagsArrayTy &Types) const {
5037 BasePointers.clear();
5038 Pointers.clear();
5039 Sizes.clear();
5040 Types.clear();
5041
5042 struct MapInfo {
5043 OMPClauseMappableExprCommon::MappableExprComponentListRef Components;
5044 OpenMPMapClauseKind MapType;
5045 OpenMPMapClauseKind MapTypeModifier;
5046 };
5047
5048 // We have to process the component lists that relate with the same
5049 // declaration in a single chunk so that we can generate the map flags
5050 // correctly. Therefore, we organize all lists in a map.
5051 llvm::DenseMap<const ValueDecl *, SmallVector<MapInfo, 8>> Info;
5052 for (auto *C : Directive.getClausesOfKind<OMPMapClause>())
5053 for (auto L : C->component_lists()) {
5054 const ValueDecl *VD =
5055 L.first ? cast<ValueDecl>(L.first->getCanonicalDecl()) : nullptr;
5056 Info[VD].push_back(
5057 {L.second, C->getMapType(), C->getMapTypeModifier()});
5058 }
5059
5060 for (auto &M : Info) {
5061 // We need to know when we generate information for the first component
5062 // associated with a capture, because the mapping flags depend on it.
5063 bool IsFirstComponentList = true;
5064 for (MapInfo &L : M.second) {
5065 assert(!L.Components.empty() &&
5066 "Not expecting declaration with no component lists.");
5067 generateInfoForComponentList(L.MapType, L.MapTypeModifier, L.Components,
5068 BasePointers, Pointers, Sizes, Types,
5069 IsFirstComponentList);
5070 IsFirstComponentList = false;
5071 }
5072 }
5073 }
5074
5075 /// \brief Generate the base pointers, section pointers, sizes and map types
5076 /// associated to a given capture.
5077 void generateInfoForCapture(const CapturedStmt::Capture *Cap,
5078 MapValuesArrayTy &BasePointers,
5079 MapValuesArrayTy &Pointers,
5080 MapValuesArrayTy &Sizes,
5081 MapFlagsArrayTy &Types) const {
5082 assert(!Cap->capturesVariableArrayType() &&
5083 "Not expecting to generate map info for a variable array type!");
5084
5085 BasePointers.clear();
5086 Pointers.clear();
5087 Sizes.clear();
5088 Types.clear();
5089
5090 const ValueDecl *VD =
5091 Cap->capturesThis()
5092 ? nullptr
5093 : cast<ValueDecl>(Cap->getCapturedVar()->getCanonicalDecl());
5094
5095 // We need to know when we generating information for the first component
5096 // associated with a capture, because the mapping flags depend on it.
5097 bool IsFirstComponentList = true;
5098 for (auto *C : Directive.getClausesOfKind<OMPMapClause>())
5099 for (auto L : C->decl_component_lists(VD)) {
5100 assert(L.first == VD &&
5101 "We got information for the wrong declaration??");
5102 assert(!L.second.empty() &&
5103 "Not expecting declaration with no component lists.");
5104 generateInfoForComponentList(C->getMapType(), C->getMapTypeModifier(),
5105 L.second, BasePointers, Pointers, Sizes,
5106 Types, IsFirstComponentList);
5107 IsFirstComponentList = false;
5108 }
5109
5110 return;
5111 }
5112};
5113}
5114
Samuel Antaobed3c462015-10-02 16:14:20 +00005115void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF,
5116 const OMPExecutableDirective &D,
5117 llvm::Value *OutlinedFn,
Samuel Antaoee8fb302016-01-06 13:42:12 +00005118 llvm::Value *OutlinedFnID,
Samuel Antaobed3c462015-10-02 16:14:20 +00005119 const Expr *IfCond, const Expr *Device,
5120 ArrayRef<llvm::Value *> CapturedVars) {
Alexey Bataev8ef31412015-12-18 07:58:25 +00005121 if (!CGF.HaveInsertPoint())
5122 return;
Samuel Antaobed3c462015-10-02 16:14:20 +00005123
5124 enum OpenMPOffloadingReservedDeviceIDs {
5125 /// \brief Device ID if the device was not defined, runtime should get it
5126 /// from environment variables in the spec.
5127 OMP_DEVICEID_UNDEF = -1,
5128 };
5129
Samuel Antaoee8fb302016-01-06 13:42:12 +00005130 assert(OutlinedFn && "Invalid outlined function!");
5131
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005132 auto &Ctx = CGF.getContext();
5133
Samuel Antao86ace552016-04-27 22:40:57 +00005134 // Fill up the arrays with all the captured variables.
5135 MappableExprsHandler::MapValuesArrayTy KernelArgs;
5136 MappableExprsHandler::MapValuesArrayTy BasePointers;
5137 MappableExprsHandler::MapValuesArrayTy Pointers;
5138 MappableExprsHandler::MapValuesArrayTy Sizes;
5139 MappableExprsHandler::MapFlagsArrayTy MapTypes;
Samuel Antaobed3c462015-10-02 16:14:20 +00005140
Samuel Antao86ace552016-04-27 22:40:57 +00005141 MappableExprsHandler::MapValuesArrayTy CurBasePointers;
5142 MappableExprsHandler::MapValuesArrayTy CurPointers;
5143 MappableExprsHandler::MapValuesArrayTy CurSizes;
5144 MappableExprsHandler::MapFlagsArrayTy CurMapTypes;
5145
5146 // Get map clause information.
5147 MappableExprsHandler MCHandler(D, CGF);
Samuel Antaobed3c462015-10-02 16:14:20 +00005148
5149 const CapturedStmt &CS = *cast<CapturedStmt>(D.getAssociatedStmt());
5150 auto RI = CS.getCapturedRecordDecl()->field_begin();
Samuel Antaobed3c462015-10-02 16:14:20 +00005151 auto CV = CapturedVars.begin();
5152 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(),
5153 CE = CS.capture_end();
5154 CI != CE; ++CI, ++RI, ++CV) {
5155 StringRef Name;
5156 QualType Ty;
Samuel Antaobed3c462015-10-02 16:14:20 +00005157
Samuel Antao86ace552016-04-27 22:40:57 +00005158 CurBasePointers.clear();
5159 CurPointers.clear();
5160 CurSizes.clear();
5161 CurMapTypes.clear();
5162
5163 // VLA sizes are passed to the outlined region by copy and do not have map
5164 // information associated.
Samuel Antaobed3c462015-10-02 16:14:20 +00005165 if (CI->capturesVariableArrayType()) {
Samuel Antao86ace552016-04-27 22:40:57 +00005166 CurBasePointers.push_back(*CV);
5167 CurPointers.push_back(*CV);
5168 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005169 // Copy to the device as an argument. No need to retrieve it.
Samuel Antao86ace552016-04-27 22:40:57 +00005170 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_BYCOPY);
Samuel Antaobed3c462015-10-02 16:14:20 +00005171 } else {
Samuel Antao86ace552016-04-27 22:40:57 +00005172 // If we have any information in the map clause, we use it, otherwise we
5173 // just do a default mapping.
5174 MCHandler.generateInfoForCapture(CI, CurBasePointers, CurPointers,
5175 CurSizes, CurMapTypes);
Samuel Antaobed3c462015-10-02 16:14:20 +00005176
Samuel Antao86ace552016-04-27 22:40:57 +00005177 if (CurBasePointers.empty()) {
5178 // Do the default mapping.
5179 if (CI->capturesThis()) {
5180 CurBasePointers.push_back(*CV);
5181 CurPointers.push_back(*CV);
5182 const PointerType *PtrTy =
5183 cast<PointerType>(RI->getType().getTypePtr());
5184 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType()));
5185 // Default map type.
5186 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_TO |
5187 MappableExprsHandler::OMP_MAP_FROM);
5188 } else if (CI->capturesVariableByCopy()) {
5189 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_BYCOPY);
5190 if (!RI->getType()->isAnyPointerType()) {
5191 // If the field is not a pointer, we need to save the actual value
5192 // and
5193 // load it as a void pointer.
5194 auto DstAddr = CGF.CreateMemTemp(
5195 Ctx.getUIntPtrType(),
5196 Twine(CI->getCapturedVar()->getName()) + ".casted");
5197 LValue DstLV = CGF.MakeAddrLValue(DstAddr, Ctx.getUIntPtrType());
5198
5199 auto *SrcAddrVal = CGF.EmitScalarConversion(
5200 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()),
5201 Ctx.getPointerType(RI->getType()), SourceLocation());
5202 LValue SrcLV =
5203 CGF.MakeNaturalAlignAddrLValue(SrcAddrVal, RI->getType());
5204
5205 // Store the value using the source type pointer.
5206 CGF.EmitStoreThroughLValue(RValue::get(*CV), SrcLV);
5207
5208 // Load the value using the destination type pointer.
5209 CurBasePointers.push_back(
5210 CGF.EmitLoadOfLValue(DstLV, SourceLocation()).getScalarVal());
5211 CurPointers.push_back(CurBasePointers.back());
5212 } else {
5213 CurBasePointers.push_back(*CV);
5214 CurPointers.push_back(*CV);
5215 }
5216 CurSizes.push_back(CGF.getTypeSize(RI->getType()));
5217 } else {
5218 assert(CI->capturesVariable() && "Expected captured reference.");
5219 CurBasePointers.push_back(*CV);
5220 CurPointers.push_back(*CV);
5221
5222 const ReferenceType *PtrTy =
5223 cast<ReferenceType>(RI->getType().getTypePtr());
5224 QualType ElementType = PtrTy->getPointeeType();
5225 CurSizes.push_back(CGF.getTypeSize(ElementType));
5226 // The default map type for a scalar/complex type is 'to' because by
5227 // default the value doesn't have to be retrieved. For an aggregate
5228 // type,
5229 // the default is 'tofrom'.
5230 CurMapTypes.push_back(ElementType->isAggregateType()
5231 ? (MappableExprsHandler::OMP_MAP_TO |
5232 MappableExprsHandler::OMP_MAP_FROM)
5233 : MappableExprsHandler::OMP_MAP_TO);
5234 }
5235 }
Samuel Antaobed3c462015-10-02 16:14:20 +00005236 }
Samuel Antao86ace552016-04-27 22:40:57 +00005237 // We expect to have at least an element of information for this capture.
5238 assert(!CurBasePointers.empty() && "Non-existing map pointer for capture!");
5239 assert(CurBasePointers.size() == CurPointers.size() &&
5240 CurBasePointers.size() == CurSizes.size() &&
5241 CurBasePointers.size() == CurMapTypes.size() &&
5242 "Inconsistent map information sizes!");
Samuel Antaobed3c462015-10-02 16:14:20 +00005243
Samuel Antao86ace552016-04-27 22:40:57 +00005244 // The kernel args are always the first elements of the base pointers
5245 // associated with a capture.
5246 KernelArgs.push_back(CurBasePointers.front());
5247 // We need to append the results of this capture to what we already have.
5248 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end());
5249 Pointers.append(CurPointers.begin(), CurPointers.end());
5250 Sizes.append(CurSizes.begin(), CurSizes.end());
5251 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end());
Samuel Antaobed3c462015-10-02 16:14:20 +00005252 }
5253
Samuel Antao86ace552016-04-27 22:40:57 +00005254 // Detect if we have any capture size requiring runtime evaluation of the size
5255 // so that a constant array could be eventually used.
5256 bool hasRuntimeEvaluationCaptureSize = false;
5257 for (auto *S : Sizes)
5258 if (!isa<llvm::Constant>(S)) {
5259 hasRuntimeEvaluationCaptureSize = true;
5260 break;
5261 }
5262
Samuel Antaobed3c462015-10-02 16:14:20 +00005263 // Keep track on whether the host function has to be executed.
5264 auto OffloadErrorQType =
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005265 Ctx.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00005266 auto OffloadError = CGF.MakeAddrLValue(
5267 CGF.CreateMemTemp(OffloadErrorQType, ".run_host_version"),
5268 OffloadErrorQType);
5269 CGF.EmitStoreOfScalar(llvm::Constant::getNullValue(CGM.Int32Ty),
5270 OffloadError);
5271
5272 // Fill up the pointer arrays and transfer execution to the device.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005273 auto &&ThenGen = [&Ctx, &BasePointers, &Pointers, &Sizes, &MapTypes,
Samuel Antao86ace552016-04-27 22:40:57 +00005274 hasRuntimeEvaluationCaptureSize, Device, OutlinedFnID,
5275 OffloadError, OffloadErrorQType,
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005276 &D](CodeGenFunction &CGF, PrePostActionTy &) {
5277 auto &RT = CGF.CGM.getOpenMPRuntime();
Samuel Antaobed3c462015-10-02 16:14:20 +00005278 unsigned PointerNumVal = BasePointers.size();
5279 llvm::Value *PointerNum = CGF.Builder.getInt32(PointerNumVal);
5280 llvm::Value *BasePointersArray;
5281 llvm::Value *PointersArray;
5282 llvm::Value *SizesArray;
5283 llvm::Value *MapTypesArray;
5284
5285 if (PointerNumVal) {
5286 llvm::APInt PointerNumAP(32, PointerNumVal, /*isSigned=*/true);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005287 QualType PointerArrayType = Ctx.getConstantArrayType(
5288 Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal,
Samuel Antaobed3c462015-10-02 16:14:20 +00005289 /*IndexTypeQuals=*/0);
5290
5291 BasePointersArray =
5292 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer();
5293 PointersArray =
5294 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer();
5295
5296 // If we don't have any VLA types, we can use a constant array for the map
5297 // sizes, otherwise we need to fill up the arrays as we do for the
5298 // pointers.
Samuel Antao86ace552016-04-27 22:40:57 +00005299 if (hasRuntimeEvaluationCaptureSize) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005300 QualType SizeArrayType = Ctx.getConstantArrayType(
5301 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal,
Samuel Antaobed3c462015-10-02 16:14:20 +00005302 /*IndexTypeQuals=*/0);
5303 SizesArray =
5304 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer();
5305 } else {
5306 // We expect all the sizes to be constant, so we collect them to create
5307 // a constant array.
5308 SmallVector<llvm::Constant *, 16> ConstSizes;
5309 for (auto S : Sizes)
5310 ConstSizes.push_back(cast<llvm::Constant>(S));
5311
5312 auto *SizesArrayInit = llvm::ConstantArray::get(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005313 llvm::ArrayType::get(CGF.CGM.SizeTy, ConstSizes.size()),
5314 ConstSizes);
Samuel Antaobed3c462015-10-02 16:14:20 +00005315 auto *SizesArrayGbl = new llvm::GlobalVariable(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005316 CGF.CGM.getModule(), SizesArrayInit->getType(),
Samuel Antaobed3c462015-10-02 16:14:20 +00005317 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
5318 SizesArrayInit, ".offload_sizes");
5319 SizesArrayGbl->setUnnamedAddr(true);
5320 SizesArray = SizesArrayGbl;
5321 }
5322
5323 // The map types are always constant so we don't need to generate code to
5324 // fill arrays. Instead, we create an array constant.
5325 llvm::Constant *MapTypesArrayInit =
5326 llvm::ConstantDataArray::get(CGF.Builder.getContext(), MapTypes);
5327 auto *MapTypesArrayGbl = new llvm::GlobalVariable(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005328 CGF.CGM.getModule(), MapTypesArrayInit->getType(),
Samuel Antaobed3c462015-10-02 16:14:20 +00005329 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage,
5330 MapTypesArrayInit, ".offload_maptypes");
5331 MapTypesArrayGbl->setUnnamedAddr(true);
5332 MapTypesArray = MapTypesArrayGbl;
5333
5334 for (unsigned i = 0; i < PointerNumVal; ++i) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005335 llvm::Value *BPVal = BasePointers[i];
5336 if (BPVal->getType()->isPointerTy())
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005337 BPVal = CGF.Builder.CreateBitCast(BPVal, CGF.VoidPtrTy);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005338 else {
5339 assert(BPVal->getType()->isIntegerTy() &&
5340 "If not a pointer, the value type must be an integer.");
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005341 BPVal = CGF.Builder.CreateIntToPtr(BPVal, CGF.VoidPtrTy);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005342 }
Samuel Antaobed3c462015-10-02 16:14:20 +00005343 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005344 llvm::ArrayType::get(CGF.VoidPtrTy, PointerNumVal),
Samuel Antaobed3c462015-10-02 16:14:20 +00005345 BasePointersArray, 0, i);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005346 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
5347 CGF.Builder.CreateStore(BPVal, BPAddr);
Samuel Antaobed3c462015-10-02 16:14:20 +00005348
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005349 llvm::Value *PVal = Pointers[i];
5350 if (PVal->getType()->isPointerTy())
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005351 PVal = CGF.Builder.CreateBitCast(PVal, CGF.VoidPtrTy);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005352 else {
5353 assert(PVal->getType()->isIntegerTy() &&
5354 "If not a pointer, the value type must be an integer.");
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005355 PVal = CGF.Builder.CreateIntToPtr(PVal, CGF.VoidPtrTy);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005356 }
Samuel Antaobed3c462015-10-02 16:14:20 +00005357 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005358 llvm::ArrayType::get(CGF.VoidPtrTy, PointerNumVal), PointersArray,
Samuel Antaobed3c462015-10-02 16:14:20 +00005359 0, i);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005360 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy));
5361 CGF.Builder.CreateStore(PVal, PAddr);
Samuel Antaobed3c462015-10-02 16:14:20 +00005362
Samuel Antao86ace552016-04-27 22:40:57 +00005363 if (hasRuntimeEvaluationCaptureSize) {
Samuel Antaobed3c462015-10-02 16:14:20 +00005364 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005365 llvm::ArrayType::get(CGF.SizeTy, PointerNumVal), SizesArray,
Samuel Antaobed3c462015-10-02 16:14:20 +00005366 /*Idx0=*/0,
5367 /*Idx1=*/i);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00005368 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType()));
Samuel Antaobed3c462015-10-02 16:14:20 +00005369 CGF.Builder.CreateStore(CGF.Builder.CreateIntCast(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005370 Sizes[i], CGF.SizeTy, /*isSigned=*/true),
Samuel Antaobed3c462015-10-02 16:14:20 +00005371 SAddr);
5372 }
5373 }
5374
5375 BasePointersArray = CGF.Builder.CreateConstInBoundsGEP2_32(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005376 llvm::ArrayType::get(CGF.VoidPtrTy, PointerNumVal), BasePointersArray,
Samuel Antaobed3c462015-10-02 16:14:20 +00005377 /*Idx0=*/0, /*Idx1=*/0);
5378 PointersArray = CGF.Builder.CreateConstInBoundsGEP2_32(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005379 llvm::ArrayType::get(CGF.VoidPtrTy, PointerNumVal), PointersArray,
Samuel Antaobed3c462015-10-02 16:14:20 +00005380 /*Idx0=*/0,
5381 /*Idx1=*/0);
5382 SizesArray = CGF.Builder.CreateConstInBoundsGEP2_32(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005383 llvm::ArrayType::get(CGF.SizeTy, PointerNumVal), SizesArray,
Samuel Antaobed3c462015-10-02 16:14:20 +00005384 /*Idx0=*/0, /*Idx1=*/0);
5385 MapTypesArray = CGF.Builder.CreateConstInBoundsGEP2_32(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005386 llvm::ArrayType::get(CGF.Int32Ty, PointerNumVal), MapTypesArray,
Samuel Antaobed3c462015-10-02 16:14:20 +00005387 /*Idx0=*/0,
5388 /*Idx1=*/0);
5389
5390 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005391 BasePointersArray = llvm::ConstantPointerNull::get(CGF.VoidPtrPtrTy);
5392 PointersArray = llvm::ConstantPointerNull::get(CGF.VoidPtrPtrTy);
5393 SizesArray = llvm::ConstantPointerNull::get(CGF.SizeTy->getPointerTo());
Samuel Antaobed3c462015-10-02 16:14:20 +00005394 MapTypesArray =
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005395 llvm::ConstantPointerNull::get(CGF.Int32Ty->getPointerTo());
Samuel Antaobed3c462015-10-02 16:14:20 +00005396 }
5397
5398 // On top of the arrays that were filled up, the target offloading call
5399 // takes as arguments the device id as well as the host pointer. The host
5400 // pointer is used by the runtime library to identify the current target
5401 // region, so it only has to be unique and not necessarily point to
5402 // anything. It could be the pointer to the outlined function that
5403 // implements the target region, but we aren't using that so that the
5404 // compiler doesn't need to keep that, and could therefore inline the host
5405 // function if proven worthwhile during optimization.
5406
Samuel Antaoee8fb302016-01-06 13:42:12 +00005407 // From this point on, we need to have an ID of the target region defined.
5408 assert(OutlinedFnID && "Invalid outlined function ID!");
Samuel Antaobed3c462015-10-02 16:14:20 +00005409
5410 // Emit device ID if any.
5411 llvm::Value *DeviceID;
5412 if (Device)
5413 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005414 CGF.Int32Ty, /*isSigned=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00005415 else
5416 DeviceID = CGF.Builder.getInt32(OMP_DEVICEID_UNDEF);
5417
Samuel Antaob68e2db2016-03-03 16:20:23 +00005418 // Return value of the runtime offloading call.
5419 llvm::Value *Return;
5420
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005421 auto *NumTeams = emitNumTeamsClauseForTargetDirective(RT, CGF, D);
5422 auto *ThreadLimit = emitThreadLimitClauseForTargetDirective(RT, CGF, D);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005423
5424 // If we have NumTeams defined this means that we have an enclosed teams
5425 // region. Therefore we also expect to have ThreadLimit defined. These two
5426 // values should be defined in the presence of a teams directive, regardless
5427 // of having any clauses associated. If the user is using teams but no
5428 // clauses, these two values will be the default that should be passed to
5429 // the runtime library - a 32-bit integer with the value zero.
5430 if (NumTeams) {
5431 assert(ThreadLimit && "Thread limit expression should be available along "
5432 "with number of teams.");
5433 llvm::Value *OffloadingArgs[] = {
5434 DeviceID, OutlinedFnID, PointerNum,
5435 BasePointersArray, PointersArray, SizesArray,
5436 MapTypesArray, NumTeams, ThreadLimit};
5437 Return = CGF.EmitRuntimeCall(
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005438 RT.createRuntimeFunction(OMPRTL__tgt_target_teams), OffloadingArgs);
Samuel Antaob68e2db2016-03-03 16:20:23 +00005439 } else {
5440 llvm::Value *OffloadingArgs[] = {
5441 DeviceID, OutlinedFnID, PointerNum, BasePointersArray,
5442 PointersArray, SizesArray, MapTypesArray};
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005443 Return = CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__tgt_target),
Samuel Antaob68e2db2016-03-03 16:20:23 +00005444 OffloadingArgs);
5445 }
Samuel Antaobed3c462015-10-02 16:14:20 +00005446
5447 CGF.EmitStoreOfScalar(Return, OffloadError);
5448 };
5449
Samuel Antaoee8fb302016-01-06 13:42:12 +00005450 // Notify that the host version must be executed.
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005451 auto &&ElseGen = [OffloadError](CodeGenFunction &CGF, PrePostActionTy &) {
5452 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.Int32Ty, /*V=*/-1u),
Samuel Antaoee8fb302016-01-06 13:42:12 +00005453 OffloadError);
5454 };
5455
5456 // If we have a target function ID it means that we need to support
5457 // offloading, otherwise, just execute on the host. We need to execute on host
5458 // regardless of the conditional in the if clause if, e.g., the user do not
5459 // specify target triples.
5460 if (OutlinedFnID) {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005461 if (IfCond)
Samuel Antaoee8fb302016-01-06 13:42:12 +00005462 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen);
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005463 else {
5464 RegionCodeGenTy ThenRCG(ThenGen);
5465 ThenRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00005466 }
5467 } else {
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005468 RegionCodeGenTy ElseRCG(ElseGen);
5469 ElseRCG(CGF);
Alexey Bataevf539faa2016-03-28 12:58:34 +00005470 }
Samuel Antaobed3c462015-10-02 16:14:20 +00005471
5472 // Check the error code and execute the host version if required.
5473 auto OffloadFailedBlock = CGF.createBasicBlock("omp_offload.failed");
5474 auto OffloadContBlock = CGF.createBasicBlock("omp_offload.cont");
5475 auto OffloadErrorVal = CGF.EmitLoadOfScalar(OffloadError, SourceLocation());
5476 auto Failed = CGF.Builder.CreateIsNotNull(OffloadErrorVal);
5477 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock);
5478
5479 CGF.EmitBlock(OffloadFailedBlock);
Samuel Antao86ace552016-04-27 22:40:57 +00005480 CGF.Builder.CreateCall(OutlinedFn, KernelArgs);
Samuel Antaobed3c462015-10-02 16:14:20 +00005481 CGF.EmitBranch(OffloadContBlock);
5482
5483 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true);
Samuel Antaobed3c462015-10-02 16:14:20 +00005484}
Samuel Antaoee8fb302016-01-06 13:42:12 +00005485
5486void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
5487 StringRef ParentName) {
5488 if (!S)
5489 return;
5490
5491 // If we find a OMP target directive, codegen the outline function and
5492 // register the result.
5493 // FIXME: Add other directives with target when they become supported.
5494 bool isTargetDirective = isa<OMPTargetDirective>(S);
5495
5496 if (isTargetDirective) {
5497 auto *E = cast<OMPExecutableDirective>(S);
5498 unsigned DeviceID;
5499 unsigned FileID;
5500 unsigned Line;
Samuel Antaoee8fb302016-01-06 13:42:12 +00005501 getTargetEntryUniqueInfo(CGM.getContext(), E->getLocStart(), DeviceID,
Samuel Antao2de62b02016-02-13 23:35:10 +00005502 FileID, Line);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005503
5504 // Is this a target region that should not be emitted as an entry point? If
5505 // so just signal we are done with this target region.
Samuel Antao2de62b02016-02-13 23:35:10 +00005506 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID,
5507 ParentName, Line))
Samuel Antaoee8fb302016-01-06 13:42:12 +00005508 return;
5509
5510 llvm::Function *Fn;
5511 llvm::Constant *Addr;
Alexey Bataev14fa1c62016-03-29 05:34:15 +00005512 std::tie(Fn, Addr) =
5513 CodeGenFunction::EmitOMPTargetDirectiveOutlinedFunction(
5514 CGM, cast<OMPTargetDirective>(*E), ParentName,
5515 /*isOffloadEntry=*/true);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005516 assert(Fn && Addr && "Target region emission failed.");
5517 return;
5518 }
5519
5520 if (const OMPExecutableDirective *E = dyn_cast<OMPExecutableDirective>(S)) {
5521 if (!E->getAssociatedStmt())
5522 return;
5523
5524 scanForTargetRegionsFunctions(
5525 cast<CapturedStmt>(E->getAssociatedStmt())->getCapturedStmt(),
5526 ParentName);
5527 return;
5528 }
5529
5530 // If this is a lambda function, look into its body.
5531 if (auto *L = dyn_cast<LambdaExpr>(S))
5532 S = L->getBody();
5533
5534 // Keep looking for target regions recursively.
5535 for (auto *II : S->children())
5536 scanForTargetRegionsFunctions(II, ParentName);
Samuel Antaoee8fb302016-01-06 13:42:12 +00005537}
5538
5539bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) {
5540 auto &FD = *cast<FunctionDecl>(GD.getDecl());
5541
5542 // If emitting code for the host, we do not process FD here. Instead we do
5543 // the normal code generation.
5544 if (!CGM.getLangOpts().OpenMPIsDevice)
5545 return false;
5546
5547 // Try to detect target regions in the function.
5548 scanForTargetRegionsFunctions(FD.getBody(), CGM.getMangledName(GD));
5549
5550 // We should not emit any function othen that the ones created during the
5551 // scanning. Therefore, we signal that this function is completely dealt
5552 // with.
5553 return true;
5554}
5555
5556bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) {
5557 if (!CGM.getLangOpts().OpenMPIsDevice)
5558 return false;
5559
5560 // Check if there are Ctors/Dtors in this declaration and look for target
5561 // regions in it. We use the complete variant to produce the kernel name
5562 // mangling.
5563 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType();
5564 if (auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) {
5565 for (auto *Ctor : RD->ctors()) {
5566 StringRef ParentName =
5567 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete));
5568 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName);
5569 }
5570 auto *Dtor = RD->getDestructor();
5571 if (Dtor) {
5572 StringRef ParentName =
5573 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete));
5574 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName);
5575 }
5576 }
5577
5578 // If we are in target mode we do not emit any global (declare target is not
5579 // implemented yet). Therefore we signal that GD was processed in this case.
5580 return true;
5581}
5582
5583bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) {
5584 auto *VD = GD.getDecl();
5585 if (isa<FunctionDecl>(VD))
5586 return emitTargetFunctions(GD);
5587
5588 return emitTargetGlobalVariable(GD);
5589}
5590
5591llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() {
5592 // If we have offloading in the current module, we need to emit the entries
5593 // now and register the offloading descriptor.
5594 createOffloadEntriesAndInfoMetadata();
5595
5596 // Create and register the offloading binary descriptors. This is the main
5597 // entity that captures all the information about offloading in the current
5598 // compilation unit.
5599 return createOffloadingBinaryDescriptorRegistration();
5600}
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00005601
5602void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF,
5603 const OMPExecutableDirective &D,
5604 SourceLocation Loc,
5605 llvm::Value *OutlinedFn,
5606 ArrayRef<llvm::Value *> CapturedVars) {
5607 if (!CGF.HaveInsertPoint())
5608 return;
5609
5610 auto *RTLoc = emitUpdateLocation(CGF, Loc);
5611 CodeGenFunction::RunCleanupsScope Scope(CGF);
5612
5613 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn);
5614 llvm::Value *Args[] = {
5615 RTLoc,
5616 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
5617 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())};
5618 llvm::SmallVector<llvm::Value *, 16> RealArgs;
5619 RealArgs.append(std::begin(Args), std::end(Args));
5620 RealArgs.append(CapturedVars.begin(), CapturedVars.end());
5621
5622 auto RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams);
5623 CGF.EmitRuntimeCall(RTLFn, RealArgs);
5624}
5625
5626void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF,
Carlo Bertollic6872252016-04-04 15:55:02 +00005627 const Expr *NumTeams,
5628 const Expr *ThreadLimit,
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00005629 SourceLocation Loc) {
5630 if (!CGF.HaveInsertPoint())
5631 return;
5632
5633 auto *RTLoc = emitUpdateLocation(CGF, Loc);
5634
Carlo Bertollic6872252016-04-04 15:55:02 +00005635 llvm::Value *NumTeamsVal =
5636 (NumTeams)
5637 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams),
5638 CGF.CGM.Int32Ty, /* isSigned = */ true)
5639 : CGF.Builder.getInt32(0);
5640
5641 llvm::Value *ThreadLimitVal =
5642 (ThreadLimit)
5643 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit),
5644 CGF.CGM.Int32Ty, /* isSigned = */ true)
5645 : CGF.Builder.getInt32(0);
5646
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00005647 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit)
Carlo Bertollic6872252016-04-04 15:55:02 +00005648 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal,
5649 ThreadLimitVal};
Carlo Bertolli430d8ec2016-03-03 20:34:23 +00005650 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams),
5651 PushNumTeamsArgs);
5652}