Coverage Report

Created: 2022-01-18 06:27

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