Coverage Report

Created: 2021-09-21 08:58

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/CodeGen/CGOpenMPRuntime.cpp
Line
Count
Source (jump to first uncovered line)
1
//===----- CGOpenMPRuntime.cpp - Interface to OpenMP Runtimes -------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This provides a class for OpenMP runtime code generation.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "CGOpenMPRuntime.h"
14
#include "CGCXXABI.h"
15
#include "CGCleanup.h"
16
#include "CGRecordLayout.h"
17
#include "CodeGenFunction.h"
18
#include "clang/AST/APValue.h"
19
#include "clang/AST/Attr.h"
20
#include "clang/AST/Decl.h"
21
#include "clang/AST/OpenMPClause.h"
22
#include "clang/AST/StmtOpenMP.h"
23
#include "clang/AST/StmtVisitor.h"
24
#include "clang/Basic/BitmaskEnum.h"
25
#include "clang/Basic/FileManager.h"
26
#include "clang/Basic/OpenMPKinds.h"
27
#include "clang/Basic/SourceManager.h"
28
#include "clang/CodeGen/ConstantInitBuilder.h"
29
#include "llvm/ADT/ArrayRef.h"
30
#include "llvm/ADT/SetOperations.h"
31
#include "llvm/ADT/StringExtras.h"
32
#include "llvm/Bitcode/BitcodeReader.h"
33
#include "llvm/IR/Constants.h"
34
#include "llvm/IR/DerivedTypes.h"
35
#include "llvm/IR/GlobalValue.h"
36
#include "llvm/IR/Value.h"
37
#include "llvm/Support/AtomicOrdering.h"
38
#include "llvm/Support/Format.h"
39
#include "llvm/Support/raw_ostream.h"
40
#include <cassert>
41
#include <numeric>
42
43
using namespace clang;
44
using namespace CodeGen;
45
using namespace llvm::omp;
46
47
namespace {
48
/// Base class for handling code generation inside OpenMP regions.
49
class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo {
50
public:
51
  /// Kinds of OpenMP regions used in codegen.
52
  enum CGOpenMPRegionKind {
53
    /// Region with outlined function for standalone 'parallel'
54
    /// directive.
55
    ParallelOutlinedRegion,
56
    /// Region with outlined function for standalone 'task' directive.
57
    TaskOutlinedRegion,
58
    /// Region for constructs that do not require function outlining,
59
    /// like 'for', 'sections', 'atomic' etc. directives.
60
    InlinedRegion,
61
    /// Region with outlined function for standalone 'target' directive.
62
    TargetRegion,
63
  };
64
65
  CGOpenMPRegionInfo(const CapturedStmt &CS,
66
                     const CGOpenMPRegionKind RegionKind,
67
                     const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
68
                     bool HasCancel)
69
      : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind),
70
24.7k
        CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {}
71
72
  CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind,
73
                     const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind,
74
                     bool HasCancel)
75
      : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen),
76
43.5k
        Kind(Kind), HasCancel(HasCancel) {}
77
78
  /// Get a variable or parameter for storing global thread id
79
  /// inside OpenMP construct.
80
  virtual const VarDecl *getThreadIDVariable() const = 0;
81
82
  /// Emit the captured statement body.
83
  void EmitBody(CodeGenFunction &CGF, const Stmt *S) override;
84
85
  /// Get an LValue for the current ThreadID variable.
86
  /// \return LValue for thread id variable. This LValue always has type int32*.
87
  virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF);
88
89
28
  virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {}
90
91
43.2k
  CGOpenMPRegionKind getRegionKind() const { return RegionKind; }
92
93
187
  OpenMPDirectiveKind getDirectiveKind() const { return Kind; }
94
95
356
  bool hasCancel() const { return HasCancel; }
96
97
143k
  static bool classof(const CGCapturedStmtInfo *Info) {
98
143k
    return Info->getKind() == CR_OpenMP;
99
143k
  }
100
101
68.3k
  ~CGOpenMPRegionInfo() override = default;
102
103
protected:
104
  CGOpenMPRegionKind RegionKind;
105
  RegionCodeGenTy CodeGen;
106
  OpenMPDirectiveKind Kind;
107
  bool HasCancel;
108
};
109
110
/// API for captured statement code generation in OpenMP constructs.
111
class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo {
112
public:
113
  CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar,
114
                             const RegionCodeGenTy &CodeGen,
115
                             OpenMPDirectiveKind Kind, bool HasCancel,
116
                             StringRef HelperName)
117
      : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind,
118
                           HasCancel),
119
11.9k
        ThreadIDVar(ThreadIDVar), HelperName(HelperName) {
120
11.9k
    assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
121
11.9k
  }
122
123
  /// Get a variable or parameter for storing global thread id
124
  /// inside OpenMP construct.
125
37.3k
  const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
126
127
  /// Get the name of the capture helper.
128
11.9k
  StringRef getHelperName() const override { return HelperName; }
129
130
0
  static bool classof(const CGCapturedStmtInfo *Info) {
131
0
    return CGOpenMPRegionInfo::classof(Info) &&
132
0
           cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
133
0
               ParallelOutlinedRegion;
134
0
  }
135
136
private:
137
  /// A variable or parameter storing global thread id for OpenMP
138
  /// constructs.
139
  const VarDecl *ThreadIDVar;
140
  StringRef HelperName;
141
};
142
143
/// API for captured statement code generation in OpenMP constructs.
144
class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo {
145
public:
146
  class UntiedTaskActionTy final : public PrePostActionTy {
147
    bool Untied;
148
    const VarDecl *PartIDVar;
149
    const RegionCodeGenTy UntiedCodeGen;
150
    llvm::SwitchInst *UntiedSwitch = nullptr;
151
152
  public:
153
    UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar,
154
                       const RegionCodeGenTy &UntiedCodeGen)
155
869
        : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {}
156
869
    void Enter(CodeGenFunction &CGF) override {
157
869
      if (Untied) {
158
        // Emit task switching point.
159
16
        LValue PartIdLVal = CGF.EmitLoadOfPointerLValue(
160
16
            CGF.GetAddrOfLocalVar(PartIDVar),
161
16
            PartIDVar->getType()->castAs<PointerType>());
162
16
        llvm::Value *Res =
163
16
            CGF.EmitLoadOfScalar(PartIdLVal, PartIDVar->getLocation());
164
16
        llvm::BasicBlock *DoneBB = CGF.createBasicBlock(".untied.done.");
165
16
        UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB);
166
16
        CGF.EmitBlock(DoneBB);
167
16
        CGF.EmitBranchThroughCleanup(CGF.ReturnBlock);
168
16
        CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
169
16
        UntiedSwitch->addCase(CGF.Builder.getInt32(0),
170
16
                              CGF.Builder.GetInsertBlock());
171
16
        emitUntiedSwitch(CGF);
172
16
      }
173
869
    }
174
34
    void emitUntiedSwitch(CodeGenFunction &CGF) const {
175
34
      if (Untied) {
176
30
        LValue PartIdLVal = CGF.EmitLoadOfPointerLValue(
177
30
            CGF.GetAddrOfLocalVar(PartIDVar),
178
30
            PartIDVar->getType()->castAs<PointerType>());
179
30
        CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
180
30
                              PartIdLVal);
181
30
        UntiedCodeGen(CGF);
182
30
        CodeGenFunction::JumpDest CurPoint =
183
30
            CGF.getJumpDestInCurrentScope(".untied.next.");
184
30
        CGF.EmitBranch(CGF.ReturnBlock.getBlock());
185
30
        CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp."));
186
30
        UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()),
187
30
                              CGF.Builder.GetInsertBlock());
188
30
        CGF.EmitBranchThroughCleanup(CurPoint);
189
30
        CGF.EmitBlock(CurPoint.getBlock());
190
30
      }
191
34
    }
192
16
    unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); }
193
  };
194
  CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS,
195
                                 const VarDecl *ThreadIDVar,
196
                                 const RegionCodeGenTy &CodeGen,
197
                                 OpenMPDirectiveKind Kind, bool HasCancel,
198
                                 const UntiedTaskActionTy &Action)
199
      : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel),
200
869
        ThreadIDVar(ThreadIDVar), Action(Action) {
201
869
    assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region.");
202
869
  }
203
204
  /// Get a variable or parameter for storing global thread id
205
  /// inside OpenMP construct.
206
282
  const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; }
207
208
  /// Get an LValue for the current ThreadID variable.
209
  LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override;
210
211
  /// Get the name of the capture helper.
212
869
  StringRef getHelperName() const override { return ".omp_outlined."; }
213
214
18
  void emitUntiedSwitch(CodeGenFunction &CGF) override {
215
18
    Action.emitUntiedSwitch(CGF);
216
18
  }
217
218
0
  static bool classof(const CGCapturedStmtInfo *Info) {
219
0
    return CGOpenMPRegionInfo::classof(Info) &&
220
0
           cast<CGOpenMPRegionInfo>(Info)->getRegionKind() ==
221
0
               TaskOutlinedRegion;
222
0
  }
223
224
private:
225
  /// A variable or parameter storing global thread id for OpenMP
226
  /// constructs.
227
  const VarDecl *ThreadIDVar;
228
  /// Action for emitting code for untied tasks.
229
  const UntiedTaskActionTy &Action;
230
};
231
232
/// API for inlined captured statement code generation in OpenMP
233
/// constructs.
234
class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo {
235
public:
236
  CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI,
237
                            const RegionCodeGenTy &CodeGen,
238
                            OpenMPDirectiveKind Kind, bool HasCancel)
239
      : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel),
240
        OldCSI(OldCSI),
241
43.5k
        OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {}
242
243
  // Retrieve the value of the context parameter.
244
0
  llvm::Value *getContextValue() const override {
245
0
    if (OuterRegionInfo)
246
0
      return OuterRegionInfo->getContextValue();
247
0
    llvm_unreachable("No context value for inlined OpenMP region");
248
0
  }
249
250
0
  void setContextValue(llvm::Value *V) override {
251
0
    if (OuterRegionInfo) {
252
0
      OuterRegionInfo->setContextValue(V);
253
0
      return;
254
0
    }
255
0
    llvm_unreachable("No context value for inlined OpenMP region");
256
0
  }
257
258
  /// Lookup the captured field decl for a variable.
259
26.2k
  const FieldDecl *lookup(const VarDecl *VD) const override {
260
26.2k
    if (OuterRegionInfo)
261
13.1k
      return OuterRegionInfo->lookup(VD);
262
    // If there is no outer outlined region,no need to lookup in a list of
263
    // captured variables, we can use the original one.
264
13.0k
    return nullptr;
265
26.2k
  }
266
267
0
  FieldDecl *getThisFieldDecl() const override {
268
0
    if (OuterRegionInfo)
269
0
      return OuterRegionInfo->getThisFieldDecl();
270
0
    return nullptr;
271
0
  }
272
273
  /// Get a variable or parameter for storing global thread id
274
  /// inside OpenMP construct.
275
6.74k
  const VarDecl *getThreadIDVariable() const override {
276
6.74k
    if (OuterRegionInfo)
277
6.51k
      return OuterRegionInfo->getThreadIDVariable();
278
227
    return nullptr;
279
6.74k
  }
280
281
  /// Get an LValue for the current ThreadID variable.
282
6.51k
  LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override {
283
6.51k
    if (OuterRegionInfo)
284
6.51k
      return OuterRegionInfo->getThreadIDVariableLValue(CGF);
285
0
    llvm_unreachable("No LValue for inlined OpenMP construct");
286
0
  }
287
288
  /// Get the name of the capture helper.
289
0
  StringRef getHelperName() const override {
290
0
    if (auto *OuterRegionInfo = getOldCSI())
291
0
      return OuterRegionInfo->getHelperName();
292
0
    llvm_unreachable("No helper name for inlined OpenMP construct");
293
0
  }
294
295
16
  void emitUntiedSwitch(CodeGenFunction &CGF) override {
296
16
    if (OuterRegionInfo)
297
14
      OuterRegionInfo->emitUntiedSwitch(CGF);
298
16
  }
299
300
43.2k
  CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; }
301
302
43.2k
  static bool classof(const CGCapturedStmtInfo *Info) {
303
43.2k
    return CGOpenMPRegionInfo::classof(Info) &&
304
43.2k
           cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion;
305
43.2k
  }
306
307
43.5k
  ~CGOpenMPInlinedRegionInfo() override = default;
308
309
private:
310
  /// CodeGen info about outer OpenMP region.
311
  CodeGenFunction::CGCapturedStmtInfo *OldCSI;
312
  CGOpenMPRegionInfo *OuterRegionInfo;
313
};
314
315
/// API for captured statement code generation in OpenMP target
316
/// constructs. For this captures, implicit parameters are used instead of the
317
/// captured fields. The name of the target region has to be unique in a given
318
/// application so it is provided by the client, because only the client has
319
/// the information to generate that.
320
class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo {
321
public:
322
  CGOpenMPTargetRegionInfo(const CapturedStmt &CS,
323
                           const RegionCodeGenTy &CodeGen, StringRef HelperName)
324
      : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target,
325
                           /*HasCancel=*/false),
326
12.0k
        HelperName(HelperName) {}
327
328
  /// This is unused for target regions because each starts executing
329
  /// with a single thread.
330
2.03k
  const VarDecl *getThreadIDVariable() const override { return nullptr; }
331
332
  /// Get the name of the capture helper.
333
12.1k
  StringRef getHelperName() const override { return HelperName; }
334
335
0
  static bool classof(const CGCapturedStmtInfo *Info) {
336
0
    return CGOpenMPRegionInfo::classof(Info) &&
337
0
           cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion;
338
0
  }
339
340
private:
341
  StringRef HelperName;
342
};
343
344
0
static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) {
345
0
  llvm_unreachable("No codegen for expressions");
346
0
}
347
/// API for generation of expressions captured in a innermost OpenMP
348
/// region.
349
class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo {
350
public:
351
  CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS)
352
      : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen,
353
                                  OMPD_unknown,
354
                                  /*HasCancel=*/false),
355
282
        PrivScope(CGF) {
356
    // Make sure the globals captured in the provided statement are local by
357
    // using the privatization logic. We assume the same variable is not
358
    // captured more than once.
359
412
    for (const auto &C : CS.captures()) {
360
412
      if (!C.capturesVariable() && 
!C.capturesVariableByCopy()320
)
361
16
        continue;
362
363
396
      const VarDecl *VD = C.getCapturedVar();
364
396
      if (VD->isLocalVarDeclOrParm())
365
318
        continue;
366
367
78
      DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(VD),
368
78
                      /*RefersToEnclosingVariableOrCapture=*/false,
369
78
                      VD->getType().getNonReferenceType(), VK_LValue,
370
78
                      C.getLocation());
371
78
      PrivScope.addPrivate(
372
78
          VD, [&CGF, &DRE]() { return CGF.EmitLValue(&DRE).getAddress(CGF); });
373
78
    }
374
282
    (void)PrivScope.Privatize();
375
282
  }
376
377
  /// Lookup the captured field decl for a variable.
378
0
  const FieldDecl *lookup(const VarDecl *VD) const override {
379
0
    if (const FieldDecl *FD = CGOpenMPInlinedRegionInfo::lookup(VD))
380
0
      return FD;
381
0
    return nullptr;
382
0
  }
383
384
  /// Emit the captured statement body.
385
0
  void EmitBody(CodeGenFunction &CGF, const Stmt *S) override {
386
0
    llvm_unreachable("No body for expressions");
387
0
  }
388
389
  /// Get a variable or parameter for storing global thread id
390
  /// inside OpenMP construct.
391
0
  const VarDecl *getThreadIDVariable() const override {
392
0
    llvm_unreachable("No thread id for expressions");
393
0
  }
394
395
  /// Get the name of the capture helper.
396
0
  StringRef getHelperName() const override {
397
0
    llvm_unreachable("No helper name for expressions");
398
0
  }
399
400
0
  static bool classof(const CGCapturedStmtInfo *Info) { return false; }
401
402
private:
403
  /// Private scope to capture global variables.
404
  CodeGenFunction::OMPPrivateScope PrivScope;
405
};
406
407
/// RAII for emitting code of OpenMP constructs.
408
class InlinedOpenMPRegionRAII {
409
  CodeGenFunction &CGF;
410
  llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
411
  FieldDecl *LambdaThisCaptureField = nullptr;
412
  const CodeGen::CGBlockInfo *BlockInfo = nullptr;
413
  bool NoInheritance = false;
414
415
public:
416
  /// Constructs region for combined constructs.
417
  /// \param CodeGen Code generation sequence for combined directives. Includes
418
  /// a list of functions used for code generation of implicitly inlined
419
  /// regions.
420
  InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen,
421
                          OpenMPDirectiveKind Kind, bool HasCancel,
422
                          bool NoInheritance = true)
423
43.2k
      : CGF(CGF), NoInheritance(NoInheritance) {
424
    // Start emission for the construct.
425
43.2k
    CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo(
426
43.2k
        CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel);
427
43.2k
    if (NoInheritance) {
428
42.8k
      std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
429
42.8k
      LambdaThisCaptureField = CGF.LambdaThisCaptureField;
430
42.8k
      CGF.LambdaThisCaptureField = nullptr;
431
42.8k
      BlockInfo = CGF.BlockInfo;
432
42.8k
      CGF.BlockInfo = nullptr;
433
42.8k
    }
434
43.2k
  }
435
436
43.2k
  ~InlinedOpenMPRegionRAII() {
437
    // Restore original CapturedStmtInfo only if we're done with code emission.
438
43.2k
    auto *OldCSI =
439
43.2k
        cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI();
440
43.2k
    delete CGF.CapturedStmtInfo;
441
43.2k
    CGF.CapturedStmtInfo = OldCSI;
442
43.2k
    if (NoInheritance) {
443
42.8k
      std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields);
444
42.8k
      CGF.LambdaThisCaptureField = LambdaThisCaptureField;
445
42.8k
      CGF.BlockInfo = BlockInfo;
446
42.8k
    }
447
43.2k
  }
448
};
449
450
/// Values for bit flags used in the ident_t to describe the fields.
451
/// All enumeric elements are named and described in accordance with the code
452
/// from https://github.com/llvm/llvm-project/blob/main/openmp/runtime/src/kmp.h
453
enum OpenMPLocationFlags : unsigned {
454
  /// Use trampoline for internal microtask.
455
  OMP_IDENT_IMD = 0x01,
456
  /// Use c-style ident structure.
457
  OMP_IDENT_KMPC = 0x02,
458
  /// Atomic reduction option for kmpc_reduce.
459
  OMP_ATOMIC_REDUCE = 0x10,
460
  /// Explicit 'barrier' directive.
461
  OMP_IDENT_BARRIER_EXPL = 0x20,
462
  /// Implicit barrier in code.
463
  OMP_IDENT_BARRIER_IMPL = 0x40,
464
  /// Implicit barrier in 'for' directive.
465
  OMP_IDENT_BARRIER_IMPL_FOR = 0x40,
466
  /// Implicit barrier in 'sections' directive.
467
  OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0,
468
  /// Implicit barrier in 'single' directive.
469
  OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140,
470
  /// Call of __kmp_for_static_init for static loop.
471
  OMP_IDENT_WORK_LOOP = 0x200,
472
  /// Call of __kmp_for_static_init for sections.
473
  OMP_IDENT_WORK_SECTIONS = 0x400,
474
  /// Call of __kmp_for_static_init for distribute.
475
  OMP_IDENT_WORK_DISTRIBUTE = 0x800,
476
  LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_IDENT_WORK_DISTRIBUTE)
477
};
478
479
namespace {
480
LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
481
/// Values for bit flags for marking which requires clauses have been used.
482
enum OpenMPOffloadingRequiresDirFlags : int64_t {
483
  /// flag undefined.
484
  OMP_REQ_UNDEFINED               = 0x000,
485
  /// no requires clause present.
486
  OMP_REQ_NONE                    = 0x001,
487
  /// reverse_offload clause.
488
  OMP_REQ_REVERSE_OFFLOAD         = 0x002,
489
  /// unified_address clause.
490
  OMP_REQ_UNIFIED_ADDRESS         = 0x004,
491
  /// unified_shared_memory clause.
492
  OMP_REQ_UNIFIED_SHARED_MEMORY   = 0x008,
493
  /// dynamic_allocators clause.
494
  OMP_REQ_DYNAMIC_ALLOCATORS      = 0x010,
495
  LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_REQ_DYNAMIC_ALLOCATORS)
496
};
497
498
enum OpenMPOffloadingReservedDeviceIDs {
499
  /// Device ID if the device was not defined, runtime should get it
500
  /// from environment variables in the spec.
501
  OMP_DEVICEID_UNDEF = -1,
502
};
503
} // anonymous namespace
504
505
/// Describes ident structure that describes a source location.
506
/// All descriptions are taken from
507
/// https://github.com/llvm/llvm-project/blob/main/openmp/runtime/src/kmp.h
508
/// Original structure:
509
/// typedef struct ident {
510
///    kmp_int32 reserved_1;   /**<  might be used in Fortran;
511
///                                  see above  */
512
///    kmp_int32 flags;        /**<  also f.flags; KMP_IDENT_xxx flags;
513
///                                  KMP_IDENT_KMPC identifies this union
514
///                                  member  */
515
///    kmp_int32 reserved_2;   /**<  not really used in Fortran any more;
516
///                                  see above */
517
///#if USE_ITT_BUILD
518
///                            /*  but currently used for storing
519
///                                region-specific ITT */
520
///                            /*  contextual information. */
521
///#endif /* USE_ITT_BUILD */
522
///    kmp_int32 reserved_3;   /**< source[4] in Fortran, do not use for
523
///                                 C++  */
524
///    char const *psource;    /**< String describing the source location.
525
///                            The string is composed of semi-colon separated
526
//                             fields which describe the source file,
527
///                            the function and a pair of line numbers that
528
///                            delimit the construct.
529
///                             */
530
/// } ident_t;
531
enum IdentFieldIndex {
532
  /// might be used in Fortran
533
  IdentField_Reserved_1,
534
  /// OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member.
535
  IdentField_Flags,
536
  /// Not really used in Fortran any more
537
  IdentField_Reserved_2,
538
  /// Source[4] in Fortran, do not use for C++
539
  IdentField_Reserved_3,
540
  /// String describing the source location. The string is composed of
541
  /// semi-colon separated fields which describe the source file, the function
542
  /// and a pair of line numbers that delimit the construct.
543
  IdentField_PSource
544
};
545
546
/// Schedule types for 'omp for' loops (these enumerators are taken from
547
/// the enum sched_type in kmp.h).
548
enum OpenMPSchedType {
549
  /// Lower bound for default (unordered) versions.
550
  OMP_sch_lower = 32,
551
  OMP_sch_static_chunked = 33,
552
  OMP_sch_static = 34,
553
  OMP_sch_dynamic_chunked = 35,
554
  OMP_sch_guided_chunked = 36,
555
  OMP_sch_runtime = 37,
556
  OMP_sch_auto = 38,
557
  /// static with chunk adjustment (e.g., simd)
558
  OMP_sch_static_balanced_chunked = 45,
559
  /// Lower bound for 'ordered' versions.
560
  OMP_ord_lower = 64,
561
  OMP_ord_static_chunked = 65,
562
  OMP_ord_static = 66,
563
  OMP_ord_dynamic_chunked = 67,
564
  OMP_ord_guided_chunked = 68,
565
  OMP_ord_runtime = 69,
566
  OMP_ord_auto = 70,
567
  OMP_sch_default = OMP_sch_static,
568
  /// dist_schedule types
569
  OMP_dist_sch_static_chunked = 91,
570
  OMP_dist_sch_static = 92,
571
  /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers.
572
  /// Set if the monotonic schedule modifier was present.
573
  OMP_sch_modifier_monotonic = (1 << 29),
574
  /// Set if the nonmonotonic schedule modifier was present.
575
  OMP_sch_modifier_nonmonotonic = (1 << 30),
576
};
577
578
/// A basic class for pre|post-action for advanced codegen sequence for OpenMP
579
/// region.
580
class CleanupTy final : public EHScopeStack::Cleanup {
581
  PrePostActionTy *Action;
582
583
public:
584
15.7k
  explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {}
585
15.8k
  void Emit(CodeGenFunction &CGF, Flags /*flags*/) override {
586
15.8k
    if (!CGF.HaveInsertPoint())
587
0
      return;
588
15.8k
    Action->Exit(CGF);
589
15.8k
  }
590
};
591
592
} // anonymous namespace
593
594
128k
void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const {
595
128k
  CodeGenFunction::RunCleanupsScope Scope(CGF);
596
128k
  if (PrePostAction) {
597
15.7k
    CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction);
598
15.7k
    Callback(CodeGen, CGF, *PrePostAction);
599
113k
  } else {
600
113k
    PrePostActionTy Action;
601
113k
    Callback(CodeGen, CGF, Action);
602
113k
  }
603
128k
}
604
605
/// Check if the combiner is a call to UDR combiner and if it is so return the
606
/// UDR decl used for reduction.
607
static const OMPDeclareReductionDecl *
608
1.09k
getReductionInit(const Expr *ReductionOp) {
609
1.09k
  if (const auto *CE = dyn_cast<CallExpr>(ReductionOp))
610
146
    if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee()))
611
83
      if (const auto *DRE =
612
83
              dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts()))
613
83
        if (const auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl()))
614
83
          return DRD;
615
1.01k
  return nullptr;
616
1.09k
}
617
618
static void emitInitWithReductionInitializer(CodeGenFunction &CGF,
619
                                             const OMPDeclareReductionDecl *DRD,
620
                                             const Expr *InitOp,
621
                                             Address Private, Address Original,
622
67
                                             QualType Ty) {
623
67
  if (DRD->getInitializer()) {
624
53
    std::pair<llvm::Function *, llvm::Function *> Reduction =
625
53
        CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD);
626
53
    const auto *CE = cast<CallExpr>(InitOp);
627
53
    const auto *OVE = cast<OpaqueValueExpr>(CE->getCallee());
628
53
    const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
629
53
    const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
630
53
    const auto *LHSDRE =
631
53
        cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr());
632
53
    const auto *RHSDRE =
633
53
        cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr());
634
53
    CodeGenFunction::OMPPrivateScope PrivateScope(CGF);
635
53
    PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()),
636
53
                            [=]() { return Private; });
637
53
    PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()),
638
53
                            [=]() { return Original; });
639
53
    (void)PrivateScope.Privatize();
640
53
    RValue Func = RValue::get(Reduction.second);
641
53
    CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func);
642
53
    CGF.EmitIgnoredExpr(InitOp);
643
53
  } else {
644
14
    llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty);
645
14
    std::string Name = CGF.CGM.getOpenMPRuntime().getName({"init"});
646
14
    auto *GV = new llvm::GlobalVariable(
647
14
        CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
648
14
        llvm::GlobalValue::PrivateLinkage, Init, Name);
649
14
    LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty);
650
14
    RValue InitRVal;
651
14
    switch (CGF.getEvaluationKind(Ty)) {
652
11
    case TEK_Scalar:
653
11
      InitRVal = CGF.EmitLoadOfLValue(LV, DRD->getLocation());
654
11
      break;
655
0
    case TEK_Complex:
656
0
      InitRVal =
657
0
          RValue::getComplex(CGF.EmitLoadOfComplex(LV, DRD->getLocation()));
658
0
      break;
659
3
    case TEK_Aggregate: {
660
3
      OpaqueValueExpr OVE(DRD->getLocation(), Ty, VK_LValue);
661
3
      CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, LV);
662
3
      CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
663
3
                           /*IsInitializer=*/false);
664
3
      return;
665
0
    }
666
14
    }
667
11
    OpaqueValueExpr OVE(DRD->getLocation(), Ty, VK_PRValue);
668
11
    CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal);
669
11
    CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(),
670
11
                         /*IsInitializer=*/false);
671
11
  }
672
67
}
673
674
/// Emit initialization of arrays of complex types.
675
/// \param DestAddr Address of the array.
676
/// \param Type Type of array.
677
/// \param Init Initial expression of array.
678
/// \param SrcAddr Address of the original array.
679
static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr,
680
                                 QualType Type, bool EmitDeclareReductionInit,
681
                                 const Expr *Init,
682
                                 const OMPDeclareReductionDecl *DRD,
683
282
                                 Address SrcAddr = Address::invalid()) {
684
  // Perform element-by-element initialization.
685
282
  QualType ElementTy;
686
687
  // Drill down to the base element type on both arrays.
688
282
  const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe();
689
282
  llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr);
690
282
  DestAddr =
691
282
      CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType());
692
282
  if (DRD)
693
31
    SrcAddr =
694
31
        CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType());
695
696
282
  llvm::Value *SrcBegin = nullptr;
697
282
  if (DRD)
698
31
    SrcBegin = SrcAddr.getPointer();
699
282
  llvm::Value *DestBegin = DestAddr.getPointer();
700
  // Cast from pointer to array type to pointer to single element.
701
282
  llvm::Value *DestEnd =
702
282
      CGF.Builder.CreateGEP(DestAddr.getElementType(), DestBegin, NumElements);
703
  // The basic structure here is a while-do loop.
704
282
  llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arrayinit.body");
705
282
  llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arrayinit.done");
706
282
  llvm::Value *IsEmpty =
707
282
      CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty");
708
282
  CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB);
709
710
  // Enter the loop body, making that address the current address.
711
282
  llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock();
712
282
  CGF.EmitBlock(BodyBB);
713
714
282
  CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy);
715
716
282
  llvm::PHINode *SrcElementPHI = nullptr;
717
282
  Address SrcElementCurrent = Address::invalid();
718
282
  if (DRD) {
719
31
    SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2,
720
31
                                          "omp.arraycpy.srcElementPast");
721
31
    SrcElementPHI->addIncoming(SrcBegin, EntryBB);
722
31
    SrcElementCurrent =
723
31
        Address(SrcElementPHI,
724
31
                SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize));
725
31
  }
726
282
  llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI(
727
282
      DestBegin->getType(), 2, "omp.arraycpy.destElementPast");
728
282
  DestElementPHI->addIncoming(DestBegin, EntryBB);
729
282
  Address DestElementCurrent =
730
282
      Address(DestElementPHI,
731
282
              DestAddr.getAlignment().alignmentOfArrayElement(ElementSize));
732
733
  // Emit copy.
734
282
  {
735
282
    CodeGenFunction::RunCleanupsScope InitScope(CGF);
736
282
    if (EmitDeclareReductionInit) {
737
31
      emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent,
738
31
                                       SrcElementCurrent, ElementTy);
739
31
    } else
740
251
      CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(),
741
251
                           /*IsInitializer=*/false);
742
282
  }
743
744
282
  if (DRD) {
745
    // Shift the address forward by one element.
746
31
    llvm::Value *SrcElementNext = CGF.Builder.CreateConstGEP1_32(
747
31
        SrcAddr.getElementType(), SrcElementPHI, /*Idx0=*/1,
748
31
        "omp.arraycpy.dest.element");
749
31
    SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock());
750
31
  }
751
752
  // Shift the address forward by one element.
753
282
  llvm::Value *DestElementNext = CGF.Builder.CreateConstGEP1_32(
754
282
      DestAddr.getElementType(), DestElementPHI, /*Idx0=*/1,
755
282
      "omp.arraycpy.dest.element");
756
  // Check whether we've reached the end.
757
282
  llvm::Value *Done =
758
282
      CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done");
759
282
  CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB);
760
282
  DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock());
761
762
  // Done.
763
282
  CGF.EmitBlock(DoneBB, /*IsFinished=*/true);
764
282
}
765
766
1.11k
LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) {
767
1.11k
  return CGF.EmitOMPSharedLValue(E);
768
1.11k
}
769
770
LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF,
771
1.11k
                                            const Expr *E) {
772
1.11k
  if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E))
773
234
    return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false);
774
880
  return LValue();
