FLANG
symbol.h
1//===-- include/flang/Semantics/symbol.h ------------------------*- C++ -*-===//
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#ifndef FORTRAN_SEMANTICS_SYMBOL_H_
10#define FORTRAN_SEMANTICS_SYMBOL_H_
11
12#include "type.h"
13#include "flang/Common/enum-set.h"
14#include "flang/Common/reference.h"
15#include "flang/Common/visit.h"
16#include "flang/Semantics/module-dependences.h"
17#include "flang/Semantics/omp-declare-variant.h"
18#include "flang/Support/Fortran.h"
19#include "llvm/ADT/DenseMapInfo.h"
20#include "llvm/Frontend/OpenMP/OMP.h"
21
22#include <array>
23#include <functional>
24#include <list>
25#include <optional>
26#include <set>
27#include <variant>
28#include <vector>
29
30namespace llvm {
31class raw_ostream;
32}
33namespace Fortran::parser {
34struct Expr;
36} // namespace Fortran::parser
37
38namespace Fortran::semantics {
39
43
44class Scope;
45class Symbol;
46class ProgramTree;
47
48using SymbolRef = common::Reference<const Symbol>;
49using SymbolVector = std::vector<SymbolRef>;
50using MutableSymbolRef = common::Reference<Symbol>;
51using MutableSymbolVector = std::vector<MutableSymbolRef>;
52
53// Mixin for details with OpenMP declarative constructs.
55public:
56 const llvm::omp::Clauses &ompRequires() const { return ompRequires_; }
57 void set_ompRequires(llvm::omp::Clauses clauses) { ompRequires_ = clauses; }
58
59 const std::optional<common::OmpMemoryOrderType> &
60 ompAtomicDefaultMemOrder() const {
61 return ompAtomicDefaultMemOrder_;
62 }
63 void set_ompAtomicDefaultMemOrder(common::OmpMemoryOrderType flags) {
64 ompAtomicDefaultMemOrder_ = flags;
65 }
66
67 const llvm::omp::Clauses &ompAssumes() const { return ompAssumes_; }
68 void set_ompAssumes(llvm::omp::Clauses clauses) { ompAssumes_ = clauses; }
69
70 const llvm::omp::Directives &ompAssumesAbsent() const {
71 return ompAssumesAbsent_;
72 }
73 void add_ompAssumesAbsent(llvm::omp::Directive directive) {
74 ompAssumesAbsent_.set(directive);
75 }
76
77 const llvm::omp::Clauses &ompDeclTarget() const { return ompDeclTarget_; }
78 void set_ompDeclTarget(llvm::omp::Clauses clauses) {
79 ompDeclTarget_ = clauses;
80 }
81
82 const std::optional<common::OmpDeviceType> &ompDeclTargetDeviceType() const {
83 return ompDeclTargetDeviceType_;
84 }
85 void set_ompDeclTarget(common::OmpDeviceType device) {
86 ompDeclTargetDeviceType_ = device;
87 }
88
89 const llvm::omp::Clauses &ompGroupprivate() const { return ompGroupprivate_; }
90 void set_ompGroupprivate(llvm::omp::Clauses clauses) {
91 ompGroupprivate_ = clauses;
92 }
93
94 const std::optional<common::OmpDeviceType> &
95 ompGroupprivateDeviceType() const {
96 return ompGroupprivateDeviceType_;
97 }
98 void set_ompGroupprivate(common::OmpDeviceType device) {
99 ompGroupprivateDeviceType_ = device;
100 }
101
102 // \p dir indicates to which declarative directive the given clauses
103 // belong to.
104 void printClauseSet(llvm::raw_ostream &os, const llvm::omp::Clauses &clauses,
105 llvm::omp::Directive dir,
106 parser::CharBlock name = parser::CharBlock{}) const;
107 friend llvm::raw_ostream &operator<<(
108 llvm::raw_ostream &, const WithOmpDeclarative &);
109
110 void set_version(llvm::omp::Version version) { version_ = version; }
111
112private:
113 llvm::omp::Version version_;
114 // The set of clauses from a REQUIRES directive. Only applicable
115 // to program unit symbols (i.e. scopes of the REQUIRES directive).
116 // The set of requirements for any program unit include requirements
117 // from any module used in the program unit.
118 llvm::omp::Clauses ompRequires_;
119 // The argument to ATOMIC_DEFAULT_MEM_ORDER. Only needed when the ADMO
120 // clause is present in the ompRequires_ set.
121 std::optional<common::OmpMemoryOrderType> ompAtomicDefaultMemOrder_;
122 llvm::omp::Clauses ompAssumes_;
123 llvm::omp::Directives ompAssumesAbsent_;
124 // The set of clauses on DECLARE_TARGET directive that apply to this
125 // symbol.
126 llvm::omp::Clauses ompDeclTarget_;
127 // The argument to DEVICE_TYPE clause. Only needed when the clause is
128 // present in the ompDeclTarget_ set.
129 std::optional<common::OmpDeviceType> ompDeclTargetDeviceType_;
130 // The set of clauses on a GROUPPRIVATE directive declaring this symbol.
131 llvm::omp::Clauses ompGroupprivate_;
132 // The argument to a DEVICE_TYPE clause on a GROUPPRIVATE directive declaring
133 // this symbol. Only needed when the clause is present in ompGroupprivate_.
134 std::optional<common::OmpDeviceType> ompGroupprivateDeviceType_;
135};
136
137// A module or submodule.
138class ModuleDetails : public WithOmpDeclarative {
139public:
140 ModuleDetails(bool isSubmodule = false) : isSubmodule_{isSubmodule} {}
141 bool isSubmodule() const { return isSubmodule_; }
142 const Scope *scope() const { return scope_; }
143 const Scope *ancestor() const; // for submodule; nullptr for module
144 const Scope *parent() const; // for submodule; nullptr for module
145 void set_scope(const Scope *);
146 bool isDefaultPrivate() const { return isDefaultPrivate_; }
147 void set_isDefaultPrivate(bool yes = true) { isDefaultPrivate_ = yes; }
148 std::optional<ModuleCheckSumType> moduleFileHash() const {
149 return moduleFileHash_;
150 }
151 void set_moduleFileHash(ModuleCheckSumType x) { moduleFileHash_ = x; }
152 const Symbol *previous() const { return previous_; }
153 void set_previous(const Symbol *p) { previous_ = p; }
154
155private:
156 bool isSubmodule_;
157 bool isDefaultPrivate_{false};
158 const Scope *scope_{nullptr};
159 std::optional<ModuleCheckSumType> moduleFileHash_;
160 const Symbol *previous_{nullptr}; // same name, different module file hash
161};
162
164public:
165private:
166};
167
169public:
170 const std::string *bindName() const {
171 return bindName_ ? &*bindName_ : nullptr;
172 }
173 bool isExplicitBindName() const { return isExplicitBindName_; }
174 void set_bindName(std::string &&name) { bindName_ = std::move(name); }
175 void set_isExplicitBindName(bool yes) { isExplicitBindName_ = yes; }
176 bool isCDefined() const { return isCDefined_; }
177 void set_isCDefined(bool yes) { isCDefined_ = yes; }
178
179private:
180 std::optional<std::string> bindName_;
181 bool isExplicitBindName_{false};
182 bool isCDefined_{false};
183};
184
185// Device type specific OpenACC routine information
186class OpenACCRoutineDeviceTypeInfo {
187public:
188 explicit OpenACCRoutineDeviceTypeInfo(
189 Fortran::common::OpenACCDeviceType dType)
190 : deviceType_{dType} {}
191 bool isSeq() const { return isSeq_; }
192 void set_isSeq(bool value = true) { isSeq_ = value; }
193 bool isVector() const { return isVector_; }
194 void set_isVector(bool value = true) { isVector_ = value; }
195 bool isWorker() const { return isWorker_; }
196 void set_isWorker(bool value = true) { isWorker_ = value; }
197 bool isGang() const { return isGang_; }
198 void set_isGang(bool value = true) { isGang_ = value; }
199 unsigned gangDim() const { return gangDim_; }
200 void set_gangDim(unsigned value) { gangDim_ = value; }
201 const std::variant<std::string, SymbolRef> *bindName() const {
202 return bindName_.has_value() ? &*bindName_ : nullptr;
203 }
204 const std::optional<std::variant<std::string, SymbolRef>> &
205 bindNameOpt() const {
206 return bindName_;
207 }
208 void set_bindName(std::string &&name) { bindName_.emplace(std::move(name)); }
209 void set_bindName(SymbolRef symbol) { bindName_.emplace(symbol); }
210
211 Fortran::common::OpenACCDeviceType dType() const { return deviceType_; }
212
213 friend llvm::raw_ostream &operator<<(
214 llvm::raw_ostream &, const OpenACCRoutineDeviceTypeInfo &);
215
216private:
217 bool isSeq_{false};
218 bool isVector_{false};
219 bool isWorker_{false};
220 bool isGang_{false};
221 unsigned gangDim_{0};
222 // bind("name") -> std::string
223 // bind(sym) -> SymbolRef (requires namemangling in lowering)
224 std::optional<std::variant<std::string, SymbolRef>> bindName_;
225 Fortran::common::OpenACCDeviceType deviceType_{
226 Fortran::common::OpenACCDeviceType::None};
227};
228
229// OpenACC routine information. Device independent info are stored on the
230// OpenACCRoutineInfo instance while device dependent info are stored
231// in as objects in the OpenACCRoutineDeviceTypeInfo list.
232class OpenACCRoutineInfo : public OpenACCRoutineDeviceTypeInfo {
233public:
234 OpenACCRoutineInfo()
235 : OpenACCRoutineDeviceTypeInfo(Fortran::common::OpenACCDeviceType::None) {
236 }
237 bool isNohost() const { return isNohost_; }
238 void set_isNohost(bool value = true) { isNohost_ = value; }
239 const std::list<OpenACCRoutineDeviceTypeInfo> &deviceTypeInfos() const {
240 return deviceTypeInfos_;
241 }
242
243 OpenACCRoutineDeviceTypeInfo &add_deviceTypeInfo(
244 Fortran::common::OpenACCDeviceType type) {
245 return add_deviceTypeInfo(OpenACCRoutineDeviceTypeInfo(type));
246 }
247
248 OpenACCRoutineDeviceTypeInfo &add_deviceTypeInfo(
249 OpenACCRoutineDeviceTypeInfo &&info) {
250 deviceTypeInfos_.push_back(std::move(info));
251 return deviceTypeInfos_.back();
252 }
253
254 friend llvm::raw_ostream &operator<<(
255 llvm::raw_ostream &, const OpenACCRoutineInfo &);
256
257private:
258 std::list<OpenACCRoutineDeviceTypeInfo> deviceTypeInfos_;
259 bool isNohost_{false};
260};
261
262// A subroutine or function definition, or a subprogram interface defined
263// in an INTERFACE block as part of the definition of a dummy procedure
264// or a procedure pointer (with just POINTER).
266public:
267 bool isFunction() const { return result_ != nullptr; }
268 bool isInterface() const { return isInterface_; }
269 void set_isInterface(bool value = true) { isInterface_ = value; }
270 bool isDummy() const { return isDummy_; }
271 void set_isDummy(bool value = true) { isDummy_ = value; }
272 Scope *entryScope() { return entryScope_; }
273 const Scope *entryScope() const { return entryScope_; }
274 void set_entryScope(Scope &scope) { entryScope_ = &scope; }
275 const Symbol &result() const {
276 CHECK(isFunction());
277 return *result_;
278 }
279 void set_result(Symbol &result) {
280 CHECK(!result_);
281 result_ = &result;
282 }
283 const std::vector<Symbol *> &dummyArgs() const { return dummyArgs_; }
284 void add_dummyArg(Symbol &symbol) { dummyArgs_.push_back(&symbol); }
285 void add_alternateReturn() { dummyArgs_.push_back(nullptr); }
286 const MaybeExpr &stmtFunction() const { return stmtFunction_; }
287 void set_stmtFunction(SomeExpr &&expr) { stmtFunction_ = std::move(expr); }
288 Symbol *moduleInterface() { return moduleInterface_; }
289 const Symbol *moduleInterface() const { return moduleInterface_; }
290 void set_moduleInterface(Symbol &);
291 void ReplaceResult(Symbol &result) {
292 CHECK(result_ != nullptr);
293 result_ = &result;
294 }
295 bool defaultIgnoreTKR() const { return defaultIgnoreTKR_; }
296 void set_defaultIgnoreTKR(bool yes) { defaultIgnoreTKR_ = yes; }
297 std::optional<common::CUDASubprogramAttrs> cudaSubprogramAttrs() const {
298 return cudaSubprogramAttrs_;
299 }
300 void set_cudaSubprogramAttrs(common::CUDASubprogramAttrs csas) {
301 cudaSubprogramAttrs_ = csas;
302 }
303 std::vector<std::int64_t> &cudaLaunchBounds() { return cudaLaunchBounds_; }
304 const std::vector<std::int64_t> &cudaLaunchBounds() const {
305 return cudaLaunchBounds_;
306 }
307 void set_cudaLaunchBounds(std::vector<std::int64_t> &&x) {
308 cudaLaunchBounds_ = std::move(x);
309 }
310 std::vector<std::int64_t> &cudaClusterDims() { return cudaClusterDims_; }
311 const std::vector<std::int64_t> &cudaClusterDims() const {
312 return cudaClusterDims_;
313 }
314 void set_cudaClusterDims(std::vector<std::int64_t> &&x) {
315 cudaClusterDims_ = std::move(x);
316 }
317 const std::vector<OpenACCRoutineInfo> &openACCRoutineInfos() const {
318 return openACCRoutineInfos_;
319 }
320 void add_openACCRoutineInfo(OpenACCRoutineInfo info) {
321 openACCRoutineInfos_.push_back(info);
322 }
323
324 const std::vector<OmpDeclareVariantEntry> &ompDeclareVariants() const {
325 return ompDeclareVariants_;
326 }
327 void addOmpDeclareVariant(OmpDeclareVariantEntry &&entry) {
328 ompDeclareVariants_.push_back(std::move(entry));
329 }
330
331private:
332 bool isInterface_{false}; // true if this represents an interface-body
333 bool isDummy_{false}; // true when interface of dummy procedure
334 std::vector<Symbol *> dummyArgs_; // nullptr -> alternate return indicator
335 Symbol *result_{nullptr};
336 Scope *entryScope_{nullptr}; // if ENTRY, points to subprogram's scope
337 MaybeExpr stmtFunction_;
338 // For MODULE FUNCTION or SUBROUTINE, this is the symbol of its declared
339 // interface. For MODULE PROCEDURE, this is the declared interface if it
340 // appeared in an ancestor (sub)module.
341 Symbol *moduleInterface_{nullptr};
342 bool defaultIgnoreTKR_{false};
343 // CUDA ATTRIBUTES(...) from subroutine/function prefix
344 std::optional<common::CUDASubprogramAttrs> cudaSubprogramAttrs_;
345 // CUDA LAUNCH_BOUNDS(...) & CLUSTER_DIMS(...) from prefix
346 std::vector<std::int64_t> cudaLaunchBounds_, cudaClusterDims_;
347 // OpenACC routine information
348 std::vector<OpenACCRoutineInfo> openACCRoutineInfos_;
349 std::vector<OmpDeclareVariantEntry> ompDeclareVariants_;
350
351 friend llvm::raw_ostream &operator<<(
352 llvm::raw_ostream &, const SubprogramDetails &);
353};
354
355// For SubprogramNameDetails, the kind indicates whether it is the name
356// of a module subprogram or an internal subprogram or ENTRY.
357ENUM_CLASS(SubprogramKind, Module, Internal)
358
359// Symbol with SubprogramNameDetails is created when we scan for module and
360// internal procedure names, to record that there is a subprogram with this
361// name. Later they are replaced by SubprogramDetails with dummy and result
362// type information.
363class SubprogramNameDetails {
364public:
365 SubprogramNameDetails(SubprogramKind kind, ProgramTree &node)
366 : kind_{kind}, node_{node} {}
367 SubprogramNameDetails() = delete;
368 SubprogramKind kind() const { return kind_; }
369 ProgramTree &node() const { return *node_; }
370
371private:
372 SubprogramKind kind_;
374};
375
376// A name from an entity-decl -- could be object or function.
377class EntityDetails : public WithBindName {
378public:
379 explicit EntityDetails(bool isDummy = false) : isDummy_{isDummy} {}
380 const DeclTypeSpec *type() const { return type_; }
381 void set_type(const DeclTypeSpec &);
382 void ReplaceType(const DeclTypeSpec &);
383 bool isDummy() const { return isDummy_; }
384 void set_isDummy(bool value = true) { isDummy_ = value; }
385 bool isFuncResult() const { return isFuncResult_; }
386 void set_funcResult(bool x) { isFuncResult_ = x; }
387
388private:
389 bool isDummy_{false};
390 bool isFuncResult_{false};
391 const DeclTypeSpec *type_{nullptr};
392 friend llvm::raw_ostream &operator<<(
393 llvm::raw_ostream &, const EntityDetails &);
394};
395
396// Symbol is associated with a name or expression in an ASSOCIATE,
397// SELECT TYPE, or SELECT RANK construct.
398class AssocEntityDetails : public EntityDetails {
399public:
400 AssocEntityDetails() {}
401 explicit AssocEntityDetails(SomeExpr &&expr) : expr_{std::move(expr)} {}
402 AssocEntityDetails(const AssocEntityDetails &) = default;
403 AssocEntityDetails(AssocEntityDetails &&) = default;
404 AssocEntityDetails &operator=(const AssocEntityDetails &) = default;
405 AssocEntityDetails &operator=(AssocEntityDetails &&) = default;
406 const MaybeExpr &expr() const { return expr_; }
407
408 // SELECT RANK's rank cases will return a populated result for
409 // RANK(n) and RANK(*), and IsAssumedRank() will be true for
410 // RANK DEFAULT.
411 std::optional<int> rank() const {
412 int r{rank_.value_or(0)};
413 if (r == isAssumedSize) {
414 return 1; // RANK(*)
415 } else if (r == isAssumedRank) {
416 return std::nullopt; // RANK DEFAULT
417 } else {
418 return rank_;
419 }
420 }
421 bool IsAssumedSize() const { return rank_.value_or(0) == isAssumedSize; }
422 bool IsAssumedRank() const { return rank_.value_or(0) == isAssumedRank; }
423 bool isTypeGuard() const { return isTypeGuard_; }
424 void set_rank(int rank);
425 void set_IsAssumedSize();
426 void set_IsAssumedRank();
427 void set_isTypeGuard(bool yes = true);
428
429private:
430 MaybeExpr expr_;
431 // Populated for SELECT RANK with rank (n>=0) for RANK(n),
432 // isAssumedSize for RANK(*), or isAssumedRank for RANK DEFAULT.
433 static constexpr int isAssumedSize{-1}; // RANK(*)
434 static constexpr int isAssumedRank{-2}; // RANK DEFAULT
435 std::optional<int> rank_;
436 bool isTypeGuard_{false}; // TYPE IS or CLASS IS, but not CLASS(DEFAULT)
437};
438llvm::raw_ostream &operator<<(llvm::raw_ostream &, const AssocEntityDetails &);
439
440// An entity known to be an object.
441class ObjectEntityDetails : public EntityDetails, public WithOmpDeclarative {
442public:
443 explicit ObjectEntityDetails(EntityDetails &&);
444 ObjectEntityDetails(const ObjectEntityDetails &) = default;
445 ObjectEntityDetails(ObjectEntityDetails &&) = default;
446 ObjectEntityDetails &operator=(const ObjectEntityDetails &) = default;
447 ObjectEntityDetails(bool isDummy = false) : EntityDetails(isDummy) {}
448 MaybeExpr &init() { return init_; }
449 const MaybeExpr &init() const { return init_; }
450 void set_init(MaybeExpr &&expr) { init_ = std::move(expr); }
451 const parser::Expr *unanalyzedPDTComponentInit() const {
452 return unanalyzedPDTComponentInit_;
453 }
454 void set_unanalyzedPDTComponentInit(const parser::Expr *expr) {
455 unanalyzedPDTComponentInit_ = expr;
456 }
457 ArraySpec &shape() { return shape_; }
458 const ArraySpec &shape() const { return shape_; }
459 ArraySpec &coshape() { return coshape_; }
460 const ArraySpec &coshape() const { return coshape_; }
461 void set_shape(const ArraySpec &);
462 void set_coshape(const ArraySpec &);
463 const Symbol *commonBlock() const { return commonBlock_; }
464 void set_commonBlock(const Symbol &commonBlock) {
465 commonBlock_ = &commonBlock;
466 }
467 common::IgnoreTKRSet ignoreTKR() const { return ignoreTKR_; }
468 void set_ignoreTKR(common::IgnoreTKRSet set) { ignoreTKR_ = set; }
469 bool IsArray() const { return !shape_.empty(); }
470 bool IsCoarray() const { return !coshape_.empty(); }
471 bool IsAssumedShape() const {
472 return isDummy() && shape_.CanBeAssumedShape();
473 }
474 bool CanBeDeferredShape() const { return shape_.CanBeDeferredShape(); }
475 bool IsAssumedRank() const { return isDummy() && shape_.IsAssumedRank(); }
476 std::optional<common::CUDADataAttr> cudaDataAttr() const {
477 return cudaDataAttr_;
478 }
479 void set_cudaDataAttr(std::optional<common::CUDADataAttr> attr) {
480 cudaDataAttr_ = attr;
481 }
482 bool cudaDataAttrIsImplicit() const { return cudaDataAttrIsImplicit_; }
483 void set_cudaDataAttrIsImplicit(bool yes = true) {
484 cudaDataAttrIsImplicit_ = yes;
485 }
486 // Specification expressions from the bounds of a zero-size explicit-shape
487 // bounds array (F2023). The entity is scalar, so these bounds are not
488 // part of shape(), but they are still specification expressions that must be
489 // validated during declaration checking, when the scope is fully resolved.
490 void add_droppedBoundToCheck(Bound &&bound) {
491 droppedBoundsToCheck_.emplace_back(std::move(bound));
492 }
493 const std::vector<Bound> &droppedBoundsToCheck() const {
494 return droppedBoundsToCheck_;
495 }
496
497private:
498 MaybeExpr init_;
499 const parser::Expr *unanalyzedPDTComponentInit_{nullptr};
500 ArraySpec shape_;
501 ArraySpec coshape_;
502 std::vector<Bound> droppedBoundsToCheck_;
503 common::IgnoreTKRSet ignoreTKR_;
504 const Symbol *commonBlock_{nullptr}; // common block this object is in
505 std::optional<common::CUDADataAttr> cudaDataAttr_;
506 bool cudaDataAttrIsImplicit_{false}; // Tracks whether cudaDataAttr_ was
507 // applied implicitly by the compiler
508 friend llvm::raw_ostream &operator<<(
509 llvm::raw_ostream &, const ObjectEntityDetails &);
510};
511
512// Mixin for details with passed-object dummy argument.
513// If a procedure pointer component or type-bound procedure does not have
514// the NOPASS attribute on its symbol, then PASS is assumed; the name
515// is optional; if it is missing, the first dummy argument of the procedure's
516// interface is the passed-object dummy argument.
518public:
519 std::optional<SourceName> passName() const { return passName_; }
520 void set_passName(const SourceName &passName) { passName_ = passName; }
521
522private:
523 std::optional<SourceName> passName_;
524};
525
526// A procedure pointer (other than one defined with POINTER and an
527// INTERFACE block), a dummy procedure (without an INTERFACE but with
528// EXTERNAL or use in a procedure reference), or external procedure.
529class ProcEntityDetails : public EntityDetails,
530 public WithPassArg,
531 public WithOmpDeclarative {
532public:
533 ProcEntityDetails() = default;
534 explicit ProcEntityDetails(EntityDetails &&);
535 ProcEntityDetails(const ProcEntityDetails &) = default;
536 ProcEntityDetails(ProcEntityDetails &&) = default;
537 ProcEntityDetails &operator=(const ProcEntityDetails &) = default;
538
539 const Symbol *rawProcInterface() const { return rawProcInterface_; }
540 const Symbol *procInterface() const { return procInterface_; }
541 void set_procInterfaces(const Symbol &raw, const Symbol &resolved) {
542 rawProcInterface_ = &raw;
543 procInterface_ = &resolved;
544 }
545 inline bool HasExplicitInterface() const;
546
547 // Be advised: !init().has_value() => uninitialized pointer,
548 // while *init() == nullptr => explicit NULL() initialization.
549 std::optional<const Symbol *> init() const { return init_; }
550 void set_init(const Symbol &symbol) { init_ = &symbol; }
551 void set_init(std::nullptr_t) { init_ = nullptr; }
552 bool isCUDAKernel() const { return isCUDAKernel_; }
553 void set_isCUDAKernel(bool yes = true) { isCUDAKernel_ = yes; }
554 std::optional<SourceName> usedAsProcedureHere() const {
555 return usedAsProcedureHere_;
556 }
557 void set_usedAsProcedureHere(SourceName here) { usedAsProcedureHere_ = here; }
558 const std::vector<OpenACCRoutineInfo> &openACCRoutineInfos() const {
559 return openACCRoutineInfos_;
560 }
561 void add_openACCRoutineInfo(OpenACCRoutineInfo info) {
562 openACCRoutineInfos_.push_back(info);
563 }
564
565private:
566 const Symbol *rawProcInterface_{nullptr};
567 const Symbol *procInterface_{nullptr};
568 std::optional<const Symbol *> init_;
569 bool isCUDAKernel_{false};
570 std::optional<SourceName> usedAsProcedureHere_;
571 std::vector<OpenACCRoutineInfo> openACCRoutineInfos_;
572 friend llvm::raw_ostream &operator<<(
573 llvm::raw_ostream &, const ProcEntityDetails &);
574};
575
576// These derived type details represent the characteristics of a derived
577// type definition that are shared by all instantiations of that type.
578// The DerivedTypeSpec instances whose type symbols share these details
579// each own a scope into which the components' symbols have been cloned
580// and specialized for each distinct set of type parameter values.
582public:
583 const SymbolVector &paramNameOrder() const { return paramNameOrder_; }
584 const SymbolVector &paramDeclOrder() const { return paramDeclOrder_; }
585 bool sequence() const { return sequence_; }
586 bool isDECStructure() const { return isDECStructure_; }
587 bool isEnumerationType() const { return isEnumerationType_; }
588 void set_isEnumerationType(bool x = true) { isEnumerationType_ = x; }
589 std::optional<Attr> enumeratorDefaultAccess() const {
590 return enumeratorDefaultAccess_;
591 }
592 void set_enumeratorDefaultAccess(Attr a) { enumeratorDefaultAccess_ = a; }
593 // Name of the hidden component created for an enumeration type to hold
594 // the 1-based enumerator ordinal.
595 // Copy-initialized: MSVC 19.29 (VS 2019 16.11) rejects a braced string
596 // literal for an in-class static constexpr array.
597 static constexpr char ordinalComponentName[] = "__ordinal";
598 int enumeratorCount() const { return enumeratorCount_; }
599 void set_enumeratorCount(int n) { enumeratorCount_ = n; }
600 std::map<SourceName, SymbolRef> &finals() { return finals_; }
601 const std::map<SourceName, SymbolRef> &finals() const { return finals_; }
602 bool isForwardReferenced() const { return isForwardReferenced_; }
603 void add_paramNameOrder(const Symbol &symbol) {
604 paramNameOrder_.push_back(symbol);
605 }
606 void add_paramDeclOrder(const Symbol &symbol) {
607 paramDeclOrder_.push_back(symbol);
608 }
609 void add_component(const Symbol &);
610 void set_sequence(bool x = true) { sequence_ = x; }
611 void set_isDECStructure(bool x = true) { isDECStructure_ = x; }
612 void set_isForwardReferenced(bool value) { isForwardReferenced_ = value; }
613 const std::list<SourceName> &componentNames() const {
614 return componentNames_;
615 }
616 const std::map<SourceName, const parser::Expr *> &
617 originalKindParameterMap() const {
618 return originalKindParameterMap_;
619 }
620 void add_originalKindParameter(SourceName, const parser::Expr *);
621
622 // If this derived type extends another, locate the parent component's symbol.
623 const Symbol *GetParentComponent(const Scope &) const;
624
625 std::optional<SourceName> GetParentComponentName() const {
626 if (componentNames_.empty()) {
627 return std::nullopt;
628 } else {
629 return componentNames_.front();
630 }
631 }
632
633 const Symbol *GetFinalForRank(int) const;
634
635private:
636 // These are (1) the symbols of the derived type parameters in the order
637 // in which they appear on the type definition statement(s), and (2) the
638 // symbols that correspond to those names in the order in which their
639 // declarations appear in the derived type definition(s).
640 SymbolVector paramNameOrder_;
641 SymbolVector paramDeclOrder_;
642 // These are the names of the derived type's components in component
643 // order. A parent component, if any, appears first in this list.
644 std::list<SourceName> componentNames_;
645 std::map<SourceName, SymbolRef> finals_; // FINAL :: subr
646 bool sequence_{false};
647 bool isDECStructure_{false};
648 bool isForwardReferenced_{false};
649 std::map<SourceName, const parser::Expr *> originalKindParameterMap_;
650
651 // These fields are only used if the derived type is an enumeration type.
652 bool isEnumerationType_{false};
653 int enumeratorCount_{0};
654 std::optional<Attr> enumeratorDefaultAccess_;
655
656 friend llvm::raw_ostream &operator<<(
657 llvm::raw_ostream &, const DerivedTypeDetails &);
658};
659
660class ProcBindingDetails : public WithPassArg {
661public:
662 explicit ProcBindingDetails(const Symbol &symbol) : symbol_{symbol} {}
663 const Symbol &symbol() const { return symbol_; }
664 void ReplaceSymbol(const Symbol &symbol) { symbol_ = symbol; }
665 int numPrivatesNotOverridden() const { return numPrivatesNotOverridden_; }
666 void set_numPrivatesNotOverridden(int n) { numPrivatesNotOverridden_ = n; }
667
668private:
669 SymbolRef symbol_; // procedure bound to; may be forward
670 // Homonymous private bindings in ancestor types from other modules
671 int numPrivatesNotOverridden_{0};
672};
673
675public:
676 const SymbolVector &objects() const { return objects_; }
677 void add_object(const Symbol &object) { objects_.push_back(object); }
678 void add_objects(const SymbolVector &objects) {
679 objects_.insert(objects_.end(), objects.begin(), objects.end());
680 }
681
682private:
683 SymbolVector objects_;
684};
685
686class CommonBlockDetails : public WithBindName, public WithOmpDeclarative {
687public:
688 explicit CommonBlockDetails(SourceName location)
689 : sourceLocation_{location} {}
690 SourceName sourceLocation() const { return sourceLocation_; }
691 MutableSymbolVector &objects() { return objects_; }
692 const MutableSymbolVector &objects() const { return objects_; }
693 void add_object(Symbol &object) { objects_.emplace_back(object); }
694 void replace_object(Symbol &object, unsigned index) {
695 CHECK(index < objects_.size());
696 objects_[index] = object;
697 }
698 std::size_t alignment() const { return alignment_; }
699 void set_alignment(std::size_t alignment) { alignment_ = alignment; }
700
701private:
702 SourceName sourceLocation_;
703 MutableSymbolVector objects_;
704 std::size_t alignment_{0}; // required alignment in bytes
705};
706
707class MiscDetails {
708public:
709 ENUM_CLASS(Kind, None, ConstructName, ScopeName, PassName, ComplexPartRe,
710 ComplexPartIm, KindParamInquiry, LenParamInquiry, SelectRankAssociateName,
711 SelectTypeAssociateName, TypeBoundDefinedOp);
712 MiscDetails(Kind kind) : kind_{kind} {}
713 Kind kind() const { return kind_; }
714
715private:
716 Kind kind_;
717};
718
719class TypeParamDetails {
720public:
721 TypeParamDetails() = default;
722 TypeParamDetails(const TypeParamDetails &) = default;
723 TypeParamDetails &operator=(const TypeParamDetails &) = default;
724 std::optional<common::TypeParamAttr> attr() const { return attr_; }
725 TypeParamDetails &set_attr(common::TypeParamAttr);
726 MaybeIntExpr &init() { return init_; }
727 const MaybeIntExpr &init() const { return init_; }
728 void set_init(MaybeIntExpr &&expr) { init_ = std::move(expr); }
729 const DeclTypeSpec *type() const { return type_; }
730 TypeParamDetails &set_type(const DeclTypeSpec &);
731 void ReplaceType(const DeclTypeSpec &);
732
733private:
734 std::optional<common::TypeParamAttr> attr_;
735 MaybeIntExpr init_;
736 const DeclTypeSpec *type_{nullptr};
737};
738
739// Record the USE of a symbol: location is where (USE statement or renaming);
740// symbol is in the USEd module.
741class UseDetails {
742public:
743 UseDetails(const SourceName &location, const Symbol &symbol)
744 : location_{location}, symbol_{symbol} {}
745 const SourceName &location() const { return location_; }
746 const Symbol &symbol() const { return symbol_; }
747
748private:
749 SourceName location_;
750 SymbolRef symbol_;
751};
752
753// A symbol with ambiguous use-associations. Record where they were so
754// we can report the error if it is used.
755class UseErrorDetails {
756public:
757 UseErrorDetails(const UseDetails &);
758 UseErrorDetails &add_occurrence(const SourceName &, const Symbol &);
759 using ListType = std::list<std::pair<SourceName, const Symbol *>>;
760 const ListType occurrences() const { return occurrences_; };
761
762private:
763 ListType occurrences_;
764};
765
766// A symbol host-associated from an enclosing scope.
767class HostAssocDetails {
768public:
769 HostAssocDetails(const Symbol &symbol) : symbol_{symbol} {}
770 const Symbol &symbol() const { return symbol_; }
771 bool implicitOrSpecExprError{false};
772 bool implicitOrExplicitTypeError{false};
773
774private:
775 SymbolRef symbol_;
776};
777
778// A GenericKind is one of: generic name, defined operator,
779// defined assignment, intrinsic operator, or defined I/O.
780struct GenericKind {
781 ENUM_CLASS(OtherKind, Name, DefinedOp, Assignment, Concat)
782 GenericKind() : u{OtherKind::Name} {}
783 template <typename T> GenericKind(const T &x) { u = x; }
784 bool IsName() const { return Is(OtherKind::Name); }
785 bool IsAssignment() const { return Is(OtherKind::Assignment); }
786 bool IsDefinedOperator() const { return Is(OtherKind::DefinedOp); }
787 bool IsIntrinsicOperator() const;
788 bool IsOperator() const;
789 std::string ToString() const;
790 static SourceName AsFortran(common::DefinedIo);
791 std::variant<OtherKind, common::NumericOperator, common::LogicalOperator,
792 common::RelationalOperator, common::DefinedIo>
793 u;
794
795private:
796 template <typename T> bool Has() const {
797 return std::holds_alternative<T>(u);
798 }
799 bool Is(OtherKind) const;
800};
801
802// A generic interface or type-bound generic.
803class GenericDetails {
804public:
805 GenericDetails() {}
806
807 GenericKind kind() const { return kind_; }
808 void set_kind(GenericKind kind) { kind_ = kind; }
809
810 const SymbolVector &specificProcs() const { return specificProcs_; }
811 const std::vector<SourceName> &bindingNames() const { return bindingNames_; }
812 void AddSpecificProc(const Symbol &, SourceName bindingName);
813 const SymbolVector &uses() const { return uses_; }
814
815 // specific and derivedType indicate a specific procedure or derived type
816 // with the same name as this generic. Only one of them may be set in
817 // a scope that declares them, but both can be set during USE association
818 // when generics are combined.
819 Symbol *specific() { return specific_; }
820 const Symbol *specific() const { return specific_; }
821 void set_specific(Symbol &specific);
822 void clear_specific();
823 Symbol *derivedType() { return derivedType_; }
824 const Symbol *derivedType() const { return derivedType_; }
825 void set_derivedType(Symbol &derivedType);
826 void clear_derivedType();
827 void AddUse(const Symbol &);
828
829 // Copy in specificProcs, specific, and derivedType from another generic
830 void CopyFrom(const GenericDetails &);
831
832 // Check that specific is one of the specificProcs. If not, return the
833 // specific as a raw pointer.
834 const Symbol *CheckSpecific() const;
835 Symbol *CheckSpecific();
836
837private:
838 GenericKind kind_;
839 // all of the specific procedures for this generic
840 SymbolVector specificProcs_;
841 std::vector<SourceName> bindingNames_;
842 // Symbols used from other modules merged into this one
843 SymbolVector uses_;
844 // a specific procedure with the same name as this generic, if any
845 Symbol *specific_{nullptr};
846 // a derived type with the same name as this generic, if any
847 Symbol *derivedType_{nullptr};
848};
849llvm::raw_ostream &operator<<(llvm::raw_ostream &, const GenericDetails &);
850
851// Used for OpenMP DECLARE REDUCTION, it holds the information
852// needed to resolve which declaration (there could be multiple
853// with the same name) to use for a given type.
854class UserReductionDetails {
855public:
856 using TypeVector = std::vector<const DeclTypeSpec *>;
857 using DeclVector = std::vector<const parser::OpenMPDeclarativeConstruct *>;
858
859 UserReductionDetails() = default;
860
861 void AddType(const DeclTypeSpec &type) { typeList_.push_back(&type); }
862 const TypeVector &GetTypeList() const { return typeList_; }
863
864 bool SupportsType(const DeclTypeSpec &type) const;
865
866 void AddDecl(const parser::OpenMPDeclarativeConstruct *decl) {
867 declList_.emplace_back(decl);
868 }
869 const DeclVector &GetDeclList() const { return declList_; }
870
871private:
872 TypeVector typeList_;
873 DeclVector declList_;
874};
875
876// Used for OpenMP DECLARE MAPPER, it holds the declaration constructs
877// so they can be serialized into module files and later re-parsed when
878// USE-associated.
879class MapperDetails {
880public:
881 using DeclVector = std::vector<const parser::OpenMPDeclarativeConstruct *>;
882
883 MapperDetails() = default;
884
885 void AddDecl(const parser::OpenMPDeclarativeConstruct *decl) {
886 declList_.emplace_back(decl);
887 }
888 const DeclVector &GetDeclList() const { return declList_; }
889
890private:
891 DeclVector declList_;
892};
893
895
896using Details = std::variant<UnknownDetails, MainProgramDetails, ModuleDetails,
902llvm::raw_ostream &operator<<(llvm::raw_ostream &, const Details &);
903std::string DetailsToString(const Details &);
904
905class Symbol {
906public:
907 ENUM_CLASS(Flag,
908 Function, // symbol is a function or statement function
909 Subroutine, // symbol is a subroutine
910 StmtFunction, // symbol is a statement function or result
911 Implicit, // symbol is implicitly typed
912 ImplicitOrError, // symbol must be implicitly typed or it's an error
913 ModFile, // symbol came from .mod file
914 ParentComp, // symbol is the "parent component" of an extended type
915 CrayPointer, CrayPointee,
916 LocalityLocal, // named in LOCAL locality-spec
917 LocalityLocalInit, // named in LOCAL_INIT locality-spec
918 LocalityReduce, // named in REDUCE locality-spec
919 LocalityShared, // named in SHARED locality-spec
920 InDataStmt, // initialized in a DATA statement, =>object, or /init/
921 InNamelist, // in a Namelist group
922 InCommonBlock, // referenced in a common block
923 EntryDummyArgument,
924 CompilerCreated, // A compiler created symbol
925 // For compiler created symbols that are constant but cannot legally have
926 // the PARAMETER attribute.
927 ReadOnly,
928 // A named constant created by an ENUMERATOR statement within an
929 // ENUMERATION TYPE definition (F2023 R768). Distinguishes the intrinsic
930 // enumerators of an enumeration type from user-declared PARAMETERs of
931 // that type.
932 EnumeratorParameter,
933 // OpenACC data-sharing attribute
934 AccPrivate, AccFirstPrivate, AccShared,
935 // OpenACC data-mapping attribute
936 AccCopy, AccCopyIn, AccCopyInReadOnly, AccCopyOut, AccCreate, AccDelete,
937 AccNoCreate, AccPresent, AccLink, AccDeviceResident, AccDevicePtr,
938 AccUseDevice,
939 // OpenACC declare
940 AccDeclare,
941 // OpenACC declare on allocatable/pointer needs cross-TU action recipes
942 AccDeclareAction,
943 // OpenACC data-movement attribute
944 AccDevice, AccHost, AccSelf,
945 // OpenACC miscellaneous flags
946 AccCommonBlock, AccThreadPrivate, AccReduction, AccNone, AccPreDetermined,
947 // OpenMP data-sharing attribute
948 OmpShared, OmpPrivate, OmpLinear, OmpFirstPrivate, OmpLastPrivate,
949 OmpGroupPrivate,
950 // OpenMP data-mapping attribute
951 OmpMapTo, OmpMapFrom, OmpMapToFrom, OmpMapStorage, OmpMapDelete,
952 OmpUseDevicePtr, OmpUseDeviceAddr, OmpIsDevicePtr, OmpHasDeviceAddr,
953 // OpenMP data-copying attribute
954 OmpCopyIn, OmpCopyPrivate,
955 // OpenMP special variables
956 OmpInVar, OmpOrigVar, OmpOutVar, OmpPrivVar,
957 // OpenMP miscellaneous flags
958 OmpReserved, OmpCommonBlock, OmpReduction, OmpInReduction, OmpAligned,
959 OmpNontemporal, OmpAllocate, OmpDeclarativeAllocateDirective,
960 OmpExecutableAllocateDirective, OmpDeclareSimd, OmpDeclareTarget,
961 OmpThreadprivate, OmpDeclareReduction, OmpFlushed, OmpCriticalLock,
962 OmpIfSpecified, OmpNone, OmpPreDetermined, OmpExplicit, OmpImplicit,
963 OmpDependObject, OmpInclusiveScan, OmpExclusiveScan, OmpInScanReduction,
964 OmpUniform);
966
967 const Scope &owner() const { return *owner_; }
968 const SourceName &name() const { return name_; }
969 Attrs &attrs() { return attrs_; }
970 const Attrs &attrs() const { return attrs_; }
971 Attrs &implicitAttrs() { return implicitAttrs_; }
972 const Attrs &implicitAttrs() const { return implicitAttrs_; }
973 Flags &flags() { return flags_; }
974 const Flags &flags() const { return flags_; }
975 bool test(Flag flag) const { return flags_.test(flag); }
976 void set(Flag flag, bool value = true) { flags_.set(flag, value); }
977 // The Scope introduced by this symbol, if any.
978 Scope *scope() { return scope_; }
979 const Scope *scope() const { return scope_; }
980 void set_scope(Scope *scope) { scope_ = scope; }
981 std::size_t size() const { return size_; }
982 void set_size(std::size_t size) { size_ = size; }
983 std::size_t offset() const { return offset_; }
984 void set_offset(std::size_t offset) { offset_ = offset; }
985 // Give the symbol a name with a different source location but same chars.
986 void ReplaceName(const SourceName &);
987 static std::string OmpFlagToClauseName(Flag ompFlag);
988
989 // Does symbol have this type of details?
990 template <typename D> bool has() const {
991 return std::holds_alternative<D>(details_);
992 }
993
994 // Return a non-owning pointer to details if it is type D, else nullptr.
995 template <typename D> D *detailsIf() { return std::get_if<D>(&details_); }
996 template <typename D> const D *detailsIf() const {
997 return std::get_if<D>(&details_);
998 }
999
1000 // Return a reference to the details which must be of type D.
1001 template <typename D> D &get() {
1002 return const_cast<D &>(const_cast<const Symbol *>(this)->get<D>());
1003 }
1004 template <typename D> const D &get() const {
1005 const auto *p{detailsIf<D>()};
1006 CHECK(p);
1007 return *p;
1008 }
1009
1010 Details &details() { return details_; }
1011 const Details &details() const { return details_; }
1012 // Assign the details of the symbol from one of the variants.
1013 // Only allowed in certain cases.
1014 void set_details(Details &&);
1015
1016 // Can the details of this symbol be replaced with the given details?
1017 bool CanReplaceDetails(const Details &details) const;
1018
1019 // Follow use-associations and host-associations to get the ultimate entity.
1020 inline Symbol &GetUltimate();
1021 inline const Symbol &GetUltimate() const;
1022
1023 inline DeclTypeSpec *GetType();
1024 inline const DeclTypeSpec *GetType() const;
1025 void SetType(const DeclTypeSpec &);
1026
1027 const std::string *GetBindName() const;
1028 void SetBindName(std::string &&);
1029 bool GetIsExplicitBindName() const;
1030 void SetIsExplicitBindName(bool);
1031 void SetIsCDefined(bool);
1032 bool IsFuncResult() const;
1033 bool IsObjectArray() const;
1034 const ArraySpec *GetShape() const;
1035 bool IsSubprogram() const;
1036 bool IsFromModFile() const;
1037 bool HasExplicitInterface() const {
1038 return common::visit(
1040 [](const SubprogramDetails &) { return true; },
1041 [](const SubprogramNameDetails &) { return true; },
1042 [&](const ProcEntityDetails &x) {
1043 return attrs_.test(Attr::INTRINSIC) || x.HasExplicitInterface();
1044 },
1045 [](const ProcBindingDetails &x) {
1046 return x.symbol().HasExplicitInterface();
1047 },
1048 [](const UseDetails &x) {
1049 return x.symbol().HasExplicitInterface();
1050 },
1051 [](const HostAssocDetails &x) {
1052 return x.symbol().HasExplicitInterface();
1053 },
1054 [](const GenericDetails &x) {
1055 return x.specific() && x.specific()->HasExplicitInterface();
1056 },
1057 [](const auto &) { return false; },
1058 },
1059 details_);
1060 }
1061 bool HasLocalLocality() const {
1062 return test(Flag::LocalityLocal) || test(Flag::LocalityLocalInit);
1063 }
1064
1065 bool operator==(const Symbol &that) const { return this == &that; }
1066 bool operator!=(const Symbol &that) const { return !(*this == that); }
1067
1068 int Rank() const { return RankImpl(); }
1069 int Corank() const { return CorankImpl(); }
1070
1071 // If there is a parent component, return a pointer to its derived type spec.
1072 // The Scope * argument defaults to this->scope_ but should be overridden
1073 // for a parameterized derived type instantiation with the instance's scope.
1074 const DerivedTypeSpec *GetParentTypeSpec(const Scope * = nullptr) const;
1075
1076 // If a derived type's symbol refers to an extended derived type,
1077 // return the parent component's symbol. The scope of the derived type
1078 // can be overridden.
1079 const Symbol *GetParentComponent(const Scope * = nullptr) const;
1080
1081 SemanticsContext &GetSemanticsContext() const;
1082#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1083 LLVM_DUMP_METHOD void dump() const;
1084#endif
1085
1086private:
1087 const Scope *owner_;
1088 SourceName name_;
1089 Attrs attrs_;
1090 Attrs implicitAttrs_; // subset of attrs_ that were not explicit
1091 Flags flags_;
1092 Scope *scope_{nullptr};
1093 std::size_t size_{0}; // size in bytes
1094 std::size_t offset_{0}; // byte offset in scope or common block
1095 Details details_;
1096
1097 Symbol() {} // only created in class Symbols
1098 std::string GetDetailsName() const;
1099 friend llvm::raw_ostream &operator<<(llvm::raw_ostream &, const Symbol &);
1100 friend llvm::raw_ostream &DumpForUnparse(
1101 llvm::raw_ostream &, const Symbol &, bool);
1102
1103 static constexpr int startRecursionDepth{100};
1104
1105 inline const DeclTypeSpec *GetTypeImpl(int depth = startRecursionDepth) const;
1106 inline int RankImpl(int depth = startRecursionDepth) const {
1107 if (depth-- == 0) {
1108 return 0;
1109 }
1110 return common::visit(
1112 [&](const SubprogramDetails &sd) {
1113 return sd.isFunction() ? sd.result().RankImpl(depth) : 0;
1114 },
1115 [](const GenericDetails &) {
1116 return 0; /*TODO*/
1117 },
1118 [&](const ProcBindingDetails &x) {
1119 return x.symbol().RankImpl(depth);
1120 },
1121 [&](const UseDetails &x) { return x.symbol().RankImpl(depth); },
1122 [&](const HostAssocDetails &x) {
1123 return x.symbol().RankImpl(depth);
1124 },
1125 [](const ObjectEntityDetails &oed) { return oed.shape().Rank(); },
1126 [&](const ProcEntityDetails &ped) {
1127 const Symbol *iface{ped.procInterface()};
1128 return iface ? iface->RankImpl(depth) : 0;
1129 },
1130 [](const AssocEntityDetails &aed) {
1131 if (auto assocRank{aed.rank()}) {
1132 // RANK(n) & RANK(*)
1133 return *assocRank;
1134 } else if (aed.IsAssumedRank()) {
1135 // RANK DEFAULT
1136 return 0;
1137 } else if (const auto &expr{aed.expr()}) {
1138 return expr->Rank();
1139 } else {
1140 return 0;
1141 }
1142 },
1143 [](const auto &) { return 0; },
1144 },
1145 details_);
1146 }
1147 inline int CorankImpl(int depth = startRecursionDepth) const {
1148 if (depth-- == 0) {
1149 return 0;
1150 }
1151 return common::visit(
1153 [&](const SubprogramDetails &sd) {
1154 return sd.isFunction() ? sd.result().CorankImpl(depth) : 0;
1155 },
1156 [](const GenericDetails &) { return 0; },
1157 [&](const ProcEntityDetails &ped) {
1158 const Symbol *iface{ped.procInterface()};
1159 return iface ? iface->CorankImpl(depth) : 0;
1160 },
1161 [&](const UseDetails &x) { return x.symbol().CorankImpl(depth); },
1162 [&](const HostAssocDetails &x) {
1163 return x.symbol().CorankImpl(depth);
1164 },
1165 [](const ObjectEntityDetails &oed) { return oed.coshape().Rank(); },
1166 [](const AssocEntityDetails &aed) {
1167 return aed.expr() ? aed.expr()->Corank() : 0;
1168 },
1169 [](const auto &) { return 0; },
1170 },
1171 details_);
1172 }
1173 template <std::size_t> friend class Symbols;
1174 template <class, std::size_t> friend class std::array;
1175};
1176
1177llvm::raw_ostream &operator<<(llvm::raw_ostream &, Symbol::Flag);
1178
1179// Manage memory for all symbols. BLOCK_SIZE symbols at a time are allocated.
1180// Make() returns a reference to the next available one. They are never
1181// deleted.
1182template <std::size_t BLOCK_SIZE> class Symbols {
1183public:
1184 Symbol &Make(const Scope &owner, const SourceName &name, const Attrs &attrs,
1185 Details &&details) {
1186 Symbol &symbol = Get();
1187 symbol.owner_ = &owner;
1188 symbol.name_ = name;
1189 symbol.attrs_ = attrs;
1190 symbol.details_ = std::move(details);
1191 return symbol;
1192 }
1193
1194private:
1195 using blockType = std::array<Symbol, BLOCK_SIZE>;
1196 std::list<blockType *> blocks_;
1197 std::size_t nextIndex_{0};
1198 blockType *currBlock_{nullptr};
1199
1200 Symbol &Get() {
1201 if (nextIndex_ == 0) {
1202 blocks_.push_back(new blockType());
1203 currBlock_ = blocks_.back();
1204 }
1205 Symbol &result = (*currBlock_)[nextIndex_];
1206 if (++nextIndex_ >= BLOCK_SIZE) {
1207 nextIndex_ = 0; // allocate a new block next time
1208 }
1209 return result;
1210 }
1211};
1212
1213// Define a few member functions here in the header so that they
1214// can be used by lib/Evaluate without inducing a dependence cycle
1215// between the two shared libraries.
1216
1217inline bool ProcEntityDetails::HasExplicitInterface() const {
1218 return procInterface_ && procInterface_->HasExplicitInterface();
1219}
1220
1221inline Symbol &Symbol::GetUltimate() {
1222 return const_cast<Symbol &>(const_cast<const Symbol *>(this)->GetUltimate());
1223}
1224inline const Symbol &Symbol::GetUltimate() const {
1225 if (const auto *details{detailsIf<UseDetails>()}) {
1226 return details->symbol().GetUltimate();
1227 } else if (const auto *details{detailsIf<HostAssocDetails>()}) {
1228 return details->symbol().GetUltimate();
1229 } else {
1230 return *this;
1231 }
1232}
1233
1234inline DeclTypeSpec *Symbol::GetType() {
1235 return const_cast<DeclTypeSpec *>(
1236 const_cast<const Symbol *>(this)->GetType());
1237}
1238
1239inline const DeclTypeSpec *Symbol::GetTypeImpl(int depth) const {
1240 if (depth-- == 0) {
1241 return nullptr;
1242 }
1243 return common::visit(
1244 common::visitors{
1245 [](const EntityDetails &x) { return x.type(); },
1246 [](const ObjectEntityDetails &x) { return x.type(); },
1247 [](const AssocEntityDetails &x) { return x.type(); },
1248 [&](const SubprogramDetails &x) {
1249 return x.isFunction() ? x.result().GetTypeImpl(depth) : nullptr;
1250 },
1251 [&](const ProcEntityDetails &x) {
1252 const Symbol *symbol{x.procInterface()};
1253 return symbol ? symbol->GetTypeImpl(depth) : x.type();
1254 },
1255 [&](const ProcBindingDetails &x) {
1256 return x.symbol().GetTypeImpl(depth);
1257 },
1258 [](const TypeParamDetails &x) { return x.type(); },
1259 [&](const UseDetails &x) { return x.symbol().GetTypeImpl(depth); },
1260 [&](const HostAssocDetails &x) {
1261 return x.symbol().GetTypeImpl(depth);
1262 },
1263 [&](const GenericDetails &x) {
1264 return x.specific() ? x.specific()->GetTypeImpl(depth) : nullptr;
1265 },
1266 [](const auto &) -> const DeclTypeSpec * { return nullptr; },
1267 },
1268 details_);
1269}
1270
1271inline const DeclTypeSpec *Symbol::GetType() const { return GetTypeImpl(); }
1272
1273// Defined here, where Symbol is a complete type, so that it can be inlined
1274// into FortranEvaluate without that library needing to link FortranSemantics.
1275inline const Scope *DerivedTypeSpec::GetScope() const {
1276 return scope_ ? scope_ : typeSymbol_.scope();
1277}
1278
1279// Sets and maps keyed by Symbols
1280
1282 bool operator()(const SymbolRef &x, const SymbolRef &y) const {
1283 return &*x < &*y;
1284 }
1285 bool operator()(const MutableSymbolRef &x, const MutableSymbolRef &y) const {
1286 return &*x < &*y;
1287 }
1288};
1289
1290// Symbol comparison is usually based on the order of cooked source
1291// stream creation and, when both are from the same cooked source,
1292// their positions in that cooked source stream.
1293// Don't use this comparator or SourceOrderedSymbolSet to hold
1294// Symbols that might be subject to ReplaceName().
1296 // These functions are implemented in Evaluate/tools.cpp to
1297 // satisfy complicated shared library interdependency.
1298 bool operator()(const SymbolRef &, const SymbolRef &) const;
1299 bool operator()(const MutableSymbolRef &, const MutableSymbolRef &) const;
1300};
1301
1303 bool operator()(const SymbolRef &, const SymbolRef &) const;
1304 bool operator()(const MutableSymbolRef &, const MutableSymbolRef &) const;
1305};
1306
1307using UnorderedSymbolSet = std::set<SymbolRef, SymbolAddressCompare>;
1308using SourceOrderedSymbolSet = std::set<SymbolRef, SymbolSourcePositionCompare>;
1309
1310template <typename A>
1311SourceOrderedSymbolSet OrderBySourcePosition(const A &container) {
1312 SourceOrderedSymbolSet result;
1313 for (SymbolRef x : container) {
1314 result.emplace(x);
1315 }
1316 return result;
1317}
1318
1319} // namespace Fortran::semantics
1320
1321// Define required info so that SymbolRef can be used inside llvm::DenseMap.
1322namespace llvm {
1323template <> struct DenseMapInfo<Fortran::semantics::SymbolRef> {
1324 static unsigned getHashValue(const Fortran::semantics::SymbolRef &sym) {
1325 return DenseMapInfo<const Fortran::semantics::Symbol *>::getHashValue(
1326 &sym.get());
1327 }
1328
1329 static bool isEqual(const Fortran::semantics::SymbolRef &LHS,
1330 const Fortran::semantics::SymbolRef &RHS) {
1331 return LHS == RHS;
1332 }
1333};
1334} // namespace llvm
1335#endif // FORTRAN_SEMANTICS_SYMBOL_H_
Definition enum-set.h:28
Definition reference.h:18
Definition char-block.h:27
Definition type.h:68
Definition symbol.h:377
Definition symbol.h:803
Definition symbol.h:879
Definition symbol.h:707
Definition symbol.h:138
Definition program-tree.h:31
Definition scope.h:68
Definition symbol.h:905
Definition symbol.h:1182
Definition symbol.h:894
Definition symbol.h:741
Definition symbol.h:168
Definition symbol.h:517
Definition check-expression.h:19
Definition bit-population-count.h:20
Definition idioms.h:60
Definition parse-tree.h:1749
Definition type.h:247
Definition symbol.h:780
Definition omp-declare-variant.h:25