775
1.11k
}
776
777
void ReductionCodeGen::emitAggregateInitialization(
778
    CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
779
282
    const OMPDeclareReductionDecl *DRD) {
780
  // Emit VarDecl with copy init for arrays.
781
  // Get the address of the original variable captured in current
782
  // captured region.
783
282
  const auto *PrivateVD =
784
282
      cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
785
282
  bool EmitDeclareReductionInit =
786
282
      DRD && 
(31
DRD->getInitializer()31
||
!PrivateVD->hasInit()4
);
787
282
  EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(),
788
282
                       EmitDeclareReductionInit,
789
282
                       EmitDeclareReductionInit ? 
ClausesData[N].ReductionOp31
790
282
                                                : 
PrivateVD->getInit()251
,
791
282
                       DRD, SharedLVal.getAddress(CGF));
792
282
}
793
794
ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds,
795
                                   ArrayRef<const Expr *> Origs,
796
                                   ArrayRef<const Expr *> Privates,
797
27.9k
                                   ArrayRef<const Expr *> ReductionOps) {
798
27.9k
  ClausesData.reserve(Shareds.size());
799
27.9k
  SharedAddresses.reserve(Shareds.size());
800
27.9k
  Sizes.reserve(Shareds.size());
801
27.9k
  BaseDecls.reserve(Shareds.size());
802
27.9k
  const auto *IOrig = Origs.begin();
803
27.9k
  const auto *IPriv = Privates.begin();
804
27.9k
  const auto *IRed = ReductionOps.begin();
805
27.9k
  for (const Expr *Ref : Shareds) {
806
1.07k
    ClausesData.emplace_back(Ref, *IOrig, *IPriv, *IRed);
807
1.07k
    std::advance(IOrig, 1);
808
1.07k
    std::advance(IPriv, 1);
809
1.07k
    std::advance(IRed, 1);
810
1.07k
  }
811
27.9k
}
812
813
1.06k
void ReductionCodeGen::emitSharedOrigLValue(CodeGenFunction &CGF, unsigned N) {
814
1.06k
  assert(SharedAddresses.size() == N && OrigAddresses.size() == N &&
815
1.06k
         "Number of generated lvalues must be exactly N.");
816
0
  LValue First = emitSharedLValue(CGF, ClausesData[N].Shared);
817
1.06k
  LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Shared);
818
1.06k
  SharedAddresses.emplace_back(First, Second);
819
1.06k
  if (ClausesData[N].Shared == ClausesData[N].Ref) {
820
1.00k
    OrigAddresses.emplace_back(First, Second);
821
1.00k
  } else {
822
53
    LValue First = emitSharedLValue(CGF, ClausesData[N].Ref);
823
53
    LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Ref);
824
53
    OrigAddresses.emplace_back(First, Second);
825
53
  }
826
1.06k
}
827
828
1.06k
void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) {
829
1.06k
  const auto *PrivateVD =
830
1.06k
      cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
831
1.06k
  QualType PrivateType = PrivateVD->getType();
832
1.06k
  bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref);
833
1.06k
  if (!PrivateType->isVariablyModifiedType()) {
834
824
    Sizes.emplace_back(
835
824
        CGF.getTypeSize(OrigAddresses[N].first.getType().getNonReferenceType()),
836
824
        nullptr);
837
824
    return;
838
824
  }
839
237
  llvm::Value *Size;
840
237
  llvm::Value *SizeInChars;
841
237
  auto *ElemType =
842
237
      cast<llvm::PointerType>(OrigAddresses[N].first.getPointer(CGF)->getType())
843
237
          ->getElementType();
844
237
  auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType);
845
237
  if (AsArraySection) {
846
186
    Size = CGF.Builder.CreatePtrDiff(OrigAddresses[N].second.getPointer(CGF),
847
186
                                     OrigAddresses[N].first.getPointer(CGF));
848
186
    Size = CGF.Builder.CreateNUWAdd(
849
186
        Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1));
850
186
    SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf);
851
186
  } else {
852
51
    SizeInChars =
853
51
        CGF.getTypeSize(OrigAddresses[N].first.getType().getNonReferenceType());
854
51
    Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf);
855
51
  }
856
237
  Sizes.emplace_back(SizeInChars, Size);
857
237
  CodeGenFunction::OpaqueValueMapping OpaqueMap(
858
237
      CGF,
859
237
      cast<OpaqueValueExpr>(
860
237
          CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
861
237
      RValue::get(Size));
862
237
  CGF.EmitVariablyModifiedType(PrivateType);
863
237
}
864
865
void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N,
866
303
                                         llvm::Value *Size) {
867
303
  const auto *PrivateVD =
868
303
      cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
869
303
  QualType PrivateType = PrivateVD->getType();
870
303
  if (!PrivateType->isVariablyModifiedType()) {
871
193
    assert(!Size && !Sizes[N].second &&
872
193
           "Size should be nullptr for non-variably modified reduction "
873
193
           "items.");
874
0
    return;
875
193
  }
876
110
  CodeGenFunction::OpaqueValueMapping OpaqueMap(
877
110
      CGF,
878
110
      cast<OpaqueValueExpr>(
879
110
          CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()),
880
110
      RValue::get(Size));
881
110
  CGF.EmitVariablyModifiedType(PrivateType);
882
110
}
883
884
void ReductionCodeGen::emitInitialization(
885
    CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal,
886
955
    llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) {
887
955
  assert(SharedAddresses.size() > N && "No variable was generated");
888
0
  const auto *PrivateVD =
889
955
      cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
890
955
  const OMPDeclareReductionDecl *DRD =
891
955
      getReductionInit(ClausesData[N].ReductionOp);
892
955
  QualType PrivateType = PrivateVD->getType();
893
955
  PrivateAddr = CGF.Builder.CreateElementBitCast(
894
955
      PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
895
955
  QualType SharedType = SharedAddresses[N].first.getType();
896
955
  SharedLVal = CGF.MakeAddrLValue(
897
955
      CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(CGF),
898
955
                                       CGF.ConvertTypeForMem(SharedType)),
899
955
      SharedType, SharedAddresses[N].first.getBaseInfo(),
900
955
      CGF.CGM.getTBAAInfoForSubobject(SharedAddresses[N].first, SharedType));
901
955
  if (CGF.getContext().getAsArrayType(PrivateVD->getType())) {
902
282
    if (DRD && 
DRD->getInitializer()31
)
903
27
      (void)DefaultInit(CGF);
904
282
    emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD);
905
673
  } else if (DRD && 
(46
DRD->getInitializer()46
||
!PrivateVD->hasInit()20
)) {
906
36
    (void)DefaultInit(CGF);
907
36
    emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp,
908
36
                                     PrivateAddr, SharedLVal.getAddress(CGF),
909
36
                                     SharedLVal.getType());
910
637
  } else if (!DefaultInit(CGF) && 
PrivateVD->hasInit()77
&&
911
637
             
!CGF.isTrivialInitializer(PrivateVD->getInit())77
) {
912
77
    CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr,
913
77
                         PrivateVD->getType().getQualifiers(),
914
77
                         /*IsInitializer=*/false);
915
77
  }
916
955
}
917
918
161
bool ReductionCodeGen::needCleanups(unsigned N) {
919
161
  const auto *PrivateVD =
920
161
      cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
921
161
  QualType PrivateType = PrivateVD->getType();
922
161
  QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
923
161
  return DTorKind != QualType::DK_none;
924
161
}
925
926
void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N,
927
19
                                    Address PrivateAddr) {
928
19
  const auto *PrivateVD =
929
19
      cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl());
930
19
  QualType PrivateType = PrivateVD->getType();
931
19
  QualType::DestructionKind DTorKind = PrivateType.isDestructedType();
932
19
  if (needCleanups(N)) {
933
19
    PrivateAddr = CGF.Builder.CreateElementBitCast(
934
19
        PrivateAddr, CGF.ConvertTypeForMem(PrivateType));
935
19
    CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType);
936
19
  }
937
19
}
938
939
static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
940
189
                          LValue BaseLV) {
941
189
  BaseTy = BaseTy.getNonReferenceType();
942
315
  while ((BaseTy->isPointerType() || 
BaseTy->isReferenceType()189
) &&
943
315
         
!CGF.getContext().hasSameType(BaseTy, ElTy)126
) {
944
126
    if (const auto *PtrTy = BaseTy->getAs<PointerType>()) {
945
126
      BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(CGF), PtrTy);
946
126
    } else {
947
0
      LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(CGF), BaseTy);
948
0
      BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal);
949
0
    }
950
126
    BaseTy = BaseTy->getPointeeType();
951
126
  }
952
189
  return CGF.MakeAddrLValue(
953
189
      CGF.Builder.CreateElementBitCast(BaseLV.getAddress(CGF),
954
189
                                       CGF.ConvertTypeForMem(ElTy)),
955
189
      BaseLV.getType(), BaseLV.getBaseInfo(),
956
189
      CGF.CGM.getTBAAInfoForSubobject(BaseLV, BaseLV.getType()));
957
189
}
958
959
static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy,
960
                          llvm::Type *BaseLVType, CharUnits BaseLVAlignment,
961
189
                          llvm::Value *Addr) {
962
189
  Address Tmp = Address::invalid();
963
189
  Address TopTmp = Address::invalid();
964
189
  Address MostTopTmp = Address::invalid();
965
189
  BaseTy = BaseTy.getNonReferenceType();
966
315
  while ((BaseTy->isPointerType() || 
BaseTy->isReferenceType()189
) &&
967
315
         
!CGF.getContext().hasSameType(BaseTy, ElTy)126
) {
968
126
    Tmp = CGF.CreateMemTemp(BaseTy);
969
126
    if (TopTmp.isValid())
970
58
      CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp);
971
68
    else
972
68
      MostTopTmp = Tmp;
973
126
    TopTmp = Tmp;
974
126
    BaseTy = BaseTy->getPointeeType();
975
126
  }
976
189
  llvm::Type *Ty = BaseLVType;
977
189
  if (Tmp.isValid())
978
68
    Ty = Tmp.getElementType();
979
189
  Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty);
980
189
  if (Tmp.isValid()) {
981
68
    CGF.Builder.CreateStore(Addr, Tmp);
982
68
    return MostTopTmp;
983
68
  }
984
121
  return Address(Addr, BaseLVAlignment);
985
189
}
986
987
1.06k
static const VarDecl *getBaseDecl(const Expr *Ref, const DeclRefExpr *&DE) {
988
1.06k
  const VarDecl *OrigVD = nullptr;
989
1.06k
  if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(Ref)) {
990
285
    const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
991
425
    while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
992
140
      Base = TempOASE->getBase()->IgnoreParenImpCasts();
993
293
    while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
994
8
      Base = TempASE->getBase()->IgnoreParenImpCasts();
995
285
    DE = cast<DeclRefExpr>(Base);
996
285
    OrigVD = cast<VarDecl>(DE->getDecl());
997
784
  } else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Ref)) {
998
4
    const Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
999
4
    while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
1000
0
      Base = TempASE->getBase()->IgnoreParenImpCasts();
1001
4
    DE = cast<DeclRefExpr>(Base);
1002
4
    OrigVD = cast<VarDecl>(DE->getDecl());
1003
4
  }
1004
1.06k
  return OrigVD;
1005
1.06k
}
1006
1007
Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N,
1008
903
                                               Address PrivateAddr) {
1009
903
  const DeclRefExpr *DE;
1010
903
  if (const VarDecl *OrigVD = ::getBaseDecl(ClausesData[N].Ref, DE)) {
1011
189
    BaseDecls.emplace_back(OrigVD);
1012
189
    LValue OriginalBaseLValue = CGF.EmitLValue(DE);
1013
189
    LValue BaseLValue =
1014
189
        loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(),
1015
189
                    OriginalBaseLValue);
1016
189
    Address SharedAddr = SharedAddresses[N].first.getAddress(CGF);
1017
189
    llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff(
1018
189
        BaseLValue.getPointer(CGF), SharedAddr.getPointer());
1019
189
    llvm::Value *PrivatePointer =
1020
189
        CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
1021
189
            PrivateAddr.getPointer(), SharedAddr.getType());
1022
189
    llvm::Value *Ptr = CGF.Builder.CreateGEP(
1023
189
        SharedAddr.getElementType(), PrivatePointer, Adjustment);
1024
189
    return castToBase(CGF, OrigVD->getType(),
1025
189
                      SharedAddresses[N].first.getType(),
1026
189
                      OriginalBaseLValue.getAddress(CGF).getType(),
1027
189
                      OriginalBaseLValue.getAlignment(), Ptr);
1028
189
  }
1029
714
  BaseDecls.emplace_back(
1030
714
      cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl()));
1031
714
  return PrivateAddr;
1032
903
}
1033
1034
142
bool ReductionCodeGen::usesReductionInitializer(unsigned N) const {
1035
142
  const OMPDeclareReductionDecl *DRD =
1036
142
      getReductionInit(ClausesData[N].ReductionOp);
1037
142
  return DRD && 
DRD->getInitializer()6
;
1038
142
}
1039
1040
12.4k
LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) {
1041
12.4k
  return CGF.EmitLoadOfPointerLValue(
1042
12.4k
      CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1043
12.4k
      getThreadIDVariable()->getType()->castAs<PointerType>());
1044
12.4k
}
1045
1046
67.4k
void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt *S) {
1047
67.4k
  if (!CGF.HaveInsertPoint())
1048
0
    return;
1049
  // 1.2.2 OpenMP Language Terminology
1050
  // Structured block - An executable statement with a single entry at the
1051
  // top and a single exit at the bottom.
1052
  // The point of exit cannot be a branch out of the structured block.
1053
  // longjmp() and throw() must not violate the entry/exit criteria.
1054
67.4k
  CGF.EHStack.pushTerminate();
1055
67.4k
  if (S)
1056
24.7k
    CGF.incrementProfileCounter(S);
1057
67.4k
  CodeGen(CGF);
1058
67.4k
  CGF.EHStack.popTerminate();
1059
67.4k
}
1060
1061
LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue(
1062
94
    CodeGenFunction &CGF) {
1063
94
  return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()),
1064
94
                            getThreadIDVariable()->getType(),
1065
94
                            AlignmentSource::Decl);
1066
94
}
1067
1068
static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC,
1069
18.8k
                                       QualType FieldTy) {
1070
18.8k
  auto *Field = FieldDecl::Create(
1071
18.8k
      C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy,
1072
18.8k
      C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()),
1073
18.8k
      /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit);
1074
18.8k
  Field->setAccess(AS_public);
1075
18.8k
  DC->addDecl(Field);
1076
18.8k
  return Field;
1077
18.8k
}
1078
1079
CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM, StringRef FirstSeparator,
1080
                                 StringRef Separator)
1081
    : CGM(CGM), FirstSeparator(FirstSeparator), Separator(Separator),
1082
5.87k
      OMPBuilder(CGM.getModule()), OffloadEntriesInfoManager(CGM) {
1083
5.87k
  KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8);
1084
1085
  // Initialize Types used in OpenMPIRBuilder from OMPKinds.def
1086
5.87k
  OMPBuilder.initialize();
1087
5.87k
  loadOffloadInfoMetadata();
1088
5.87k
}
1089
1090
5.87k
void CGOpenMPRuntime::clear() {
1091
5.87k
  InternalVars.clear();
1092
  // Clean non-target variable declarations possibly used only in debug info.
1093
5.87k
  for (const auto &Data : EmittedNonTargetVariables) {
1094
12
    if (!Data.getValue().pointsToAliveValue())
1095
0
      continue;
1096
12
    auto *GV = dyn_cast<llvm::GlobalVariable>(Data.getValue());
1097
12
    if (!GV)
1098
0
      continue;
1099
12
    if (!GV->isDeclaration() || GV->getNumUses() > 0)
1100
11
      continue;
1101
1
    GV->eraseFromParent();
1102
1
  }
1103
5.87k
}
1104
1105
52.0k
std::string CGOpenMPRuntime::getName(ArrayRef<StringRef> Parts) const {
1106
52.0k
  SmallString<128> Buffer;
1107
52.0k
  llvm::raw_svector_ostream OS(Buffer);
1108
52.0k
  StringRef Sep = FirstSeparator;
1109
100k
  for (StringRef Part : Parts) {
1110
100k
    OS << Sep << Part;
1111
100k
    Sep = Separator;
1112
100k
  }
1113
52.0k
  return std::string(OS.str());
1114
52.0k
}
1115
1116
static llvm::Function *
1117
emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty,
1118
                          const Expr *CombinerInitializer, const VarDecl *In,
1119
226
                          const VarDecl *Out, bool IsCombiner) {
1120
  // void .omp_combiner.(Ty *in, Ty *out);
1121
226
  ASTContext &C = CGM.getContext();
1122
226
  QualType PtrTy = C.getPointerType(Ty).withRestrict();
1123
226
  FunctionArgList Args;
1124
226
  ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(),
1125
226
                               /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
1126
226
  ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(),
1127
226
                              /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other);
1128
226
  Args.push_back(&OmpOutParm);
1129
226
  Args.push_back(&OmpInParm);
1130
226
  const CGFunctionInfo &FnInfo =
1131
226
      CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
1132
226
  llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo);
1133
226
  std::string Name = CGM.getOpenMPRuntime().getName(
1134
226
      {IsCombiner ? 
"omp_combiner"147
:
"omp_initializer"79
, ""});
1135
226
  auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage,
1136
226
                                    Name, &CGM.getModule());
1137
226
  CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo);
1138
226
  if (CGM.getLangOpts().Optimize) {
1139
0
    Fn->removeFnAttr(llvm::Attribute::NoInline);
1140
0
    Fn->removeFnAttr(llvm::Attribute::OptimizeNone);
1141
0
    Fn->addFnAttr(llvm::Attribute::AlwaysInline);
1142
0
  }
1143
226
  CodeGenFunction CGF(CGM);
1144
  // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions.
1145
  // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions.
1146
226
  CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, In->getLocation(),
1147
226
                    Out->getLocation());
1148
226
  CodeGenFunction::OMPPrivateScope Scope(CGF);
1149
226
  Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm);
1150
226
  Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() {
1151
226
    return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>())
1152
226
        .getAddress(CGF);
1153
226
  });
1154
226
  Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm);
1155
226
  Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() {
1156
226
    return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>())
1157
226
        .getAddress(CGF);
1158
226
  });
1159
226
  (void)Scope.Privatize();
1160
226
  if (!IsCombiner && 
Out->hasInit()79
&&
1161
226
      
!CGF.isTrivialInitializer(Out->getInit())50
) {
1162
50
    CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out),
1163
50
                         Out->getType().getQualifiers(),
1164
50
                         /*IsInitializer=*/true);
1165
50
  }
1166
226
  if (CombinerInitializer)
1167
176
    CGF.EmitIgnoredExpr(CombinerInitializer);
1168
226
  Scope.ForceCleanup();
1169
226
  CGF.FinishFunction();
1170
226
  return Fn;
1171
226
}
1172
1173
void CGOpenMPRuntime::emitUserDefinedReduction(
1174
148
    CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) {
1175
148
  if (UDRMap.count(D) > 0)
1176
1
    return;
1177
147
  llvm::Function *Combiner = emitCombinerOrInitializer(
1178
147
      CGM, D->getType(), D->getCombiner(),
1179
147
      cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerIn())->getDecl()),
1180
147
      cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerOut())->getDecl()),
1181
147
      /*IsCombiner=*/true);
1182
147
  llvm::Function *Initializer = nullptr;
1183
147
  if (const Expr *Init = D->getInitializer()) {
1184
79
    Initializer = emitCombinerOrInitializer(
1185
79
        CGM, D->getType(),
1186
79
        D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? 
Init29
1187
79
                                                                     : 
nullptr50
,
1188
79
        cast<VarDecl>(cast<DeclRefExpr>(D->getInitOrig())->getDecl()),
1189
79
        cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl()),
1190
79
        /*IsCombiner=*/false);
1191
79
  }
1192
147
  UDRMap.try_emplace(D, Combiner, Initializer);
1193
147
  if (CGF) {
1194
48
    auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn);
1195
48
    Decls.second.push_back(D);
1196
48
  }
1197
147
}
1198
1199
std::pair<llvm::Function *, llvm::Function *>
1200
258
CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) {
1201
258
  auto I = UDRMap.find(D);
1202
258
  if (I != UDRMap.end())
1203
224
    return I->second;
1204
34
  emitUserDefinedReduction(/*CGF=*/nullptr, D);
1205
34
  return UDRMap.lookup(D);
1206
258
}
1207
1208
namespace {
1209
// Temporary RAII solution to perform a push/pop stack event on the OpenMP IR
1210
// Builder if one is present.
1211
struct PushAndPopStackRAII {
1212
  PushAndPopStackRAII(llvm::OpenMPIRBuilder *OMPBuilder, CodeGenFunction &CGF,
1213
                      bool HasCancel, llvm::omp::Directive Kind)
1214
11.9k
      : OMPBuilder(OMPBuilder) {
1215
11.9k
    if (!OMPBuilder)
1216
0
      return;
1217
1218
    // The following callback is the crucial part of clangs cleanup process.
1219
    //
1220
    // NOTE:
1221
    // Once the OpenMPIRBuilder is used to create parallel regions (and
1222
    // similar), the cancellation destination (Dest below) is determined via
1223
    // IP. That means if we have variables to finalize we split the block at IP,
1224
    // use the new block (=BB) as destination to build a JumpDest (via
1225
    // getJumpDestInCurrentScope(BB)) which then is fed to
1226
    // EmitBranchThroughCleanup. Furthermore, there will not be the need
1227
    // to push & pop an FinalizationInfo object.
1228
    // The FiniCB will still be needed but at the point where the
1229
    // OpenMPIRBuilder is asked to construct a parallel (or similar) construct.
1230
11.9k
    auto FiniCB = [&CGF](llvm::OpenMPIRBuilder::InsertPointTy IP) {
1231
8
      assert(IP.getBlock()->end() == IP.getPoint() &&
1232
8
             "Clang CG should cause non-terminated block!");
1233
0
      CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1234
8
      CGF.Builder.restoreIP(IP);
1235
8
      CodeGenFunction::JumpDest Dest =
1236
8
          CGF.getOMPCancelDestination(OMPD_parallel);
1237
8
      CGF.EmitBranchThroughCleanup(Dest);
1238
8
    };
1239
1240
    // TODO: Remove this once we emit parallel regions through the
1241
    //       OpenMPIRBuilder as it can do this setup internally.
1242
11.9k
    llvm::OpenMPIRBuilder::FinalizationInfo FI({FiniCB, Kind, HasCancel});
1243
11.9k
    OMPBuilder->pushFinalizationCB(std::move(FI));
1244
11.9k
  }
1245
11.9k
  ~PushAndPopStackRAII() {
1246
11.9k
    if (OMPBuilder)
1247
11.9k
      OMPBuilder->popFinalizationCB();
1248
11.9k
  }
1249
  llvm::OpenMPIRBuilder *OMPBuilder;
1250
};
1251
} // namespace
1252
1253
static llvm::Function *emitParallelOrTeamsOutlinedFunction(
1254
    CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS,
1255
    const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind,
1256
11.9k
    const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) {
1257
11.9k
  assert(ThreadIDVar->getType()->isPointerType() &&
1258
11.9k
         "thread id variable must be of type kmp_int32 *");
1259
0
  CodeGenFunction CGF(CGM, true);
1260
11.9k
  bool HasCancel = false;
1261
11.9k
  if (const auto *OPD = dyn_cast<OMPParallelDirective>(&D))
1262
994
    HasCancel = OPD->hasCancel();
1263
10.9k
  else if (const auto *OPD = dyn_cast<OMPTargetParallelDirective>(&D))
1264
922
    HasCancel = OPD->hasCancel();
1265
9.99k
  else if (const auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D))
1266
26
    HasCancel = OPSD->hasCancel();
1267
9.96k
  else if (const auto *OPFD = dyn_cast<OMPParallelForDirective>(&D))
1268
266
    HasCancel = OPFD->hasCancel();
1269
9.70k
  else if (const auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D))
1270
557
    HasCancel = OPFD->hasCancel();
1271
9.14k
  else if (const auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&D))
1272
401
    HasCancel = OPFD->hasCancel();
1273
8.74k
  else if (const auto *OPFD =
1274
8.74k
               dyn_cast<OMPTeamsDistributeParallelForDirective>(&D))
1275
680
    HasCancel = OPFD->hasCancel();
1276
8.06k
  else if (const auto *OPFD =
1277
8.06k
               dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D))
1278
1.21k
    HasCancel = OPFD->hasCancel();
1279
1280
  // TODO: Temporarily inform the OpenMPIRBuilder, if any, about the new
1281
  //       parallel region to make cancellation barriers work properly.
1282
11.9k
  llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder();
1283
11.9k
  PushAndPopStackRAII PSR(&OMPBuilder, CGF, HasCancel, InnermostKind);
1284
11.9k
  CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind,
1285
11.9k
                                    HasCancel, OutlinedHelperName);
1286
11.9k
  CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
1287
11.9k
  return CGF.GenerateOpenMPCapturedStmtFunction(*CS, D.getBeginLoc());
1288
11.9k
}
1289
1290
llvm::Function *CGOpenMPRuntime::emitParallelOutlinedFunction(
1291
    const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1292
6.19k
    OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1293
6.19k
  const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel);
1294
6.19k
  return emitParallelOrTeamsOutlinedFunction(
1295
6.19k
      CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1296
6.19k
}
1297
1298
llvm::Function *CGOpenMPRuntime::emitTeamsOutlinedFunction(
1299
    const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1300
5.71k
    OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) {
1301
5.71k
  const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams);
1302
5.71k
  return emitParallelOrTeamsOutlinedFunction(
1303
5.71k
      CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen);
1304
5.71k
}
1305
1306
llvm::Function *CGOpenMPRuntime::emitTaskOutlinedFunction(
1307
    const OMPExecutableDirective &D, const VarDecl *ThreadIDVar,
1308
    const VarDecl *PartIDVar, const VarDecl *TaskTVar,
1309
    OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen,
1310
869
    bool Tied, unsigned &NumberOfParts) {
1311
869
  auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF,
1312
869
                                              PrePostActionTy &) {
1313
30
    llvm::Value *ThreadID = getThreadID(CGF, D.getBeginLoc());
1314
30
    llvm::Value *UpLoc = emitUpdateLocation(CGF, D.getBeginLoc());
1315
30
    llvm::Value *TaskArgs[] = {
1316
30
        UpLoc, ThreadID,
1317
30
        CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar),
1318
30
                                    TaskTVar->getType()->castAs<PointerType>())
1319
30
            .getPointer(CGF)};
1320
30
    CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1321
30
                            CGM.getModule(), OMPRTL___kmpc_omp_task),
1322
30
                        TaskArgs);
1323
30
  };
1324
869
  CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar,
1325
869
                                                            UntiedCodeGen);
1326
869
  CodeGen.setAction(Action);
1327
869
  assert(!ThreadIDVar->getType()->isPointerType() &&
1328
869
         "thread id variable must be of type kmp_int32 for tasks");
1329
0
  const OpenMPDirectiveKind Region =
1330
869
      isOpenMPTaskLoopDirective(D.getDirectiveKind()) ? 
OMPD_taskloop226
1331
869
                                                      : 
OMPD_task643
;
1332
869
  const CapturedStmt *CS = D.getCapturedStmt(Region);
1333
869
  bool HasCancel = false;
1334
869
  if (const auto *TD = dyn_cast<OMPTaskDirective>(&D))
1335
183
    HasCancel = TD->hasCancel();
1336
686
  else if (const auto *TD = dyn_cast<OMPTaskLoopDirective>(&D))
1337
39
    HasCancel = TD->hasCancel();
1338
647
  else if (const auto *TD = dyn_cast<OMPMasterTaskLoopDirective>(&D))
1339
35
    HasCancel = TD->hasCancel();
1340
612
  else if (const auto *TD = dyn_cast<OMPParallelMasterTaskLoopDirective>(&D))
1341
33
    HasCancel = TD->hasCancel();
1342
1343
869
  CodeGenFunction CGF(CGM, true);
1344
869
  CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen,
1345
869
                                        InnermostKind, HasCancel, Action);
1346
869
  CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo);
1347
869
  llvm::Function *Res = CGF.GenerateCapturedStmtFunction(*CS);
1348
869
  if (!Tied)
1349
16
    NumberOfParts = Action.getNumberOfParts();
1350
869
  return Res;
1351
869
}
1352
1353
static void buildStructValue(ConstantStructBuilder &Fields, CodeGenModule &CGM,
1354
                             const RecordDecl *RD, const CGRecordLayout &RL,
1355
11.0k
                             ArrayRef<llvm::Constant *> Data) {
1356
11.0k
  llvm::StructType *StructTy = RL.getLLVMType();
1357
11.0k
  unsigned PrevIdx = 0;
1358
11.0k
  ConstantInitBuilder CIBuilder(CGM);
1359
11.0k
  auto DI = Data.begin();
1360
55.2k
  for (const FieldDecl *FD : RD->fields()) {
1361
55.2k
    unsigned Idx = RL.getLLVMFieldNo(FD);
1362
    // Fill the alignment.
1363
55.2k
    for (unsigned I = PrevIdx; I < Idx; 
++I0
)
1364
0
      Fields.add(llvm::Constant::getNullValue(StructTy->getElementType(I)));
1365
55.2k
    PrevIdx = Idx + 1;
1366
55.2k
    Fields.add(*DI);
1367
55.2k
    ++DI;
1368
55.2k
  }
1369
11.0k
}
1370
1371
template <class... As>
1372
static llvm::GlobalVariable *
1373
createGlobalStruct(CodeGenModule &CGM, QualType Ty, bool IsConstant,
1374
                   ArrayRef<llvm::Constant *> Data, const Twine &Name,
1375
11.0k
                   As &&... Args) {
1376
11.0k
  const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1377
11.0k
  const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1378
11.0k
  ConstantInitBuilder CIBuilder(CGM);
1379
11.0k
  ConstantStructBuilder Fields = CIBuilder.beginStruct(RL.getLLVMType());
1380
11.0k
  buildStructValue(Fields, CGM, RD, RL, Data);
1381
11.0k
  return Fields.finishAndCreateGlobal(
1382
11.0k
      Name, CGM.getContext().getAlignOfGlobalVarInChars(Ty), IsConstant,
1383
11.0k
      std::forward<As>(Args)...);
1384
11.0k
}
1385
1386
template <typename T>
1387
static void
1388
createConstantGlobalStructAndAddToParent(CodeGenModule &CGM, QualType Ty,
1389
                                         ArrayRef<llvm::Constant *> Data,
1390
                                         T &Parent) {
1391
  const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl());
1392
  const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD);
1393
  ConstantStructBuilder Fields = Parent.beginStruct(RL.getLLVMType());
1394
  buildStructValue(Fields, CGM, RD, RL, Data);
1395
  Fields.finishAndAddTo(Parent);
1396
}
1397
1398
void CGOpenMPRuntime::setLocThreadIdInsertPt(CodeGenFunction &CGF,
1399
2.60k
                                             bool AtCurrentPoint) {
1400
2.60k
  auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1401
2.60k
  assert(!Elem.second.ServiceInsertPt && "Insert point is set already.");
1402
1403
0
  llvm::Value *Undef = llvm::UndefValue::get(CGF.Int32Ty);
1404
2.60k
  if (AtCurrentPoint) {
1405
758
    Elem.second.ServiceInsertPt = new llvm::BitCastInst(
1406
758
        Undef, CGF.Int32Ty, "svcpt", CGF.Builder.GetInsertBlock());
1407
1.84k
  } else {
1408
1.84k
    Elem.second.ServiceInsertPt =
1409
1.84k
        new llvm::BitCastInst(Undef, CGF.Int32Ty, "svcpt");
1410
1.84k
    Elem.second.ServiceInsertPt->insertAfter(CGF.AllocaInsertPt);
1411
1.84k
  }
1412
2.60k
}
1413
1414
10.4k
void CGOpenMPRuntime::clearLocThreadIdInsertPt(CodeGenFunction &CGF) {
1415
10.4k
  auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1416
10.4k
  if (Elem.second.ServiceInsertPt) {
1417
2.60k
    llvm::Instruction *Ptr = Elem.second.ServiceInsertPt;
1418
2.60k
    Elem.second.ServiceInsertPt = nullptr;
1419
2.60k
    Ptr->eraseFromParent();
1420
2.60k
  }
1421
10.4k
}
1422
1423
static StringRef getIdentStringFromSourceLocation(CodeGenFunction &CGF,
1424
                                                  SourceLocation Loc,
1425
248
                                                  SmallString<128> &Buffer) {
1426
248
  llvm::raw_svector_ostream OS(Buffer);
1427
  // Build debug location
1428
248
  PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1429
248
  OS << ";" << PLoc.getFilename() << ";";
1430
248
  if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl))
1431
248
    OS << FD->getQualifiedNameAsString();
1432
248
  OS << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;";
1433
248
  return OS.str();
1434
248
}
1435
1436
llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF,
1437
                                                 SourceLocation Loc,
1438
52.0k
                                                 unsigned Flags) {
1439
52.0k
  llvm::Constant *SrcLocStr;
1440
52.0k
  if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo ||
1441
52.0k
      
Loc.isInvalid()997
) {
1442
51.0k
    SrcLocStr = OMPBuilder.getOrCreateDefaultSrcLocStr();
1443
51.0k
  } else {
1444
933
    std::string FunctionName = "";
1445
933
    if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl))
1446
921
      FunctionName = FD->getQualifiedNameAsString();
1447
933
    PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc);
1448
933
    const char *FileName = PLoc.getFilename();
1449
933
    unsigned Line = PLoc.getLine();
1450
933
    unsigned Column = PLoc.getColumn();
1451
933
    SrcLocStr =
1452
933
        OMPBuilder.getOrCreateSrcLocStr(FunctionName, FileName, Line, Column);
1453
933
  }
1454
52.0k
  unsigned Reserved2Flags = getDefaultLocationReserved2Flags();
1455
52.0k
  return OMPBuilder.getOrCreateIdent(SrcLocStr, llvm::omp::IdentFlag(Flags),
1456
52.0k
                                     Reserved2Flags);
1457
52.0k
}
1458
1459
llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF,
1460
26.3k
                                          SourceLocation Loc) {
1461
26.3k
  assert(CGF.CurFn && "No function in current CodeGenFunction.");
1462
  // If the OpenMPIRBuilder is used we need to use it for all thread id calls as
1463
  // the clang invariants used below might be broken.
1464
26.3k
  if (CGM.getLangOpts().OpenMPIRBuilder) {
1465
248
    SmallString<128> Buffer;
1466
248
    OMPBuilder.updateToLocation(CGF.Builder.saveIP());
1467
248
    auto *SrcLocStr = OMPBuilder.getOrCreateSrcLocStr(
1468
248
        getIdentStringFromSourceLocation(CGF, Loc, Buffer));
1469
248
    return OMPBuilder.getOrCreateThreadID(
1470
248
        OMPBuilder.getOrCreateIdent(SrcLocStr));
1471
248
  }
1472
1473
26.1k
  llvm::Value *ThreadID = nullptr;
1474
  // Check whether we've already cached a load of the thread id in this
1475
  // function.
1476
26.1k
  auto I = OpenMPLocThreadIDMap.find(CGF.CurFn);
1477
26.1k
  if (I != OpenMPLocThreadIDMap.end()) {
1478
12.0k
    ThreadID = I->second.ThreadID;
1479
12.0k
    if (ThreadID != nullptr)
1480
11.4k
      return ThreadID;
1481
12.0k
  }
1482
  // If exceptions are enabled, do not use parameter to avoid possible crash.
1483
14.7k
  if (auto *OMPRegionInfo =
1484
14.7k
          dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) {
1485
14.0k
    if (OMPRegionInfo->getThreadIDVariable()) {
1486
      // Check if this an outlined function with thread id passed as argument.
1487
12.2k
      LValue LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF);
1488
12.2k
      llvm::BasicBlock *TopBlock = CGF.AllocaInsertPt->getParent();
1489
12.2k
      if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions ||
1490
12.2k
          
!CGF.getLangOpts().CXXExceptions850
||
1491
12.2k
          
CGF.Builder.GetInsertBlock() == TopBlock850
||
1492
12.2k
          
!isa<llvm::Instruction>(LVal.getPointer(CGF))318
||
1493
12.2k
          cast<llvm::Instruction>(LVal.getPointer(CGF))->getParent() ==
1494
318
              TopBlock ||
1495
12.2k
          cast<llvm::Instruction>(LVal.getPointer(CGF))->getParent() ==
1496
12.2k
              CGF.Builder.GetInsertBlock()) {
1497
12.2k
        ThreadID = CGF.EmitLoadOfScalar(LVal, Loc);
1498
        // If value loaded in entry block, cache it and use it everywhere in
1499
        // function.
1500
12.2k
        if (CGF.Builder.GetInsertBlock() == TopBlock) {
1501
7.12k
          auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1502
7.12k
          Elem.second.ThreadID = ThreadID;
1503
7.12k
        }
1504
12.2k
        return ThreadID;
1505
12.2k
      }
1506
12.2k
    }
1507
14.0k
  }
1508
1509
  // This is not an outlined function region - need to call __kmpc_int32
1510
  // kmpc_global_thread_num(ident_t *loc).
1511
  // Generate thread id value and cache this value for use across the
1512
  // function.
1513
2.43k
  auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn);
1514
2.43k
  if (!Elem.second.ServiceInsertPt)
1515
1.84k
    setLocThreadIdInsertPt(CGF);
1516
2.43k
  CGBuilderTy::InsertPointGuard IPG(CGF.Builder);
1517
2.43k
  CGF.Builder.SetInsertPoint(Elem.second.ServiceInsertPt);
1518
2.43k
  llvm::CallInst *Call = CGF.Builder.CreateCall(
1519
2.43k
      OMPBuilder.getOrCreateRuntimeFunction(CGM.getModule(),
1520
2.43k
                                            OMPRTL___kmpc_global_thread_num),
1521
2.43k
      emitUpdateLocation(CGF, Loc));
1522
2.43k
  Call->setCallingConv(CGF.getRuntimeCC());
1523
2.43k
  Elem.second.ThreadID = Call;
1524
2.43k
  return Call;
1525
14.7k
}
1526
1527
70.4k
void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) {
1528
70.4k
  assert(CGF.CurFn && "No function in current CodeGenFunction.");
1529
70.4k
  if (OpenMPLocThreadIDMap.count(CGF.CurFn)) {
1530
9.73k
    clearLocThreadIdInsertPt(CGF);
1531
9.73k
    OpenMPLocThreadIDMap.erase(CGF.CurFn);
1532
9.73k
  }
1533
70.4k
  if (FunctionUDRMap.count(CGF.CurFn) > 0) {
1534
32
    for(const auto *D : FunctionUDRMap[CGF.CurFn])
1535
48
      UDRMap.erase(D);
1536
32
    FunctionUDRMap.erase(CGF.CurFn);
1537
32
  }
1538
70.4k
  auto I = FunctionUDMMap.find(CGF.CurFn);
1539
70.4k
  if (I != FunctionUDMMap.end()) {
1540
0
    for(const auto *D : I->second)
1541
0
      UDMMap.erase(D);
1542
0
    FunctionUDMMap.erase(I);
1543
0
  }
1544
70.4k
  LastprivateConditionalToTypes.erase(CGF.CurFn);
1545
70.4k
  FunctionToUntiedTaskStackMap.erase(CGF.CurFn);
1546
70.4k
}
1547
1548
10.2k
llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() {
1549
10.2k
  return OMPBuilder.IdentPtr;
1550
10.2k
}
1551
1552
10.7k
llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() {
1553
10.7k
  if (!Kmpc_MicroTy) {
1554
    // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...)
1555
1.90k
    llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty),
1556
1.90k
                                 llvm::PointerType::getUnqual(CGM.Int32Ty)};
1557
1.90k
    Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true);
1558
1.90k
  }
1559
10.7k
  return llvm::PointerType::getUnqual(Kmpc_MicroTy);
1560
10.7k
}
1561
1562
llvm::FunctionCallee
1563
8.63k
CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize, bool IVSigned) {
1564
8.63k
  assert((IVSize == 32 || IVSize == 64) &&
1565
8.63k
         "IV size is not compatible with the omp runtime");
1566
8.63k
  StringRef Name = IVSize == 32 ? 
(8.28k
IVSigned8.28k
?
"__kmpc_for_static_init_4"8.10k
1567
8.28k
                                            : 
"__kmpc_for_static_init_4u"176
)
1568
8.63k
                                : 
(349
IVSigned349
?
"__kmpc_for_static_init_8"241
1569
349
                                            : 
"__kmpc_for_static_init_8u"108
);
1570
8.63k
  llvm::Type *ITy = IVSize == 32 ? 
CGM.Int32Ty8.28k
:
CGM.Int64Ty349
;
1571
8.63k
  auto *PtrTy = llvm::PointerType::getUnqual(ITy);
1572
8.63k
  llvm::Type *TypeParams[] = {
1573
8.63k
    getIdentTyPointerTy(),                     // loc
1574
8.63k
    CGM.Int32Ty,                               // tid
1575
8.63k
    CGM.Int32Ty,                               // schedtype
1576
8.63k
    llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1577
8.63k
    PtrTy,                                     // p_lower
1578
8.63k
    PtrTy,                                     // p_upper
1579
8.63k
    PtrTy,                                     // p_stride
1580
8.63k
    ITy,                                       // incr
1581
8.63k
    ITy                                        // chunk
1582
8.63k
  };
1583
8.63k
  auto *FnTy =
1584
8.63k
      llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1585
8.63k
  return CGM.CreateRuntimeFunction(FnTy, Name);
1586
8.63k
}
1587
1588
llvm::FunctionCallee
1589
764
CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize, bool IVSigned) {
1590
764
  assert((IVSize == 32 || IVSize == 64) &&
1591
764
         "IV size is not compatible with the omp runtime");
1592
0
  StringRef Name =
1593
764
      IVSize == 32
1594
764
          ? 
(715
IVSigned715
?
"__kmpc_dispatch_init_4"707
:
"__kmpc_dispatch_init_4u"8
)
1595
764
          : 
(49
IVSigned49
?
"__kmpc_dispatch_init_8"19
:
"__kmpc_dispatch_init_8u"30
);
1596
764
  llvm::Type *ITy = IVSize == 32 ? 
CGM.Int32Ty715
:
CGM.Int64Ty49
;
1597
764
  llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc
1598
764
                               CGM.Int32Ty,           // tid
1599
764
                               CGM.Int32Ty,           // schedtype
1600
764
                               ITy,                   // lower
1601
764
                               ITy,                   // upper
1602
764
                               ITy,                   // stride
1603
764
                               ITy                    // chunk
1604
764
  };
1605
764
  auto *FnTy =
1606
764
      llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false);
1607
764
  return CGM.CreateRuntimeFunction(FnTy, Name);
1608
764
}
1609
1610
llvm::FunctionCallee
1611
57
CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize, bool IVSigned) {
1612
57
  assert((IVSize == 32 || IVSize == 64) &&
1613
57
         "IV size is not compatible with the omp runtime");
1614
0
  StringRef Name =
1615
57
      IVSize == 32
1616
57
          ? 
(41
IVSigned41
?
"__kmpc_dispatch_fini_4"33
:
"__kmpc_dispatch_fini_4u"8
)
1617
57
          : 
(16
IVSigned16
?
"__kmpc_dispatch_fini_8"8
:
"__kmpc_dispatch_fini_8u"8
);
1618
57
  llvm::Type *TypeParams[] = {
1619
57
      getIdentTyPointerTy(), // loc
1620
57
      CGM.Int32Ty,           // tid
1621
57
  };
1622
57
  auto *FnTy =
1623
57
      llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false);
1624
57
  return CGM.CreateRuntimeFunction(FnTy, Name);
1625
57
}
1626
1627
llvm::FunctionCallee
1628
764
CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize, bool IVSigned) {
1629
764
  assert((IVSize == 32 || IVSize == 64) &&
1630
764
         "IV size is not compatible with the omp runtime");
1631
0
  StringRef Name =
1632
764
      IVSize == 32
1633
764
          ? 
(715
IVSigned715
?
"__kmpc_dispatch_next_4"707
:
"__kmpc_dispatch_next_4u"8
)
1634
764
          : 
(49
IVSigned49
?
"__kmpc_dispatch_next_8"19
:
"__kmpc_dispatch_next_8u"30
);
1635
764
  llvm::Type *ITy = IVSize == 32 ? 
CGM.Int32Ty715
:
CGM.Int64Ty49
;
1636
764
  auto *PtrTy = llvm::PointerType::getUnqual(ITy);
1637
764
  llvm::Type *TypeParams[] = {
1638
764
    getIdentTyPointerTy(),                     // loc
1639
764
    CGM.Int32Ty,                               // tid
1640
764
    llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter
1641
764
    PtrTy,                                     // p_lower
1642
764
    PtrTy,                                     // p_upper
1643
764
    PtrTy                                      // p_stride
1644
764
  };
1645
764
  auto *FnTy =
1646
764
      llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false);
1647
764
  return CGM.CreateRuntimeFunction(FnTy, Name);
1648
764
}
1649
1650
/// Obtain information that uniquely identifies a target entry. This
1651
/// consists of the file and device IDs as well as line number associated with
1652
/// the relevant entry source location.
1653
static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc,
1654
                                     unsigned &DeviceID, unsigned &FileID,
1655
15.9k
                                     unsigned &LineNum) {
1656
15.9k
  SourceManager &SM = C.getSourceManager();
1657
1658
  // The loc should be always valid and have a file ID (the user cannot use
1659
  // #pragma directives in macros)
1660
1661
15.9k
  assert(Loc.isValid() && "Source location is expected to be always valid.");
1662
1663
0
  PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1664
15.9k
  assert(PLoc.isValid() && "Source location is expected to be always valid.");
1665
1666
0
  llvm::sys::fs::UniqueID ID;
1667
15.9k
  if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) {
1668
1
    PLoc = SM.getPresumedLoc(Loc, /*UseLineDirectives=*/false);
1669
1
    assert(PLoc.isValid() && "Source location is expected to be always valid.");
1670
1
    if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID))
1671
0
      SM.getDiagnostics().Report(diag::err_cannot_open_file)
1672
0
          << PLoc.getFilename() << EC.message();
1673
1
  }
1674
1675
0
  DeviceID = ID.getDevice();
1676
15.9k
  FileID = ID.getFile();
1677
15.9k
  LineNum = PLoc.getLine();
1678
15.9k
}
1679
1680
518
Address CGOpenMPRuntime::getAddrOfDeclareTargetVar(const VarDecl *VD) {
1681
518
  if (CGM.getLangOpts().OpenMPSimd)
1682
20
    return Address::invalid();
1683
498
  llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
1684
498
      OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
1685
498
  if (Res && (*Res == OMPDeclareTargetDeclAttr::MT_Link ||
1686
498
              
(44
*Res == OMPDeclareTargetDeclAttr::MT_To44
&&
1687
498
               
HasRequiresUnifiedSharedMemory44
))) {
1688
498
    SmallString<64> PtrName;
1689
498
    {
1690
498
      llvm::raw_svector_ostream OS(PtrName);
1691
498
      OS << CGM.getMangledName(GlobalDecl(VD));
1692
498
      if (!VD->isExternallyVisible()) {
1693
34
        unsigned DeviceID, FileID, Line;
1694
34
        getTargetEntryUniqueInfo(CGM.getContext(),
1695
34
                                 VD->getCanonicalDecl()->getBeginLoc(),
1696
34
                                 DeviceID, FileID, Line);
1697
34
        OS << llvm::format("_%x", FileID);
1698
34
      }
1699
498
      OS << "_decl_tgt_ref_ptr";
1700
498
    }
1701
498
    llvm::Value *Ptr = CGM.getModule().getNamedValue(PtrName);
1702
498
    if (!Ptr) {
1703
58
      QualType PtrTy = CGM.getContext().getPointerType(VD->getType());
1704
58
      Ptr = getOrCreateInternalVariable(CGM.getTypes().ConvertTypeForMem(PtrTy),
1705
58
                                        PtrName);
1706
1707
58
      auto *GV = cast<llvm::GlobalVariable>(Ptr);
1708
58
      GV->setLinkage(llvm::GlobalValue::WeakAnyLinkage);
1709
1710
58
      if (!CGM.getLangOpts().OpenMPIsDevice)
1711
38
        GV->setInitializer(CGM.GetAddrOfGlobal(VD));
1712
58
      registerTargetGlobalVariable(VD, cast<llvm::Constant>(Ptr));
1713
58
    }
1714
498
    return Address(Ptr, CGM.getContext().getDeclAlign(VD));
1715
498
  }
1716
0
  return Address::invalid();
1717
498
}
1718
1719
llvm::Constant *
1720
138
CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) {
1721
138
  assert(!CGM.getLangOpts().OpenMPUseTLS ||
1722
138
         !CGM.getContext().getTargetInfo().isTLSSupported());
1723
  // Lookup the entry, lazily creating it if necessary.
1724
0
  std::string Suffix = getName({"cache", ""});
1725
138
  return getOrCreateInternalVariable(
1726
138
      CGM.Int8PtrPtrTy, Twine(CGM.getMangledName(VD)).concat(Suffix));
1727
138
}
1728
1729
Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF,
1730
                                                const VarDecl *VD,
1731
                                                Address VDAddr,
1732
241
                                                SourceLocation Loc) {
1733
241
  if (CGM.getLangOpts().OpenMPUseTLS &&
1734
241
      
CGM.getContext().getTargetInfo().isTLSSupported()103
)
1735
103
    return VDAddr;
1736
1737
138
  llvm::Type *VarTy = VDAddr.getElementType();
1738
138
  llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
1739
138
                         CGF.Builder.CreatePointerCast(VDAddr.getPointer(),
1740
138
                                                       CGM.Int8PtrTy),
1741
138
                         CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)),
1742
138
                         getOrCreateThreadPrivateCache(VD)};
1743
138
  return Address(CGF.EmitRuntimeCall(
1744
138
                     OMPBuilder.getOrCreateRuntimeFunction(
1745
138
                         CGM.getModule(), OMPRTL___kmpc_threadprivate_cached),
1746
138
                     Args),
1747
138
                 VDAddr.getAlignment());
1748
241
}
1749
1750
void CGOpenMPRuntime::emitThreadPrivateVarInit(
1751
    CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor,
1752
37
    llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) {
1753
  // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime
1754
  // library.
1755
37
  llvm::Value *OMPLoc = emitUpdateLocation(CGF, Loc);
1756
37
  CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
1757
37
                          CGM.getModule(), OMPRTL___kmpc_global_thread_num),
1758
37
                      OMPLoc);
1759
  // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor)
1760
  // to register constructor/destructor for variable.
1761
37
  llvm::Value *Args[] = {
1762
37
      OMPLoc, CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.VoidPtrTy),
1763
37
      Ctor, CopyCtor, Dtor};
1764
37
  CGF.EmitRuntimeCall(
1765
37
      OMPBuilder.getOrCreateRuntimeFunction(
1766
37
          CGM.getModule(), OMPRTL___kmpc_threadprivate_register),
1767
37
      Args);
1768
37
}
1769
1770
llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition(
1771
    const VarDecl *VD, Address VDAddr, SourceLocation Loc,
1772
151
    bool PerformInit, CodeGenFunction *CGF) {
1773
151
  if (CGM.getLangOpts().OpenMPUseTLS &&
1774
151
      
CGM.getContext().getTargetInfo().isTLSSupported()71
)
1775
71
    return nullptr;
1776
1777
80
  VD = VD->getDefinition(CGM.getContext());
1778
80
  if (VD && 
ThreadPrivateWithDefinition.insert(CGM.getMangledName(VD)).second68
) {
1779
48
    QualType ASTTy = VD->getType();
1780
1781
48
    llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr;
1782
48
    const Expr *Init = VD->getAnyInitializer();
1783
48
    if (CGM.getLangOpts().CPlusPlus && PerformInit) {
1784
      // Generate function that re-emits the declaration's initializer into the
1785
      // threadprivate copy of the variable VD
1786
37
      CodeGenFunction CtorCGF(CGM);
1787
37
      FunctionArgList Args;
1788
37
      ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
1789
37
                            /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
1790
37
                            ImplicitParamDecl::Other);
1791
37
      Args.push_back(&Dst);
1792
1793
37
      const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1794
37
          CGM.getContext().VoidPtrTy, Args);
1795
37
      llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
1796
37
      std::string Name = getName({"__kmpc_global_ctor_", ""});
1797
37
      llvm::Function *Fn =
1798
37
          CGM.CreateGlobalInitOrCleanUpFunction(FTy, Name, FI, Loc);
1799
37
      CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI,
1800
37
                            Args, Loc, Loc);
1801
37
      llvm::Value *ArgVal = CtorCGF.EmitLoadOfScalar(
1802
37
          CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
1803
37
          CGM.getContext().VoidPtrTy, Dst.getLocation());
1804
37
      Address Arg = Address(ArgVal, VDAddr.getAlignment());
1805
37
      Arg = CtorCGF.Builder.CreateElementBitCast(
1806
37
          Arg, CtorCGF.ConvertTypeForMem(ASTTy));
1807
37
      CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(),
1808
37
                               /*IsInitializer=*/true);
1809
37
      ArgVal = CtorCGF.EmitLoadOfScalar(
1810
37
          CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false,
1811
37
          CGM.getContext().VoidPtrTy, Dst.getLocation());
1812
37
      CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue);
1813
37
      CtorCGF.FinishFunction();
1814
37
      Ctor = Fn;
1815
37
    }
1816
48
    if (VD->getType().isDestructedType() != QualType::DK_none) {
1817
      // Generate function that emits destructor call for the threadprivate copy
1818
      // of the variable VD
1819
35
      CodeGenFunction DtorCGF(CGM);
1820
35
      FunctionArgList Args;
1821
35
      ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc,
1822
35
                            /*Id=*/nullptr, CGM.getContext().VoidPtrTy,
1823
35
                            ImplicitParamDecl::Other);
1824
35
      Args.push_back(&Dst);
1825
1826
35
      const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration(
1827
35
          CGM.getContext().VoidTy, Args);
1828
35
      llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
1829
35
      std::string Name = getName({"__kmpc_global_dtor_", ""});
1830
35
      llvm::Function *Fn =
1831
35
          CGM.CreateGlobalInitOrCleanUpFunction(FTy, Name, FI, Loc);
1832
35
      auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
1833
35
      DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args,
1834
35
                            Loc, Loc);
1835
      // Create a scope with an artificial location for the body of this function.
1836
35
      auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
1837
35
      llvm::Value *ArgVal = DtorCGF.EmitLoadOfScalar(
1838
35
          DtorCGF.GetAddrOfLocalVar(&Dst),
1839
35
          /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation());
1840
35
      DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy,
1841
35
                          DtorCGF.getDestroyer(ASTTy.isDestructedType()),
1842
35
                          DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
1843
35
      DtorCGF.FinishFunction();
1844
35
      Dtor = Fn;
1845
35
    }
1846
    // Do not emit init function if it is not required.
1847
48
    if (!Ctor && 
!Dtor11
)
1848
11
      return nullptr;
1849
1850
37
    llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy};
1851
37
    auto *CopyCtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs,
1852
37
                                               /*isVarArg=*/false)
1853
37
                           ->getPointerTo();
1854
    // Copying constructor for the threadprivate variable.
1855
    // Must be NULL - reserved by runtime, but currently it requires that this
1856
    // parameter is always NULL. Otherwise it fires assertion.
1857
37
    CopyCtor = llvm::Constant::getNullValue(CopyCtorTy);
1858
37
    if (Ctor == nullptr) {
1859
0
      auto *CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy,
1860
0
                                             /*isVarArg=*/false)
1861
0
                         ->getPointerTo();
1862
0
      Ctor = llvm::Constant::getNullValue(CtorTy);
1863
0
    }
1864
37
    if (Dtor == nullptr) {
1865
2
      auto *DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy,
1866
2
                                             /*isVarArg=*/false)
1867
2
                         ->getPointerTo();
1868
2
      Dtor = llvm::Constant::getNullValue(DtorTy);
1869
2
    }
1870
37
    if (!CGF) {
1871
16
      auto *InitFunctionTy =
1872
16
          llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false);
1873
16
      std::string Name = getName({"__omp_threadprivate_init_", ""});
1874
16
      llvm::Function *InitFunction = CGM.CreateGlobalInitOrCleanUpFunction(
1875
16
          InitFunctionTy, Name, CGM.getTypes().arrangeNullaryFunction());
1876
16
      CodeGenFunction InitCGF(CGM);
1877
16
      FunctionArgList ArgList;
1878
16
      InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction,
1879
16
                            CGM.getTypes().arrangeNullaryFunction(), ArgList,
1880
16
                            Loc, Loc);
1881
16
      emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
1882
16
      InitCGF.FinishFunction();
1883
16
      return InitFunction;
1884
16
    }
1885
21
    emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc);
1886
21
  }
1887
53
  return nullptr;
1888
80
}
1889
1890
bool CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD,
1891
                                                     llvm::GlobalVariable *Addr,
1892
3.89k
                                                     bool PerformInit) {
1893
3.89k
  if (CGM.getLangOpts().OMPTargetTriples.empty() &&
1894
3.89k
      
!CGM.getLangOpts().OpenMPIsDevice649
)
1895
587
    return false;
1896
3.31k
  Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
1897
3.31k
      OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
1898
3.31k
  if (!Res || 
*Res == OMPDeclareTargetDeclAttr::MT_Link147
||
1899
3.31k
      
(147
*Res == OMPDeclareTargetDeclAttr::MT_To147
&&
1900
147
       HasRequiresUnifiedSharedMemory))
1901
3.16k
    return CGM.getLangOpts().OpenMPIsDevice;
1902
147
  VD = VD->getDefinition(CGM.getContext());
1903
147
  assert(VD && "Unknown VarDecl");
1904
1905
147
  if (!DeclareTargetWithDefinition.insert(CGM.getMangledName(VD)).second)
1906
4
    return CGM.getLangOpts().OpenMPIsDevice;
1907
1908
143
  QualType ASTTy = VD->getType();
1909
143
  SourceLocation Loc = VD->getCanonicalDecl()->getBeginLoc();
1910
1911
  // Produce the unique prefix to identify the new target regions. We use
1912
  // the source location of the variable declaration which we know to not
1913
  // conflict with any target region.
1914
143
  unsigned DeviceID;
1915
143
  unsigned FileID;
1916
143
  unsigned Line;
1917
143
  getTargetEntryUniqueInfo(CGM.getContext(), Loc, DeviceID, FileID, Line);
1918
143
  SmallString<128> Buffer, Out;
1919
143
  {
1920
143
    llvm::raw_svector_ostream OS(Buffer);
1921
143
    OS << "__omp_offloading_" << llvm::format("_%x", DeviceID)
1922
143
       << llvm::format("_%x_", FileID) << VD->getName() << "_l" << Line;
1923
143
  }
1924
1925
143
  const Expr *Init = VD->getAnyInitializer();
1926
143
  if (CGM.getLangOpts().CPlusPlus && PerformInit) {
1927
143
    llvm::Constant *Ctor;
1928
143
    llvm::Constant *ID;
1929
143
    if (CGM.getLangOpts().OpenMPIsDevice) {
1930
      // Generate function that re-emits the declaration's initializer into
1931
      // the threadprivate copy of the variable VD
1932
74
      CodeGenFunction CtorCGF(CGM);
1933
1934
74
      const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
1935
74
      llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
1936
74
      llvm::Function *Fn = CGM.CreateGlobalInitOrCleanUpFunction(
1937
74
          FTy, Twine(Buffer, "_ctor"), FI, Loc);
1938
74
      auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF);
1939
74
      CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
1940
74
                            FunctionArgList(), Loc, Loc);
1941
74
      auto AL = ApplyDebugLocation::CreateArtificial(CtorCGF);
1942
74
      CtorCGF.EmitAnyExprToMem(Init,
1943
74
                               Address(Addr, CGM.getContext().getDeclAlign(VD)),
1944
74
                               Init->getType().getQualifiers(),
1945
74
                               /*IsInitializer=*/true);
1946
74
      CtorCGF.FinishFunction();
1947
74
      Ctor = Fn;
1948
74
      ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
1949
74
      CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ctor));
1950
74
    } else {
1951
69
      Ctor = new llvm::GlobalVariable(
1952
69
          CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1953
69
          llvm::GlobalValue::PrivateLinkage,
1954
69
          llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_ctor"));
1955
69
      ID = Ctor;
1956
69
    }
1957
1958
    // Register the information for the entry associated with the constructor.
1959
143
    Out.clear();
1960
143
    OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
1961
143
        DeviceID, FileID, Twine(Buffer, "_ctor").toStringRef(Out), Line, Ctor,
1962
143
        ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryCtor);
1963
143
  }
1964
143
  if (VD->getType().isDestructedType() != QualType::DK_none) {
1965
92
    llvm::Constant *Dtor;
1966
92
    llvm::Constant *ID;
1967
92
    if (CGM.getLangOpts().OpenMPIsDevice) {
1968
      // Generate function that emits destructor call for the threadprivate
1969
      // copy of the variable VD
1970
58
      CodeGenFunction DtorCGF(CGM);
1971
1972
58
      const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction();
1973
58
      llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
1974
58
      llvm::Function *Fn = CGM.CreateGlobalInitOrCleanUpFunction(
1975
58
          FTy, Twine(Buffer, "_dtor"), FI, Loc);
1976
58
      auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF);
1977
58
      DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI,
1978
58
                            FunctionArgList(), Loc, Loc);
1979
      // Create a scope with an artificial location for the body of this
1980
      // function.
1981
58
      auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF);
1982
58
      DtorCGF.emitDestroy(Address(Addr, CGM.getContext().getDeclAlign(VD)),
1983
58
                          ASTTy, DtorCGF.getDestroyer(ASTTy.isDestructedType()),
1984
58
                          DtorCGF.needsEHCleanup(ASTTy.isDestructedType()));
1985
58
      DtorCGF.FinishFunction();
1986
58
      Dtor = Fn;
1987
58
      ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy);
1988
58
      CGM.addUsedGlobal(cast<llvm::GlobalValue>(Dtor));
1989
58
    } else {
1990
34
      Dtor = new llvm::GlobalVariable(
1991
34
          CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true,
1992
34
          llvm::GlobalValue::PrivateLinkage,
1993
34
          llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_dtor"));
1994
34
      ID = Dtor;
1995
34
    }
1996
    // Register the information for the entry associated with the destructor.
1997
92
    Out.clear();
1998
92
    OffloadEntriesInfoManager.registerTargetRegionEntryInfo(
1999
92
        DeviceID, FileID, Twine(Buffer, "_dtor").toStringRef(Out), Line, Dtor,
2000
92
        ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryDtor);
2001
92
  }
2002
143
  return CGM.getLangOpts().OpenMPIsDevice;
2003
147
}
2004
2005
Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF,
2006
                                                          QualType VarType,
2007
154
                                                          StringRef Name) {
2008
154
  std::string Suffix = getName({"artificial", ""});
2009
154
  llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType);
2010
154
  llvm::Value *GAddr =
2011
154
      getOrCreateInternalVariable(VarLVType, Twine(Name).concat(Suffix));
2012
154
  if (CGM.getLangOpts().OpenMP && CGM.getLangOpts().OpenMPUseTLS &&
2013
154
      
CGM.getTarget().isTLSSupported()119
) {
2014
83
    cast<llvm::GlobalVariable>(GAddr)->setThreadLocal(/*Val=*/true);
2015
83
    return Address(GAddr, CGM.getContext().getTypeAlignInChars(VarType));
2016
83
  }
2017
71
  std::string CacheSuffix = getName({"cache", ""});
2018
71
  llvm::Value *Args[] = {
2019
71
      emitUpdateLocation(CGF, SourceLocation()),
2020
71
      getThreadID(CGF, SourceLocation()),
2021
71
      CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy),
2022
71
      CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy,
2023
71
                                /*isSigned=*/false),
2024
71
      getOrCreateInternalVariable(
2025
71
          CGM.VoidPtrPtrTy, Twine(Name).concat(Suffix).concat(CacheSuffix))};
2026
71
  return Address(
2027
71
      CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2028
71
          CGF.EmitRuntimeCall(
2029
71
              OMPBuilder.getOrCreateRuntimeFunction(
2030
71
                  CGM.getModule(), OMPRTL___kmpc_threadprivate_cached),
2031
71
              Args),
2032
71
          VarLVType->getPointerTo(/*AddrSpace=*/0)),
2033
71
      CGM.getContext().getTypeAlignInChars(VarType));
2034
154
}
2035
2036
void CGOpenMPRuntime::emitIfClause(CodeGenFunction &CGF, const Expr *Cond,
2037
                                   const RegionCodeGenTy &ThenGen,
2038
2.53k
                                   const RegionCodeGenTy &ElseGen) {
2039
2.53k
  CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange());
2040
2041
  // If the condition constant folds and can be elided, try to avoid emitting
2042
  // the condition and the dead arm of the if/else.
2043
2.53k
  bool CondConstant;
2044
2.53k
  if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) {
2045
1.30k
    if (CondConstant)
2046
754
      ThenGen(CGF);
2047
550
    else
2048
550
      ElseGen(CGF);
2049
1.30k
    return;
2050
1.30k
  }
2051
2052
  // Otherwise, the condition did not fold, or we couldn't elide it.  Just
2053
  // emit the conditional branch.
2054
1.22k
  llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("omp_if.then");
2055
1.22k
  llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else");
2056
1.22k
  llvm::BasicBlock *ContBlock = CGF.createBasicBlock("omp_if.end");
2057
1.22k
  CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0);
2058
2059
  // Emit the 'then' code.
2060
1.22k
  CGF.EmitBlock(ThenBlock);
2061
1.22k
  ThenGen(CGF);
2062
1.22k
  CGF.EmitBranch(ContBlock);
2063
  // Emit the 'else' code if present.
2064
  // There is no need to emit line number for unconditional branch.
2065
1.22k
  (void)ApplyDebugLocation::CreateEmpty(CGF);
2066
1.22k
  CGF.EmitBlock(ElseBlock);
2067
1.22k
  ElseGen(CGF);
2068
  // There is no need to emit line number for unconditional branch.
2069
1.22k
  (void)ApplyDebugLocation::CreateEmpty(CGF);
2070
1.22k
  CGF.EmitBranch(ContBlock);
2071
  // Emit the continuation block for code after the if.
2072
1.22k
  CGF.EmitBlock(ContBlock, /*IsFinished=*/true);
2073
1.22k
}
2074
2075
void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc,
2076
                                       llvm::Function *OutlinedFn,
2077
                                       ArrayRef<llvm::Value *> CapturedVars,
2078
5.62k
                                       const Expr *IfCond) {
2079
5.62k
  if (!CGF.HaveInsertPoint())
2080
0
    return;
2081
5.62k
  llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc);
2082
5.62k
  auto &M = CGM.getModule();
2083
5.62k
  auto &&ThenGen = [&M, OutlinedFn, CapturedVars, RTLoc,
2084
5.62k
                    this](CodeGenFunction &CGF, PrePostActionTy &) {
2085
    // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn);
2086
5.40k
    CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
2087
5.40k
    llvm::Value *Args[] = {
2088
5.40k
        RTLoc,
2089
5.40k
        CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars
2090
5.40k
        CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())};
2091
5.40k
    llvm::SmallVector<llvm::Value *, 16> RealArgs;
2092
5.40k
    RealArgs.append(std::begin(Args), std::end(Args));
2093
5.40k
    RealArgs.append(CapturedVars.begin(), CapturedVars.end());
2094
2095
5.40k
    llvm::FunctionCallee RTLFn =
2096
5.40k
        OMPBuilder.getOrCreateRuntimeFunction(M, OMPRTL___kmpc_fork_call);
2097
5.40k
    CGF.EmitRuntimeCall(RTLFn, RealArgs);
2098
5.40k
  };
2099
5.62k
  auto &&ElseGen = [&M, OutlinedFn, CapturedVars, RTLoc, Loc,
2100
5.62k
                    this](CodeGenFunction &CGF, PrePostActionTy &) {
2101
439
    CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime();
2102
439
    llvm::Value *ThreadID = RT.getThreadID(CGF, Loc);
2103
    // Build calls:
2104
    // __kmpc_serialized_parallel(&Loc, GTid);
2105
439
    llvm::Value *Args[] = {RTLoc, ThreadID};
2106
439
    CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2107
439
                            M, OMPRTL___kmpc_serialized_parallel),
2108
439
                        Args);
2109
2110
    // OutlinedFn(&GTid, &zero_bound, CapturedStruct);
2111
439
    Address ThreadIDAddr = RT.emitThreadIDAddress(CGF, Loc);
2112
439
    Address ZeroAddrBound =
2113
439
        CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty,
2114
439
                                         /*Name=*/".bound.zero.addr");
2115
439
    CGF.InitTempAlloca(ZeroAddrBound, CGF.Builder.getInt32(/*C*/ 0));
2116
439
    llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs;
2117
    // ThreadId for serialized parallels is 0.
2118
439
    OutlinedFnArgs.push_back(ThreadIDAddr.getPointer());
2119
439
    OutlinedFnArgs.push_back(ZeroAddrBound.getPointer());
2120
439
    OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end());
2121
2122
    // Ensure we do not inline the function. This is trivially true for the ones
2123
    // passed to __kmpc_fork_call but the ones called in serialized regions
2124
    // could be inlined. This is not a perfect but it is closer to the invariant
2125
    // we want, namely, every data environment starts with a new function.
2126
    // TODO: We should pass the if condition to the runtime function and do the
2127
    //       handling there. Much cleaner code.
2128
439
    OutlinedFn->removeFnAttr(llvm::Attribute::AlwaysInline);
2129
439
    OutlinedFn->addFnAttr(llvm::Attribute::NoInline);
2130
439
    RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs);
2131
2132
    // __kmpc_end_serialized_parallel(&Loc, GTid);
2133
439
    llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID};
2134
439
    CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2135
439
                            M, OMPRTL___kmpc_end_serialized_parallel),
2136
439
                        EndArgs);
2137
439
  };
2138
5.62k
  if (IfCond) {
2139
567
    emitIfClause(CGF, IfCond, ThenGen, ElseGen);
2140
5.05k
  } else {
2141
5.05k
    RegionCodeGenTy ThenRCG(ThenGen);
2142
5.05k
    ThenRCG(CGF);
2143
5.05k
  }
2144
5.62k
}
2145
2146
// If we're inside an (outlined) parallel region, use the region info's
2147
// thread-ID variable (it is passed in a first argument of the outlined function
2148
// as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in
2149
// regular serial code region, get thread ID by calling kmp_int32
2150
// kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and
2151
// return the address of that temp.
2152
Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF,
2153
769
                                             SourceLocation Loc) {
2154
769
  if (auto *OMPRegionInfo =
2155
769
          dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2156
734
    if (OMPRegionInfo->getThreadIDVariable())
2157
275
      return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress(CGF);
2158
2159
494
  llvm::Value *ThreadID = getThreadID(CGF, Loc);
2160
494
  QualType Int32Ty =
2161
494
      CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true);
2162
494
  Address ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp.");
2163
494
  CGF.EmitStoreOfScalar(ThreadID,
2164
494
                        CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty));
2165
2166
494
  return ThreadIDTemp;
2167
769
}
2168
2169
llvm::Constant *CGOpenMPRuntime::getOrCreateInternalVariable(
2170
1.12k
    llvm::Type *Ty, const llvm::Twine &Name, unsigned AddressSpace) {
2171
1.12k
  SmallString<256> Buffer;
2172
1.12k
  llvm::raw_svector_ostream Out(Buffer);
2173
1.12k
  Out << Name;
2174
1.12k
  StringRef RuntimeName = Out.str();
2175
1.12k
  auto &Elem = *InternalVars.try_emplace(RuntimeName, nullptr).first;
2176
1.12k
  if (Elem.second) {
2177
685
    assert(Elem.second->getType()->getPointerElementType() == Ty &&
2178
685
           "OMP internal variable has different type than requested");
2179
0
    return &*Elem.second;
2180
685
  }
2181
2182
443
  return Elem.second = new llvm::GlobalVariable(
2183
443
             CGM.getModule(), Ty, /*IsConstant*/ false,
2184
443
             llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty),
2185
443
             Elem.first(), /*InsertBefore=*/nullptr,
2186
443
             llvm::GlobalValue::NotThreadLocal, AddressSpace);
2187
1.12k
}
2188
2189
670
llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) {
2190
670
  std::string Prefix = Twine("gomp_critical_user_", CriticalName).str();
2191
670
  std::string Name = getName({Prefix, "var"});
2192
670
  return getOrCreateInternalVariable(KmpCriticalNameTy, Name);
2193
670
}
2194
2195
namespace {
2196
/// Common pre(post)-action for different OpenMP constructs.
2197
class CommonActionTy final : public PrePostActionTy {
2198
  llvm::FunctionCallee EnterCallee;
2199
  ArrayRef<llvm::Value *> EnterArgs;
2200
  llvm::FunctionCallee ExitCallee;
2201
  ArrayRef<llvm::Value *> ExitArgs;
2202
  bool Conditional;
2203
  llvm::BasicBlock *ContBlock = nullptr;
2204
2205
public:
2206
  CommonActionTy(llvm::FunctionCallee EnterCallee,
2207
                 ArrayRef<llvm::Value *> EnterArgs,
2208
                 llvm::FunctionCallee ExitCallee,
2209
                 ArrayRef<llvm::Value *> ExitArgs, bool Conditional = false)
2210
      : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee),
2211
1.59k
        ExitArgs(ExitArgs), Conditional(Conditional) {}
2212
959
  void Enter(CodeGenFunction &CGF) override {
2213
959
    llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs);
2214
959
    if (Conditional) {
2215
273
      llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes);
2216
273
      auto *ThenBlock = CGF.createBasicBlock("omp_if.then");
2217
273
      ContBlock = CGF.createBasicBlock("omp_if.end");
2218
      // Generate the branch (If-stmt)
2219
273
      CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock);
2220
273
      CGF.EmitBlock(ThenBlock);
2221
273
    }
2222
959
  }
2223
273
  void Done(CodeGenFunction &CGF) {
2224
    // Emit the rest of blocks/branches
2225
273
    CGF.EmitBranch(ContBlock);
2226
273
    CGF.EmitBlock(ContBlock, true);
2227
273
  }
2228
1.69k
  void Exit(CodeGenFunction &CGF) override {
2229
1.69k
    CGF.EmitRuntimeCall(ExitCallee, ExitArgs);
2230
1.69k
  }
2231
};
2232
} // anonymous namespace
2233
2234
void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF,
2235
                                         StringRef CriticalName,
2236
                                         const RegionCodeGenTy &CriticalOpGen,
2237
223
                                         SourceLocation Loc, const Expr *Hint) {
2238
  // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]);
2239
  // CriticalOpGen();
2240
  // __kmpc_end_critical(ident_t *, gtid, Lock);
2241
  // Prepare arguments and build a call to __kmpc_critical
2242
223
  if (!CGF.HaveInsertPoint())
2243
0
    return;
2244
223
  llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2245
223
                         getCriticalRegionLock(CriticalName)};
2246
223
  llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args),
2247
223
                                                std::end(Args));
2248
223
  if (Hint) {
2249
6
    EnterArgs.push_back(CGF.Builder.CreateIntCast(
2250
6
        CGF.EmitScalarExpr(Hint), CGM.Int32Ty, /*isSigned=*/false));
2251
6
  }
2252
223
  CommonActionTy Action(
2253
223
      OMPBuilder.getOrCreateRuntimeFunction(
2254
223
          CGM.getModule(),
2255
223
          Hint ? 
OMPRTL___kmpc_critical_with_hint6
:
OMPRTL___kmpc_critical217
),
2256
223
      EnterArgs,
2257
223
      OMPBuilder.getOrCreateRuntimeFunction(CGM.getModule(),
2258
223
                                            OMPRTL___kmpc_end_critical),
2259
223
      Args);
2260
223
  CriticalOpGen.setAction(Action);
2261
223
  emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen);
2262
223
}
2263
2264
void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF,
2265
                                       const RegionCodeGenTy &MasterOpGen,
2266
192
                                       SourceLocation Loc) {
2267
192
  if (!CGF.HaveInsertPoint())
2268
0
    return;
2269
  // if(__kmpc_master(ident_t *, gtid)) {
2270
  //   MasterOpGen();
2271
  //   __kmpc_end_master(ident_t *, gtid);
2272
  // }
2273
  // Prepare arguments and build a call to __kmpc_master
2274
192
  llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2275
192
  CommonActionTy Action(OMPBuilder.getOrCreateRuntimeFunction(
2276
192
                            CGM.getModule(), OMPRTL___kmpc_master),
2277
192
                        Args,
2278
192
                        OMPBuilder.getOrCreateRuntimeFunction(
2279
192
                            CGM.getModule(), OMPRTL___kmpc_end_master),
2280
192
                        Args,
2281
192
                        /*Conditional=*/true);
2282
192
  MasterOpGen.setAction(Action);
2283
192
  emitInlinedDirective(CGF, OMPD_master, MasterOpGen);
2284
192
  Action.Done(CGF);
2285
192
}
2286
2287
void CGOpenMPRuntime::emitMaskedRegion(CodeGenFunction &CGF,
2288
                                       const RegionCodeGenTy &MaskedOpGen,
2289
24
                                       SourceLocation Loc, const Expr *Filter) {
2290
24
  if (!CGF.HaveInsertPoint())
2291
0
    return;
2292
  // if(__kmpc_masked(ident_t *, gtid, filter)) {
2293
  //   MaskedOpGen();
2294
  //   __kmpc_end_masked(iden_t *, gtid);
2295
  // }
2296
  // Prepare arguments and build a call to __kmpc_masked
2297
24
  llvm::Value *FilterVal = Filter
2298
24
                               ? 
CGF.EmitScalarExpr(Filter, CGF.Int32Ty)18
2299
24
                               : 
llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/0)6
;
2300
24
  llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2301
24
                         FilterVal};
2302
24
  llvm::Value *ArgsEnd[] = {emitUpdateLocation(CGF, Loc),
2303
24
                            getThreadID(CGF, Loc)};
2304
24
  CommonActionTy Action(OMPBuilder.getOrCreateRuntimeFunction(
2305
24
                            CGM.getModule(), OMPRTL___kmpc_masked),
2306
24
                        Args,
2307
24
                        OMPBuilder.getOrCreateRuntimeFunction(
2308
24
                            CGM.getModule(), OMPRTL___kmpc_end_masked),
2309
24
                        ArgsEnd,
2310
24
                        /*Conditional=*/true);
2311
24
  MaskedOpGen.setAction(Action);
2312
24
  emitInlinedDirective(CGF, OMPD_masked, MaskedOpGen);
2313
24
  Action.Done(CGF);
2314
24
}
2315
2316
void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF,
2317
16
                                        SourceLocation Loc) {
2318
16
  if (!CGF.HaveInsertPoint())
2319
0
    return;
2320
16
  if (CGF.CGM.getLangOpts().OpenMPIRBuilder) {
2321
8
    OMPBuilder.createTaskyield(CGF.Builder);
2322
8
  } else {
2323
    // Build call __kmpc_omp_taskyield(loc, thread_id, 0);
2324
8
    llvm::Value *Args[] = {
2325
8
        emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2326
8
        llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)};
2327
8
    CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2328
8
                            CGM.getModule(), OMPRTL___kmpc_omp_taskyield),
2329
8
                        Args);
2330
8
  }
2331
2332
16
  if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo))
2333
4
    Region->emitUntiedSwitch(CGF);
2334
16
}
2335
2336
void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF,
2337
                                          const RegionCodeGenTy &TaskgroupOpGen,
2338
247
                                          SourceLocation Loc) {
2339
247
  if (!CGF.HaveInsertPoint())
2340
0
    return;
2341
  // __kmpc_taskgroup(ident_t *, gtid);
2342
  // TaskgroupOpGen();
2343
  // __kmpc_end_taskgroup(ident_t *, gtid);
2344
  // Prepare arguments and build a call to __kmpc_taskgroup
2345
247
  llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2346
247
  CommonActionTy Action(OMPBuilder.getOrCreateRuntimeFunction(
2347
247
                            CGM.getModule(), OMPRTL___kmpc_taskgroup),
2348
247
                        Args,
2349
247
                        OMPBuilder.getOrCreateRuntimeFunction(
2350
247
                            CGM.getModule(), OMPRTL___kmpc_end_taskgroup),
2351
247
                        Args);
2352
247
  TaskgroupOpGen.setAction(Action);
2353
247
  emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen);
2354
247
}
2355
2356
/// Given an array of pointers to variables, project the address of a
2357
/// given variable.
2358
static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array,
2359
1.35k
                                      unsigned Index, const VarDecl *Var) {
2360
  // Pull out the pointer to the variable.
2361
1.35k
  Address PtrAddr = CGF.Builder.CreateConstArrayGEP(Array, Index);
2362
1.35k
  llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr);
2363
2364
1.35k
  Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var));
2365
1.35k
  Addr = CGF.Builder.CreateElementBitCast(
2366
1.35k
      Addr, CGF.ConvertTypeForMem(Var->getType()));
2367
1.35k
  return Addr;
2368
1.35k
}
2369
2370
static llvm::Value *emitCopyprivateCopyFunction(
2371
    CodeGenModule &CGM, llvm::Type *ArgsType,
2372
    ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs,
2373
    ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps,
2374
28
    SourceLocation Loc) {
2375
28
  ASTContext &C = CGM.getContext();
2376
  // void copy_func(void *LHSArg, void *RHSArg);
2377
28
  FunctionArgList Args;
2378
28
  ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
2379
28
                           ImplicitParamDecl::Other);
2380
28
  ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy,
2381
28
                           ImplicitParamDecl::Other);
2382
28
  Args.push_back(&LHSArg);
2383
28
  Args.push_back(&RHSArg);
2384
28
  const auto &CGFI =
2385
28
      CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
2386
28
  std::string Name =
2387
28
      CGM.getOpenMPRuntime().getName({"omp", "copyprivate", "copy_func"});
2388
28
  auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI),
2389
28
                                    llvm::GlobalValue::InternalLinkage, Name,
2390
28
                                    &CGM.getModule());
2391
28
  CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI);
2392
28
  Fn->setDoesNotRecurse();
2393
28
  CodeGenFunction CGF(CGM);
2394
28
  CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc);
2395
  // Dest = (void*[n])(LHSArg);
2396
  // Src = (void*[n])(RHSArg);
2397
28
  Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2398
28
      CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)),
2399
28
      ArgsType), CGF.getPointerAlign());
2400
28
  Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2401
28
      CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)),
2402
28
      ArgsType), CGF.getPointerAlign());
2403
  // *(Type0*)Dst[0] = *(Type0*)Src[0];
2404
  // *(Type1*)Dst[1] = *(Type1*)Src[1];
2405
  // ...
2406
  // *(Typen*)Dst[n] = *(Typen*)Src[n];
2407
97
  for (unsigned I = 0, E = AssignmentOps.size(); I < E; 
++I69
) {
2408
69
    const auto *DestVar =
2409
69
        cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl());
2410
69
    Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar);
2411
2412
69
    const auto *SrcVar =
2413
69
        cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl());
2414
69
    Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar);
2415
2416
69
    const auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl();
2417
69
    QualType Type = VD->getType();
2418
69
    CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]);
2419
69
  }
2420
28
  CGF.FinishFunction();
2421
28
  return Fn;
2422
28
}
2423
2424
void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF,
2425
                                       const RegionCodeGenTy &SingleOpGen,
2426
                                       SourceLocation Loc,
2427
                                       ArrayRef<const Expr *> CopyprivateVars,
2428
                                       ArrayRef<const Expr *> SrcExprs,
2429
                                       ArrayRef<const Expr *> DstExprs,
2430
57
                                       ArrayRef<const Expr *> AssignmentOps) {
2431
57
  if (!CGF.HaveInsertPoint())
2432
0
    return;
2433
57
  assert(CopyprivateVars.size() == SrcExprs.size() &&
2434
57
         CopyprivateVars.size() == DstExprs.size() &&
2435
57
         CopyprivateVars.size() == AssignmentOps.size());
2436
0
  ASTContext &C = CGM.getContext();
2437
  // int32 did_it = 0;
2438
  // if(__kmpc_single(ident_t *, gtid)) {
2439
  //   SingleOpGen();
2440
  //   __kmpc_end_single(ident_t *, gtid);
2441
  //   did_it = 1;
2442
  // }
2443
  // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2444
  // <copy_func>, did_it);
2445
2446
57
  Address DidIt = Address::invalid();
2447
57
  if (!CopyprivateVars.empty()) {
2448
    // int32 did_it = 0;
2449
28
    QualType KmpInt32Ty =
2450
28
        C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2451
28
    DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it");
2452
28
    CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt);
2453
28
  }
2454
  // Prepare arguments and build a call to __kmpc_single
2455
57
  llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2456
57
  CommonActionTy Action(OMPBuilder.getOrCreateRuntimeFunction(
2457
57
                            CGM.getModule(), OMPRTL___kmpc_single),
2458
57
                        Args,
2459
57
                        OMPBuilder.getOrCreateRuntimeFunction(
2460
57
                            CGM.getModule(), OMPRTL___kmpc_end_single),
2461
57
                        Args,
2462
57
                        /*Conditional=*/true);
2463
57
  SingleOpGen.setAction(Action);
2464
57
  emitInlinedDirective(CGF, OMPD_single, SingleOpGen);
2465
57
  if (DidIt.isValid()) {
2466
    // did_it = 1;
2467
28
    CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt);
2468
28
  }
2469
57
  Action.Done(CGF);
2470
  // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>,
2471
  // <copy_func>, did_it);
2472
57
  if (DidIt.isValid()) {
2473
28
    llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size());
2474
28
    QualType CopyprivateArrayTy = C.getConstantArrayType(
2475
28
        C.VoidPtrTy, ArraySize, nullptr, ArrayType::Normal,
2476
28
        /*IndexTypeQuals=*/0);
2477
    // Create a list of all private variables for copyprivate.
2478
28
    Address CopyprivateList =
2479
28
        CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list");
2480
97
    for (unsigned I = 0, E = CopyprivateVars.size(); I < E; 
++I69
) {
2481
69
      Address Elem = CGF.Builder.CreateConstArrayGEP(CopyprivateList, I);
2482
69
      CGF.Builder.CreateStore(
2483
69
          CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
2484
69
              CGF.EmitLValue(CopyprivateVars[I]).getPointer(CGF),
2485
69
              CGF.VoidPtrTy),
2486
69
          Elem);
2487
69
    }
2488
    // Build function that copies private values from single region to all other
2489
    // threads in the corresponding parallel region.
2490
28
    llvm::Value *CpyFn = emitCopyprivateCopyFunction(
2491
28
        CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(),
2492
28
        CopyprivateVars, SrcExprs, DstExprs, AssignmentOps, Loc);
2493
28
    llvm::Value *BufSize = CGF.getTypeSize(CopyprivateArrayTy);
2494
28
    Address CL =
2495
28
      CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList,
2496
28
                                                      CGF.VoidPtrTy);
2497
28
    llvm::Value *DidItVal = CGF.Builder.CreateLoad(DidIt);
2498
28
    llvm::Value *Args[] = {
2499
28
        emitUpdateLocation(CGF, Loc), // ident_t *<loc>
2500
28
        getThreadID(CGF, Loc),        // i32 <gtid>
2501
28
        BufSize,                      // size_t <buf_size>
2502
28
        CL.getPointer(),              // void *<copyprivate list>
2503
28
        CpyFn,                        // void (*) (void *, void *) <copy_func>
2504
28
        DidItVal                      // i32 did_it
2505
28
    };
2506
28
    CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2507
28
                            CGM.getModule(), OMPRTL___kmpc_copyprivate),
2508
28
                        Args);
2509
28
  }
2510
57
}
2511
2512
void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF,
2513
                                        const RegionCodeGenTy &OrderedOpGen,
2514
24
                                        SourceLocation Loc, bool IsThreads) {
2515
24
  if (!CGF.HaveInsertPoint())
2516
0
    return;
2517
  // __kmpc_ordered(ident_t *, gtid);
2518
  // OrderedOpGen();
2519
  // __kmpc_end_ordered(ident_t *, gtid);
2520
  // Prepare arguments and build a call to __kmpc_ordered
2521
24
  if (IsThreads) {
2522
16
    llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2523
16
    CommonActionTy Action(OMPBuilder.getOrCreateRuntimeFunction(
2524
16
                              CGM.getModule(), OMPRTL___kmpc_ordered),
2525
16
                          Args,
2526
16
                          OMPBuilder.getOrCreateRuntimeFunction(
2527
16
                              CGM.getModule(), OMPRTL___kmpc_end_ordered),
2528
16
                          Args);
2529
16
    OrderedOpGen.setAction(Action);
2530
16
    emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2531
16
    return;
2532
16
  }
2533
8
  emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen);
2534
8
}
2535
2536
1.00k
unsigned CGOpenMPRuntime::getDefaultFlagsForBarriers(OpenMPDirectiveKind Kind) {
2537
1.00k
  unsigned Flags;
2538
1.00k
  if (Kind == OMPD_for)
2539
618
    Flags = OMP_IDENT_BARRIER_IMPL_FOR;
2540
388
  else if (Kind == OMPD_sections)
2541
48
    Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS;
2542
340
  else if (Kind == OMPD_single)
2543
22
    Flags = OMP_IDENT_BARRIER_IMPL_SINGLE;
2544
318
  else if (Kind == OMPD_barrier)
2545
14
    Flags = OMP_IDENT_BARRIER_EXPL;
2546
304
  else
2547
304
    Flags = OMP_IDENT_BARRIER_IMPL;
2548
1.00k
  return Flags;
2549
1.00k
}
2550
2551
void CGOpenMPRuntime::getDefaultScheduleAndChunk(
2552
    CodeGenFunction &CGF, const OMPLoopDirective &S,
2553
3.44k
    OpenMPScheduleClauseKind &ScheduleKind, const Expr *&ChunkExpr) const {
2554
  // Check if the loop directive is actually a doacross loop directive. In this
2555
  // case choose static, 1 schedule.
2556
3.44k
  if (llvm::any_of(
2557
3.44k
          S.getClausesOfKind<OMPOrderedClause>(),
2558
3.44k
          [](const OMPOrderedClause *C) 
{ return C->getNumForLoops(); }36
)) {
2559
24
    ScheduleKind = OMPC_SCHEDULE_static;
2560
    // Chunk size is 1 in this case.
2561
24
    llvm::APInt ChunkSize(32, 1);
2562
24
    ChunkExpr = IntegerLiteral::Create(
2563
24
        CGF.getContext(), ChunkSize,
2564
24
        CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/0),
2565
24
        SourceLocation());
2566
24
  }
2567
3.44k
}
2568
2569
void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc,
2570
                                      OpenMPDirectiveKind Kind, bool EmitChecks,
2571
886
                                      bool ForceSimpleCall) {
2572
  // Check if we should use the OMPBuilder
2573
886
  auto *OMPRegionInfo =
2574
886
      dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo);
2575
886
  if (CGF.CGM.getLangOpts().OpenMPIRBuilder) {
2576
52
    CGF.Builder.restoreIP(OMPBuilder.createBarrier(
2577
52
        CGF.Builder, Kind, ForceSimpleCall, EmitChecks));
2578
52
    return;
2579
52
  }
2580
2581
834
  if (!CGF.HaveInsertPoint())
2582
0
    return;
2583
  // Build call __kmpc_cancel_barrier(loc, thread_id);
2584
  // Build call __kmpc_barrier(loc, thread_id);
2585
834
  unsigned Flags = getDefaultFlagsForBarriers(Kind);
2586
  // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc,
2587
  // thread_id);
2588
834
  llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags),
2589
834
                         getThreadID(CGF, Loc)};
2590
834
  if (OMPRegionInfo) {
2591
508
    if (!ForceSimpleCall && 
OMPRegionInfo->hasCancel()318
) {
2592
32
      llvm::Value *Result = CGF.EmitRuntimeCall(
2593
32
          OMPBuilder.getOrCreateRuntimeFunction(CGM.getModule(),
2594
32
                                                OMPRTL___kmpc_cancel_barrier),
2595
32
          Args);
2596
32
      if (EmitChecks) {
2597
        // if (__kmpc_cancel_barrier()) {
2598
        //   exit from construct;
2599
        // }
2600
4
        llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit");
2601
4
        llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue");
2602
4
        llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result);
2603
4
        CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB);
2604
4
        CGF.EmitBlock(ExitBB);
2605
        //   exit from construct;
2606
4
        CodeGenFunction::JumpDest CancelDestination =
2607
4
            CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind());
2608
4
        CGF.EmitBranchThroughCleanup(CancelDestination);
2609
4
        CGF.EmitBlock(ContBB, /*IsFinished=*/true);
2610
4
      }
2611
32
      return;
2612
32
    }
2613
508
  }
2614
802
  CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2615
802
                          CGM.getModule(), OMPRTL___kmpc_barrier),
2616
802
                      Args);
2617
802
}
2618
2619
/// Map the OpenMP loop schedule to the runtime enumeration.
2620
static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind,
2621
16.4k
                                          bool Chunked, bool Ordered) {
2622
16.4k
  switch (ScheduleKind) {
2623
2.53k
  case OMPC_SCHEDULE_static:
2624
2.53k
    return Chunked ? 
(1.54k
Ordered1.54k
?
OMP_ord_static_chunked7
:
OMP_sch_static_chunked1.54k
)
2625
2.53k
                   : 
(983
Ordered983
?
OMP_ord_static10
:
OMP_sch_static973
);
2626
1.95k
  case OMPC_SCHEDULE_dynamic:
2627
1.95k
    return Ordered ? 
OMP_ord_dynamic_chunked8
:
OMP_sch_dynamic_chunked1.94k
;
2628
543
  case OMPC_SCHEDULE_guided:
2629
543
    return Ordered ? 
OMP_ord_guided_chunked1
:
OMP_sch_guided_chunked542
;
2630
560
  case OMPC_SCHEDULE_runtime:
2631
560
    return Ordered ? 
OMP_ord_runtime10
:
OMP_sch_runtime550
;
2632
562
  case OMPC_SCHEDULE_auto:
2633
562
    return Ordered ? 
OMP_ord_auto9
:
OMP_sch_auto553
;
2634
10.2k
  case OMPC_SCHEDULE_unknown:
2635
10.2k
    assert(!Chunked && "chunk was specified but schedule kind not known");
2636
10.2k
    return Ordered ? 
OMP_ord_static12
:
OMP_sch_static10.2k
;
2637
16.4k
  }
2638
0
  llvm_unreachable("Unexpected runtime schedule");
2639
0
}
2640
2641
/// Map the OpenMP distribute schedule to the runtime enumeration.
2642
static OpenMPSchedType
2643
13.4k
getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) {
2644
  // only static is allowed for dist_schedule
2645
13.4k
  return Chunked ? 
OMP_dist_sch_static_chunked1.58k
:
OMP_dist_sch_static11.9k
;
2646
13.4k
}
2647
2648
bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind,
2649
5.77k
                                         bool Chunked) const {
2650
5.77k
  OpenMPSchedType Schedule =
2651
5.77k
      getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
2652
5.77k
  return Schedule == OMP_sch_static;
2653
5.77k
}
2654
2655
bool CGOpenMPRuntime::isStaticNonchunked(
2656
4.49k
    OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2657
4.49k
  OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2658
4.49k
  return Schedule == OMP_dist_sch_static;
2659
4.49k
}
2660
2661
bool CGOpenMPRuntime::isStaticChunked(OpenMPScheduleClauseKind ScheduleKind,
2662
4.77k
                                      bool Chunked) const {
2663
4.77k
  OpenMPSchedType Schedule =
2664
4.77k
      getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false);
2665
4.77k
  return Schedule == OMP_sch_static_chunked;
2666
4.77k
}
2667
2668
bool CGOpenMPRuntime::isStaticChunked(
2669
4.49k
    OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const {
2670
4.49k
  OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked);
2671
4.49k
  return Schedule == OMP_dist_sch_static_chunked;
2672
4.49k
}
2673
2674
998
bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const {
2675
998
  OpenMPSchedType Schedule =
2676
998
      getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false);
2677
998
  assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here");
2678
0
  return Schedule != OMP_sch_static;
2679
998
}
2680
2681
static int addMonoNonMonoModifier(CodeGenModule &CGM, OpenMPSchedType Schedule,
2682
                                  OpenMPScheduleClauseModifier M1,
2683
9.39k
                                  OpenMPScheduleClauseModifier M2) {
2684
9.39k
  int Modifier = 0;
2685
9.39k
  switch (M1) {
2686
17
  case OMPC_SCHEDULE_MODIFIER_monotonic:
2687
17
    Modifier = OMP_sch_modifier_monotonic;
2688
17
    break;
2689
12
  case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
2690
12
    Modifier = OMP_sch_modifier_nonmonotonic;
2691
12
    break;
2692
12
  case OMPC_SCHEDULE_MODIFIER_simd:
2693
12
    if (Schedule == OMP_sch_static_chunked)
2694
6
      Schedule = OMP_sch_static_balanced_chunked;
2695
12
    break;
2696
0
  case OMPC_SCHEDULE_MODIFIER_last:
2697
9.35k
  case OMPC_SCHEDULE_MODIFIER_unknown:
2698
9.35k
    break;
2699
9.39k
  }
2700
9.39k
  switch (M2) {
2701
0
  case OMPC_SCHEDULE_MODIFIER_monotonic:
2702
0
    Modifier = OMP_sch_modifier_monotonic;
2703
0
    break;
2704
6
  case OMPC_SCHEDULE_MODIFIER_nonmonotonic:
2705
6
    Modifier = OMP_sch_modifier_nonmonotonic;
2706
6
    break;
2707
0
  case OMPC_SCHEDULE_MODIFIER_simd:
2708
0
    if (Schedule == OMP_sch_static_chunked)
2709
0
      Schedule = OMP_sch_static_balanced_chunked;
2710
0
    break;
2711
0
  case OMPC_SCHEDULE_MODIFIER_last:
2712
9.39k
  case OMPC_SCHEDULE_MODIFIER_unknown:
2713
9.39k
    break;
2714
9.39k
  }
2715
  // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Desription.
2716
  // If the static schedule kind is specified or if the ordered clause is
2717
  // specified, and if the nonmonotonic modifier is not specified, the effect is
2718
  // as if the monotonic modifier is specified. Otherwise, unless the monotonic
2719
  // modifier is specified, the effect is as if the nonmonotonic modifier is
2720
  // specified.
2721
9.39k
  if (CGM.getLangOpts().OpenMP >= 50 && 
Modifier == 06.35k
) {
2722
6.32k
    if (!(Schedule == OMP_sch_static_chunked || 
Schedule == OMP_sch_static6.01k
||
2723
6.32k
          
Schedule == OMP_sch_static_balanced_chunked3.58k
||
2724
6.32k
          
Schedule == OMP_ord_static_chunked3.58k
||
Schedule == OMP_ord_static3.57k
||
2725
6.32k
          
Schedule == OMP_dist_sch_static_chunked3.56k
||
2726
6.32k
          
Schedule == OMP_dist_sch_static3.14k
))
2727
525
      Modifier = OMP_sch_modifier_nonmonotonic;
2728
6.32k
  }
2729
9.39k
  return Schedule | Modifier;
2730
9.39k
}
2731
2732
void CGOpenMPRuntime::emitForDispatchInit(
2733
    CodeGenFunction &CGF, SourceLocation Loc,
2734
    const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned,
2735
764
    bool Ordered, const DispatchRTInput &DispatchValues) {
2736
764
  if (!CGF.HaveInsertPoint())
2737
0
    return;
2738
764
  OpenMPSchedType Schedule = getRuntimeSchedule(
2739
764
      ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered);
2740
764
  assert(Ordered ||
2741
764
         (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked &&
2742
764
          Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked &&
2743
764
          Schedule != OMP_sch_static_balanced_chunked));
2744
  // Call __kmpc_dispatch_init(
2745
  //          ident_t *loc, kmp_int32 tid, kmp_int32 schedule,
2746
  //          kmp_int[32|64] lower, kmp_int[32|64] upper,
2747
  //          kmp_int[32|64] stride, kmp_int[32|64] chunk);
2748
2749
  // If the Chunk was not specified in the clause - use default value 1.
2750
764
  llvm::Value *Chunk = DispatchValues.Chunk ? 
DispatchValues.Chunk139
2751
764
                                            : 
CGF.Builder.getIntN(IVSize, 1)625
;
2752
764
  llvm::Value *Args[] = {
2753
764
      emitUpdateLocation(CGF, Loc),
2754
764
      getThreadID(CGF, Loc),
2755
764
      CGF.Builder.getInt32(addMonoNonMonoModifier(
2756
764
          CGM, Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type
2757
764
      DispatchValues.LB,                                     // Lower
2758
764
      DispatchValues.UB,                                     // Upper
2759
764
      CGF.Builder.getIntN(IVSize, 1),                        // Stride
2760
764
      Chunk                                                  // Chunk
2761
764
  };
2762
764
  CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args);
2763
764
}
2764
2765
static void emitForStaticInitCall(
2766
    CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId,
2767
    llvm::FunctionCallee ForStaticInitFunction, OpenMPSchedType Schedule,
2768
    OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
2769
8.63k
    const CGOpenMPRuntime::StaticRTInput &Values) {
2770
8.63k
  if (!CGF.HaveInsertPoint())
2771
0
    return;
2772
2773
8.63k
  assert(!Values.Ordered);
2774
0
  assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked ||
2775
8.63k
         Schedule == OMP_sch_static_balanced_chunked ||
2776
8.63k
         Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked ||
2777
8.63k
         Schedule == OMP_dist_sch_static ||
2778
8.63k
         Schedule == OMP_dist_sch_static_chunked);
2779
2780
  // Call __kmpc_for_static_init(
2781
  //          ident_t *loc, kmp_int32 tid, kmp_int32 schedtype,
2782
  //          kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower,
2783
  //          kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride,
2784
  //          kmp_int[32|64] incr, kmp_int[32|64] chunk);
2785
0
  llvm::Value *Chunk = Values.Chunk;
2786
8.63k
  if (Chunk == nullptr) {
2787
7.68k
    assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static ||
2788
7.68k
            Schedule == OMP_dist_sch_static) &&
2789
7.68k
           "expected static non-chunked schedule");
2790
    // If the Chunk was not specified in the clause - use default value 1.
2791
0
    Chunk = CGF.Builder.getIntN(Values.IVSize, 1);
2792
7.68k
  } else {
2793
944
    assert((Schedule == OMP_sch_static_chunked ||
2794
944
            Schedule == OMP_sch_static_balanced_chunked ||
2795
944
            Schedule == OMP_ord_static_chunked ||
2796
944
            Schedule == OMP_dist_sch_static_chunked) &&
2797
944
           "expected static chunked schedule");
2798
944
  }
2799
0
  llvm::Value *Args[] = {
2800
8.63k
      UpdateLocation,
2801
8.63k
      ThreadId,
2802
8.63k
      CGF.Builder.getInt32(addMonoNonMonoModifier(CGF.CGM, Schedule, M1,
2803
8.63k
                                                  M2)), // Schedule type
2804
8.63k
      Values.IL.getPointer(),                           // &isLastIter
2805
8.63k
      Values.LB.getPointer(),                           // &LB
2806
8.63k
      Values.UB.getPointer(),                           // &UB
2807
8.63k
      Values.ST.getPointer(),                           // &Stride
2808
8.63k
      CGF.Builder.getIntN(Values.IVSize, 1),            // Incr
2809
8.63k
      Chunk                                             // Chunk
2810
8.63k
  };
2811
8.63k
  CGF.EmitRuntimeCall(ForStaticInitFunction, Args);
2812
8.63k
}
2813
2814
void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF,
2815
                                        SourceLocation Loc,
2816
                                        OpenMPDirectiveKind DKind,
2817
                                        const OpenMPScheduleTy &ScheduleKind,
2818
4.13k
                                        const StaticRTInput &Values) {
2819
4.13k
  OpenMPSchedType ScheduleNum = getRuntimeSchedule(
2820
4.13k
      ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered);
2821
4.13k
  assert(isOpenMPWorksharingDirective(DKind) &&
2822
4.13k
         "Expected loop-based or sections-based directive.");
2823
0
  llvm::Value *UpdatedLocation = emitUpdateLocation(CGF, Loc,
2824
4.13k
                                             isOpenMPLoopDirective(DKind)
2825
4.13k
                                                 ? 
OMP_IDENT_WORK_LOOP4.05k
2826
4.13k
                                                 : 
OMP_IDENT_WORK_SECTIONS80
);
2827
4.13k
  llvm::Value *ThreadId = getThreadID(CGF, Loc);
2828
4.13k
  llvm::FunctionCallee StaticInitFunction =
2829
4.13k
      createForStaticInitFunction(Values.IVSize, Values.IVSigned);
2830
4.13k
  auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
2831
4.13k
  emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
2832
4.13k
                        ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values);
2833
4.13k
}
2834
2835
void CGOpenMPRuntime::emitDistributeStaticInit(
2836
    CodeGenFunction &CGF, SourceLocation Loc,
2837
    OpenMPDistScheduleClauseKind SchedKind,
2838
4.49k
    const CGOpenMPRuntime::StaticRTInput &Values) {
2839
4.49k
  OpenMPSchedType ScheduleNum =
2840
4.49k
      getRuntimeSchedule(SchedKind, Values.Chunk != nullptr);
2841
4.49k
  llvm::Value *UpdatedLocation =
2842
4.49k
      emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE);
2843
4.49k
  llvm::Value *ThreadId = getThreadID(CGF, Loc);
2844
4.49k
  llvm::FunctionCallee StaticInitFunction =
2845
4.49k
      createForStaticInitFunction(Values.IVSize, Values.IVSigned);
2846
4.49k
  emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction,
2847
4.49k
                        ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown,
2848
4.49k
                        OMPC_SCHEDULE_MODIFIER_unknown, Values);
2849
4.49k
}
2850
2851
void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF,
2852
                                          SourceLocation Loc,
2853
8.67k
                                          OpenMPDirectiveKind DKind) {
2854
8.67k
  if (!CGF.HaveInsertPoint())
2855
0
    return;
2856
  // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid);
2857
8.67k
  llvm::Value *Args[] = {
2858
8.67k
      emitUpdateLocation(CGF, Loc,
2859
8.67k
                         isOpenMPDistributeDirective(DKind)
2860
8.67k
                             ? 
OMP_IDENT_WORK_DISTRIBUTE6.82k
2861
8.67k
                             : 
isOpenMPLoopDirective(DKind)1.84k
2862
1.84k
                                   ? 
OMP_IDENT_WORK_LOOP1.73k
2863
1.84k
                                   : 
OMP_IDENT_WORK_SECTIONS112
),
2864
8.67k
      getThreadID(CGF, Loc)};
2865
8.67k
  auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc);
2866
8.67k
  CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2867
8.67k
                          CGM.getModule(), OMPRTL___kmpc_for_static_fini),
2868
8.67k
                      Args);
2869
8.67k
}
2870
2871
void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF,
2872
                                                 SourceLocation Loc,
2873
                                                 unsigned IVSize,
2874
57
                                                 bool IVSigned) {
2875
57
  if (!CGF.HaveInsertPoint())
2876
0
    return;
2877
  // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid);
2878
57
  llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)};
2879
57
  CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args);
2880
57
}
2881
2882
llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF,
2883
                                          SourceLocation Loc, unsigned IVSize,
2884
                                          bool IVSigned, Address IL,
2885
                                          Address LB, Address UB,
2886
764
                                          Address ST) {
2887
  // Call __kmpc_dispatch_next(
2888
  //          ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter,
2889
  //          kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper,
2890
  //          kmp_int[32|64] *p_stride);
2891
764
  llvm::Value *Args[] = {
2892
764
      emitUpdateLocation(CGF, Loc),
2893
764
      getThreadID(CGF, Loc),
2894
764
      IL.getPointer(), // &isLastIter
2895
764
      LB.getPointer(), // &Lower
2896
764
      UB.getPointer(), // &Upper
2897
764
      ST.getPointer()  // &Stride
2898
764
  };
2899
764
  llvm::Value *Call =
2900
764
      CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args);
2901
764
  return CGF.EmitScalarConversion(
2902
764
      Call, CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/1),
2903
764
      CGF.getContext().BoolTy, Loc);
2904
764
}
2905
2906
void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF,
2907
                                           llvm::Value *NumThreads,
2908
336
                                           SourceLocation Loc) {
2909
336
  if (!CGF.HaveInsertPoint())
2910
0
    return;
2911
  // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads)
2912
336
  llvm::Value *Args[] = {
2913
336
      emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2914
336
      CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)};
2915
336
  CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2916
336
                          CGM.getModule(), OMPRTL___kmpc_push_num_threads),
2917
336
                      Args);
2918
336
}
2919
2920
void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF,
2921
                                         ProcBindKind ProcBind,
2922
62
                                         SourceLocation Loc) {
2923
62
  if (!CGF.HaveInsertPoint())
2924
0
    return;
2925
62
  assert(ProcBind != OMP_PROC_BIND_unknown && "Unsupported proc_bind value.");
2926
  // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind)
2927
0
  llvm::Value *Args[] = {
2928
62
      emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc),
2929
62
      llvm::ConstantInt::get(CGM.IntTy, unsigned(ProcBind), /*isSigned=*/true)};
2930
62
  CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2931
62
                          CGM.getModule(), OMPRTL___kmpc_push_proc_bind),
2932
62
                      Args);
2933
62
}
2934
2935
void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>,
2936
104
                                SourceLocation Loc, llvm::AtomicOrdering AO) {
2937
104
  if (CGF.CGM.getLangOpts().OpenMPIRBuilder) {
2938
20
    OMPBuilder.createFlush(CGF.Builder);
2939
84
  } else {
2940
84
    if (!CGF.HaveInsertPoint())
2941
0
      return;
2942
    // Build call void __kmpc_flush(ident_t *loc)
2943
84
    CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
2944
84
                            CGM.getModule(), OMPRTL___kmpc_flush),
2945
84
                        emitUpdateLocation(CGF, Loc));
2946
84
  }
2947
104
}
2948
2949
namespace {
2950
/// Indexes of fields for type kmp_task_t.
2951
enum KmpTaskTFields {
2952
  /// List of shared variables.
2953
  KmpTaskTShareds,
2954
  /// Task routine.
2955
  KmpTaskTRoutine,
2956
  /// Partition id for the untied tasks.
2957
  KmpTaskTPartId,
2958
  /// Function with call of destructors for private variables.
2959
  Data1,
2960
  /// Task priority.
2961
  Data2,
2962
  /// (Taskloops only) Lower bound.
2963
  KmpTaskTLowerBound,
2964
  /// (Taskloops only) Upper bound.
2965
  KmpTaskTUpperBound,
2966
  /// (Taskloops only) Stride.
2967
  KmpTaskTStride,
2968
  /// (Taskloops only) Is last iteration flag.
2969
  KmpTaskTLastIter,
2970
  /// (Taskloops only) Reduction data.
2971
  KmpTaskTReductions,
2972
};
2973
} // anonymous namespace
2974
2975
5.60k
bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const {
2976
5.60k
  return OffloadEntriesTargetRegion.empty() &&
2977
5.60k
         
OffloadEntriesDeviceGlobalVar.empty()1.17k
;
2978
5.60k
}
2979
2980
/// Initialize target region entry.
2981
void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2982
    initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2983
                                    StringRef ParentName, unsigned LineNum,
2984
2.86k
                                    unsigned Order) {
2985
2.86k
  assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
2986
2.86k
                                             "only required for the device "
2987
2.86k
                                             "code generation.");
2988
0
  OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] =
2989
2.86k
      OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr,
2990
2.86k
                                   OMPTargetRegionEntryTargetRegion);
2991
2.86k
  ++OffloadingEntriesNum;
2992
2.86k
}
2993
2994
void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
2995
    registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID,
2996
                                  StringRef ParentName, unsigned LineNum,
2997
                                  llvm::Constant *Addr, llvm::Constant *ID,
2998
11.6k
                                  OMPTargetRegionEntryKind Flags) {
2999
  // If we are emitting code for a target, the entry is already initialized,
3000
  // only has to be registered.
3001
11.6k
  if (CGM.getLangOpts().OpenMPIsDevice) {
3002
    // This could happen if the device compilation is invoked standalone.
3003
2.83k
    if (!hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum))
3004
0
      return;
3005
2.83k
    auto &Entry =
3006
2.83k
        OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum];
3007
2.83k
    Entry.setAddress(Addr);
3008
2.83k
    Entry.setID(ID);
3009
2.83k
    Entry.setFlags(Flags);
3010
8.84k
  } else {
3011
8.84k
    if (Flags ==
3012
8.84k
            OffloadEntriesInfoManagerTy::OMPTargetRegionEntryTargetRegion &&
3013
8.84k
        hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum,
3014
8.74k
                                 /*IgnoreAddressId*/ true))
3015
4
      return;
3016
8.84k
    assert(!hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum) &&
3017
8.84k
           "Target region entry already registered!");
3018
0
    OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum, Addr, ID, Flags);
3019
8.84k
    OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry;
3020
8.84k
    ++OffloadingEntriesNum;
3021
8.84k
  }
3022
11.6k
}
3023
3024
bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo(
3025
    unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned LineNum,
3026
24.1k
    bool IgnoreAddressId) const {
3027
24.1k
  auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID);
3028
24.1k
  if (PerDevice == OffloadEntriesTargetRegion.end())
3029
3.91k
    return false;
3030
20.2k
  auto PerFile = PerDevice->second.find(FileID);
3031
20.2k
  if (PerFile == PerDevice->second.end())
3032
0
    return false;
3033
20.2k
  auto PerParentName = PerFile->second.find(ParentName);
3034
20.2k
  if (PerParentName == PerFile->second.end())
3035
6.00k
    return false;
3036
14.2k
  auto PerLine = PerParentName->second.find(LineNum);
3037
14.2k
  if (PerLine == PerParentName->second.end())
3038
8.42k
    return false;
3039
  // Fail if this entry is already registered.
3040
5.81k
  if (!IgnoreAddressId &&
3041
5.81k
      
(5.81k
PerLine->second.getAddress()5.81k
||
PerLine->second.getID()5.53k
))
3042
279
    return false;
3043
5.53k
  return true;
3044
5.81k
}
3045
3046
void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo(
3047
2.47k
    const OffloadTargetRegionEntryInfoActTy &Action) {
3048
  // Scan all target region entries and perform the provided action.
3049
2.47k
  for (const auto &D : OffloadEntriesTargetRegion)
3050
2.46k
    for (const auto &F : D.second)
3051
2.46k
      for (const auto &P : F.second)
3052
6.55k
        for (const auto &L : P.second)
3053
11.6k
          Action(D.first, F.first, P.first(), L.first, L.second);
3054
2.47k
}
3055
3056
void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3057
    initializeDeviceGlobalVarEntryInfo(StringRef Name,
3058
                                       OMPTargetGlobalVarEntryKind Flags,
3059
145
                                       unsigned Order) {
3060
145
  assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is "
3061
145
                                             "only required for the device "
3062
145
                                             "code generation.");
3063
0
  OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags);
3064
145
  ++OffloadingEntriesNum;
3065
145
}
3066
3067
void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3068
    registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr,
3069
                                     CharUnits VarSize,
3070
                                     OMPTargetGlobalVarEntryKind Flags,
3071
953
                                     llvm::GlobalValue::LinkageTypes Linkage) {
3072
953
  if (CGM.getLangOpts().OpenMPIsDevice) {
3073
    // This could happen if the device compilation is invoked standalone.
3074
302
    if (!hasDeviceGlobalVarEntryInfo(VarName))
3075
6
      return;
3076
296
    auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
3077
296
    if (Entry.getAddress() && 
hasDeviceGlobalVarEntryInfo(VarName)155
) {
3078
155
      if (Entry.getVarSize().isZero()) {
3079
4
        Entry.setVarSize(VarSize);
3080
4
        Entry.setLinkage(Linkage);
3081
4
      }
3082
155
      return;
3083
155
    }
3084
141
    Entry.setVarSize(VarSize);
3085
141
    Entry.setLinkage(Linkage);
3086
141
    Entry.setAddress(Addr);
3087
651
  } else {
3088
651
    if (hasDeviceGlobalVarEntryInfo(VarName)) {
3089
476
      auto &Entry = OffloadEntriesDeviceGlobalVar[VarName];
3090
476
      assert(Entry.isValid() && Entry.getFlags() == Flags &&
3091
476
             "Entry not initialized!");
3092
476
      if (Entry.getVarSize().isZero()) {
3093
27
        Entry.setVarSize(VarSize);
3094
27
        Entry.setLinkage(Linkage);
3095
27
      }
3096
476
      return;
3097
476
    }
3098
175
    OffloadEntriesDeviceGlobalVar.try_emplace(
3099
175
        VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage);
3100
175
    ++OffloadingEntriesNum;
3101
175
  }
3102
953
}
3103
3104
void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::
3105
    actOnDeviceGlobalVarEntriesInfo(
3106
2.47k
        const OffloadDeviceGlobalVarEntryInfoActTy &Action) {
3107
  // Scan all target region entries and perform the provided action.
3108
2.47k
  for (const auto &E : OffloadEntriesDeviceGlobalVar)
3109
316
    Action(E.getKey(), E.getValue());
3110
2.47k
}
3111
3112
void CGOpenMPRuntime::createOffloadEntry(
3113
    llvm::Constant *ID, llvm::Constant *Addr, uint64_t Size, int32_t Flags,
3114
11.0k
    llvm::GlobalValue::LinkageTypes Linkage) {
3115
11.0k
  StringRef Name = Addr->getName();
3116
11.0k
  llvm::Module &M = CGM.getModule();
3117
11.0k
  llvm::LLVMContext &C = M.getContext();
3118
3119
  // Create constant string with the name.
3120
11.0k
  llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name);
3121
3122
11.0k
  std::string StringName = getName({"omp_offloading", "entry_name"});
3123
11.0k
  auto *Str = new llvm::GlobalVariable(
3124
11.0k
      M, StrPtrInit->getType(), /*isConstant=*/true,
3125
11.0k
      llvm::GlobalValue::InternalLinkage, StrPtrInit, StringName);
3126
11.0k
  Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3127
3128
11.0k
  llvm::Constant *Data[] = {
3129
11.0k
      llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(ID, CGM.VoidPtrTy),
3130
11.0k
      llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(Str, CGM.Int8PtrTy),
3131
11.0k
      llvm::ConstantInt::get(CGM.SizeTy, Size),
3132
11.0k
      llvm::ConstantInt::get(CGM.Int32Ty, Flags),
3133
11.0k
      llvm::ConstantInt::get(CGM.Int32Ty, 0)};
3134
11.0k
  std::string EntryName = getName({"omp_offloading", "entry", ""});
3135
11.0k
  llvm::GlobalVariable *Entry = createGlobalStruct(
3136
11.0k
      CGM, getTgtOffloadEntryQTy(), /*IsConstant=*/true, Data,
3137
11.0k
      Twine(EntryName).concat(Name), llvm::GlobalValue::WeakAnyLinkage);
3138
3139
  // The entry has to be created in the section the linker expects it to be.
3140
11.0k
  Entry->setSection("omp_offloading_entries");
3141
11.0k
}
3142
3143
5.85k
void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() {
3144
  // Emit the offloading entries and metadata so that the device codegen side
3145
  // can easily figure out what to emit. The produced metadata looks like
3146
  // this:
3147
  //
3148
  // !omp_offload.info = !{!1, ...}
3149
  //
3150
  // Right now we only generate metadata for function that contain target
3151
  // regions.
3152
3153
  // If we are in simd mode or there are no entries, we don't need to do
3154
  // anything.
3155
5.85k
  if (CGM.getLangOpts().OpenMPSimd || 
OffloadEntriesInfoManager.empty()3.39k
)
3156
3.37k
    return;
3157
3158
2.47k
  llvm::Module &M = CGM.getModule();
3159
2.47k
  llvm::LLVMContext &C = M.getContext();
3160
2.47k
  SmallVector<std::tuple<const OffloadEntriesInfoManagerTy::OffloadEntryInfo *,
3161
2.47k
                         SourceLocation, StringRef>,
3162
2.47k
              16>
3163
2.47k
      OrderedEntries(OffloadEntriesInfoManager.size());
3164
2.47k
  llvm::SmallVector<StringRef, 16> ParentFunctions(
3165
2.47k
      OffloadEntriesInfoManager.size());
3166
3167
  // Auxiliary methods to create metadata values and strings.
3168
59.2k
  auto &&GetMDInt = [this](unsigned V) {
3169
59.2k
    return llvm::ConstantAsMetadata::get(
3170
59.2k
        llvm::ConstantInt::get(CGM.Int32Ty, V));
3171
59.2k
  };
3172
3173
11.9k
  auto &&GetMDString = [&C](StringRef V) { return llvm::MDString::get(C, V); };
3174
3175
  // Create the offloading info metadata node.
3176
2.47k
  llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info");
3177
3178
  // Create function that emits metadata for each target region entry;
3179
2.47k
  auto &&TargetRegionMetadataEmitter =
3180
2.47k
      [this, &C, MD, &OrderedEntries, &ParentFunctions, &GetMDInt,
3181
2.47k
       &GetMDString](
3182
2.47k
          unsigned DeviceID, unsigned FileID, StringRef ParentName,
3183
2.47k
          unsigned Line,
3184
11.6k
          const OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) {
3185
        // Generate metadata for target regions. Each entry of this metadata
3186
        // contains:
3187
        // - Entry 0 -> Kind of this type of metadata (0).
3188
        // - Entry 1 -> Device ID of the file where the entry was identified.
3189
        // - Entry 2 -> File ID of the file where the entry was identified.
3190
        // - Entry 3 -> Mangled name of the function where the entry was
3191
        // identified.
3192
        // - Entry 4 -> Line in the file where the entry was identified.
3193
        // - Entry 5 -> Order the entry was created.
3194
        // The first element of the metadata node is the kind.
3195
11.6k
        llvm::Metadata *Ops[] = {GetMDInt(E.getKind()), GetMDInt(DeviceID),
3196
11.6k
                                 GetMDInt(FileID),      GetMDString(ParentName),
3197
11.6k
                                 GetMDInt(Line),        GetMDInt(E.getOrder())};
3198
3199
11.6k
        SourceLocation Loc;
3200
11.6k
        for (auto I = CGM.getContext().getSourceManager().fileinfo_begin(),
3201
11.6k
                  E = CGM.getContext().getSourceManager().fileinfo_end();
3202
25.7k
             I != E; 
++I14.0k
) {
3203
14.0k
          if (I->getFirst()->getUniqueID().getDevice() == DeviceID &&
3204
14.0k
              I->getFirst()->getUniqueID().getFile() == FileID) {
3205
0
            Loc = CGM.getContext().getSourceManager().translateFileLineCol(
3206
0
                I->getFirst(), Line, 1);
3207
0
            break;
3208
0
          }
3209
14.0k
        }
3210
        // Save this entry in the right position of the ordered entries array.
3211
11.6k
        OrderedEntries[E.getOrder()] = std::make_tuple(&E, Loc, ParentName);
3212
11.6k
        ParentFunctions[E.getOrder()] = ParentName;
3213
3214
        // Add metadata to the named metadata node.
3215
11.6k
        MD->addOperand(llvm::MDNode::get(C, Ops));
3216
11.6k
      };
3217
3218
2.47k
  OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo(
3219
2.47k
      TargetRegionMetadataEmitter);
3220
3221
  // Create function that emits metadata for each device global variable entry;
3222
2.47k
  auto &&DeviceGlobalVarMetadataEmitter =
3223
2.47k
      [&C, &OrderedEntries, &GetMDInt, &GetMDString,
3224
2.47k
       MD](StringRef MangledName,
3225
2.47k
           const OffloadEntriesInfoManagerTy::OffloadEntryInfoDeviceGlobalVar
3226
2.47k
               &E) {
3227
        // Generate metadata for global variables. Each entry of this metadata
3228
        // contains:
3229
        // - Entry 0 -> Kind of this type of metadata (1).
3230
        // - Entry 1 -> Mangled name of the variable.
3231
        // - Entry 2 -> Declare target kind.
3232
        // - Entry 3 -> Order the entry was created.
3233
        // The first element of the metadata node is the kind.
3234
316
        llvm::Metadata *Ops[] = {
3235
316
            GetMDInt(E.getKind()), GetMDString(MangledName),
3236
316
            GetMDInt(E.getFlags()), GetMDInt(E.getOrder())};
3237
3238
        // Save this entry in the right position of the ordered entries array.
3239
316
        OrderedEntries[E.getOrder()] =
3240
316
            std::make_tuple(&E, SourceLocation(), MangledName);
3241
3242
        // Add metadata to the named metadata node.
3243
316
        MD->addOperand(llvm::MDNode::get(C, Ops));
3244
316
      };
3245
3246
2.47k
  OffloadEntriesInfoManager.actOnDeviceGlobalVarEntriesInfo(
3247
2.47k
      DeviceGlobalVarMetadataEmitter);
3248
3249
11.9k
  for (const auto &E : OrderedEntries) {
3250
11.9k
    assert(std::get<0>(E) && "All ordered entries must exist!");
3251
11.9k
    if (const auto *CE =
3252
11.9k
            dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>(
3253
11.9k
                std::get<0>(E))) {
3254
11.6k
      if (!CE->getID() || 
!CE->getAddress()11.6k
) {
3255
        // Do not blame the entry if the parent funtion is not emitted.
3256
4
        StringRef FnName = ParentFunctions[CE->getOrder()];
3257
4
        if (!CGM.GetGlobalValue(FnName))
3258
2
          continue;
3259
2
        unsigned DiagID = CGM.getDiags().getCustomDiagID(
3260
2
            DiagnosticsEngine::Error,
3261
2
            "Offloading entry for target region in %0 is incorrect: either the "
3262
2
            "address or the ID is invalid.");
3263
2
        CGM.getDiags().Report(std::get<1>(E), DiagID) << FnName;
3264
2
        continue;
3265
4
      }
3266
11.6k
      createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0,
3267
11.6k
                         CE->getFlags(), llvm::GlobalValue::WeakAnyLinkage);
3268
11.6k
    } else 
if (const auto *316
CE316
= dyn_cast<OffloadEntriesInfoManagerTy::
3269
316
                                             OffloadEntryInfoDeviceGlobalVar>(
3270
316
                   std::get<0>(E))) {
3271
316
      OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags =
3272
316
          static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
3273
316
              CE->getFlags());
3274
316
      switch (Flags) {
3275
266
      case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo: {
3276
266
        if (CGM.getLangOpts().OpenMPIsDevice &&
3277
266
            
CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory()123
)
3278
2
          continue;
3279
264
        if (!CE->getAddress()) {
3280
0
          unsigned DiagID = CGM.getDiags().getCustomDiagID(
3281
0
              DiagnosticsEngine::Error, "Offloading entry for declare target "
3282
0
                                        "variable %0 is incorrect: the "
3283
0
                                        "address is invalid.");
3284
0
          CGM.getDiags().Report(std::get<1>(E), DiagID) << std::get<2>(E);
3285
0
          continue;
3286
0
        }
3287
        // The vaiable has no definition - no need to add the entry.
3288
264
        if (CE->getVarSize().isZero())
3289
49
          continue;
3290
215
        break;
3291
264
      }
3292
215
      case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink:
3293
50
        assert(((CGM.getLangOpts().OpenMPIsDevice && !CE->getAddress()) ||
3294
50
                (!CGM.getLangOpts().OpenMPIsDevice && CE->getAddress())) &&
3295
50
               "Declaret target link address is set.");
3296
50
        if (CGM.getLangOpts().OpenMPIsDevice)
3297
18
          continue;
3298
32
        if (!CE->getAddress()) {
3299
0
          unsigned DiagID = CGM.getDiags().getCustomDiagID(
3300
0
              DiagnosticsEngine::Error,
3301
0
              "Offloading entry for declare target variable is incorrect: the "
3302
0
              "address is invalid.");
3303
0
          CGM.getDiags().Report(DiagID);
3304
0
          continue;
3305
0
        }
3306
32
        break;
3307
316
      }
3308
247
      createOffloadEntry(CE->getAddress(), CE->getAddress(),
3309
247
                         CE->getVarSize().getQuantity(), Flags,
3310
247
                         CE->getLinkage());
3311
247
    } else {
3312
0
      llvm_unreachable("Unsupported entry kind.");
3313
0
    }
3314
11.9k
  }
3315
2.47k
}
3316
3317
/// Loads all the offload entries information from the host IR
3318
/// metadata.
3319
5.87k
void CGOpenMPRuntime::loadOffloadInfoMetadata() {
3320
  // If we are in target mode, load the metadata from the host IR. This code has
3321
  // to match the metadaata creation in createOffloadEntriesAndInfoMetadata().
3322
3323
5.87k
  if (!CGM.getLangOpts().OpenMPIsDevice)
3324
5.33k
    return;
3325
3326
533
  if (CGM.getLangOpts().OMPHostIRFile.empty())
3327
2
    return;
3328
3329
531
  auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile);
3330
531
  if (auto EC = Buf.getError()) {
3331
0
    CGM.getDiags().Report(diag::err_cannot_open_file)
3332
0
        << CGM.getLangOpts().OMPHostIRFile << EC.message();
3333
0
    return;
3334
0
  }
3335
3336
531
  llvm::LLVMContext C;
3337
531
  auto ME = expectedToErrorOrAndEmitErrors(
3338
531
      C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C));
3339
3340
531
  if (auto EC = ME.getError()) {
3341
0
    unsigned DiagID = CGM.getDiags().getCustomDiagID(
3342
0
        DiagnosticsEngine::Error, "Unable to parse host IR file '%0':'%1'");
3343
0
    CGM.getDiags().Report(DiagID)
3344
0
        << CGM.getLangOpts().OMPHostIRFile << EC.message();
3345
0
    return;
3346
0
  }
3347
3348
531
  llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info");
3349
531
  if (!MD)
3350
28
    return;
3351
3352
3.01k
  
for (llvm::MDNode *MN : MD->operands())503
{
3353
14.7k
    auto &&GetMDInt = [MN](unsigned Idx) {
3354
14.7k
      auto *V = cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx));
3355
14.7k
      return cast<llvm::ConstantInt>(V->getValue())->getZExtValue();
3356
14.7k
    };
3357
3358
3.01k
    auto &&GetMDString = [MN](unsigned Idx) {
3359
3.01k
      auto *V = cast<llvm::MDString>(MN->getOperand(Idx));
3360
3.01k
      return V->getString();
3361
3.01k
    };
3362
3363
3.01k
    switch (GetMDInt(0)) {
3364
0
    default:
3365
0
      llvm_unreachable("Unexpected metadata!");
3366
0
      break;
3367
2.86k
    case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3368
2.86k
        OffloadingEntryInfoTargetRegion:
3369
2.86k
      OffloadEntriesInfoManager.initializeTargetRegionEntryInfo(
3370
2.86k
          /*DeviceID=*/GetMDInt(1), /*FileID=*/GetMDInt(2),
3371
2.86k
          /*ParentName=*/GetMDString(3), /*Line=*/GetMDInt(4),
3372
2.86k
          /*Order=*/GetMDInt(5));
3373
2.86k
      break;
3374
145
    case OffloadEntriesInfoManagerTy::OffloadEntryInfo::
3375
145
        OffloadingEntryInfoDeviceGlobalVar:
3376
145
      OffloadEntriesInfoManager.initializeDeviceGlobalVarEntryInfo(
3377
145
          /*MangledName=*/GetMDString(1),
3378
145
          static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>(
3379
145
              /*Flags=*/GetMDInt(2)),
3380
145
          /*Order=*/GetMDInt(3));
3381
145
      break;
3382
3.01k
    }
3383
3.01k
  }
3384
503
}
3385
3386
869
void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) {
3387
869
  if (!KmpRoutineEntryPtrTy) {
3388
    // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type.
3389
384
    ASTContext &C = CGM.getContext();
3390
384
    QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy};
3391
384
    FunctionProtoType::ExtProtoInfo EPI;
3392
384
    KmpRoutineEntryPtrQTy = C.getPointerType(
3393
384
        C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI));
3394
384
    KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy);
3395
384
  }
3396
869
}
3397
3398
11.0k
QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() {
3399
  // Make sure the type of the entry is already created. This is the type we
3400
  // have to create:
3401
  // struct __tgt_offload_entry{
3402
  //   void      *addr;       // Pointer to the offload entry info.
3403
  //                          // (function or global)
3404
  //   char      *name;       // Name of the function or global.
3405
  //   size_t     size;       // Size of the entry info (0 if it a function).
3406
  //   int32_t    flags;      // Flags associated with the entry, e.g. 'link'.
3407
  //   int32_t    reserved;   // Reserved, to use by the runtime library.
3408
  // };
3409
11.0k
  if (TgtOffloadEntryQTy.isNull()) {
3410
2.30k
    ASTContext &C = CGM.getContext();
3411
2.30k
    RecordDecl *RD = C.buildImplicitRecord("__tgt_offload_entry");
3412
2.30k
    RD->startDefinition();
3413
2.30k
    addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3414
2.30k
    addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy));
3415
2.30k
    addFieldToRecordDecl(C, RD, C.getSizeType());
3416
2.30k
    addFieldToRecordDecl(
3417
2.30k
        C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3418
2.30k
    addFieldToRecordDecl(
3419
2.30k
        C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true));
3420
2.30k
    RD->completeDefinition();
3421
2.30k
    RD->addAttr(PackedAttr::CreateImplicit(C));
3422
2.30k
    TgtOffloadEntryQTy = C.getRecordType(RD);
3423
2.30k
  }
3424
11.0k
  return TgtOffloadEntryQTy;
3425
11.0k
}
3426
3427
namespace {
3428
struct PrivateHelpersTy {
3429
  PrivateHelpersTy(const Expr *OriginalRef, const VarDecl *Original,
3430
                   const VarDecl *PrivateCopy, const VarDecl *PrivateElemInit)
3431
      : OriginalRef(OriginalRef), Original(Original), PrivateCopy(PrivateCopy),
3432
1.68k
        PrivateElemInit(PrivateElemInit) {}
3433
8
  PrivateHelpersTy(const VarDecl *Original) : Original(Original) {}
3434
  const Expr *OriginalRef = nullptr;
3435
  const VarDecl *Original = nullptr;
3436
  const VarDecl *PrivateCopy = nullptr;
3437
  const VarDecl *PrivateElemInit = nullptr;
3438
5.45k
  bool isLocalPrivate() const {
3439
5.45k
    return !OriginalRef && 
!PrivateCopy24
&&
!PrivateElemInit24
;
3440
5.45k
  }
3441
};
3442
typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy;
3443
} // anonymous namespace
3444
3445
95
static bool isAllocatableDecl(const VarDecl *VD) {
3446
95
  const VarDecl *CVD = VD->getCanonicalDecl();
3447
95
  if (!CVD->hasAttr<OMPAllocateDeclAttr>())
3448
18
    return false;
3449
77
  const auto *AA = CVD->getAttr<OMPAllocateDeclAttr>();
3450
  // Use the default allocation.
3451
77
  return !((AA->getAllocatorType() == OMPAllocateDeclAttr::OMPDefaultMemAlloc ||
3452
77
            
AA->getAllocatorType() == OMPAllocateDeclAttr::OMPNullMemAlloc55
) &&
3453
77
           
!AA->getAllocator()34
);
3454
95
}
3455
3456
static RecordDecl *
3457
869
createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) {
3458
869
  if (!Privates.empty()) {
3459
568
    ASTContext &C = CGM.getContext();
3460
    // Build struct .kmp_privates_t. {
3461
    //         /*  private vars  */
3462
    //       };
3463
568
    RecordDecl *RD = C.buildImplicitRecord(".kmp_privates.t");
3464
568
    RD->startDefinition();
3465
1.69k
    for (const auto &Pair : Privates) {
3466
1.69k
      const VarDecl *VD = Pair.second.Original;
3467
1.69k
      QualType Type = VD->getType().getNonReferenceType();
3468
      // If the private variable is a local variable with lvalue ref type,
3469
      // allocate the pointer instead of the pointee type.
3470
1.69k
      if (Pair.second.isLocalPrivate()) {
3471
8
        if (VD->getType()->isLValueReferenceType())
3472
0
          Type = C.getPointerType(Type);
3473
8
        if (isAllocatableDecl(VD))
3474
2
          Type = C.getPointerType(Type);
3475
8
      }
3476
1.69k
      FieldDecl *FD = addFieldToRecordDecl(C, RD, Type);
3477
1.69k
      if (VD->hasAttrs()) {
3478
50
        for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()),
3479
50
             E(VD->getAttrs().end());
3480
98
             I != E; 
++I48
)
3481
48
          FD->addAttr(*I);
3482
50
      }
3483
1.69k
    }
3484
568
    RD->completeDefinition();
3485
568
    return RD;
3486
568
  }
3487
301
  return nullptr;
3488
869
}
3489
3490
static RecordDecl *
3491
createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind,
3492
                         QualType KmpInt32Ty,
3493
400
                         QualType KmpRoutineEntryPointerQTy) {
3494
400
  ASTContext &C = CGM.getContext();
3495
  // Build struct kmp_task_t {
3496
  //         void *              shareds;
3497
  //         kmp_routine_entry_t routine;
3498
  //         kmp_int32           part_id;
3499
  //         kmp_cmplrdata_t data1;
3500
  //         kmp_cmplrdata_t data2;
3501
  // For taskloops additional fields:
3502
  //         kmp_uint64          lb;
3503
  //         kmp_uint64          ub;
3504
  //         kmp_int64           st;
3505
  //         kmp_int32           liter;
3506
  //         void *              reductions;
3507
  //       };
3508
400
  RecordDecl *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union);
3509
400
  UD->startDefinition();
3510
400
  addFieldToRecordDecl(C, UD, KmpInt32Ty);
3511
400
  addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy);
3512
400
  UD->completeDefinition();
3513
400
  QualType KmpCmplrdataTy = C.getRecordType(UD);
3514
400
  RecordDecl *RD = C.buildImplicitRecord("kmp_task_t");
3515
400
  RD->startDefinition();
3516
400
  addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3517
400
  addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy);
3518
400
  addFieldToRecordDecl(C, RD, KmpInt32Ty);
3519
400
  addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3520
400
  addFieldToRecordDecl(C, RD, KmpCmplrdataTy);
3521
400
  if (isOpenMPTaskLoopDirective(Kind)) {
3522
128
    QualType KmpUInt64Ty =
3523
128
        CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
3524
128
    QualType KmpInt64Ty =
3525
128
        CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
3526
128
    addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3527
128
    addFieldToRecordDecl(C, RD, KmpUInt64Ty);
3528
128
    addFieldToRecordDecl(C, RD, KmpInt64Ty);
3529
128
    addFieldToRecordDecl(C, RD, KmpInt32Ty);
3530
128
    addFieldToRecordDecl(C, RD, C.VoidPtrTy);
3531
128
  }
3532
400
  RD->completeDefinition();
3533
400
  return RD;
3534
400
}
3535
3536
static RecordDecl *
3537
createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy,
3538
869
                                     ArrayRef<PrivateDataTy> Privates) {
3539
869
  ASTContext &C = CGM.getContext();
3540
  // Build struct kmp_task_t_with_privates {
3541
  //         kmp_task_t task_data;
3542
  //         .kmp_privates_t. privates;
3543
  //       };
3544
869
  RecordDecl *RD = C.buildImplicitRecord("kmp_task_t_with_privates");
3545
869
  RD->startDefinition();
3546
869
  addFieldToRecordDecl(C, RD, KmpTaskTQTy);
3547
869
  if (const RecordDecl *PrivateRD = createPrivatesRecordDecl(CGM, Privates))
3548
568
    addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD));
3549
869
  RD->completeDefinition();
3550
869
  return RD;
3551
869
}
3552
3553
/// Emit a proxy function which accepts kmp_task_t as the second
3554
/// argument.
3555
/// \code
3556
/// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) {
3557
///   TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt,
3558
///   For taskloops:
3559
///   tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3560
///   tt->reductions, tt->shareds);
3561
///   return 0;
3562
/// }
3563
/// \endcode
3564
static llvm::Function *
3565
emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc,
3566
                      OpenMPDirectiveKind Kind, QualType KmpInt32Ty,
3567
                      QualType KmpTaskTWithPrivatesPtrQTy,
3568
                      QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy,
3569
                      QualType SharedsPtrTy, llvm::Function *TaskFunction,
3570
869
                      llvm::Value *TaskPrivatesMap) {
3571
869
  ASTContext &C = CGM.getContext();
3572
869
  FunctionArgList Args;
3573
869
  ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3574
869
                            ImplicitParamDecl::Other);
3575
869
  ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3576
869
                                KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3577
869
                                ImplicitParamDecl::Other);
3578
869
  Args.push_back(&GtidArg);
3579
869
  Args.push_back(&TaskTypeArg);
3580
869
  const auto &TaskEntryFnInfo =
3581
869
      CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
3582
869
  llvm::FunctionType *TaskEntryTy =
3583
869
      CGM.getTypes().GetFunctionType(TaskEntryFnInfo);
3584
869
  std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_entry", ""});
3585
869
  auto *TaskEntry = llvm::Function::Create(
3586
869
      TaskEntryTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
3587
869
  CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskEntry, TaskEntryFnInfo);
3588
869
  TaskEntry->setDoesNotRecurse();
3589
869
  CodeGenFunction CGF(CGM);
3590
869
  CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args,
3591
869
                    Loc, Loc);
3592
3593
  // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map,
3594
  // tt,
3595
  // For taskloops:
3596
  // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter,
3597
  // tt->task_data.shareds);
3598
869
  llvm::Value *GtidParam = CGF.EmitLoadOfScalar(
3599
869
      CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc);
3600
869
  LValue TDBase = CGF.EmitLoadOfPointerLValue(
3601
869
      CGF.GetAddrOfLocalVar(&TaskTypeArg),
3602
869
      KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3603
869
  const auto *KmpTaskTWithPrivatesQTyRD =
3604
869
      cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3605
869
  LValue Base =
3606
869
      CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
3607
869
  const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
3608
869
  auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId);
3609
869
  LValue PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI);
3610
869
  llvm::Value *PartidParam = PartIdLVal.getPointer(CGF);
3611
3612
869
  auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds);
3613
869
  LValue SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI);
3614
869
  llvm::Value *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3615
869
      CGF.EmitLoadOfScalar(SharedsLVal, Loc),
3616
869
      CGF.ConvertTypeForMem(SharedsPtrTy));
3617
3618
869
  auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1);
3619
869
  llvm::Value *PrivatesParam;
3620
869
  if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) {
3621
568
    LValue PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI);
3622
568
    PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3623
568
        PrivatesLVal.getPointer(CGF), CGF.VoidPtrTy);
3624
568
  } else {
3625
301
    PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
3626
301
  }
3627
3628
869
  llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam,
3629
869
                               TaskPrivatesMap,
3630
869
                               CGF.Builder
3631
869
                                   .CreatePointerBitCastOrAddrSpaceCast(
3632
869
                                       TDBase.getAddress(CGF), CGF.VoidPtrTy)
3633
869
                                   .getPointer()};
3634
869
  SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs),
3635
869
                                          std::end(CommonArgs));
3636
869
  if (isOpenMPTaskLoopDirective(Kind)) {
3637
226
    auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound);
3638
226
    LValue LBLVal = CGF.EmitLValueForField(Base, *LBFI);
3639
226
    llvm::Value *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc);
3640
226
    auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound);
3641
226
    LValue UBLVal = CGF.EmitLValueForField(Base, *UBFI);
3642
226
    llvm::Value *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc);
3643
226
    auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride);
3644
226
    LValue StLVal = CGF.EmitLValueForField(Base, *StFI);
3645
226
    llvm::Value *StParam = CGF.EmitLoadOfScalar(StLVal, Loc);
3646
226
    auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
3647
226
    LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
3648
226
    llvm::Value *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc);
3649
226
    auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions);
3650
226
    LValue RLVal = CGF.EmitLValueForField(Base, *RFI);
3651
226
    llvm::Value *RParam = CGF.EmitLoadOfScalar(RLVal, Loc);
3652
226
    CallArgs.push_back(LBParam);
3653
226
    CallArgs.push_back(UBParam);
3654
226
    CallArgs.push_back(StParam);
3655
226
    CallArgs.push_back(LIParam);
3656
226
    CallArgs.push_back(RParam);
3657
226
  }
3658
869
  CallArgs.push_back(SharedsParam);
3659
3660
869
  CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction,
3661
869
                                                  CallArgs);
3662
869
  CGF.EmitStoreThroughLValue(RValue::get(CGF.Builder.getInt32(/*C=*/0)),
3663
869
                             CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty));
3664
869
  CGF.FinishFunction();
3665
869
  return TaskEntry;
3666
869
}
3667
3668
static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM,
3669
                                            SourceLocation Loc,
3670
                                            QualType KmpInt32Ty,
3671
                                            QualType KmpTaskTWithPrivatesPtrQTy,
3672
81
                                            QualType KmpTaskTWithPrivatesQTy) {
3673
81
  ASTContext &C = CGM.getContext();
3674
81
  FunctionArgList Args;
3675
81
  ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty,
3676
81
                            ImplicitParamDecl::Other);
3677
81
  ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3678
81
                                KmpTaskTWithPrivatesPtrQTy.withRestrict(),
3679
81
                                ImplicitParamDecl::Other);
3680
81
  Args.push_back(&GtidArg);
3681
81
  Args.push_back(&TaskTypeArg);
3682
81
  const auto &DestructorFnInfo =
3683
81
      CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args);
3684
81
  llvm::FunctionType *DestructorFnTy =
3685
81
      CGM.getTypes().GetFunctionType(DestructorFnInfo);
3686
81
  std::string Name =
3687
81
      CGM.getOpenMPRuntime().getName({"omp_task_destructor", ""});
3688
81
  auto *DestructorFn =
3689
81
      llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage,
3690
81
                             Name, &CGM.getModule());
3691
81
  CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn,
3692
81
                                    DestructorFnInfo);
3693
81
  DestructorFn->setDoesNotRecurse();
3694
81
  CodeGenFunction CGF(CGM);
3695
81
  CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo,
3696
81
                    Args, Loc, Loc);
3697
3698
81
  LValue Base = CGF.EmitLoadOfPointerLValue(
3699
81
      CGF.GetAddrOfLocalVar(&TaskTypeArg),
3700
81
      KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
3701
81
  const auto *KmpTaskTWithPrivatesQTyRD =
3702
81
      cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl());
3703
81
  auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3704
81
  Base = CGF.EmitLValueForField(Base, *FI);
3705
81
  for (const auto *Field :
3706
362
       cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) {
3707
362
    if (QualType::DestructionKind DtorKind =
3708
362
            Field->getType().isDestructedType()) {
3709
162
      LValue FieldLValue = CGF.EmitLValueForField(Base, Field);
3710
162
      CGF.pushDestroy(DtorKind, FieldLValue.getAddress(CGF), Field->getType());
3711
162
    }
3712
362
  }
3713
81
  CGF.FinishFunction();
3714
81
  return DestructorFn;
3715
81
}
3716
3717
/// Emit a privates mapping function for correct handling of private and
3718
/// firstprivate variables.
3719
/// \code
3720
/// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1>
3721
/// **noalias priv1,...,  <tyn> **noalias privn) {
3722
///   *priv1 = &.privates.priv1;
3723
///   ...;
3724
///   *privn = &.privates.privn;
3725
/// }
3726
/// \endcode
3727
static llvm::Value *
3728
emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc,
3729
                               const OMPTaskDataTy &Data, QualType PrivatesQTy,
3730
568
                               ArrayRef<PrivateDataTy> Privates) {
3731
568
  ASTContext &C = CGM.getContext();
3732
568
  FunctionArgList Args;
3733
568
  ImplicitParamDecl TaskPrivatesArg(
3734
568
      C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3735
568
      C.getPointerType(PrivatesQTy).withConst().withRestrict(),
3736
568
      ImplicitParamDecl::Other);
3737
568
  Args.push_back(&TaskPrivatesArg);
3738
568
  llvm::DenseMap<CanonicalDeclPtr<const VarDecl>, unsigned> PrivateVarsPos;
3739
568
  unsigned Counter = 1;
3740
568
  for (const Expr *E : Data.PrivateVars) {
3741
170
    Args.push_back(ImplicitParamDecl::Create(
3742
170
        C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3743
170
        C.getPointerType(C.getPointerType(E->getType()))
3744
170
            .withConst()
3745
170
            .withRestrict(),
3746
170
        ImplicitParamDecl::Other));
3747
170
    const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3748
170
    PrivateVarsPos[VD] = Counter;
3749
170
    ++Counter;
3750
170
  }
3751
1.36k
  for (const Expr *E : Data.FirstprivateVars) {
3752
1.36k
    Args.push_back(ImplicitParamDecl::Create(
3753
1.36k
        C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3754
1.36k
        C.getPointerType(C.getPointerType(E->getType()))
3755
1.36k
            .withConst()
3756
1.36k
            .withRestrict(),
3757
1.36k
        ImplicitParamDecl::Other));
3758
1.36k
    const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3759
1.36k
    PrivateVarsPos[VD] = Counter;
3760
1.36k
    ++Counter;
3761
1.36k
  }
3762
568
  for (const Expr *E : Data.LastprivateVars) {
3763
151
    Args.push_back(ImplicitParamDecl::Create(
3764
151
        C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3765
151
        C.getPointerType(C.getPointerType(E->getType()))
3766
151
            .withConst()
3767
151
            .withRestrict(),
3768
151
        ImplicitParamDecl::Other));
3769
151
    const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
3770
151
    PrivateVarsPos[VD] = Counter;
3771
151
    ++Counter;
3772
151
  }
3773
568
  for (const VarDecl *VD : Data.PrivateLocals) {
3774
8
    QualType Ty = VD->getType().getNonReferenceType();
3775
8
    if (VD->getType()->isLValueReferenceType())
3776
0
      Ty = C.getPointerType(Ty);
3777
8
    if (isAllocatableDecl(VD))
3778
2
      Ty = C.getPointerType(Ty);
3779
8
    Args.push_back(ImplicitParamDecl::Create(
3780
8
        C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3781
8
        C.getPointerType(C.getPointerType(Ty)).withConst().withRestrict(),
3782
8
        ImplicitParamDecl::Other));
3783
8
    PrivateVarsPos[VD] = Counter;
3784
8
    ++Counter;
3785
8
  }
3786
568
  const auto &TaskPrivatesMapFnInfo =
3787
568
      CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3788
568
  llvm::FunctionType *TaskPrivatesMapTy =
3789
568
      CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo);
3790
568
  std::string Name =
3791
568
      CGM.getOpenMPRuntime().getName({"omp_task_privates_map", ""});
3792
568
  auto *TaskPrivatesMap = llvm::Function::Create(
3793
568
      TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage, Name,
3794
568
      &CGM.getModule());
3795
568
  CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap,
3796
568
                                    TaskPrivatesMapFnInfo);
3797
568
  if (CGM.getLangOpts().Optimize) {
3798
0
    TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline);
3799
0
    TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone);
3800
0
    TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline);
3801
0
  }
3802
568
  CodeGenFunction CGF(CGM);
3803
568
  CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap,
3804
568
                    TaskPrivatesMapFnInfo, Args, Loc, Loc);
3805
3806
  // *privi = &.privates.privi;
3807
568
  LValue Base = CGF.EmitLoadOfPointerLValue(
3808
568
      CGF.GetAddrOfLocalVar(&TaskPrivatesArg),
3809
568
      TaskPrivatesArg.getType()->castAs<PointerType>());
3810
568
  const auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl());
3811
568
  Counter = 0;
3812
1.69k
  for (const FieldDecl *Field : PrivatesQTyRD->fields()) {
3813
1.69k
    LValue FieldLVal = CGF.EmitLValueForField(Base, Field);
3814
1.69k
    const VarDecl *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]];
3815
1.69k
    LValue RefLVal =
3816
1.69k
        CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType());
3817
1.69k
    LValue RefLoadLVal = CGF.EmitLoadOfPointerLValue(
3818
1.69k
        RefLVal.getAddress(CGF), RefLVal.getType()->castAs<PointerType>());
3819
1.69k
    CGF.EmitStoreOfScalar(FieldLVal.getPointer(CGF), RefLoadLVal);
3820
1.69k
    ++Counter;
3821
1.69k
  }
3822
568
  CGF.FinishFunction();
3823
568
  return TaskPrivatesMap;
3824
568
}
3825
3826
/// Emit initialization for private variables in task-based directives.
3827
static void emitPrivatesInit(CodeGenFunction &CGF,
3828
                             const OMPExecutableDirective &D,
3829
                             Address KmpTaskSharedsPtr, LValue TDBase,
3830
                             const RecordDecl *KmpTaskTWithPrivatesQTyRD,
3831
                             QualType SharedsTy, QualType SharedsPtrTy,
3832
                             const OMPTaskDataTy &Data,
3833
667
                             ArrayRef<PrivateDataTy> Privates, bool ForDup) {
3834
667
  ASTContext &C = CGF.getContext();
3835
667
  auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
3836
667
  LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI);
3837
667
  OpenMPDirectiveKind Kind = isOpenMPTaskLoopDirective(D.getDirectiveKind())
3838
667
                                 ? 
OMPD_taskloop250
3839
667
                                 : 
OMPD_task417
;
3840
667
  const CapturedStmt &CS = *D.getCapturedStmt(Kind);
3841
667
  CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS);
3842
667
  LValue SrcBase;
3843
667
  bool IsTargetTask =
3844
667
      isOpenMPTargetDataManagementDirective(D.getDirectiveKind()) ||
3845
667
      
isOpenMPTargetExecutionDirective(D.getDirectiveKind())579
;
3846
  // For target-based directives skip 4 firstprivate arrays BasePointersArray,
3847
  // PointersArray, SizesArray, and MappersArray. The original variables for
3848
  // these arrays are not captured and we get their addresses explicitly.
3849
667
  if ((!IsTargetTask && 
!Data.FirstprivateVars.empty()311
&&
ForDup139
) ||
3850
667
      
(641
IsTargetTask641
&&
KmpTaskSharedsPtr.isValid()356
)) {
3851
322
    SrcBase = CGF.MakeAddrLValue(
3852
322
        CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
3853
322
            KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)),
3854
322
        SharedsTy);
3855
322
  }
3856
667
  FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin();
3857
2.06k
  for (const PrivateDataTy &Pair : Privates) {
3858
    // Do not initialize private locals.
3859
2.06k
    if (Pair.second.isLocalPrivate()) {
3860
8
      ++FI;
3861
8
      continue;
3862
8
    }
3863
2.05k
    const VarDecl *VD = Pair.second.PrivateCopy;
3864
2.05k
    const Expr *Init = VD->getAnyInitializer();
3865
2.05k
    if (Init && 
(1.67k
!ForDup1.67k
||
(206
isa<CXXConstructExpr>(Init)206
&&
3866
1.61k
                             
!CGF.isTrivialInitializer(Init)146
))) {
3867
1.61k
      LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI);
3868
1.61k
      if (const VarDecl *Elem = Pair.second.PrivateElemInit) {
3869
1.41k
        const VarDecl *OriginalVD = Pair.second.Original;
3870
        // Check if the variable is the target-based BasePointersArray,
3871
        // PointersArray, SizesArray, or MappersArray.
3872
1.41k
        LValue SharedRefLValue;
3873
1.41k
        QualType Type = PrivateLValue.getType();
3874
1.41k
        const FieldDecl *SharedField = CapturesInfo.lookup(OriginalVD);
3875
1.41k
        if (IsTargetTask && 
!SharedField1.10k
) {
3876
710
          assert(isa<ImplicitParamDecl>(OriginalVD) &&
3877
710
                 isa<CapturedDecl>(OriginalVD->getDeclContext()) &&
3878
710
                 cast<CapturedDecl>(OriginalVD->getDeclContext())
3879
710
                         ->getNumParams() == 0 &&
3880
710
                 isa<TranslationUnitDecl>(
3881
710
                     cast<CapturedDecl>(OriginalVD->getDeclContext())
3882
710
                         ->getDeclContext()) &&
3883
710
                 "Expected artificial target data variable.");
3884
0
          SharedRefLValue =
3885
710
              CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type);
3886
710
        } else 
if (703
ForDup703
) {
3887
50
          SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField);
3888
50
          SharedRefLValue = CGF.MakeAddrLValue(
3889
50
              Address(SharedRefLValue.getPointer(CGF),
3890
50
                      C.getDeclAlign(OriginalVD)),
3891
50
              SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl),
3892
50
              SharedRefLValue.getTBAAInfo());
3893
653
        } else if (CGF.LambdaCaptureFields.count(
3894
653
                       Pair.second.Original->getCanonicalDecl()) > 0 ||
3895
653
                   
dyn_cast_or_null<BlockDecl>(CGF.CurCodeDecl)651
) {
3896
13
          SharedRefLValue = CGF.EmitLValue(Pair.second.OriginalRef);
3897
640
        } else {
3898
          // Processing for implicitly captured variables.
3899
640
          InlinedOpenMPRegionRAII Region(
3900
640
              CGF, [](CodeGenFunction &, PrePostActionTy &) 
{}0
, OMPD_unknown,
3901
640
              /*HasCancel=*/false, /*NoInheritance=*/true);
3902
640
          SharedRefLValue = CGF.EmitLValue(Pair.second.OriginalRef);
3903
640
        }
3904
1.41k
        if (Type->isArrayType()) {
3905
          // Initialize firstprivate array.
3906
803
          if (!isa<CXXConstructExpr>(Init) || 
CGF.isTrivialInitializer(Init)52
) {
3907
            // Perform simple memcpy.
3908
751
            CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type);
3909
751
          } else {
3910
            // Initialize firstprivate array using element-by-element
3911
            // initialization.
3912
52
            CGF.EmitOMPAggregateAssign(
3913
52
                PrivateLValue.getAddress(CGF), SharedRefLValue.getAddress(CGF),
3914
52
                Type,
3915
52
                [&CGF, Elem, Init, &CapturesInfo](Address DestElement,
3916
52
                                                  Address SrcElement) {
3917
                  // Clean up any temporaries needed by the initialization.
3918
52
                  CodeGenFunction::OMPPrivateScope InitScope(CGF);
3919
52
                  InitScope.addPrivate(
3920
52
                      Elem, [SrcElement]() -> Address { return SrcElement; });
3921
52
                  (void)InitScope.Privatize();
3922
                  // Emit initialization for single element.
3923
52
                  CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(
3924
52
                      CGF, &CapturesInfo);
3925
52
                  CGF.EmitAnyExprToMem(Init, DestElement,
3926
52
                                       Init->getType().getQualifiers(),
3927
52
                                       /*IsInitializer=*/false);
3928
52
                });
3929
52
          }
3930
803
        } else {
3931
610
          CodeGenFunction::OMPPrivateScope InitScope(CGF);
3932
610
          InitScope.addPrivate(Elem, [SharedRefLValue, &CGF]() -> Address {
3933
610
            return SharedRefLValue.getAddress(CGF);
3934
610
          });
3935
610
          (void)InitScope.Privatize();
3936
610
          CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo);
3937
610
          CGF.EmitExprAsInit(Init, VD, PrivateLValue,
3938
610
                             /*capturedByInit=*/false);
3939
610
        }
3940
1.41k
      } else {
3941
202
        CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false);
3942
202
      }
3943
1.61k
    }
3944
0
    ++FI;
3945
2.05k
  }
3946
667
}
3947
3948
/// Check if duplication function is required for taskloops.
3949
static bool checkInitIsRequired(CodeGenFunction &CGF,
3950
102
                                ArrayRef<PrivateDataTy> Privates) {
3951
102
  bool InitRequired = false;
3952
206
  for (const PrivateDataTy &Pair : Privates) {
3953
206
    if (Pair.second.isLocalPrivate())
3954
0
      continue;
3955
206
    const VarDecl *VD = Pair.second.PrivateCopy;
3956
206
    const Expr *Init = VD->getAnyInitializer();
3957
206
    InitRequired = InitRequired || (Init && 
isa<CXXConstructExpr>(Init)146
&&
3958
206
                                    
!CGF.isTrivialInitializer(Init)50
);
3959
206
    if (InitRequired)
3960
50
      break;
3961
206
  }
3962
102
  return InitRequired;
3963
102
}
3964
3965
3966
/// Emit task_dup function (for initialization of
3967
/// private/firstprivate/lastprivate vars and last_iter flag)
3968
/// \code
3969
/// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int
3970
/// lastpriv) {
3971
/// // setup lastprivate flag
3972
///    task_dst->last = lastpriv;
3973
/// // could be constructor calls here...
3974
/// }
3975
/// \endcode
3976
static llvm::Value *
3977
emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc,
3978
                    const OMPExecutableDirective &D,
3979
                    QualType KmpTaskTWithPrivatesPtrQTy,
3980
                    const RecordDecl *KmpTaskTWithPrivatesQTyRD,
3981
                    const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy,
3982
                    QualType SharedsPtrTy, const OMPTaskDataTy &Data,
3983
99
                    ArrayRef<PrivateDataTy> Privates, bool WithLastIter) {
3984
99
  ASTContext &C = CGM.getContext();
3985
99
  FunctionArgList Args;
3986
99
  ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3987
99
                           KmpTaskTWithPrivatesPtrQTy,
3988
99
                           ImplicitParamDecl::Other);
3989
99
  ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr,
3990
99
                           KmpTaskTWithPrivatesPtrQTy,
3991
99
                           ImplicitParamDecl::Other);
3992
99
  ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy,
3993
99
                                ImplicitParamDecl::Other);
3994
99
  Args.push_back(&DstArg);
3995
99
  Args.push_back(&SrcArg);
3996
99
  Args.push_back(&LastprivArg);
3997
99
  const auto &TaskDupFnInfo =
3998
99
      CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args);
3999
99
  llvm::FunctionType *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo);
4000
99
  std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_dup", ""});
4001
99
  auto *TaskDup = llvm::Function::Create(
4002
99
      TaskDupTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule());
4003
99
  CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskDup, TaskDupFnInfo);
4004
99
  TaskDup->setDoesNotRecurse();
4005
99
  CodeGenFunction CGF(CGM);
4006
99
  CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args, Loc,
4007
99
                    Loc);
4008
4009
99
  LValue TDBase = CGF.EmitLoadOfPointerLValue(
4010
99
      CGF.GetAddrOfLocalVar(&DstArg),
4011
99
      KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4012
  // task_dst->liter = lastpriv;
4013
99
  if (WithLastIter) {
4014
49
    auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter);
4015
49
    LValue Base = CGF.EmitLValueForField(
4016
49
        TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4017
49
    LValue LILVal = CGF.EmitLValueForField(Base, *LIFI);
4018
49
    llvm::Value *Lastpriv = CGF.EmitLoadOfScalar(
4019
49
        CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc);
4020
49
    CGF.EmitStoreOfScalar(Lastpriv, LILVal);
4021
49
  }
4022
4023
  // Emit initial values for private copies (if any).
4024
99
  assert(!Privates.empty());
4025
0
  Address KmpTaskSharedsPtr = Address::invalid();
4026
99
  if (!Data.FirstprivateVars.empty()) {
4027
26
    LValue TDBase = CGF.EmitLoadOfPointerLValue(
4028
26
        CGF.GetAddrOfLocalVar(&SrcArg),
4029
26
        KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>());
4030
26
    LValue Base = CGF.EmitLValueForField(
4031
26
        TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin());
4032
26
    KmpTaskSharedsPtr = Address(
4033
26
        CGF.EmitLoadOfScalar(CGF.EmitLValueForField(
4034
26
                                 Base, *std::next(KmpTaskTQTyRD->field_begin(),
4035
26
                                                  KmpTaskTShareds)),
4036
26
                             Loc),
4037
26
        CGM.getNaturalTypeAlignment(SharedsTy));
4038
26
  }
4039
99
  emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD,
4040
99
                   SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true);
4041
99
  CGF.FinishFunction();
4042
99
  return TaskDup;
4043
99
}
4044
4045
/// Checks if destructor function is required to be generated.
4046
/// \return true if cleanups are required, false otherwise.
4047
static bool
4048
checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD,
4049
568
                         ArrayRef<PrivateDataTy> Privates) {
4050
1.49k
  for (const PrivateDataTy &P : Privates) {
4051
1.49k
    if (P.second.isLocalPrivate())
4052
8
      continue;
4053
1.48k
    QualType Ty = P.second.Original->getType().getNonReferenceType();
4054
1.48k
    if (Ty.isDestructedType())
4055
81
      return true;
4056
1.48k
  }
4057
487
  return false;
4058
568
}
4059
4060
namespace {
4061
/// Loop generator for OpenMP iterator expression.
4062
class OMPIteratorGeneratorScope final
4063
    : public CodeGenFunction::OMPPrivateScope {
4064
  CodeGenFunction &CGF;
4065
  const OMPIteratorExpr *E = nullptr;
4066
  SmallVector<CodeGenFunction::JumpDest, 4> ContDests;
4067
  SmallVector<CodeGenFunction::JumpDest, 4> ExitDests;
4068
  OMPIteratorGeneratorScope() = delete;
4069
  OMPIteratorGeneratorScope(OMPIteratorGeneratorScope &) = delete;
4070
4071
public:
4072
  OMPIteratorGeneratorScope(CodeGenFunction &CGF, const OMPIteratorExpr *E)
4073
426
      : CodeGenFunction::OMPPrivateScope(CGF), CGF(CGF), E(E) {
4074
426
    if (!E)
4075
418
      return;
4076
8
    SmallVector<llvm::Value *, 4> Uppers;
4077
16
    for (unsigned I = 0, End = E->numOfIterators(); I < End; 
++I8
) {
4078
8
      Uppers.push_back(CGF.EmitScalarExpr(E->getHelper(I).Upper));
4079
8
      const auto *VD = cast<VarDecl>(E->getIteratorDecl(I));
4080
8
      addPrivate(VD, [&CGF, VD]() {
4081
8
        return CGF.CreateMemTemp(VD->getType(), VD->getName());
4082
8
      });
4083
8
      const OMPIteratorHelperData &HelperData = E->getHelper(I);
4084
8
      addPrivate(HelperData.CounterVD, [&CGF, &HelperData]() {
4085
8
        return CGF.CreateMemTemp(HelperData.CounterVD->getType(),
4086
8
                                 "counter.addr");
4087
8
      });
4088
8
    }
4089
8
    Privatize();
4090
4091
16
    for (unsigned I = 0, End = E->numOfIterators(); I < End; 
++I8
) {
4092
8
      const OMPIteratorHelperData &HelperData = E->getHelper(I);
4093
8
      LValue CLVal =
4094
8
          CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(HelperData.CounterVD),
4095
8
                             HelperData.CounterVD->getType());
4096
      // Counter = 0;
4097
8
      CGF.EmitStoreOfScalar(
4098
8
          llvm::ConstantInt::get(CLVal.getAddress(CGF).getElementType(), 0),
4099
8
          CLVal);
4100
8
      CodeGenFunction::JumpDest &ContDest =
4101
8
          ContDests.emplace_back(CGF.getJumpDestInCurrentScope("iter.cont"));
4102
8
      CodeGenFunction::JumpDest &ExitDest =
4103
8
          ExitDests.emplace_back(CGF.getJumpDestInCurrentScope("iter.exit"));
4104
      // N = <number-of_iterations>;
4105
8
      llvm::Value *N = Uppers[I];
4106
      // cont:
4107
      // if (Counter < N) goto body; else goto exit;
4108
8
      CGF.EmitBlock(ContDest.getBlock());
4109
8
      auto *CVal =
4110
8
          CGF.EmitLoadOfScalar(CLVal, HelperData.CounterVD->getLocation());
4111
8
      llvm::Value *Cmp =
4112
8
          HelperData.CounterVD->getType()->isSignedIntegerOrEnumerationType()
4113
8
              ? 
CGF.Builder.CreateICmpSLT(CVal, N)6
4114
8
              : 
CGF.Builder.CreateICmpULT(CVal, N)2
;
4115
8
      llvm::BasicBlock *BodyBB = CGF.createBasicBlock("iter.body");
4116
8
      CGF.Builder.CreateCondBr(Cmp, BodyBB, ExitDest.getBlock());
4117
      // body:
4118
8
      CGF.EmitBlock(BodyBB);
4119
      // Iteri = Begini + Counter * Stepi;
4120
8
      CGF.EmitIgnoredExpr(HelperData.Update);
4121
8
    }
4122
8
  }
4123
426
  ~OMPIteratorGeneratorScope() {
4124
426
    if (!E)
4125
418
      return;
4126
16
    
for (unsigned I = E->numOfIterators(); 8
I > 0;
--I8
) {
4127
      // Counter = Counter + 1;
4128
8
      const OMPIteratorHelperData &HelperData = E->getHelper(I - 1);
4129
8
      CGF.EmitIgnoredExpr(HelperData.CounterUpdate);
4130
      // goto cont;
4131
8
      CGF.EmitBranchThroughCleanup(ContDests[I - 1]);
4132
      // exit:
4133
8
      CGF.EmitBlock(ExitDests[I - 1].getBlock(), /*IsFinished=*/I == 1);
4134
8
    }
4135
8
  }
4136
};
4137
} // namespace
4138
4139
static std::pair<llvm::Value *, llvm::Value *>
4140
960
getPointerAndSize(CodeGenFunction &CGF, const Expr *E) {
4141
960
  const auto *OASE = dyn_cast<OMPArrayShapingExpr>(E);
4142
960
  llvm::Value *Addr;
4143
960
  if (OASE) {
4144
6
    const Expr *Base = OASE->getBase();
4145
6
    Addr = CGF.EmitScalarExpr(Base);
4146
954
  } else {
4147
954
    Addr = CGF.EmitLValue(E).getPointer(CGF);
4148
954
  }
4149
960
  llvm::Value *SizeVal;
4150
960
  QualType Ty = E->getType();
4151
960
  if (OASE) {
4152
6
    SizeVal = CGF.getTypeSize(OASE->getBase()->getType()->getPointeeType());
4153
18
    for (const Expr *SE : OASE->getDimensions()) {
4154
18
      llvm::Value *Sz = CGF.EmitScalarExpr(SE);
4155
18
      Sz = CGF.EmitScalarConversion(
4156
18
          Sz, SE->getType(), CGF.getContext().getSizeType(), SE->getExprLoc());
4157
18
      SizeVal = CGF.Builder.CreateNUWMul(SizeVal, Sz);
4158
18
    }
4159
954
  } else if (const auto *ASE =
4160
954
                 dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) {
4161
28
    LValue UpAddrLVal =
4162
28
        CGF.EmitOMPArraySectionExpr(ASE, /*IsLowerBound=*/false);
4163
28
    Address UpAddrAddress = UpAddrLVal.getAddress(CGF);
4164
28
    llvm::Value *UpAddr = CGF.Builder.CreateConstGEP1_32(
4165
28
        UpAddrAddress.getElementType(), UpAddrAddress.getPointer(), /*Idx0=*/1);
4166
28
    llvm::Value *LowIntPtr = CGF.Builder.CreatePtrToInt(Addr, CGF.SizeTy);
4167
28
    llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGF.SizeTy);
4168
28
    SizeVal = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr);
4169
926
  } else {
4170
926
    SizeVal = CGF.getTypeSize(Ty);
4171
926
  }
4172
960
  return std::make_pair(Addr, SizeVal);
4173
960
}
4174
4175
/// Builds kmp_depend_info, if it is not built yet, and builds flags type.
4176
4
static void getKmpAffinityType(ASTContext &C, QualType &KmpTaskAffinityInfoTy) {
4177
4
  QualType FlagsTy = C.getIntTypeForBitwidth(32, /*Signed=*/false);
4178
4
  if (KmpTaskAffinityInfoTy.isNull()) {
4179
2
    RecordDecl *KmpAffinityInfoRD =
4180
2
        C.buildImplicitRecord("kmp_task_affinity_info_t");
4181
2
    KmpAffinityInfoRD->startDefinition();
4182
2
    addFieldToRecordDecl(C, KmpAffinityInfoRD, C.getIntPtrType());
4183
2
    addFieldToRecordDecl(C, KmpAffinityInfoRD, C.getSizeType());
4184
2
    addFieldToRecordDecl(C, KmpAffinityInfoRD, FlagsTy);
4185
2
    KmpAffinityInfoRD->completeDefinition();
4186
2
    KmpTaskAffinityInfoTy = C.getRecordType(KmpAffinityInfoRD);
4187
2
  }
4188
4
}
4189
4190
CGOpenMPRuntime::TaskResultTy
4191
CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc,
4192
                              const OMPExecutableDirective &D,
4193
                              llvm::Function *TaskFunction, QualType SharedsTy,
4194
869
                              Address Shareds, const OMPTaskDataTy &Data) {
4195
869
  ASTContext &C = CGM.getContext();
4196
869
  llvm::SmallVector<PrivateDataTy, 4> Privates;
4197
  // Aggregate privates and sort them by the alignment.
4198
869
  const auto *I = Data.PrivateCopies.begin();
4199
869
  for (const Expr *E : Data.PrivateVars) {
4200
170
    const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4201
170
    Privates.emplace_back(
4202
170
        C.getDeclAlign(VD),
4203
170
        PrivateHelpersTy(E, VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4204
170
                         /*PrivateElemInit=*/nullptr));
4205
170
    ++I;
4206
170
  }
4207
869
  I = Data.FirstprivateCopies.begin();
4208
869
  const auto *IElemInitRef = Data.FirstprivateInits.begin();
4209
1.36k
  for (const Expr *E : Data.FirstprivateVars) {
4210
1.36k
    const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4211
1.36k
    Privates.emplace_back(
4212
1.36k
        C.getDeclAlign(VD),
4213
1.36k
        PrivateHelpersTy(
4214
1.36k
            E, VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4215
1.36k
            cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl())));
4216
1.36k
    ++I;
4217
1.36k
    ++IElemInitRef;
4218
1.36k
  }
4219
869
  I = Data.LastprivateCopies.begin();
4220
869
  for (const Expr *E : Data.LastprivateVars) {
4221
151
    const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
4222
151
    Privates.emplace_back(
4223
151
        C.getDeclAlign(VD),
4224
151
        PrivateHelpersTy(E, VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()),
4225
151
                         /*PrivateElemInit=*/nullptr));
4226
151
    ++I;
4227
151
  }
4228
869
  for (const VarDecl *VD : Data.PrivateLocals) {
4229
8
    if (isAllocatableDecl(VD))
4230
2
      Privates.emplace_back(CGM.getPointerAlign(), PrivateHelpersTy(VD));
4231
6
    else
4232
6
      Privates.emplace_back(C.getDeclAlign(VD), PrivateHelpersTy(VD));
4233
8
  }
4234
869
  llvm::stable_sort(Privates,
4235
1.63k
                    [](const PrivateDataTy &L, const PrivateDataTy &R) {
4236
1.63k
                      return L.first > R.first;
4237
1.63k
                    });
4238
869
  QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
4239
  // Build type kmp_routine_entry_t (if not built yet).
4240
869
  emitKmpRoutineEntryT(KmpInt32Ty);
4241
  // Build type kmp_task_t (if not built yet).
4242
869
  if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) {
4243
226
    if (SavedKmpTaskloopTQTy.isNull()) {
4244
128
      SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4245
128
          CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4246
128
    }
4247
226
    KmpTaskTQTy = SavedKmpTaskloopTQTy;
4248
643
  } else {
4249
643
    assert((D.getDirectiveKind() == OMPD_task ||
4250
643
            isOpenMPTargetExecutionDirective(D.getDirectiveKind()) ||
4251
643
            isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) &&
4252
643
           "Expected taskloop, task or target directive");
4253
643
    if (SavedKmpTaskTQTy.isNull()) {
4254
272
      SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl(
4255
272
          CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy));
4256
272
    }
4257
643
    KmpTaskTQTy = SavedKmpTaskTQTy;
4258
643
  }
4259
0
  const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl());
4260
  // Build particular struct kmp_task_t for the given task.
4261
869
  const RecordDecl *KmpTaskTWithPrivatesQTyRD =
4262
869
      createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates);
4263
869
  QualType KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD);
4264
869
  QualType KmpTaskTWithPrivatesPtrQTy =
4265
869
      C.getPointerType(KmpTaskTWithPrivatesQTy);
4266
869
  llvm::Type *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy);
4267
869
  llvm::Type *KmpTaskTWithPrivatesPtrTy =
4268
869
      KmpTaskTWithPrivatesTy->getPointerTo();
4269
869
  llvm::Value *KmpTaskTWithPrivatesTySize =
4270
869
      CGF.getTypeSize(KmpTaskTWithPrivatesQTy);
4271
869
  QualType SharedsPtrTy = C.getPointerType(SharedsTy);
4272
4273
  // Emit initial values for private copies (if any).
4274
869
  llvm::Value *TaskPrivatesMap = nullptr;
4275
869
  llvm::Type *TaskPrivatesMapTy =
4276
869
      std::next(TaskFunction->arg_begin(), 3)->getType();
4277
869
  if (!Privates.empty()) {
4278
568
    auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin());
4279
568
    TaskPrivatesMap =
4280
568
        emitTaskPrivateMappingFunction(CGM, Loc, Data, FI->getType(), Privates);
4281
568
    TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4282
568
        TaskPrivatesMap, TaskPrivatesMapTy);
4283
568
  } else {
4284
301
    TaskPrivatesMap = llvm::ConstantPointerNull::get(
4285
301
        cast<llvm::PointerType>(TaskPrivatesMapTy));
4286
301
  }
4287
  // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid,
4288
  // kmp_task_t *tt);
4289
869
  llvm::Function *TaskEntry = emitProxyTaskFunction(
4290
869
      CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4291
869
      KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction,
4292
869
      TaskPrivatesMap);
4293
4294
  // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid,
4295
  // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds,
4296
  // kmp_routine_entry_t *task_entry);
4297
  // Task flags. Format is taken from
4298
  // https://github.com/llvm/llvm-project/blob/main/openmp/runtime/src/kmp.h,
4299
  // description of kmp_tasking_flags struct.
4300
869
  enum {
4301
869
    TiedFlag = 0x1,
4302
869
    FinalFlag = 0x2,
4303
869
    DestructorsFlag = 0x8,
4304
869
    PriorityFlag = 0x20,
4305
869
    DetachableFlag = 0x40,
4306
869
  };
4307
869
  unsigned Flags = Data.Tied ? 
TiedFlag853
:
016
;
4308
869
  bool NeedsCleanup = false;
4309
869
  if (!Privates.empty()) {
4310
568
    NeedsCleanup =
4311
568
        checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD, Privates);
4312
568
    if (NeedsCleanup)
4313
81
      Flags = Flags | DestructorsFlag;
4314
568
  }
4315
869
  if (Data.Priority.getInt())
4316
22
    Flags = Flags | PriorityFlag;
4317
869
  if (D.hasClausesOfKind<OMPDetachClause>())
4318
2
    Flags = Flags | DetachableFlag;
4319
869
  llvm::Value *TaskFlags =
4320
869
      Data.Final.getPointer()
4321
869
          ? CGF.Builder.CreateSelect(Data.Final.getPointer(),
4322
10
                                     CGF.Builder.getInt32(FinalFlag),
4323
10
                                     CGF.Builder.getInt32(/*C=*/0))
4324
869
          : 
CGF.Builder.getInt32(859
Data.Final.getInt()859
?
FinalFlag8
:
0851
);
4325
869
  TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags));
4326
869
  llvm::Value *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy));
4327
869
  SmallVector<llvm::Value *, 8> AllocArgs = {emitUpdateLocation(CGF, Loc),
4328
869
      getThreadID(CGF, Loc), TaskFlags, KmpTaskTWithPrivatesTySize,
4329
869
      SharedsSize, CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4330
869
          TaskEntry, KmpRoutineEntryPtrTy)};
4331
869
  llvm::Value *NewTask;
4332
869
  if (D.hasClausesOfKind<OMPNowaitClause>()) {
4333
    // Check if we have any device clause associated with the directive.
4334
296
    const Expr *Device = nullptr;
4335
296
    if (auto *C = D.getSingleClause<OMPDeviceClause>())
4336
166
      Device = C->getDevice();
4337
    // Emit device ID if any otherwise use default value.
4338
296
    llvm::Value *DeviceID;
4339
296
    if (Device)
4340
166
      DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device),
4341
166
                                           CGF.Int64Ty, /*isSigned=*/true);
4342
130
    else
4343
130
      DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF);
4344
296
    AllocArgs.push_back(DeviceID);
4345
296
    NewTask = CGF.EmitRuntimeCall(
4346
296
        OMPBuilder.getOrCreateRuntimeFunction(
4347
296
            CGM.getModule(), OMPRTL___kmpc_omp_target_task_alloc),
4348
296
        AllocArgs);
4349
573
  } else {
4350
573
    NewTask =
4351
573
        CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
4352
573
                                CGM.getModule(), OMPRTL___kmpc_omp_task_alloc),
4353
573
                            AllocArgs);
4354
573
  }
4355
  // Emit detach clause initialization.
4356
  // evt = (typeof(evt))__kmpc_task_allow_completion_event(loc, tid,
4357
  // task_descriptor);
4358
869
  if (const auto *DC = D.getSingleClause<OMPDetachClause>()) {
4359
2
    const Expr *Evt = DC->getEventHandler()->IgnoreParenImpCasts();
4360
2
    LValue EvtLVal = CGF.EmitLValue(Evt);
4361
4362
    // Build kmp_event_t *__kmpc_task_allow_completion_event(ident_t *loc_ref,
4363
    // int gtid, kmp_task_t *task);
4364
2
    llvm::Value *Loc = emitUpdateLocation(CGF, DC->getBeginLoc());
4365
2
    llvm::Value *Tid = getThreadID(CGF, DC->getBeginLoc());
4366
2
    Tid = CGF.Builder.CreateIntCast(Tid, CGF.IntTy, /*isSigned=*/false);
4367
2
    llvm::Value *EvtVal = CGF.EmitRuntimeCall(
4368
2
        OMPBuilder.getOrCreateRuntimeFunction(
4369
2
            CGM.getModule(), OMPRTL___kmpc_task_allow_completion_event),
4370
2
        {Loc, Tid, NewTask});
4371
2
    EvtVal = CGF.EmitScalarConversion(EvtVal, C.VoidPtrTy, Evt->getType(),
4372
2
                                      Evt->getExprLoc());
4373
2
    CGF.EmitStoreOfScalar(EvtVal, EvtLVal);
4374
2
  }
4375
  // Process affinity clauses.
4376
869
  if (D.hasClausesOfKind<OMPAffinityClause>()) {
4377
    // Process list of affinity data.
4378
4
    ASTContext &C = CGM.getContext();
4379
4
    Address AffinitiesArray = Address::invalid();
4380
    // Calculate number of elements to form the array of affinity data.
4381
4
    llvm::Value *NumOfElements = nullptr;
4382
4
    unsigned NumAffinities = 0;
4383
6
    for (const auto *C : D.getClausesOfKind<OMPAffinityClause>()) {
4384
6
      if (const Expr *Modifier = C->getModifier()) {
4385
2
        const auto *IE = cast<OMPIteratorExpr>(Modifier->IgnoreParenImpCasts());
4386
4
        for (unsigned I = 0, E = IE->numOfIterators(); I < E; 
++I2
) {
4387
2
          llvm::Value *Sz = CGF.EmitScalarExpr(IE->getHelper(I).Upper);
4388
2
          Sz = CGF.Builder.CreateIntCast(Sz, CGF.SizeTy, /*isSigned=*/false);
4389
2
          NumOfElements =
4390
2
              NumOfElements ? 
CGF.Builder.CreateNUWMul(NumOfElements, Sz)0
: Sz;
4391
2
        }
4392
4
      } else {
4393
4
        NumAffinities += C->varlist_size();
4394
4
      }
4395
6
    }
4396
4
    getKmpAffinityType(CGM.getContext(), KmpTaskAffinityInfoTy);
4397
    // Fields ids in kmp_task_affinity_info record.
4398
4
    enum RTLAffinityInfoFieldsTy { BaseAddr, Len, Flags };
4399
4400
4
    QualType KmpTaskAffinityInfoArrayTy;
4401
4
    if (NumOfElements) {
4402
2
      NumOfElements = CGF.Builder.CreateNUWAdd(
4403
2
          llvm::ConstantInt::get(CGF.SizeTy, NumAffinities), NumOfElements);
4404
2
      auto *OVE = new (C) OpaqueValueExpr(
4405
2
          Loc,
4406
2
          C.getIntTypeForBitwidth(C.getTypeSize(C.getSizeType()), /*Signed=*/0),
4407
2
          VK_PRValue);
4408
2
      CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, OVE,
4409
2
                                                    RValue::get(NumOfElements));
4410
2
      KmpTaskAffinityInfoArrayTy =
4411
2
          C.getVariableArrayType(KmpTaskAffinityInfoTy, OVE, ArrayType::Normal,
4412
2
                                 /*IndexTypeQuals=*/0, SourceRange(Loc, Loc));
4413
      // Properly emit variable-sized array.
4414
2
      auto *PD = ImplicitParamDecl::Create(C, KmpTaskAffinityInfoArrayTy,
4415
2
                                           ImplicitParamDecl::Other);
4416
2
      CGF.EmitVarDecl(*PD);
4417
2
      AffinitiesArray = CGF.GetAddrOfLocalVar(PD);
4418
2
      NumOfElements = CGF.Builder.CreateIntCast(NumOfElements, CGF.Int32Ty,
4419
2
                                                /*isSigned=*/false);
4420
2
    } else {
4421
2
      KmpTaskAffinityInfoArrayTy = C.getConstantArrayType(
4422
2
          KmpTaskAffinityInfoTy,
4423
2
          llvm::APInt(C.getTypeSize(C.getSizeType()), NumAffinities), nullptr,
4424
2
          ArrayType::Normal, /*IndexTypeQuals=*/0);
4425
2
      AffinitiesArray =
4426
2
          CGF.CreateMemTemp(KmpTaskAffinityInfoArrayTy, ".affs.arr.addr");
4427
2
      AffinitiesArray = CGF.Builder.CreateConstArrayGEP(AffinitiesArray, 0);
4428
2
      NumOfElements = llvm::ConstantInt::get(CGM.Int32Ty, NumAffinities,
4429
2
                                             /*isSigned=*/false);
4430
2
    }
4431
4432
4
    const auto *KmpAffinityInfoRD = KmpTaskAffinityInfoTy->getAsRecordDecl();
4433
    // Fill array by elements without iterators.
4434
4
    unsigned Pos = 0;
4435
4
    bool HasIterator = false;
4436
6
    for (const auto *C : D.getClausesOfKind<OMPAffinityClause>()) {
4437
6
      if (C->getModifier()) {
4438
2
        HasIterator = true;
4439
2
        continue;
4440
2
      }
4441
4
      for (const Expr *E : C->varlists()) {
4442
4
        llvm::Value *Addr;
4443
4
        llvm::Value *Size;
4444
4
        std::tie(Addr, Size) = getPointerAndSize(CGF, E);
4445
4
        LValue Base =
4446
4
            CGF.MakeAddrLValue(CGF.Builder.CreateConstGEP(AffinitiesArray, Pos),
4447
4
                               KmpTaskAffinityInfoTy);
4448
        // affs[i].base_addr = &<Affinities[i].second>;
4449
4
        LValue BaseAddrLVal = CGF.EmitLValueForField(
4450
4
            Base, *std::next(KmpAffinityInfoRD->field_begin(), BaseAddr));
4451
4
        CGF.EmitStoreOfScalar(CGF.Builder.CreatePtrToInt(Addr, CGF.IntPtrTy),
4452
4
                              BaseAddrLVal);
4453
        // affs[i].len = sizeof(<Affinities[i].second>);
4454
4
        LValue LenLVal = CGF.EmitLValueForField(
4455
4
            Base, *std::next(KmpAffinityInfoRD->field_begin(), Len));
4456
4
        CGF.EmitStoreOfScalar(Size, LenLVal);
4457
4
        ++Pos;
4458
4
      }
4459
4
    }
4460
4
    LValue PosLVal;
4461
4
    if (HasIterator) {
4462
2
      PosLVal = CGF.MakeAddrLValue(
4463
2
          CGF.CreateMemTemp(C.getSizeType(), "affs.counter.addr"),
4464
2
          C.getSizeType());
4465
2
      CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.SizeTy, Pos), PosLVal);
4466
2
    }
4467
    // Process elements with iterators.
4468
6
    for (const auto *C : D.getClausesOfKind<OMPAffinityClause>()) {
4469
6
      const Expr *Modifier = C->getModifier();
4470
6
      if (!Modifier)
4471
4
        continue;
4472
2
      OMPIteratorGeneratorScope IteratorScope(
4473
2
          CGF, cast_or_null<OMPIteratorExpr>(Modifier->IgnoreParenImpCasts()));
4474
2
      for (const Expr *E : C->varlists()) {
4475
2
        llvm::Value *Addr;
4476
2
        llvm::Value *Size;
4477
2
        std::tie(Addr, Size) = getPointerAndSize(CGF, E);
4478
2
        llvm::Value *Idx = CGF.EmitLoadOfScalar(PosLVal, E->getExprLoc());
4479
2
        LValue Base = CGF.MakeAddrLValue(
4480
2
            Address(CGF.Builder.CreateGEP(AffinitiesArray.getElementType(),
4481
2
                                          AffinitiesArray.getPointer(), Idx),
4482
2
                    AffinitiesArray.getAlignment()),
4483
2
            KmpTaskAffinityInfoTy);
4484
        // affs[i].base_addr = &<Affinities[i].second>;
4485
2
        LValue BaseAddrLVal = CGF.EmitLValueForField(
4486
2
            Base, *std::next(KmpAffinityInfoRD->field_begin(), BaseAddr));
4487
2
        CGF.EmitStoreOfScalar(CGF.Builder.CreatePtrToInt(Addr, CGF.IntPtrTy),
4488
2
                              BaseAddrLVal);
4489
        // affs[i].len = sizeof(<Affinities[i].second>);
4490
2
        LValue LenLVal = CGF.EmitLValueForField(
4491
2
            Base, *std::next(KmpAffinityInfoRD->field_begin(), Len));
4492
2
        CGF.EmitStoreOfScalar(Size, LenLVal);
4493
2
        Idx = CGF.Builder.CreateNUWAdd(
4494
2
            Idx, llvm::ConstantInt::get(Idx->getType(), 1));
4495
2
        CGF.EmitStoreOfScalar(Idx, PosLVal);
4496
2
      }
4497
2
    }
4498
    // Call to kmp_int32 __kmpc_omp_reg_task_with_affinity(ident_t *loc_ref,
4499
    // kmp_int32 gtid, kmp_task_t *new_task, kmp_int32
4500
    // naffins, kmp_task_affinity_info_t *affin_list);
4501
4
    llvm::Value *LocRef = emitUpdateLocation(CGF, Loc);
4502
4
    llvm::Value *GTid = getThreadID(CGF, Loc);
4503
4
    llvm::Value *AffinListPtr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4504
4
        AffinitiesArray.getPointer(), CGM.VoidPtrTy);
4505
    // FIXME: Emit the function and ignore its result for now unless the
4506
    // runtime function is properly implemented.
4507
4
    (void)CGF.EmitRuntimeCall(
4508
4
        OMPBuilder.getOrCreateRuntimeFunction(
4509
4
            CGM.getModule(), OMPRTL___kmpc_omp_reg_task_with_affinity),
4510
4
        {LocRef, GTid, NewTask, NumOfElements, AffinListPtr});
4511
4
  }
4512
869
  llvm::Value *NewTaskNewTaskTTy =
4513
869
      CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4514
869
          NewTask, KmpTaskTWithPrivatesPtrTy);
4515
869
  LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy,
4516
869
                                               KmpTaskTWithPrivatesQTy);
4517
869
  LValue TDBase =
4518
869
      CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin());
4519
  // Fill the data in the resulting kmp_task_t record.
4520
  // Copy shareds if there are any.
4521
869
  Address KmpTaskSharedsPtr = Address::invalid();
4522
869
  if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) {
4523
544
    KmpTaskSharedsPtr =
4524
544
        Address(CGF.EmitLoadOfScalar(
4525
544
                    CGF.EmitLValueForField(
4526
544
                        TDBase, *std::next(KmpTaskTQTyRD->field_begin(),
4527
544
                                           KmpTaskTShareds)),
4528
544
                    Loc),
4529
544
                CGM.getNaturalTypeAlignment(SharedsTy));
4530
544
    LValue Dest = CGF.MakeAddrLValue(KmpTaskSharedsPtr, SharedsTy);
4531
544
    LValue Src = CGF.MakeAddrLValue(Shareds, SharedsTy);
4532
544
    CGF.EmitAggregateCopy(Dest, Src, SharedsTy, AggValueSlot::DoesNotOverlap);
4533
544
  }
4534
  // Emit initial values for private copies (if any).
4535
869
  TaskResultTy Result;
4536
869
  if (!Privates.empty()) {
4537
568
    emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD,
4538
568
                     SharedsTy, SharedsPtrTy, Data, Privates,
4539
568
                     /*ForDup=*/false);
4540
568
    if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) &&
4541
568
        
(151
!Data.LastprivateVars.empty()151
||
checkInitIsRequired(CGF, Privates)102
)) {
4542
99
      Result.TaskDupFn = emitTaskDupFunction(
4543
99
          CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD,
4544
99
          KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates,
4545
99
          /*WithLastIter=*/!Data.LastprivateVars.empty());
4546
99
    }
4547
568
  }
4548
  // Fields of union "kmp_cmplrdata_t" for destructors and priority.
4549
869
  enum { Priority = 0, Destructors = 1 };
4550
  // Provide pointer to function with destructors for privates.
4551
869
  auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1);
4552
869
  const RecordDecl *KmpCmplrdataUD =
4553
869
      (*FI)->getType()->getAsUnionType()->getDecl();
4554
869
  if (NeedsCleanup) {
4555
81
    llvm::Value *DestructorFn = emitDestructorsFunction(
4556
81
        CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy,
4557
81
        KmpTaskTWithPrivatesQTy);
4558
81
    LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI);
4559
81
    LValue DestructorsLV = CGF.EmitLValueForField(
4560
81
        Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors));
4561
81
    CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4562
81
                              DestructorFn, KmpRoutineEntryPtrTy),
4563
81
                          DestructorsLV);
4564
81
  }
4565
  // Set priority.
4566
869
  if (Data.Priority.getInt()) {
4567
22
    LValue Data2LV = CGF.EmitLValueForField(
4568
22
        TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2));
4569
22
    LValue PriorityLV = CGF.EmitLValueForField(
4570
22
        Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority));
4571
22
    CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV);
4572
22
  }
4573
869
  Result.NewTask = NewTask;
4574
869
  Result.TaskEntry = TaskEntry;
4575
869
  Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy;
4576
869
  Result.TDBase = TDBase;
4577
869
  Result.KmpTaskTQTyRD = KmpTaskTQTyRD;
4578
869
  return Result;
4579
869
}
4580
4581
namespace {
4582
/// Dependence kind for RTL.
4583
enum RTLDependenceKindTy {
4584
  DepIn = 0x01,
4585
  DepInOut = 0x3,
4586
  DepMutexInOutSet = 0x4
4587
};
4588
/// Fields ids in kmp_depend_info record.
4589
enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags };
4590
} // namespace
4591
4592
/// Translates internal dependency kind into the runtime kind.
4593
958
static RTLDependenceKindTy translateDependencyKind(OpenMPDependClauseKind K) {
4594
958
  RTLDependenceKindTy DepKind;
4595
958
  switch (K) {
4596
172
  case OMPC_DEPEND_in:
4597
172
    DepKind = DepIn;
4598
172
    break;
4599
  // Out and InOut dependencies must use the same code.
4600
334
  case OMPC_DEPEND_out:
4601
776
  case OMPC_DEPEND_inout:
4602
776
    DepKind = DepInOut;
4603
776
    break;
4604
10
  case OMPC_DEPEND_mutexinoutset:
4605
10
    DepKind = DepMutexInOutSet;
4606
10
    break;
4607
0
  case OMPC_DEPEND_source:
4608
0
  case OMPC_DEPEND_sink:
4609
0
  case OMPC_DEPEND_depobj:
4610
0
  case OMPC_DEPEND_unknown:
4611
0
    llvm_unreachable("Unknown task dependence type");
4612
958
  }
4613
958
  return DepKind;
4614
958
}
4615
4616
/// Builds kmp_depend_info, if it is not built yet, and builds flags type.
4617
static void getDependTypes(ASTContext &C, QualType &KmpDependInfoTy,
4618
788
                           QualType &FlagsTy) {
4619
788
  FlagsTy = C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false);
4620
788
  if (KmpDependInfoTy.isNull()) {
4621
91
    RecordDecl *KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info");
4622
91
    KmpDependInfoRD->startDefinition();
4623
91
    addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType());
4624
91
    addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType());
4625
91
    addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy);
4626
91
    KmpDependInfoRD->completeDefinition();
4627
91
    KmpDependInfoTy = C.getRecordType(KmpDependInfoRD);
4628
91
  }
4629
788
}
4630
4631
std::pair<llvm::Value *, LValue>
4632
CGOpenMPRuntime::getDepobjElements(CodeGenFunction &CGF, LValue DepobjLVal,
4633
4
                                   SourceLocation Loc) {
4634
4
  ASTContext &C = CGM.getContext();
4635
4
  QualType FlagsTy;
4636
4
  getDependTypes(C, KmpDependInfoTy, FlagsTy);
4637
4
  RecordDecl *KmpDependInfoRD =
4638
4
      cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
4639
4
  LValue Base = CGF.EmitLoadOfPointerLValue(
4640
4
      DepobjLVal.getAddress(CGF),
4641
4
      C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
4642
4
  QualType KmpDependInfoPtrTy = C.getPointerType(KmpDependInfoTy);
4643
4
  Address Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4644
4
          Base.getAddress(CGF), CGF.ConvertTypeForMem(KmpDependInfoPtrTy));
4645
4
  Base = CGF.MakeAddrLValue(Addr, KmpDependInfoTy, Base.getBaseInfo(),
4646
4
                            Base.getTBAAInfo());
4647
4
  llvm::Value *DepObjAddr = CGF.Builder.CreateGEP(
4648
4
      Addr.getElementType(), Addr.getPointer(),
4649
4
      llvm::ConstantInt::get(CGF.IntPtrTy, -1, /*isSigned=*/true));
4650
4
  LValue NumDepsBase = CGF.MakeAddrLValue(
4651
4
      Address(DepObjAddr, Addr.getAlignment()), KmpDependInfoTy,
4652
4
      Base.getBaseInfo(), Base.getTBAAInfo());
4653
  // NumDeps = deps[i].base_addr;
4654
4
  LValue BaseAddrLVal = CGF.EmitLValueForField(
4655
4
      NumDepsBase, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
4656
4
  llvm::Value *NumDeps = CGF.EmitLoadOfScalar(BaseAddrLVal, Loc);
4657
4
  return std::make_pair(NumDeps, Base);
4658
4
}
4659
4660
static void emitDependData(CodeGenFunction &CGF, QualType &KmpDependInfoTy,
4661
                           llvm::PointerUnion<unsigned *, LValue *> Pos,
4662
                           const OMPTaskDataTy::DependData &Data,
4663
420
                           Address DependenciesArray) {
4664
420
  CodeGenModule &CGM = CGF.CGM;
4665
420
  ASTContext &C = CGM.getContext();
4666
420
  QualType FlagsTy;
4667
420
  getDependTypes(C, KmpDependInfoTy, FlagsTy);
4668
420
  RecordDecl *KmpDependInfoRD =
4669
420
      cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
4670
420
  llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy);
4671
4672
420
  OMPIteratorGeneratorScope IteratorScope(
4673
420
      CGF, cast_or_null<OMPIteratorExpr>(
4674
420
               Data.IteratorExpr ? 
Data.IteratorExpr->IgnoreParenImpCasts()6
4675
420
                                 : 
nullptr414
));
4676
954
  for (const Expr *E : Data.DepExprs) {
4677
954
    llvm::Value *Addr;
4678
954
    llvm::Value *Size;
4679
954
    std::tie(Addr, Size) = getPointerAndSize(CGF, E);
4680
954
    LValue Base;
4681
954
    if (unsigned *P = Pos.dyn_cast<unsigned *>()) {
4682
948
      Base = CGF.MakeAddrLValue(
4683
948
          CGF.Builder.CreateConstGEP(DependenciesArray, *P), KmpDependInfoTy);
4684
948
    } else {
4685
6
      LValue &PosLVal = *Pos.get<LValue *>();
4686
6
      llvm::Value *Idx = CGF.EmitLoadOfScalar(PosLVal, E->getExprLoc());
4687
6
      Base = CGF.MakeAddrLValue(
4688
6
          Address(CGF.Builder.CreateGEP(DependenciesArray.getElementType(),
4689
6
                                        DependenciesArray.getPointer(), Idx),
4690
6
                  DependenciesArray.getAlignment()),
4691
6
          KmpDependInfoTy);
4692
6
    }
4693
    // deps[i].base_addr = &<Dependencies[i].second>;
4694
954
    LValue BaseAddrLVal = CGF.EmitLValueForField(
4695
954
        Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
4696
954
    CGF.EmitStoreOfScalar(CGF.Builder.CreatePtrToInt(Addr, CGF.IntPtrTy),
4697
954
                          BaseAddrLVal);
4698
    // deps[i].len = sizeof(<Dependencies[i].second>);
4699
954
    LValue LenLVal = CGF.EmitLValueForField(
4700
954
        Base, *std::next(KmpDependInfoRD->field_begin(), Len));
4701
954
    CGF.EmitStoreOfScalar(Size, LenLVal);
4702
    // deps[i].flags = <Dependencies[i].first>;
4703
954
    RTLDependenceKindTy DepKind = translateDependencyKind(Data.DepKind);
4704
954
    LValue FlagsLVal = CGF.EmitLValueForField(
4705
954
        Base, *std::next(KmpDependInfoRD->field_begin(), Flags));
4706
954
    CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind),
4707
954
                          FlagsLVal);
4708
954
    if (unsigned *P = Pos.dyn_cast<unsigned *>()) {
4709
948
      ++(*P);
4710
948
    } else {
4711
6
      LValue &PosLVal = *Pos.get<LValue *>();
4712
6
      llvm::Value *Idx = CGF.EmitLoadOfScalar(PosLVal, E->getExprLoc());
4713
6
      Idx = CGF.Builder.CreateNUWAdd(Idx,
4714
6
                                     llvm::ConstantInt::get(Idx->getType(), 1));
4715
6
      CGF.EmitStoreOfScalar(Idx, PosLVal);
4716
6
    }
4717
954
  }
4718
420
}
4719
4720
static SmallVector<llvm::Value *, 4>
4721
emitDepobjElementsSizes(CodeGenFunction &CGF, QualType &KmpDependInfoTy,
4722
2
                        const OMPTaskDataTy::DependData &Data) {
4723
2
  assert(Data.DepKind == OMPC_DEPEND_depobj &&
4724
2
         "Expected depobj dependecy kind.");
4725
0
  SmallVector<llvm::Value *, 4> Sizes;
4726
2
  SmallVector<LValue, 4> SizeLVals;
4727
2
  ASTContext &C = CGF.getContext();
4728
2
  QualType FlagsTy;
4729
2
  getDependTypes(C, KmpDependInfoTy, FlagsTy);
4730
2
  RecordDecl *KmpDependInfoRD =
4731
2
      cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
4732
2
  QualType KmpDependInfoPtrTy = C.getPointerType(KmpDependInfoTy);
4733
2
  llvm::Type *KmpDependInfoPtrT = CGF.ConvertTypeForMem(KmpDependInfoPtrTy);
4734
2
  {
4735
2
    OMPIteratorGeneratorScope IteratorScope(
4736
2
        CGF, cast_or_null<OMPIteratorExpr>(
4737
2
                 Data.IteratorExpr ? 
Data.IteratorExpr->IgnoreParenImpCasts()0
4738
2
                                   : nullptr));
4739
4
    for (const Expr *E : Data.DepExprs) {
4740
4
      LValue DepobjLVal = CGF.EmitLValue(E->IgnoreParenImpCasts());
4741
4
      LValue Base = CGF.EmitLoadOfPointerLValue(
4742
4
          DepobjLVal.getAddress(CGF),
4743
4
          C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
4744
4
      Address Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4745
4
          Base.getAddress(CGF), KmpDependInfoPtrT);
4746
4
      Base = CGF.MakeAddrLValue(Addr, KmpDependInfoTy, Base.getBaseInfo(),
4747
4
                                Base.getTBAAInfo());
4748
4
      llvm::Value *DepObjAddr = CGF.Builder.CreateGEP(
4749
4
          Addr.getElementType(), Addr.getPointer(),
4750
4
          llvm::ConstantInt::get(CGF.IntPtrTy, -1, /*isSigned=*/true));
4751
4
      LValue NumDepsBase = CGF.MakeAddrLValue(
4752
4
          Address(DepObjAddr, Addr.getAlignment()), KmpDependInfoTy,
4753
4
          Base.getBaseInfo(), Base.getTBAAInfo());
4754
      // NumDeps = deps[i].base_addr;
4755
4
      LValue BaseAddrLVal = CGF.EmitLValueForField(
4756
4
          NumDepsBase, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
4757
4
      llvm::Value *NumDeps =
4758
4
          CGF.EmitLoadOfScalar(BaseAddrLVal, E->getExprLoc());
4759
4
      LValue NumLVal = CGF.MakeAddrLValue(
4760
4
          CGF.CreateMemTemp(C.getUIntPtrType(), "depobj.size.addr"),
4761
4
          C.getUIntPtrType());
4762
4
      CGF.InitTempAlloca(NumLVal.getAddress(CGF),
4763
4
                         llvm::ConstantInt::get(CGF.IntPtrTy, 0));
4764
4
      llvm::Value *PrevVal = CGF.EmitLoadOfScalar(NumLVal, E->getExprLoc());
4765
4
      llvm::Value *Add = CGF.Builder.CreateNUWAdd(PrevVal, NumDeps);
4766
4
      CGF.EmitStoreOfScalar(Add, NumLVal);
4767
4
      SizeLVals.push_back(NumLVal);
4768
4
    }
4769
2
  }
4770
6
  for (unsigned I = 0, E = SizeLVals.size(); I < E; 
++I4
) {
4771
4
    llvm::Value *Size =
4772
4
        CGF.EmitLoadOfScalar(SizeLVals[I], Data.DepExprs[I]->getExprLoc());
4773
4
    Sizes.push_back(Size);
4774
4
  }
4775
2
  return Sizes;
4776
2
}
4777
4778
static void emitDepobjElements(CodeGenFunction &CGF, QualType &KmpDependInfoTy,
4779
                               LValue PosLVal,
4780
                               const OMPTaskDataTy::DependData &Data,
4781
2
                               Address DependenciesArray) {
4782
2
  assert(Data.DepKind == OMPC_DEPEND_depobj &&
4783
2
         "Expected depobj dependecy kind.");
4784
0
  ASTContext &C = CGF.getContext();
4785
2
  QualType FlagsTy;
4786
2
  getDependTypes(C, KmpDependInfoTy, FlagsTy);
4787
2
  RecordDecl *KmpDependInfoRD =
4788
2
      cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
4789
2
  QualType KmpDependInfoPtrTy = C.getPointerType(KmpDependInfoTy);
4790
2
  llvm::Type *KmpDependInfoPtrT = CGF.ConvertTypeForMem(KmpDependInfoPtrTy);
4791
2
  llvm::Value *ElSize = CGF.getTypeSize(KmpDependInfoTy);
4792
2
  {
4793
2
    OMPIteratorGeneratorScope IteratorScope(
4794
2
        CGF, cast_or_null<OMPIteratorExpr>(
4795
2
                 Data.IteratorExpr ? 
Data.IteratorExpr->IgnoreParenImpCasts()0
4796
2
                                   : nullptr));
4797
6
    for (unsigned I = 0, End = Data.DepExprs.size(); I < End; 
++I4
) {
4798
4
      const Expr *E = Data.DepExprs[I];
4799
4
      LValue DepobjLVal = CGF.EmitLValue(E->IgnoreParenImpCasts());
4800
4
      LValue Base = CGF.EmitLoadOfPointerLValue(
4801
4
          DepobjLVal.getAddress(CGF),
4802
4
          C.getPointerType(C.VoidPtrTy).castAs<PointerType>());
4803
4
      Address Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4804
4
          Base.getAddress(CGF), KmpDependInfoPtrT);
4805
4
      Base = CGF.MakeAddrLValue(Addr, KmpDependInfoTy, Base.getBaseInfo(),
4806
4
                                Base.getTBAAInfo());
4807
4808
      // Get number of elements in a single depobj.
4809
4
      llvm::Value *DepObjAddr = CGF.Builder.CreateGEP(
4810
4
          Addr.getElementType(), Addr.getPointer(),
4811
4
          llvm::ConstantInt::get(CGF.IntPtrTy, -1, /*isSigned=*/true));
4812
4
      LValue NumDepsBase = CGF.MakeAddrLValue(
4813
4
          Address(DepObjAddr, Addr.getAlignment()), KmpDependInfoTy,
4814
4
          Base.getBaseInfo(), Base.getTBAAInfo());
4815
      // NumDeps = deps[i].base_addr;
4816
4
      LValue BaseAddrLVal = CGF.EmitLValueForField(
4817
4
          NumDepsBase, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
4818
4
      llvm::Value *NumDeps =
4819
4
          CGF.EmitLoadOfScalar(BaseAddrLVal, E->getExprLoc());
4820
4821
      // memcopy dependency data.
4822
4
      llvm::Value *Size = CGF.Builder.CreateNUWMul(
4823
4
          ElSize,
4824
4
          CGF.Builder.CreateIntCast(NumDeps, CGF.SizeTy, /*isSigned=*/false));
4825
4
      llvm::Value *Pos = CGF.EmitLoadOfScalar(PosLVal, E->getExprLoc());
4826
4
      Address DepAddr =
4827
4
          Address(CGF.Builder.CreateGEP(DependenciesArray.getElementType(),
4828
4
                                        DependenciesArray.getPointer(), Pos),
4829
4
                  DependenciesArray.getAlignment());
4830
4
      CGF.Builder.CreateMemCpy(DepAddr, Base.getAddress(CGF), Size);
4831
4832
      // Increase pos.
4833
      // pos += size;
4834
4
      llvm::Value *Add = CGF.Builder.CreateNUWAdd(Pos, NumDeps);
4835
4
      CGF.EmitStoreOfScalar(Add, PosLVal);
4836
4
    }
4837
2
  }
4838
2
}
4839
4840
std::pair<llvm::Value *, Address> CGOpenMPRuntime::emitDependClause(
4841
    CodeGenFunction &CGF, ArrayRef<OMPTaskDataTy::DependData> Dependencies,
4842
643
    SourceLocation Loc) {
4843
643
  if (llvm::all_of(Dependencies, [](const OMPTaskDataTy::DependData &D) {
4844
346
        return D.DepExprs.empty();
4845
346
      }))
4846
297
    return std::make_pair(nullptr, Address::invalid());
4847
  // Process list of dependencies.
4848
346
  ASTContext &C = CGM.getContext();
4849
346
  Address DependenciesArray = Address::invalid();
4850
346
  llvm::Value *NumOfElements = nullptr;
4851
346
  unsigned NumDependencies = std::accumulate(
4852
346
      Dependencies.begin(), Dependencies.end(), 0,
4853
416
      [](unsigned V, const OMPTaskDataTy::DependData &D) {
4854
416
        return D.DepKind == OMPC_DEPEND_depobj
4855
416
                   ? 
V2
4856
416
                   : 
(V + (414
D.IteratorExpr414
?
04
:
D.DepExprs.size()410
));
4857
416
      });
4858
346
  QualType FlagsTy;
4859
346
  getDependTypes(C, KmpDependInfoTy, FlagsTy);
4860
346
  bool HasDepobjDeps = false;
4861
346
  bool HasRegularWithIterators = false;
4862
346
  llvm::Value *NumOfDepobjElements = llvm::ConstantInt::get(CGF.IntPtrTy, 0);
4863
346
  llvm::Value *NumOfRegularWithIterators =
4864
346
      llvm::ConstantInt::get(CGF.IntPtrTy, 1);
4865
  // Calculate number of depobj dependecies and regular deps with the iterators.
4866
416
  for (const OMPTaskDataTy::DependData &D : Dependencies) {
4867
416
    if (D.DepKind == OMPC_DEPEND_depobj) {
4868
2
      SmallVector<llvm::Value *, 4> Sizes =
4869
2
          emitDepobjElementsSizes(CGF, KmpDependInfoTy, D);
4870
4
      for (llvm::Value *Size : Sizes) {
4871
4
        NumOfDepobjElements =
4872
4
            CGF.Builder.CreateNUWAdd(NumOfDepobjElements, Size);
4873
4
      }
4874
2
      HasDepobjDeps = true;
4875
2
      continue;
4876
2
    }
4877
    // Include number of iterations, if any.
4878
414
    if (const auto *IE = cast_or_null<OMPIteratorExpr>(D.IteratorExpr)) {
4879
8
      for (unsigned I = 0, E = IE->numOfIterators(); I < E; 
++I4
) {
4880
4
        llvm::Value *Sz = CGF.EmitScalarExpr(IE->getHelper(I).Upper);
4881
4
        Sz = CGF.Builder.CreateIntCast(Sz, CGF.IntPtrTy, /*isSigned=*/false);
4882
4
        NumOfRegularWithIterators =
4883
4
            CGF.Builder.CreateNUWMul(NumOfRegularWithIterators, Sz);
4884
4
      }
4885
4
      HasRegularWithIterators = true;
4886
4
      continue;
4887
4
    }
4888
414
  }
4889
4890
346
  QualType KmpDependInfoArrayTy;
4891
346
  if (HasDepobjDeps || 
HasRegularWithIterators344
) {
4892
6
    NumOfElements = llvm::ConstantInt::get(CGM.IntPtrTy, NumDependencies,
4893
6
                                           /*isSigned=*/false);
4894
6
    if (HasDepobjDeps) {
4895
2
      NumOfElements =
4896
2
          CGF.Builder.CreateNUWAdd(NumOfDepobjElements, NumOfElements);
4897
2
    }
4898
6
    if (HasRegularWithIterators) {
4899
4
      NumOfElements =
4900
4
          CGF.Builder.CreateNUWAdd(NumOfRegularWithIterators, NumOfElements);
4901
4
    }
4902
6
    auto *OVE = new (C) OpaqueValueExpr(
4903
6
        Loc, C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0),
4904
6
        VK_PRValue);
4905
6
    CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, OVE,
4906
6
                                                  RValue::get(NumOfElements));
4907
6
    KmpDependInfoArrayTy =
4908
6
        C.getVariableArrayType(KmpDependInfoTy, OVE, ArrayType::Normal,
4909
6
                               /*IndexTypeQuals=*/0, SourceRange(Loc, Loc));
4910
    // CGF.EmitVariablyModifiedType(KmpDependInfoArrayTy);
4911
    // Properly emit variable-sized array.
4912
6
    auto *PD = ImplicitParamDecl::Create(C, KmpDependInfoArrayTy,
4913
6
                                         ImplicitParamDecl::Other);
4914
6
    CGF.EmitVarDecl(*PD);
4915
6
    DependenciesArray = CGF.GetAddrOfLocalVar(PD);
4916
6
    NumOfElements = CGF.Builder.CreateIntCast(NumOfElements, CGF.Int32Ty,
4917
6
                                              /*isSigned=*/false);
4918
340
  } else {
4919
340
    KmpDependInfoArrayTy = C.getConstantArrayType(
4920
340
        KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies), nullptr,
4921
340
        ArrayType::Normal, /*IndexTypeQuals=*/0);
4922
340
    DependenciesArray =
4923
340
        CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr");
4924
340
    DependenciesArray = CGF.Builder.CreateConstArrayGEP(DependenciesArray, 0);
4925
340
    NumOfElements = llvm::ConstantInt::get(CGM.Int32Ty, NumDependencies,
4926
340
                                           /*isSigned=*/false);
4927
340
  }
4928
346
  unsigned Pos = 0;
4929
762
  for (unsigned I = 0, End = Dependencies.size(); I < End; 
++I416
) {
4930
416
    if (Dependencies[I].DepKind == OMPC_DEPEND_depobj ||
4931
416
        
Dependencies[I].IteratorExpr414
)
4932
6
      continue;
4933
410
    emitDependData(CGF, KmpDependInfoTy, &Pos, Dependencies[I],
4934
410
                   DependenciesArray);
4935
410
  }
4936
  // Copy regular dependecies with iterators.
4937
346
  LValue PosLVal = CGF.MakeAddrLValue(
4938
346
      CGF.CreateMemTemp(C.getSizeType(), "dep.counter.addr"), C.getSizeType());
4939
346
  CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.SizeTy, Pos), PosLVal);
4940
762
  for (unsigned I = 0, End = Dependencies.size(); I < End; 
++I416
) {
4941
416
    if (Dependencies[I].DepKind == OMPC_DEPEND_depobj ||
4942
416
        
!Dependencies[I].IteratorExpr414
)
4943
412
      continue;
4944
4
    emitDependData(CGF, KmpDependInfoTy, &PosLVal, Dependencies[I],
4945
4
                   DependenciesArray);
4946
4
  }
4947
  // Copy final depobj arrays without iterators.
4948
346
  if (HasDepobjDeps) {
4949
6
    for (unsigned I = 0, End = Dependencies.size(); I < End; 
++I4
) {
4950
4
      if (Dependencies[I].DepKind != OMPC_DEPEND_depobj)
4951
2
        continue;
4952
2
      emitDepobjElements(CGF, KmpDependInfoTy, PosLVal, Dependencies[I],
4953
2
                         DependenciesArray);
4954
2
    }
4955
2
  }
4956
346
  DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
4957
346
      DependenciesArray, CGF.VoidPtrTy);
4958
346
  return std::make_pair(NumOfElements, DependenciesArray);
4959
643
}
4960
4961
Address CGOpenMPRuntime::emitDepobjDependClause(
4962
    CodeGenFunction &CGF, const OMPTaskDataTy::DependData &Dependencies,
4963
6
    SourceLocation Loc) {
4964
6
  if (Dependencies.DepExprs.empty())
4965
0
    return Address::invalid();
4966
  // Process list of dependencies.
4967
6
  ASTContext &C = CGM.getContext();
4968
6
  Address DependenciesArray = Address::invalid();
4969
6
  unsigned NumDependencies = Dependencies.DepExprs.size();
4970
6
  QualType FlagsTy;
4971
6
  getDependTypes(C, KmpDependInfoTy, FlagsTy);
4972
6
  RecordDecl *KmpDependInfoRD =
4973
6
      cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl());
4974
4975
6
  llvm::Value *Size;
4976
  // Define type kmp_depend_info[<Dependencies.size()>];
4977
  // For depobj reserve one extra element to store the number of elements.
4978
  // It is required to handle depobj(x) update(in) construct.
4979
  // kmp_depend_info[<Dependencies.size()>] deps;
4980
6
  llvm::Value *NumDepsVal;
4981
6
  CharUnits Align = C.getTypeAlignInChars(KmpDependInfoTy);
4982
6
  if (const auto *IE =
4983
6
          cast_or_null<OMPIteratorExpr>(Dependencies.IteratorExpr)) {
4984
2
    NumDepsVal = llvm::ConstantInt::get(CGF.SizeTy, 1);
4985
4
    for (unsigned I = 0, E = IE->numOfIterators(); I < E; 
++I2
) {
4986
2
      llvm::Value *Sz = CGF.EmitScalarExpr(IE->getHelper(I).Upper);
4987
2
      Sz = CGF.Builder.CreateIntCast(Sz, CGF.SizeTy, /*isSigned=*/false);
4988
2
      NumDepsVal = CGF.Builder.CreateNUWMul(NumDepsVal, Sz);
4989
2
    }
4990
2
    Size = CGF.Builder.CreateNUWAdd(llvm::ConstantInt::get(CGF.SizeTy, 1),
4991
2
                                    NumDepsVal);
4992
2
    CharUnits SizeInBytes =
4993
2
        C.getTypeSizeInChars(KmpDependInfoTy).alignTo(Align);
4994
2
    llvm::Value *RecSize = CGM.getSize(SizeInBytes);
4995
2
    Size = CGF.Builder.CreateNUWMul(Size, RecSize);
4996
2
    NumDepsVal =
4997
2
        CGF.Builder.CreateIntCast(NumDepsVal, CGF.IntPtrTy, /*isSigned=*/false);
4998
4
  } else {
4999
4
    QualType KmpDependInfoArrayTy = C.getConstantArrayType(
5000
4
        KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies + 1),
5001
4
        nullptr, ArrayType::Normal, /*IndexTypeQuals=*/0);
5002
4
    CharUnits Sz = C.getTypeSizeInChars(KmpDependInfoArrayTy);
5003
4
    Size = CGM.getSize(Sz.alignTo(Align));
5004
4
    NumDepsVal = llvm::ConstantInt::get(CGF.IntPtrTy, NumDependencies);
5005
4
  }
5006
  // Need to allocate on the dynamic memory.
5007
6
  llvm::Value *ThreadID = getThreadID(CGF, Loc);
5008
  // Use default allocator.
5009
6
  llvm::Value *Allocator = llvm::ConstantPointerNull::get(CGF.VoidPtrTy);
5010
6
  llvm::Value *Args[] = {ThreadID, Size, Allocator};
5011
5012
6
  llvm::Value *Addr =
5013
6
      CGF.EmitRuntimeCall(OMPBuilder.getOrCreateRuntimeFunction(
5014
6
                              CGM.getModule(), OMPRTL___kmpc_alloc),
5015
6
                          Args, ".dep.arr.addr");
5016
6
  Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5017
6
      Addr, CGF.ConvertTypeForMem(KmpDependInfoTy)->getPointerTo());
5018
6
  DependenciesArray = Address(Addr, Align);
5019
  // Write number of elements in the first element of array for depobj.
5020
6
  LValue Base = CGF.MakeAddrLValue(DependenciesArray, KmpDependInfoTy);
5021
  // deps[i].base_addr = NumDependencies;
5022
6
  LValue BaseAddrLVal = CGF.EmitLValueForField(
5023
6
      Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr));
5024
6
  CGF.EmitStoreOfScalar(NumDepsVal, BaseAddrLVal);
5025
6
  llvm::PointerUnion<unsigned *, LValue *> Pos;
5026
6
  unsigned Idx = 1;
5027
6
  LValue PosLVal;
5028
6
  if (Dependencies.IteratorExpr) {
5029
2
    PosLVal = CGF.MakeAddrLValue(
5030
2
        CGF.CreateMemTemp(C.getSizeType(), "iterator.counter.addr"),
5031
2
        C.getSizeType());
5032
2
    CGF.EmitStoreOfScalar(llvm::ConstantInt::get(CGF.SizeTy, Idx), PosLVal,
5033
2
                          /*IsInit=*/true);
5034
2
    Pos = &PosLVal;
5035
4
  } else {
5036
4
    Pos = &Idx;
5037
4
  }
5038
6
  emitDependData(CGF, KmpDependInfoTy, Pos, Dependencies, DependenciesArray);
5039
6
  DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
5040
6
      CGF.Builder.CreateConstGEP(DependenciesArray, 1), CGF.VoidPtrTy);
5041
6
  return DependenciesArray;
5042
6
}
5043
5044
void CGOpenMPRuntime::emitDestroyClause(CodeGenFunction &CGF, LValue DepobjLVal,
5045
4
                                        SourceLocation Loc) {
5046
4
  ASTContext &C = CGM.getContext();
5047
4
  QualType FlagsTy;
5048
4
  getDependTypes(C, KmpDependInfoTy, FlagsTy);
5049
4