[flang] Restructure runtime to avoid recursion (relanding) (#143993)

Recursion, both direct and indirect, prevents accurate stack size
calculation at link time for GPU device code. Restructure these
recursive (often mutually so) routines in the Fortran runtime with new
implementations based on an iterative work queue with
suspendable/resumable work tickets: Assign, Initialize, initializeClone,
Finalize, and Destroy.

Default derived type I/O is also recursive, but already disabled. It can
be added to this new framework later if the overall approach succeeds.

Note that derived type FINAL subroutine calls, defined assignments, and
defined I/O procedures all perform callbacks into user code, which may
well reenter the runtime library. This kind of recursion is not handled
by this change, although it may be possible to do so in the future using
thread-local work queues.

(Relanding this patch after reverting initial attempt due to some test
failures that needed some time to analyze and fix.)

Fixes https://github.com/llvm/llvm-project/issues/142481.
This commit is contained in:
Peter Klausler 2025-06-16 14:37:01 -07:00 committed by GitHub
parent 65b06cd983
commit 2bf3ccabfa
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
32 changed files with 2375 additions and 1197 deletions

View File

@ -64,6 +64,9 @@ struct ExecutionEnvironment {
bool defaultUTF8{false}; // DEFAULT_UTF8 bool defaultUTF8{false}; // DEFAULT_UTF8
bool checkPointerDeallocation{true}; // FORT_CHECK_POINTER_DEALLOCATION bool checkPointerDeallocation{true}; // FORT_CHECK_POINTER_DEALLOCATION
enum InternalDebugging { WorkQueue = 1 };
int internalDebugging{0}; // FLANG_RT_DEBUG
// CUDA related variables // CUDA related variables
std::size_t cudaStackLimit{0}; // ACC_OFFLOAD_STACK_SIZE std::size_t cudaStackLimit{0}; // ACC_OFFLOAD_STACK_SIZE
bool cudaDeviceIsManaged{false}; // NV_CUDAFOR_DEVICE_IS_MANAGED bool cudaDeviceIsManaged{false}; // NV_CUDAFOR_DEVICE_IS_MANAGED

View File

@ -24,7 +24,7 @@ class Terminator;
enum Stat { enum Stat {
StatOk = 0, // required to be zero by Fortran StatOk = 0, // required to be zero by Fortran
// Interoperable STAT= codes // Interoperable STAT= codes (>= 11)
StatBaseNull = CFI_ERROR_BASE_ADDR_NULL, StatBaseNull = CFI_ERROR_BASE_ADDR_NULL,
StatBaseNotNull = CFI_ERROR_BASE_ADDR_NOT_NULL, StatBaseNotNull = CFI_ERROR_BASE_ADDR_NOT_NULL,
StatInvalidElemLen = CFI_INVALID_ELEM_LEN, StatInvalidElemLen = CFI_INVALID_ELEM_LEN,
@ -36,7 +36,7 @@ enum Stat {
StatMemAllocation = CFI_ERROR_MEM_ALLOCATION, StatMemAllocation = CFI_ERROR_MEM_ALLOCATION,
StatOutOfBounds = CFI_ERROR_OUT_OF_BOUNDS, StatOutOfBounds = CFI_ERROR_OUT_OF_BOUNDS,
// Standard STAT= values // Standard STAT= values (>= 101)
StatFailedImage = FORTRAN_RUNTIME_STAT_FAILED_IMAGE, StatFailedImage = FORTRAN_RUNTIME_STAT_FAILED_IMAGE,
StatLocked = FORTRAN_RUNTIME_STAT_LOCKED, StatLocked = FORTRAN_RUNTIME_STAT_LOCKED,
StatLockedOtherImage = FORTRAN_RUNTIME_STAT_LOCKED_OTHER_IMAGE, StatLockedOtherImage = FORTRAN_RUNTIME_STAT_LOCKED_OTHER_IMAGE,
@ -49,10 +49,14 @@ enum Stat {
// Additional "processor-defined" STAT= values // Additional "processor-defined" STAT= values
StatInvalidArgumentNumber = FORTRAN_RUNTIME_STAT_INVALID_ARG_NUMBER, StatInvalidArgumentNumber = FORTRAN_RUNTIME_STAT_INVALID_ARG_NUMBER,
StatMissingArgument = FORTRAN_RUNTIME_STAT_MISSING_ARG, StatMissingArgument = FORTRAN_RUNTIME_STAT_MISSING_ARG,
StatValueTooShort = FORTRAN_RUNTIME_STAT_VALUE_TOO_SHORT, StatValueTooShort = FORTRAN_RUNTIME_STAT_VALUE_TOO_SHORT, // -1
StatMoveAllocSameAllocatable = StatMoveAllocSameAllocatable =
FORTRAN_RUNTIME_STAT_MOVE_ALLOC_SAME_ALLOCATABLE, FORTRAN_RUNTIME_STAT_MOVE_ALLOC_SAME_ALLOCATABLE,
StatBadPointerDeallocation = FORTRAN_RUNTIME_STAT_BAD_POINTER_DEALLOCATION, StatBadPointerDeallocation = FORTRAN_RUNTIME_STAT_BAD_POINTER_DEALLOCATION,
// Dummy status for work queue continuation, declared here to perhaps
// avoid collisions
StatContinue = 201
}; };
RT_API_ATTRS const char *StatErrorString(int); RT_API_ATTRS const char *StatErrorString(int);

View File

@ -154,13 +154,18 @@ public:
RT_API_ATTRS bool IsArgDescriptor(int zeroBasedArg) const { RT_API_ATTRS bool IsArgDescriptor(int zeroBasedArg) const {
return (isArgDescriptorSet_ >> zeroBasedArg) & 1; return (isArgDescriptorSet_ >> zeroBasedArg) & 1;
} }
RT_API_ATTRS bool isTypeBound() const { return isTypeBound_; } RT_API_ATTRS bool IsTypeBound() const { return isTypeBound_ != 0; }
RT_API_ATTRS bool IsArgContiguous(int zeroBasedArg) const { RT_API_ATTRS bool IsArgContiguous(int zeroBasedArg) const {
return (isArgContiguousSet_ >> zeroBasedArg) & 1; return (isArgContiguousSet_ >> zeroBasedArg) & 1;
} }
template <typename PROC> RT_API_ATTRS PROC GetProc() const { template <typename PROC>
RT_API_ATTRS PROC GetProc(const Binding *bindings = nullptr) const {
if (bindings && isTypeBound_ > 0) {
return reinterpret_cast<PROC>(bindings[isTypeBound_ - 1].proc);
} else {
return reinterpret_cast<PROC>(proc_); return reinterpret_cast<PROC>(proc_);
} }
}
FILE *Dump(FILE *) const; FILE *Dump(FILE *) const;
@ -193,6 +198,8 @@ private:
// When false, the defined I/O subroutine must have been // When false, the defined I/O subroutine must have been
// called via a generic interface, not a generic TBP. // called via a generic interface, not a generic TBP.
std::uint8_t isArgDescriptorSet_{0}; std::uint8_t isArgDescriptorSet_{0};
// When a special binding is type-bound, this is its binding's index (plus 1,
// so that 0 signifies that it's not type-bound).
std::uint8_t isTypeBound_{0}; std::uint8_t isTypeBound_{0};
// True when a FINAL subroutine has a dummy argument that is an array that // True when a FINAL subroutine has a dummy argument that is an array that
// is CONTIGUOUS or neither assumed-rank nor assumed-shape. // is CONTIGUOUS or neither assumed-rank nor assumed-shape.
@ -240,6 +247,7 @@ public:
RT_API_ATTRS bool noFinalizationNeeded() const { RT_API_ATTRS bool noFinalizationNeeded() const {
return noFinalizationNeeded_; return noFinalizationNeeded_;
} }
RT_API_ATTRS bool noDefinedAssignment() const { return noDefinedAssignment_; }
RT_API_ATTRS std::size_t LenParameters() const { RT_API_ATTRS std::size_t LenParameters() const {
return lenParameterKind().Elements(); return lenParameterKind().Elements();
@ -322,6 +330,7 @@ private:
bool noInitializationNeeded_{false}; bool noInitializationNeeded_{false};
bool noDestructionNeeded_{false}; bool noDestructionNeeded_{false};
bool noFinalizationNeeded_{false}; bool noFinalizationNeeded_{false};
bool noDefinedAssignment_{false};
}; };
} // namespace Fortran::runtime::typeInfo } // namespace Fortran::runtime::typeInfo

View File

@ -0,0 +1,555 @@
//===-- include/flang-rt/runtime/work-queue.h -------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// Internal runtime utilities for work queues that replace the use of recursion
// for better GPU device support.
//
// A work queue comprises a list of tickets. Each ticket class has a Begin()
// member function, which is called once, and a Continue() member function
// that can be called zero or more times. A ticket's execution terminates
// when either of these member functions returns a status other than
// StatContinue. When that status is not StatOk, then the whole queue
// is shut down.
//
// By returning StatContinue from its Continue() member function,
// a ticket suspends its execution so that any nested tickets that it
// may have created can be run to completion. It is the reponsibility
// of each ticket class to maintain resumption information in its state
// and manage its own progress. Most ticket classes inherit from
// class ComponentsOverElements, which implements an outer loop over all
// components of a derived type, and an inner loop over all elements
// of a descriptor, possibly with multiple phases of execution per element.
//
// Tickets are created by WorkQueue::Begin...() member functions.
// There is one of these for each "top level" recursive function in the
// Fortran runtime support library that has been restructured into this
// ticket framework.
//
// When the work queue is running tickets, it always selects the last ticket
// on the list for execution -- "work stack" might have been a more accurate
// name for this framework. This ticket may, while doing its job, create
// new tickets, and since those are pushed after the active one, the first
// such nested ticket will be the next one executed to completion -- i.e.,
// the order of nested WorkQueue::Begin...() calls is respected.
// Note that a ticket's Continue() member function won't be called again
// until all nested tickets have run to completion and it is once again
// the last ticket on the queue.
//
// Example for an assignment to a derived type:
// 1. Assign() is called, and its work queue is created. It calls
// WorkQueue::BeginAssign() and then WorkQueue::Run().
// 2. Run calls AssignTicket::Begin(), which pushes a tickets via
// BeginFinalize() and returns StatContinue.
// 3. FinalizeTicket::Begin() and FinalizeTicket::Continue() are called
// until one of them returns StatOk, which ends the finalization ticket.
// 4. AssignTicket::Continue() is then called; it creates a DerivedAssignTicket
// and then returns StatOk, which ends the ticket.
// 5. At this point, only one ticket remains. DerivedAssignTicket::Begin()
// and ::Continue() are called until they are done (not StatContinue).
// Along the way, it may create nested AssignTickets for components,
// and suspend itself so that they may each run to completion.
#ifndef FLANG_RT_RUNTIME_WORK_QUEUE_H_
#define FLANG_RT_RUNTIME_WORK_QUEUE_H_
#include "flang-rt/runtime/connection.h"
#include "flang-rt/runtime/descriptor.h"
#include "flang-rt/runtime/stat.h"
#include "flang-rt/runtime/type-info.h"
#include "flang/Common/api-attrs.h"
#include "flang/Runtime/freestanding-tools.h"
#include <flang/Common/variant.h>
namespace Fortran::runtime::io {
class IoStatementState;
struct NonTbpDefinedIoTable;
} // namespace Fortran::runtime::io
namespace Fortran::runtime {
class Terminator;
class WorkQueue;
// Ticket worker base classes
template <typename TICKET> class ImmediateTicketRunner {
public:
RT_API_ATTRS explicit ImmediateTicketRunner(TICKET &ticket)
: ticket_{ticket} {}
RT_API_ATTRS int Run(WorkQueue &workQueue) {
int status{ticket_.Begin(workQueue)};
while (status == StatContinue) {
status = ticket_.Continue(workQueue);
}
return status;
}
private:
TICKET &ticket_;
};
// Base class for ticket workers that operate elementwise over descriptors
class Elementwise {
public:
RT_API_ATTRS Elementwise(
const Descriptor &instance, const Descriptor *from = nullptr)
: instance_{instance}, from_{from} {
instance_.GetLowerBounds(subscripts_);
if (from_) {
from_->GetLowerBounds(fromSubscripts_);
}
}
RT_API_ATTRS bool IsComplete() const { return elementAt_ >= elements_; }
RT_API_ATTRS void Advance() {
++elementAt_;
instance_.IncrementSubscripts(subscripts_);
if (from_) {
from_->IncrementSubscripts(fromSubscripts_);
}
}
RT_API_ATTRS void SkipToEnd() { elementAt_ = elements_; }
RT_API_ATTRS void Reset() {
elementAt_ = 0;
instance_.GetLowerBounds(subscripts_);
if (from_) {
from_->GetLowerBounds(fromSubscripts_);
}
}
protected:
const Descriptor &instance_, *from_{nullptr};
std::size_t elements_{instance_.Elements()};
std::size_t elementAt_{0};
SubscriptValue subscripts_[common::maxRank];
SubscriptValue fromSubscripts_[common::maxRank];
};
// Base class for ticket workers that operate over derived type components.
class Componentwise {
public:
RT_API_ATTRS Componentwise(const typeInfo::DerivedType &);
RT_API_ATTRS bool IsComplete() const { return componentAt_ >= components_; }
RT_API_ATTRS void Advance() {
++componentAt_;
GetComponent();
}
RT_API_ATTRS void SkipToEnd() {
component_ = nullptr;
componentAt_ = components_;
}
RT_API_ATTRS void Reset() {
component_ = nullptr;
componentAt_ = 0;
GetComponent();
}
RT_API_ATTRS void GetComponent();
protected:
const typeInfo::DerivedType &derived_;
std::size_t components_{0}, componentAt_{0};
const typeInfo::Component *component_{nullptr};
StaticDescriptor<common::maxRank, true, 0> componentDescriptor_;
};
// Base class for ticket workers that operate over derived type components
// in an outer loop, and elements in an inner loop.
class ComponentsOverElements : public Componentwise, public Elementwise {
public:
RT_API_ATTRS ComponentsOverElements(const Descriptor &instance,
const typeInfo::DerivedType &derived, const Descriptor *from = nullptr)
: Componentwise{derived}, Elementwise{instance, from} {
if (Elementwise::IsComplete()) {
Componentwise::SkipToEnd();
}
}
RT_API_ATTRS bool IsComplete() const { return Componentwise::IsComplete(); }
RT_API_ATTRS void Advance() {
SkipToNextElement();
if (Elementwise::IsComplete()) {
Elementwise::Reset();
Componentwise::Advance();
}
}
RT_API_ATTRS void SkipToNextElement() {
phase_ = 0;
Elementwise::Advance();
}
RT_API_ATTRS void SkipToNextComponent() {
phase_ = 0;
Elementwise::Reset();
Componentwise::Advance();
}
RT_API_ATTRS void Reset() {
phase_ = 0;
Elementwise::Reset();
Componentwise::Reset();
}
protected:
int phase_{0};
};
// Base class for ticket workers that operate over elements in an outer loop,
// type components in an inner loop.
class ElementsOverComponents : public Elementwise, public Componentwise {
public:
RT_API_ATTRS ElementsOverComponents(const Descriptor &instance,
const typeInfo::DerivedType &derived, const Descriptor *from = nullptr)
: Elementwise{instance, from}, Componentwise{derived} {
if (Componentwise::IsComplete()) {
Elementwise::SkipToEnd();
}
}
RT_API_ATTRS bool IsComplete() const { return Elementwise::IsComplete(); }
RT_API_ATTRS void Advance() {
SkipToNextComponent();
if (Componentwise::IsComplete()) {
Componentwise::Reset();
Elementwise::Advance();
}
}
RT_API_ATTRS void SkipToNextComponent() {
phase_ = 0;
Componentwise::Advance();
}
RT_API_ATTRS void SkipToNextElement() {
phase_ = 0;
Componentwise::Reset();
Elementwise::Advance();
}
protected:
int phase_{0};
};
// Ticket worker classes
// Implements derived type instance initialization
class InitializeTicket : public ImmediateTicketRunner<InitializeTicket>,
private ComponentsOverElements {
public:
RT_API_ATTRS InitializeTicket(
const Descriptor &instance, const typeInfo::DerivedType &derived)
: ImmediateTicketRunner<InitializeTicket>{*this},
ComponentsOverElements{instance, derived} {}
RT_API_ATTRS int Begin(WorkQueue &);
RT_API_ATTRS int Continue(WorkQueue &);
};
// Initializes one derived type instance from the value of another
class InitializeCloneTicket
: public ImmediateTicketRunner<InitializeCloneTicket>,
private ComponentsOverElements {
public:
RT_API_ATTRS InitializeCloneTicket(const Descriptor &clone,
const Descriptor &original, const typeInfo::DerivedType &derived,
bool hasStat, const Descriptor *errMsg)
: ImmediateTicketRunner<InitializeCloneTicket>{*this},
ComponentsOverElements{original, derived}, clone_{clone},
hasStat_{hasStat}, errMsg_{errMsg} {}
RT_API_ATTRS int Begin(WorkQueue &) { return StatContinue; }
RT_API_ATTRS int Continue(WorkQueue &);
private:
const Descriptor &clone_;
bool hasStat_{false};
const Descriptor *errMsg_{nullptr};
StaticDescriptor<common::maxRank, true, 0> cloneComponentDescriptor_;
};
// Implements derived type instance finalization
class FinalizeTicket : public ImmediateTicketRunner<FinalizeTicket>,
private ComponentsOverElements {
public:
RT_API_ATTRS FinalizeTicket(
const Descriptor &instance, const typeInfo::DerivedType &derived)
: ImmediateTicketRunner<FinalizeTicket>{*this},
ComponentsOverElements{instance, derived} {}
RT_API_ATTRS int Begin(WorkQueue &);
RT_API_ATTRS int Continue(WorkQueue &);
private:
const typeInfo::DerivedType *finalizableParentType_{nullptr};
};
// Implements derived type instance destruction
class DestroyTicket : public ImmediateTicketRunner<DestroyTicket>,
private ComponentsOverElements {
public:
RT_API_ATTRS DestroyTicket(const Descriptor &instance,
const typeInfo::DerivedType &derived, bool finalize)
: ImmediateTicketRunner<DestroyTicket>{*this},
ComponentsOverElements{instance, derived}, finalize_{finalize} {}
RT_API_ATTRS int Begin(WorkQueue &);
RT_API_ATTRS int Continue(WorkQueue &);
private:
bool finalize_{false};
};
// Implements general intrinsic assignment
class AssignTicket : public ImmediateTicketRunner<AssignTicket> {
public:
RT_API_ATTRS AssignTicket(Descriptor &to, const Descriptor &from, int flags,
MemmoveFct memmoveFct, const typeInfo::DerivedType *declaredType)
: ImmediateTicketRunner<AssignTicket>{*this}, to_{to}, from_{&from},
flags_{flags}, memmoveFct_{memmoveFct}, declaredType_{declaredType} {}
RT_API_ATTRS int Begin(WorkQueue &);
RT_API_ATTRS int Continue(WorkQueue &);
private:
RT_API_ATTRS bool IsSimpleMemmove() const {
return !toDerived_ && to_.rank() == from_->rank() && to_.IsContiguous() &&
from_->IsContiguous() && to_.ElementBytes() == from_->ElementBytes();
}
RT_API_ATTRS Descriptor &GetTempDescriptor();
Descriptor &to_;
const Descriptor *from_{nullptr};
int flags_{0}; // enum AssignFlags
MemmoveFct memmoveFct_{nullptr};
StaticDescriptor<common::maxRank, true, 0> tempDescriptor_;
const typeInfo::DerivedType *declaredType_{nullptr};
const typeInfo::DerivedType *toDerived_{nullptr};
Descriptor *toDeallocate_{nullptr};
bool persist_{false};
bool done_{false};
};
// Implements derived type intrinsic assignment.
template <bool IS_COMPONENTWISE>
class DerivedAssignTicket
: public ImmediateTicketRunner<DerivedAssignTicket<IS_COMPONENTWISE>>,
private std::conditional_t<IS_COMPONENTWISE, ComponentsOverElements,
ElementsOverComponents> {
public:
using Base = std::conditional_t<IS_COMPONENTWISE, ComponentsOverElements,
ElementsOverComponents>;
RT_API_ATTRS DerivedAssignTicket(const Descriptor &to, const Descriptor &from,
const typeInfo::DerivedType &derived, int flags, MemmoveFct memmoveFct,
Descriptor *deallocateAfter)
: ImmediateTicketRunner<DerivedAssignTicket>{*this},
Base{to, derived, &from}, flags_{flags}, memmoveFct_{memmoveFct},
deallocateAfter_{deallocateAfter} {}
RT_API_ATTRS int Begin(WorkQueue &);
RT_API_ATTRS int Continue(WorkQueue &);
private:
static constexpr bool isComponentwise_{IS_COMPONENTWISE};
bool toIsContiguous_{this->instance_.IsContiguous()};
bool fromIsContiguous_{this->from_->IsContiguous()};
int flags_{0};
MemmoveFct memmoveFct_{nullptr};
Descriptor *deallocateAfter_{nullptr};
StaticDescriptor<common::maxRank, true, 0> fromComponentDescriptor_;
};
namespace io::descr {
template <io::Direction DIR>
class DescriptorIoTicket
: public ImmediateTicketRunner<DescriptorIoTicket<DIR>>,
private Elementwise {
public:
RT_API_ATTRS DescriptorIoTicket(io::IoStatementState &io,
const Descriptor &descriptor, const io::NonTbpDefinedIoTable *table,
bool &anyIoTookPlace)
: ImmediateTicketRunner<DescriptorIoTicket>(*this),
Elementwise{descriptor}, io_{io}, table_{table},
anyIoTookPlace_{anyIoTookPlace} {}
RT_API_ATTRS int Begin(WorkQueue &);
RT_API_ATTRS int Continue(WorkQueue &);
RT_API_ATTRS bool &anyIoTookPlace() { return anyIoTookPlace_; }
private:
io::IoStatementState &io_;
const io::NonTbpDefinedIoTable *table_{nullptr};
bool &anyIoTookPlace_;
common::optional<typeInfo::SpecialBinding> nonTbpSpecial_;
const typeInfo::DerivedType *derived_{nullptr};
const typeInfo::SpecialBinding *special_{nullptr};
StaticDescriptor<common::maxRank, true, 0> elementDescriptor_;
};
template <io::Direction DIR>
class DerivedIoTicket : public ImmediateTicketRunner<DerivedIoTicket<DIR>>,
private ElementsOverComponents {
public:
RT_API_ATTRS DerivedIoTicket(io::IoStatementState &io,
const Descriptor &descriptor, const typeInfo::DerivedType &derived,
const io::NonTbpDefinedIoTable *table, bool &anyIoTookPlace)
: ImmediateTicketRunner<DerivedIoTicket>(*this),
ElementsOverComponents{descriptor, derived}, io_{io}, table_{table},
anyIoTookPlace_{anyIoTookPlace} {}
RT_API_ATTRS int Begin(WorkQueue &) { return StatContinue; }
RT_API_ATTRS int Continue(WorkQueue &);
private:
io::IoStatementState &io_;
const io::NonTbpDefinedIoTable *table_{nullptr};
bool &anyIoTookPlace_;
};
} // namespace io::descr
struct NullTicket {
RT_API_ATTRS int Begin(WorkQueue &) const { return StatOk; }
RT_API_ATTRS int Continue(WorkQueue &) const { return StatOk; }
};
struct Ticket {
RT_API_ATTRS int Continue(WorkQueue &);
bool begun{false};
std::variant<NullTicket, InitializeTicket, InitializeCloneTicket,
FinalizeTicket, DestroyTicket, AssignTicket, DerivedAssignTicket<false>,
DerivedAssignTicket<true>,
io::descr::DescriptorIoTicket<io::Direction::Output>,
io::descr::DescriptorIoTicket<io::Direction::Input>,
io::descr::DerivedIoTicket<io::Direction::Output>,
io::descr::DerivedIoTicket<io::Direction::Input>>
u;
};
class WorkQueue {
public:
RT_API_ATTRS explicit WorkQueue(Terminator &terminator)
: terminator_{terminator} {
for (int j{1}; j < numStatic_; ++j) {
static_[j].previous = &static_[j - 1];
static_[j - 1].next = &static_[j];
}
}
RT_API_ATTRS ~WorkQueue();
RT_API_ATTRS Terminator &terminator() { return terminator_; };
// APIs for particular tasks. These can return StatOk if the work is
// completed immediately.
RT_API_ATTRS int BeginInitialize(
const Descriptor &descriptor, const typeInfo::DerivedType &derived) {
if (runTicketsImmediately_) {
return InitializeTicket{descriptor, derived}.Run(*this);
} else {
StartTicket().u.emplace<InitializeTicket>(descriptor, derived);
return StatContinue;
}
}
RT_API_ATTRS int BeginInitializeClone(const Descriptor &clone,
const Descriptor &original, const typeInfo::DerivedType &derived,
bool hasStat, const Descriptor *errMsg) {
if (runTicketsImmediately_) {
return InitializeCloneTicket{clone, original, derived, hasStat, errMsg}
.Run(*this);
} else {
StartTicket().u.emplace<InitializeCloneTicket>(
clone, original, derived, hasStat, errMsg);
return StatContinue;
}
}
RT_API_ATTRS int BeginFinalize(
const Descriptor &descriptor, const typeInfo::DerivedType &derived) {
if (runTicketsImmediately_) {
return FinalizeTicket{descriptor, derived}.Run(*this);
} else {
StartTicket().u.emplace<FinalizeTicket>(descriptor, derived);
return StatContinue;
}
}
RT_API_ATTRS int BeginDestroy(const Descriptor &descriptor,
const typeInfo::DerivedType &derived, bool finalize) {
if (runTicketsImmediately_) {
return DestroyTicket{descriptor, derived, finalize}.Run(*this);
} else {
StartTicket().u.emplace<DestroyTicket>(descriptor, derived, finalize);
return StatContinue;
}
}
RT_API_ATTRS int BeginAssign(Descriptor &to, const Descriptor &from,
int flags, MemmoveFct memmoveFct,
const typeInfo::DerivedType *declaredType) {
if (runTicketsImmediately_) {
return AssignTicket{to, from, flags, memmoveFct, declaredType}.Run(*this);
} else {
StartTicket().u.emplace<AssignTicket>(
to, from, flags, memmoveFct, declaredType);
return StatContinue;
}
}
template <bool IS_COMPONENTWISE>
RT_API_ATTRS int BeginDerivedAssign(Descriptor &to, const Descriptor &from,
const typeInfo::DerivedType &derived, int flags, MemmoveFct memmoveFct,
Descriptor *deallocateAfter) {
if (runTicketsImmediately_) {
return DerivedAssignTicket<IS_COMPONENTWISE>{
to, from, derived, flags, memmoveFct, deallocateAfter}
.Run(*this);
} else {
StartTicket().u.emplace<DerivedAssignTicket<IS_COMPONENTWISE>>(
to, from, derived, flags, memmoveFct, deallocateAfter);
return StatContinue;
}
}
template <io::Direction DIR>
RT_API_ATTRS int BeginDescriptorIo(io::IoStatementState &io,
const Descriptor &descriptor, const io::NonTbpDefinedIoTable *table,
bool &anyIoTookPlace) {
if (runTicketsImmediately_) {
return io::descr::DescriptorIoTicket<DIR>{
io, descriptor, table, anyIoTookPlace}
.Run(*this);
} else {
StartTicket().u.emplace<io::descr::DescriptorIoTicket<DIR>>(
io, descriptor, table, anyIoTookPlace);
return StatContinue;
}
}
template <io::Direction DIR>
RT_API_ATTRS int BeginDerivedIo(io::IoStatementState &io,
const Descriptor &descriptor, const typeInfo::DerivedType &derived,
const io::NonTbpDefinedIoTable *table, bool &anyIoTookPlace) {
if (runTicketsImmediately_) {
return io::descr::DerivedIoTicket<DIR>{
io, descriptor, derived, table, anyIoTookPlace}
.Run(*this);
} else {
StartTicket().u.emplace<io::descr::DerivedIoTicket<DIR>>(
io, descriptor, derived, table, anyIoTookPlace);
return StatContinue;
}
}
RT_API_ATTRS int Run();
private:
#if RT_DEVICE_COMPILATION
// Always use the work queue on a GPU device to avoid recursion.
static constexpr bool runTicketsImmediately_{false};
#else
// Avoid the work queue overhead on the host, unless it needs
// debugging, which is so much easier there.
static constexpr bool runTicketsImmediately_{true};
#endif
// Most uses of the work queue won't go very deep.
static constexpr int numStatic_{2};
struct TicketList {
bool isStatic{true};
Ticket ticket;
TicketList *previous{nullptr}, *next{nullptr};
};
RT_API_ATTRS Ticket &StartTicket();
RT_API_ATTRS void Stop();
Terminator &terminator_;
TicketList *first_{nullptr}, *last_{nullptr}, *insertAfter_{nullptr};
TicketList static_[numStatic_];
TicketList *firstFree_{static_};
};
} // namespace Fortran::runtime
#endif // FLANG_RT_RUNTIME_WORK_QUEUE_H_

View File

@ -68,6 +68,7 @@ set(supported_sources
type-info.cpp type-info.cpp
unit.cpp unit.cpp
utf.cpp utf.cpp
work-queue.cpp
) )
# List of source not used for GPU offloading. # List of source not used for GPU offloading.
@ -131,6 +132,7 @@ set(gpu_sources
type-code.cpp type-code.cpp
type-info.cpp type-info.cpp
utf.cpp utf.cpp
work-queue.cpp
complex-powi.cpp complex-powi.cpp
reduce.cpp reduce.cpp
reduction.cpp reduction.cpp

View File

@ -14,6 +14,7 @@
#include "flang-rt/runtime/terminator.h" #include "flang-rt/runtime/terminator.h"
#include "flang-rt/runtime/tools.h" #include "flang-rt/runtime/tools.h"
#include "flang-rt/runtime/type-info.h" #include "flang-rt/runtime/type-info.h"
#include "flang-rt/runtime/work-queue.h"
namespace Fortran::runtime { namespace Fortran::runtime {
@ -62,9 +63,22 @@ static inline RT_API_ATTRS bool MustDeallocateLHS(
// Distinct shape? Deallocate // Distinct shape? Deallocate
int rank{to.rank()}; int rank{to.rank()};
for (int j{0}; j < rank; ++j) { for (int j{0}; j < rank; ++j) {
if (to.GetDimension(j).Extent() != from.GetDimension(j).Extent()) { const auto &toDim{to.GetDimension(j)};
const auto &fromDim{from.GetDimension(j)};
if (toDim.Extent() != fromDim.Extent()) {
return true; return true;
} }
if ((flags & UpdateLHSBounds) &&
toDim.LowerBound() != fromDim.LowerBound()) {
return true;
}
}
}
// Not reallocating; may have to update bounds
if (flags & UpdateLHSBounds) {
int rank{to.rank()};
for (int j{0}; j < rank; ++j) {
to.GetDimension(j).SetLowerBound(from.GetDimension(j).LowerBound());
} }
} }
return false; return false;
@ -102,11 +116,7 @@ static RT_API_ATTRS int AllocateAssignmentLHS(
toDim.SetByteStride(stride); toDim.SetByteStride(stride);
stride *= toDim.Extent(); stride *= toDim.Extent();
} }
int result{ReturnError(terminator, to.Allocate(kNoAsyncObject))}; return ReturnError(terminator, to.Allocate(kNoAsyncObject));
if (result == StatOk && derived && !derived->noInitializationNeeded()) {
result = ReturnError(terminator, Initialize(to, *derived, terminator));
}
return result;
} }
// least <= 0, most >= 0 // least <= 0, most >= 0
@ -169,24 +179,27 @@ static RT_API_ATTRS bool MayAlias(const Descriptor &x, const Descriptor &y) {
} }
static RT_API_ATTRS void DoScalarDefinedAssignment(const Descriptor &to, static RT_API_ATTRS void DoScalarDefinedAssignment(const Descriptor &to,
const Descriptor &from, const typeInfo::SpecialBinding &special) { const Descriptor &from, const typeInfo::DerivedType &derived,
const typeInfo::SpecialBinding &special) {
bool toIsDesc{special.IsArgDescriptor(0)}; bool toIsDesc{special.IsArgDescriptor(0)};
bool fromIsDesc{special.IsArgDescriptor(1)}; bool fromIsDesc{special.IsArgDescriptor(1)};
const auto *bindings{
derived.binding().OffsetElement<const typeInfo::Binding>()};
if (toIsDesc) { if (toIsDesc) {
if (fromIsDesc) { if (fromIsDesc) {
auto *p{ auto *p{special.GetProc<void (*)(const Descriptor &, const Descriptor &)>(
special.GetProc<void (*)(const Descriptor &, const Descriptor &)>()}; bindings)};
p(to, from); p(to, from);
} else { } else {
auto *p{special.GetProc<void (*)(const Descriptor &, void *)>()}; auto *p{special.GetProc<void (*)(const Descriptor &, void *)>(bindings)};
p(to, from.raw().base_addr); p(to, from.raw().base_addr);
} }
} else { } else {
if (fromIsDesc) { if (fromIsDesc) {
auto *p{special.GetProc<void (*)(void *, const Descriptor &)>()}; auto *p{special.GetProc<void (*)(void *, const Descriptor &)>(bindings)};
p(to.raw().base_addr, from); p(to.raw().base_addr, from);
} else { } else {
auto *p{special.GetProc<void (*)(void *, void *)>()}; auto *p{special.GetProc<void (*)(void *, void *)>(bindings)};
p(to.raw().base_addr, from.raw().base_addr); p(to.raw().base_addr, from.raw().base_addr);
} }
} }
@ -208,7 +221,7 @@ static RT_API_ATTRS void DoElementalDefinedAssignment(const Descriptor &to,
to.IncrementSubscripts(toAt), from.IncrementSubscripts(fromAt)) { to.IncrementSubscripts(toAt), from.IncrementSubscripts(fromAt)) {
toElementDesc.set_base_addr(to.Element<char>(toAt)); toElementDesc.set_base_addr(to.Element<char>(toAt));
fromElementDesc.set_base_addr(from.Element<char>(fromAt)); fromElementDesc.set_base_addr(from.Element<char>(fromAt));
DoScalarDefinedAssignment(toElementDesc, fromElementDesc, special); DoScalarDefinedAssignment(toElementDesc, fromElementDesc, derived, special);
} }
} }
@ -231,6 +244,8 @@ static RT_API_ATTRS void BlankPadCharacterAssignment(Descriptor &to,
} }
} }
RT_OFFLOAD_API_GROUP_BEGIN
// Common implementation of assignments, both intrinsic assignments and // Common implementation of assignments, both intrinsic assignments and
// those cases of polymorphic user-defined ASSIGNMENT(=) TBPs that could not // those cases of polymorphic user-defined ASSIGNMENT(=) TBPs that could not
// be resolved in semantics. Most assignment statements do not need any // be resolved in semantics. Most assignment statements do not need any
@ -244,45 +259,54 @@ static RT_API_ATTRS void BlankPadCharacterAssignment(Descriptor &to,
// dealing with array constructors. // dealing with array constructors.
RT_API_ATTRS void Assign(Descriptor &to, const Descriptor &from, RT_API_ATTRS void Assign(Descriptor &to, const Descriptor &from,
Terminator &terminator, int flags, MemmoveFct memmoveFct) { Terminator &terminator, int flags, MemmoveFct memmoveFct) {
bool mustDeallocateLHS{(flags & DeallocateLHS) || WorkQueue workQueue{terminator};
MustDeallocateLHS(to, from, terminator, flags)}; if (workQueue.BeginAssign(to, from, flags, memmoveFct, nullptr) ==
DescriptorAddendum *toAddendum{to.Addendum()}; StatContinue) {
const typeInfo::DerivedType *toDerived{ workQueue.Run();
toAddendum ? toAddendum->derivedType() : nullptr};
if (toDerived && (flags & NeedFinalization) &&
toDerived->noFinalizationNeeded()) {
flags &= ~NeedFinalization;
} }
std::size_t toElementBytes{to.ElementBytes()}; }
std::size_t fromElementBytes{from.ElementBytes()};
// The following lambda definition violates the conding style, RT_API_ATTRS int AssignTicket::Begin(WorkQueue &workQueue) {
// but cuda-11.8 nvcc hits an internal error with the brace initialization. bool mustDeallocateLHS{(flags_ & DeallocateLHS) ||
auto isSimpleMemmove = [&]() { MustDeallocateLHS(to_, *from_, workQueue.terminator(), flags_)};
return !toDerived && to.rank() == from.rank() && to.IsContiguous() && DescriptorAddendum *toAddendum{to_.Addendum()};
from.IsContiguous() && toElementBytes == fromElementBytes; toDerived_ = toAddendum ? toAddendum->derivedType() : nullptr;
}; if (toDerived_ && (flags_ & NeedFinalization) &&
StaticDescriptor<maxRank, true, 10 /*?*/> deferredDeallocStatDesc; toDerived_->noFinalizationNeeded()) {
Descriptor *deferDeallocation{nullptr}; flags_ &= ~NeedFinalization;
if (MayAlias(to, from)) { }
if (MayAlias(to_, *from_)) {
if (mustDeallocateLHS) { if (mustDeallocateLHS) {
deferDeallocation = &deferredDeallocStatDesc.descriptor(); // Convert the LHS into a temporary, then make it look deallocated.
toDeallocate_ = &tempDescriptor_.descriptor();
persist_ = true; // tempDescriptor_ state must outlive child tickets
std::memcpy( std::memcpy(
reinterpret_cast<void *>(deferDeallocation), &to, to.SizeInBytes()); reinterpret_cast<void *>(toDeallocate_), &to_, to_.SizeInBytes());
to.set_base_addr(nullptr); to_.set_base_addr(nullptr);
} else if (!isSimpleMemmove()) { if (toDerived_ && (flags_ & NeedFinalization)) {
if (int status{workQueue.BeginFinalize(*toDeallocate_, *toDerived_)};
status != StatOk && status != StatContinue) {
return status;
}
flags_ &= ~NeedFinalization;
}
} else if (!IsSimpleMemmove()) {
// Handle LHS/RHS aliasing by copying RHS into a temp, then // Handle LHS/RHS aliasing by copying RHS into a temp, then
// recursively assigning from that temp. // recursively assigning from that temp.
auto descBytes{from.SizeInBytes()}; auto descBytes{from_->SizeInBytes()};
StaticDescriptor<maxRank, true, 16> staticDesc; Descriptor &newFrom{tempDescriptor_.descriptor()};
Descriptor &newFrom{staticDesc.descriptor()}; persist_ = true; // tempDescriptor_ state must outlive child tickets
std::memcpy(reinterpret_cast<void *>(&newFrom), &from, descBytes); std::memcpy(reinterpret_cast<void *>(&newFrom), from_, descBytes);
// Pretend the temporary descriptor is for an ALLOCATABLE // Pretend the temporary descriptor is for an ALLOCATABLE
// entity, otherwise, the Deallocate() below will not // entity, otherwise, the Deallocate() below will not
// free the descriptor memory. // free the descriptor memory.
newFrom.raw().attribute = CFI_attribute_allocatable; newFrom.raw().attribute = CFI_attribute_allocatable;
auto stat{ReturnError(terminator, newFrom.Allocate(kNoAsyncObject))}; if (int stat{ReturnError(
if (stat == StatOk) { workQueue.terminator(), newFrom.Allocate(kNoAsyncObject))};
if (HasDynamicComponent(from)) { stat != StatOk) {
return stat;
}
if (HasDynamicComponent(*from_)) {
// If 'from' has allocatable/automatic component, we cannot // If 'from' has allocatable/automatic component, we cannot
// just make a shallow copy of the descriptor member. // just make a shallow copy of the descriptor member.
// This will still leave data overlap in 'to' and 'newFrom'. // This will still leave data overlap in 'to' and 'newFrom'.
@ -293,226 +317,403 @@ RT_API_ATTRS void Assign(Descriptor &to, const Descriptor &from,
// type(t) :: x(3) // type(t) :: x(3)
// x(2:3) = x(1:2) // x(2:3) = x(1:2)
// We have to make a deep copy into 'newFrom' in this case. // We have to make a deep copy into 'newFrom' in this case.
RTNAME(AssignTemporary) if (const DescriptorAddendum *addendum{newFrom.Addendum()}) {
(newFrom, from, terminator.sourceFileName(), terminator.sourceLine()); if (const auto *derived{addendum->derivedType()}) {
if (!derived->noInitializationNeeded()) {
if (int status{workQueue.BeginInitialize(newFrom, *derived)};
status != StatOk && status != StatContinue) {
return status;
}
}
}
}
static constexpr int nestedFlags{MaybeReallocate | PolymorphicLHS};
if (int status{workQueue.BeginAssign(
newFrom, *from_, nestedFlags, memmoveFct_, nullptr)};
status != StatOk && status != StatContinue) {
return status;
}
} else { } else {
ShallowCopy(newFrom, from, true, from.IsContiguous()); ShallowCopy(newFrom, *from_, true, from_->IsContiguous());
} }
Assign(to, newFrom, terminator, from_ = &newFrom; // this is why from_ has to be a pointer
flags & flags_ &= NeedFinalization | ComponentCanBeDefinedAssignment |
(NeedFinalization | ComponentCanBeDefinedAssignment | ExplicitLengthCharacterLHS | CanBeDefinedAssignment;
ExplicitLengthCharacterLHS | CanBeDefinedAssignment)); toDeallocate_ = &newFrom;
newFrom.Deallocate();
}
return;
} }
} }
if (to.IsAllocatable()) { if (to_.IsAllocatable()) {
if (mustDeallocateLHS) { if (mustDeallocateLHS) {
if (deferDeallocation) { if (!toDeallocate_ && to_.IsAllocated()) {
if ((flags & NeedFinalization) && toDerived) { toDeallocate_ = &to_;
Finalize(*deferDeallocation, *toDerived, &terminator);
flags &= ~NeedFinalization;
} }
} else { } else if (to_.rank() != from_->rank() && !to_.IsAllocated()) {
to.Destroy((flags & NeedFinalization) != 0, /*destroyPointers=*/false, workQueue.terminator().Crash("Assign: mismatched ranks (%d != %d) in "
&terminator); "assignment to unallocated allocatable",
flags &= ~NeedFinalization; to_.rank(), from_->rank());
} }
} else if (to.rank() != from.rank() && !to.IsAllocated()) { } else if (!to_.IsAllocated()) {
terminator.Crash("Assign: mismatched ranks (%d != %d) in assignment to " workQueue.terminator().Crash(
"unallocated allocatable", "Assign: left-hand side variable is neither allocated nor allocatable");
to.rank(), from.rank()); }
if (toDerived_ && to_.IsAllocated()) {
// Schedule finalization or destruction of the LHS.
if (flags_ & NeedFinalization) {
if (int status{workQueue.BeginFinalize(to_, *toDerived_)};
status != StatOk && status != StatContinue) {
return status;
}
} else if (!toDerived_->noDestructionNeeded()) {
if (int status{
workQueue.BeginDestroy(to_, *toDerived_, /*finalize=*/false)};
status != StatOk && status != StatContinue) {
return status;
}
}
}
return StatContinue;
}
RT_API_ATTRS int AssignTicket::Continue(WorkQueue &workQueue) {
if (done_) {
// All child tickets are complete; can release this ticket's state.
if (toDeallocate_) {
toDeallocate_->Deallocate();
}
return StatOk;
}
// All necessary finalization or destruction that was initiated by Begin()
// has been completed. Deallocation may be pending, and if it's for the LHS,
// do it now so that the LHS gets reallocated.
if (toDeallocate_ == &to_) {
toDeallocate_ = nullptr;
to_.Deallocate();
}
// Allocate the LHS if needed
if (!to_.IsAllocated()) {
if (int stat{
AllocateAssignmentLHS(to_, *from_, workQueue.terminator(), flags_)};
stat != StatOk) {
return stat;
}
const auto *addendum{to_.Addendum()};
toDerived_ = addendum ? addendum->derivedType() : nullptr;
if (toDerived_) {
if (!toDerived_->noInitializationNeeded()) {
if (int status{workQueue.BeginInitialize(to_, *toDerived_)};
status != StatOk) {
return status;
} }
if (!to.IsAllocated()) {
if (AllocateAssignmentLHS(to, from, terminator, flags) != StatOk) {
return;
} }
flags &= ~NeedFinalization;
toElementBytes = to.ElementBytes(); // may have changed
toDerived = toAddendum ? toAddendum->derivedType() : nullptr;
} }
} }
if (toDerived && (flags & CanBeDefinedAssignment)) {
// Check for a user-defined assignment type-bound procedure; // Check for a user-defined assignment type-bound procedure;
// see 10.2.1.4-5. A user-defined assignment TBP defines all of // see 10.2.1.4-5.
// the semantics, including allocatable (re)allocation and any
// finalization.
//
// Note that the aliasing and LHS (re)allocation handling above // Note that the aliasing and LHS (re)allocation handling above
// needs to run even with CanBeDefinedAssignment flag, when // needs to run even with CanBeDefinedAssignment flag, since
// the Assign() is invoked recursively for component-per-component // Assign() can be invoked recursively for component-wise assignments.
// assignments. // The declared type (if known) must be used for generic resolution
if (to.rank() == 0) { // of ASSIGNMENT(=) to a binding, but that binding can be overridden.
if (const auto *special{toDerived->FindSpecialBinding( if (declaredType_ && (flags_ & CanBeDefinedAssignment)) {
if (to_.rank() == 0) {
if (const auto *special{declaredType_->FindSpecialBinding(
typeInfo::SpecialBinding::Which::ScalarAssignment)}) { typeInfo::SpecialBinding::Which::ScalarAssignment)}) {
return DoScalarDefinedAssignment(to, from, *special); DoScalarDefinedAssignment(to_, *from_, *toDerived_, *special);
done_ = true;
return StatContinue;
} }
} }
if (const auto *special{toDerived->FindSpecialBinding( if (const auto *special{declaredType_->FindSpecialBinding(
typeInfo::SpecialBinding::Which::ElementalAssignment)}) { typeInfo::SpecialBinding::Which::ElementalAssignment)}) {
return DoElementalDefinedAssignment(to, from, *toDerived, *special); DoElementalDefinedAssignment(to_, *from_, *toDerived_, *special);
done_ = true;
return StatContinue;
} }
} }
SubscriptValue toAt[maxRank]; // Intrinsic assignment
to.GetLowerBounds(toAt); std::size_t toElements{to_.Elements()};
if (from_->rank() > 0 && toElements != from_->Elements()) {
workQueue.terminator().Crash("Assign: mismatching element counts in array "
"assignment (to %zd, from %zd)",
toElements, from_->Elements());
}
if (to_.type() != from_->type()) {
workQueue.terminator().Crash(
"Assign: mismatching types (to code %d != from code %d)",
to_.type().raw(), from_->type().raw());
}
std::size_t toElementBytes{to_.ElementBytes()};
std::size_t fromElementBytes{from_->ElementBytes()};
if (toElementBytes > fromElementBytes && !to_.type().IsCharacter()) {
workQueue.terminator().Crash("Assign: mismatching non-character element "
"sizes (to %zd bytes != from %zd bytes)",
toElementBytes, fromElementBytes);
}
if (toDerived_) {
if (toDerived_->noDefinedAssignment()) { // componentwise
if (int status{workQueue.BeginDerivedAssign<true>(
to_, *from_, *toDerived_, flags_, memmoveFct_, toDeallocate_)};
status != StatOk && status != StatContinue) {
return status;
}
} else { // elementwise
if (int status{workQueue.BeginDerivedAssign<false>(
to_, *from_, *toDerived_, flags_, memmoveFct_, toDeallocate_)};
status != StatOk && status != StatContinue) {
return status;
}
}
toDeallocate_ = nullptr;
} else if (IsSimpleMemmove()) {
memmoveFct_(to_.raw().base_addr, from_->raw().base_addr,
toElements * toElementBytes);
} else {
// Scalar expansion of the RHS is implied by using the same empty // Scalar expansion of the RHS is implied by using the same empty
// subscript values on each (seemingly) elemental reference into // subscript values on each (seemingly) elemental reference into
// "from". // "from".
SubscriptValue toAt[maxRank];
to_.GetLowerBounds(toAt);
SubscriptValue fromAt[maxRank]; SubscriptValue fromAt[maxRank];
from.GetLowerBounds(fromAt); from_->GetLowerBounds(fromAt);
std::size_t toElements{to.Elements()}; if (toElementBytes > fromElementBytes) { // blank padding
if (from.rank() > 0 && toElements != from.Elements()) { switch (to_.type().raw()) {
terminator.Crash("Assign: mismatching element counts in array assignment "
"(to %zd, from %zd)",
toElements, from.Elements());
}
if (to.type() != from.type()) {
terminator.Crash("Assign: mismatching types (to code %d != from code %d)",
to.type().raw(), from.type().raw());
}
if (toElementBytes > fromElementBytes && !to.type().IsCharacter()) {
terminator.Crash("Assign: mismatching non-character element sizes (to %zd "
"bytes != from %zd bytes)",
toElementBytes, fromElementBytes);
}
if (const typeInfo::DerivedType *
updatedToDerived{toAddendum ? toAddendum->derivedType() : nullptr}) {
// Derived type intrinsic assignment, which is componentwise and elementwise
// for all components, including parent components (10.2.1.2-3).
// The target is first finalized if still necessary (7.5.6.3(1))
if (flags & NeedFinalization) {
Finalize(to, *updatedToDerived, &terminator);
} else if (updatedToDerived && !updatedToDerived->noDestructionNeeded()) {
Destroy(to, /*finalize=*/false, *updatedToDerived, &terminator);
}
// Copy the data components (incl. the parent) first.
const Descriptor &componentDesc{updatedToDerived->component()};
std::size_t numComponents{componentDesc.Elements()};
for (std::size_t j{0}; j < toElements;
++j, to.IncrementSubscripts(toAt), from.IncrementSubscripts(fromAt)) {
for (std::size_t k{0}; k < numComponents; ++k) {
const auto &comp{
*componentDesc.ZeroBasedIndexedElement<typeInfo::Component>(
k)}; // TODO: exploit contiguity here
// Use PolymorphicLHS for components so that the right things happen
// when the components are polymorphic; when they're not, they're both
// not, and their declared types will match.
int nestedFlags{MaybeReallocate | PolymorphicLHS};
if (flags & ComponentCanBeDefinedAssignment) {
nestedFlags |=
CanBeDefinedAssignment | ComponentCanBeDefinedAssignment;
}
switch (comp.genre()) {
case typeInfo::Component::Genre::Data:
if (comp.category() == TypeCategory::Derived) {
StaticDescriptor<maxRank, true, 10 /*?*/> statDesc[2];
Descriptor &toCompDesc{statDesc[0].descriptor()};
Descriptor &fromCompDesc{statDesc[1].descriptor()};
comp.CreatePointerDescriptor(toCompDesc, to, terminator, toAt);
comp.CreatePointerDescriptor(
fromCompDesc, from, terminator, fromAt);
Assign(toCompDesc, fromCompDesc, terminator, nestedFlags);
} else { // Component has intrinsic type; simply copy raw bytes
std::size_t componentByteSize{comp.SizeInBytes(to)};
memmoveFct(to.Element<char>(toAt) + comp.offset(),
from.Element<const char>(fromAt) + comp.offset(),
componentByteSize);
}
break;
case typeInfo::Component::Genre::Pointer: {
std::size_t componentByteSize{comp.SizeInBytes(to)};
memmoveFct(to.Element<char>(toAt) + comp.offset(),
from.Element<const char>(fromAt) + comp.offset(),
componentByteSize);
} break;
case typeInfo::Component::Genre::Allocatable:
case typeInfo::Component::Genre::Automatic: {
auto *toDesc{reinterpret_cast<Descriptor *>(
to.Element<char>(toAt) + comp.offset())};
const auto *fromDesc{reinterpret_cast<const Descriptor *>(
from.Element<char>(fromAt) + comp.offset())};
// Allocatable components of the LHS are unconditionally
// deallocated before assignment (F'2018 10.2.1.3(13)(1)),
// unlike a "top-level" assignment to a variable, where
// deallocation is optional.
//
// Be careful not to destroy/reallocate the LHS, if there is
// overlap between LHS and RHS (it seems that partial overlap
// is not possible, though).
// Invoke Assign() recursively to deal with potential aliasing.
if (toDesc->IsAllocatable()) {
if (!fromDesc->IsAllocated()) {
// No aliasing.
//
// If to is not allocated, the Destroy() call is a no-op.
// This is just a shortcut, because the recursive Assign()
// below would initiate the destruction for to.
// No finalization is required.
toDesc->Destroy(
/*finalize=*/false, /*destroyPointers=*/false, &terminator);
continue; // F'2018 10.2.1.3(13)(2)
}
}
// Force LHS deallocation with DeallocateLHS flag.
// The actual deallocation may be avoided, if the existing
// location can be reoccupied.
Assign(*toDesc, *fromDesc, terminator, nestedFlags | DeallocateLHS);
} break;
}
}
// Copy procedure pointer components
const Descriptor &procPtrDesc{updatedToDerived->procPtr()};
std::size_t numProcPtrs{procPtrDesc.Elements()};
for (std::size_t k{0}; k < numProcPtrs; ++k) {
const auto &procPtr{
*procPtrDesc.ZeroBasedIndexedElement<typeInfo::ProcPtrComponent>(
k)};
memmoveFct(to.Element<char>(toAt) + procPtr.offset,
from.Element<const char>(fromAt) + procPtr.offset,
sizeof(typeInfo::ProcedurePointer));
}
}
} else { // intrinsic type, intrinsic assignment
if (isSimpleMemmove()) {
memmoveFct(to.raw().base_addr, from.raw().base_addr,
toElements * toElementBytes);
} else if (toElementBytes > fromElementBytes) { // blank padding
switch (to.type().raw()) {
case CFI_type_signed_char: case CFI_type_signed_char:
case CFI_type_char: case CFI_type_char:
BlankPadCharacterAssignment<char>(to, from, toAt, fromAt, toElements, BlankPadCharacterAssignment<char>(to_, *from_, toAt, fromAt, toElements,
toElementBytes, fromElementBytes); toElementBytes, fromElementBytes);
break; break;
case CFI_type_char16_t: case CFI_type_char16_t:
BlankPadCharacterAssignment<char16_t>(to, from, toAt, fromAt, BlankPadCharacterAssignment<char16_t>(to_, *from_, toAt, fromAt,
toElements, toElementBytes, fromElementBytes); toElements, toElementBytes, fromElementBytes);
break; break;
case CFI_type_char32_t: case CFI_type_char32_t:
BlankPadCharacterAssignment<char32_t>(to, from, toAt, fromAt, BlankPadCharacterAssignment<char32_t>(to_, *from_, toAt, fromAt,
toElements, toElementBytes, fromElementBytes); toElements, toElementBytes, fromElementBytes);
break; break;
default: default:
terminator.Crash("unexpected type code %d in blank padded Assign()", workQueue.terminator().Crash(
to.type().raw()); "unexpected type code %d in blank padded Assign()",
to_.type().raw());
} }
} else { // elemental copies, possibly with character truncation } else { // elemental copies, possibly with character truncation
for (std::size_t n{toElements}; n-- > 0; for (std::size_t n{toElements}; n-- > 0;
to.IncrementSubscripts(toAt), from.IncrementSubscripts(fromAt)) { to_.IncrementSubscripts(toAt), from_->IncrementSubscripts(fromAt)) {
memmoveFct(to.Element<char>(toAt), from.Element<const char>(fromAt), memmoveFct_(to_.Element<char>(toAt), from_->Element<const char>(fromAt),
toElementBytes); toElementBytes);
} }
} }
} }
if (deferDeallocation) { if (persist_) {
// deferDeallocation is used only when LHS is an allocatable. done_ = true;
// The finalization has already been run for it. return StatContinue;
deferDeallocation->Destroy( } else {
/*finalize=*/false, /*destroyPointers=*/false, &terminator); if (toDeallocate_) {
toDeallocate_->Deallocate();
toDeallocate_ = nullptr;
}
return StatOk;
} }
} }
RT_OFFLOAD_API_GROUP_BEGIN template <bool IS_COMPONENTWISE>
RT_API_ATTRS int DerivedAssignTicket<IS_COMPONENTWISE>::Begin(
WorkQueue &workQueue) {
if (toIsContiguous_ && fromIsContiguous_ &&
this->derived_.noDestructionNeeded() &&
this->derived_.noDefinedAssignment() &&
this->instance_.rank() == this->from_->rank()) {
if (std::size_t elementBytes{this->instance_.ElementBytes()};
elementBytes == this->from_->ElementBytes()) {
// Fastest path. Both LHS and RHS are contiguous, RHS is not a scalar
// to be expanded, the types have the same size, and there are no
// allocatable components or defined ASSIGNMENT(=) at any level.
memmoveFct_(this->instance_.template OffsetElement<char>(),
this->from_->template OffsetElement<const char *>(),
this->instance_.Elements() * elementBytes);
return StatOk;
}
}
// Use PolymorphicLHS for components so that the right things happen
// when the components are polymorphic; when they're not, they're both
// not, and their declared types will match.
int nestedFlags{MaybeReallocate | PolymorphicLHS};
if (flags_ & ComponentCanBeDefinedAssignment) {
nestedFlags |= CanBeDefinedAssignment | ComponentCanBeDefinedAssignment;
}
flags_ = nestedFlags;
// Copy procedure pointer components
const Descriptor &procPtrDesc{this->derived_.procPtr()};
bool noDataComponents{this->IsComplete()};
if (std::size_t numProcPtrs{procPtrDesc.Elements()}) {
for (std::size_t k{0}; k < numProcPtrs; ++k) {
const auto &procPtr{
*procPtrDesc.ZeroBasedIndexedElement<typeInfo::ProcPtrComponent>(k)};
// Loop only over elements
if (k > 0) {
Elementwise::Reset();
}
for (; !Elementwise::IsComplete(); Elementwise::Advance()) {
memmoveFct_(this->instance_.template ElementComponent<char>(
this->subscripts_, procPtr.offset),
this->from_->template ElementComponent<const char>(
this->fromSubscripts_, procPtr.offset),
sizeof(typeInfo::ProcedurePointer));
}
}
if (noDataComponents) {
return StatOk;
}
Elementwise::Reset();
}
if (noDataComponents) {
return StatOk;
}
return StatContinue;
}
template RT_API_ATTRS int DerivedAssignTicket<false>::Begin(WorkQueue &);
template RT_API_ATTRS int DerivedAssignTicket<true>::Begin(WorkQueue &);
template <bool IS_COMPONENTWISE>
RT_API_ATTRS int DerivedAssignTicket<IS_COMPONENTWISE>::Continue(
WorkQueue &workQueue) {
while (!this->IsComplete()) {
// Copy the data components (incl. the parent) first.
switch (this->component_->genre()) {
case typeInfo::Component::Genre::Data:
if (this->component_->category() == TypeCategory::Derived) {
Descriptor &toCompDesc{this->componentDescriptor_.descriptor()};
Descriptor &fromCompDesc{this->fromComponentDescriptor_.descriptor()};
this->component_->CreatePointerDescriptor(toCompDesc, this->instance_,
workQueue.terminator(), this->subscripts_);
this->component_->CreatePointerDescriptor(fromCompDesc, *this->from_,
workQueue.terminator(), this->fromSubscripts_);
const auto *componentDerived{this->component_->derivedType()};
this->Advance();
if (int status{workQueue.BeginAssign(toCompDesc, fromCompDesc, flags_,
memmoveFct_, componentDerived)};
status != StatOk) {
return status;
}
} else { // Component has intrinsic type; simply copy raw bytes
std::size_t componentByteSize{
this->component_->SizeInBytes(this->instance_)};
if (IS_COMPONENTWISE && toIsContiguous_ && fromIsContiguous_) {
std::size_t offset{this->component_->offset()};
char *to{this->instance_.template OffsetElement<char>(offset)};
const char *from{
this->from_->template OffsetElement<const char>(offset)};
std::size_t toElementStride{this->instance_.ElementBytes()};
std::size_t fromElementStride{
this->from_->rank() == 0 ? 0 : this->from_->ElementBytes()};
if (toElementStride == fromElementStride &&
toElementStride == componentByteSize) {
memmoveFct_(to, from, this->elements_ * componentByteSize);
} else {
for (std::size_t n{this->elements_}; n--;
to += toElementStride, from += fromElementStride) {
memmoveFct_(to, from, componentByteSize);
}
}
this->Componentwise::Advance();
} else {
memmoveFct_(
this->instance_.template Element<char>(this->subscripts_) +
this->component_->offset(),
this->from_->template Element<const char>(this->fromSubscripts_) +
this->component_->offset(),
componentByteSize);
this->Advance();
}
}
break;
case typeInfo::Component::Genre::Pointer: {
std::size_t componentByteSize{
this->component_->SizeInBytes(this->instance_)};
if (IS_COMPONENTWISE && toIsContiguous_ && fromIsContiguous_) {
std::size_t offset{this->component_->offset()};
char *to{this->instance_.template OffsetElement<char>(offset)};
const char *from{
this->from_->template OffsetElement<const char>(offset)};
std::size_t toElementStride{this->instance_.ElementBytes()};
std::size_t fromElementStride{
this->from_->rank() == 0 ? 0 : this->from_->ElementBytes()};
if (toElementStride == fromElementStride &&
toElementStride == componentByteSize) {
memmoveFct_(to, from, this->elements_ * componentByteSize);
} else {
for (std::size_t n{this->elements_}; n--;
to += toElementStride, from += fromElementStride) {
memmoveFct_(to, from, componentByteSize);
}
}
this->Componentwise::Advance();
} else {
memmoveFct_(this->instance_.template Element<char>(this->subscripts_) +
this->component_->offset(),
this->from_->template Element<const char>(this->fromSubscripts_) +
this->component_->offset(),
componentByteSize);
this->Advance();
}
} break;
case typeInfo::Component::Genre::Allocatable:
case typeInfo::Component::Genre::Automatic: {
auto *toDesc{reinterpret_cast<Descriptor *>(
this->instance_.template Element<char>(this->subscripts_) +
this->component_->offset())};
const auto *fromDesc{reinterpret_cast<const Descriptor *>(
this->from_->template Element<char>(this->fromSubscripts_) +
this->component_->offset())};
const auto *componentDerived{this->component_->derivedType()};
if (toDesc->IsAllocatable() && !fromDesc->IsAllocated()) {
if (toDesc->IsAllocated()) {
if (this->phase_ == 0) {
this->phase_++;
if (componentDerived && !componentDerived->noDestructionNeeded()) {
if (int status{workQueue.BeginDestroy(
*toDesc, *componentDerived, /*finalize=*/false)};
status != StatOk) {
return status;
}
}
}
toDesc->Deallocate();
}
this->Advance();
} else {
// Allocatable components of the LHS are unconditionally
// deallocated before assignment (F'2018 10.2.1.3(13)(1)),
// unlike a "top-level" assignment to a variable, where
// deallocation is optional.
int nestedFlags{flags_};
if (!componentDerived ||
(componentDerived->noFinalizationNeeded() &&
componentDerived->noInitializationNeeded() &&
componentDerived->noDestructionNeeded())) {
// The actual deallocation might be avoidable when the existing
// location can be reoccupied.
nestedFlags |= MaybeReallocate | UpdateLHSBounds;
} else {
// Force LHS deallocation with DeallocateLHS flag.
nestedFlags |= DeallocateLHS;
}
this->Advance();
if (int status{workQueue.BeginAssign(*toDesc, *fromDesc, nestedFlags,
memmoveFct_, componentDerived)};
status != StatOk) {
return status;
}
}
} break;
}
}
if (deallocateAfter_) {
deallocateAfter_->Deallocate();
}
return StatOk;
}
template RT_API_ATTRS int DerivedAssignTicket<false>::Continue(WorkQueue &);
template RT_API_ATTRS int DerivedAssignTicket<true>::Continue(WorkQueue &);
RT_API_ATTRS void DoFromSourceAssign(Descriptor &alloc, RT_API_ATTRS void DoFromSourceAssign(Descriptor &alloc,
const Descriptor &source, Terminator &terminator, MemmoveFct memmoveFct) { const Descriptor &source, Terminator &terminator, MemmoveFct memmoveFct) {
@ -582,7 +783,6 @@ void RTDEF(AssignTemporary)(Descriptor &to, const Descriptor &from,
} }
} }
} }
Assign(to, from, terminator, MaybeReallocate | PolymorphicLHS); Assign(to, from, terminator, MaybeReallocate | PolymorphicLHS);
} }
@ -599,7 +799,6 @@ void RTDEF(CopyInAssign)(Descriptor &temp, const Descriptor &var,
void RTDEF(CopyOutAssign)( void RTDEF(CopyOutAssign)(
Descriptor *var, Descriptor &temp, const char *sourceFile, int sourceLine) { Descriptor *var, Descriptor &temp, const char *sourceFile, int sourceLine) {
Terminator terminator{sourceFile, sourceLine}; Terminator terminator{sourceFile, sourceLine};
// Copyout from the temporary must not cause any finalizations // Copyout from the temporary must not cause any finalizations
// for LHS. The variable must be properly initialized already. // for LHS. The variable must be properly initialized already.
if (var) { if (var) {

View File

@ -12,6 +12,7 @@
#include "flang-rt/runtime/terminator.h" #include "flang-rt/runtime/terminator.h"
#include "flang-rt/runtime/tools.h" #include "flang-rt/runtime/tools.h"
#include "flang-rt/runtime/type-info.h" #include "flang-rt/runtime/type-info.h"
#include "flang-rt/runtime/work-queue.h"
namespace Fortran::runtime { namespace Fortran::runtime {
@ -30,180 +31,192 @@ static RT_API_ATTRS void GetComponentExtents(SubscriptValue (&extents)[maxRank],
} }
RT_API_ATTRS int Initialize(const Descriptor &instance, RT_API_ATTRS int Initialize(const Descriptor &instance,
const typeInfo::DerivedType &derived, Terminator &terminator, bool hasStat, const typeInfo::DerivedType &derived, Terminator &terminator, bool,
const Descriptor *errMsg) { const Descriptor *) {
const Descriptor &componentDesc{derived.component()}; WorkQueue workQueue{terminator};
std::size_t elements{instance.Elements()}; int status{workQueue.BeginInitialize(instance, derived)};
int stat{StatOk}; return status == StatContinue ? workQueue.Run() : status;
// Initialize data components in each element; the per-element iterations
// constitute the inner loops, not the outer ones
std::size_t myComponents{componentDesc.Elements()};
for (std::size_t k{0}; k < myComponents; ++k) {
const auto &comp{
*componentDesc.ZeroBasedIndexedElement<typeInfo::Component>(k)};
SubscriptValue at[maxRank];
instance.GetLowerBounds(at);
if (comp.genre() == typeInfo::Component::Genre::Allocatable ||
comp.genre() == typeInfo::Component::Genre::Automatic) {
for (std::size_t j{0}; j++ < elements; instance.IncrementSubscripts(at)) {
Descriptor &allocDesc{
*instance.ElementComponent<Descriptor>(at, comp.offset())};
comp.EstablishDescriptor(allocDesc, instance, terminator);
allocDesc.raw().attribute = CFI_attribute_allocatable;
if (comp.genre() == typeInfo::Component::Genre::Automatic) {
stat = ReturnError(
terminator, allocDesc.Allocate(kNoAsyncObject), errMsg, hasStat);
if (stat == StatOk) {
if (const DescriptorAddendum * addendum{allocDesc.Addendum()}) {
if (const auto *derived{addendum->derivedType()}) {
if (!derived->noInitializationNeeded()) {
stat = Initialize(
allocDesc, *derived, terminator, hasStat, errMsg);
}
}
}
}
if (stat != StatOk) {
break;
}
}
}
} else if (const void *init{comp.initialization()}) {
// Explicit initialization of data pointers and
// non-allocatable non-automatic components
std::size_t bytes{comp.SizeInBytes(instance)};
for (std::size_t j{0}; j++ < elements; instance.IncrementSubscripts(at)) {
char *ptr{instance.ElementComponent<char>(at, comp.offset())};
std::memcpy(ptr, init, bytes);
}
} else if (comp.genre() == typeInfo::Component::Genre::Pointer) {
// Data pointers without explicit initialization are established
// so that they are valid right-hand side targets of pointer
// assignment statements.
for (std::size_t j{0}; j++ < elements; instance.IncrementSubscripts(at)) {
Descriptor &ptrDesc{
*instance.ElementComponent<Descriptor>(at, comp.offset())};
comp.EstablishDescriptor(ptrDesc, instance, terminator);
ptrDesc.raw().attribute = CFI_attribute_pointer;
}
} else if (comp.genre() == typeInfo::Component::Genre::Data &&
comp.derivedType() && !comp.derivedType()->noInitializationNeeded()) {
// Default initialization of non-pointer non-allocatable/automatic
// data component. Handles parent component's elements. Recursive.
SubscriptValue extents[maxRank];
GetComponentExtents(extents, comp, instance);
StaticDescriptor<maxRank, true, 0> staticDescriptor;
Descriptor &compDesc{staticDescriptor.descriptor()};
const typeInfo::DerivedType &compType{*comp.derivedType()};
for (std::size_t j{0}; j++ < elements; instance.IncrementSubscripts(at)) {
compDesc.Establish(compType,
instance.ElementComponent<char>(at, comp.offset()), comp.rank(),
extents);
stat = Initialize(compDesc, compType, terminator, hasStat, errMsg);
if (stat != StatOk) {
break;
}
}
}
} }
RT_API_ATTRS int InitializeTicket::Begin(WorkQueue &) {
// Initialize procedure pointer components in each element // Initialize procedure pointer components in each element
const Descriptor &procPtrDesc{derived.procPtr()}; const Descriptor &procPtrDesc{derived_.procPtr()};
std::size_t myProcPtrs{procPtrDesc.Elements()}; if (std::size_t numProcPtrs{procPtrDesc.Elements()}) {
for (std::size_t k{0}; k < myProcPtrs; ++k) { for (std::size_t k{0}; k < numProcPtrs; ++k) {
const auto &comp{ const auto &comp{
*procPtrDesc.ZeroBasedIndexedElement<typeInfo::ProcPtrComponent>(k)}; *procPtrDesc.ZeroBasedIndexedElement<typeInfo::ProcPtrComponent>(k)};
SubscriptValue at[maxRank]; // Loop only over elements
instance.GetLowerBounds(at); if (k > 0) {
for (std::size_t j{0}; j++ < elements; instance.IncrementSubscripts(at)) { Elementwise::Reset();
auto &pptr{*instance.ElementComponent<typeInfo::ProcedurePointer>( }
at, comp.offset)}; for (; !Elementwise::IsComplete(); Elementwise::Advance()) {
auto &pptr{*instance_.ElementComponent<typeInfo::ProcedurePointer>(
subscripts_, comp.offset)};
pptr = comp.procInitialization; pptr = comp.procInitialization;
} }
} }
return stat; if (IsComplete()) {
return StatOk;
}
Elementwise::Reset();
}
return StatContinue;
}
RT_API_ATTRS int InitializeTicket::Continue(WorkQueue &workQueue) {
while (!IsComplete()) {
if (component_->genre() == typeInfo::Component::Genre::Allocatable) {
// Establish allocatable descriptors
for (; !Elementwise::IsComplete(); Elementwise::Advance()) {
Descriptor &allocDesc{*instance_.ElementComponent<Descriptor>(
subscripts_, component_->offset())};
component_->EstablishDescriptor(
allocDesc, instance_, workQueue.terminator());
allocDesc.raw().attribute = CFI_attribute_allocatable;
}
SkipToNextComponent();
} else if (const void *init{component_->initialization()}) {
// Explicit initialization of data pointers and
// non-allocatable non-automatic components
std::size_t bytes{component_->SizeInBytes(instance_)};
for (; !Elementwise::IsComplete(); Elementwise::Advance()) {
char *ptr{instance_.ElementComponent<char>(
subscripts_, component_->offset())};
std::memcpy(ptr, init, bytes);
}
SkipToNextComponent();
} else if (component_->genre() == typeInfo::Component::Genre::Pointer) {
// Data pointers without explicit initialization are established
// so that they are valid right-hand side targets of pointer
// assignment statements.
for (; !Elementwise::IsComplete(); Elementwise::Advance()) {
Descriptor &ptrDesc{*instance_.ElementComponent<Descriptor>(
subscripts_, component_->offset())};
component_->EstablishDescriptor(
ptrDesc, instance_, workQueue.terminator());
ptrDesc.raw().attribute = CFI_attribute_pointer;
}
SkipToNextComponent();
} else if (component_->genre() == typeInfo::Component::Genre::Data &&
component_->derivedType() &&
!component_->derivedType()->noInitializationNeeded()) {
// Default initialization of non-pointer non-allocatable/automatic
// data component. Handles parent component's elements.
SubscriptValue extents[maxRank];
GetComponentExtents(extents, *component_, instance_);
Descriptor &compDesc{componentDescriptor_.descriptor()};
const typeInfo::DerivedType &compType{*component_->derivedType()};
compDesc.Establish(compType,
instance_.ElementComponent<char>(subscripts_, component_->offset()),
component_->rank(), extents);
Advance();
if (int status{workQueue.BeginInitialize(compDesc, compType)};
status != StatOk) {
return status;
}
} else {
SkipToNextComponent();
}
}
return StatOk;
} }
RT_API_ATTRS int InitializeClone(const Descriptor &clone, RT_API_ATTRS int InitializeClone(const Descriptor &clone,
const Descriptor &orig, const typeInfo::DerivedType &derived, const Descriptor &original, const typeInfo::DerivedType &derived,
Terminator &terminator, bool hasStat, const Descriptor *errMsg) { Terminator &terminator, bool hasStat, const Descriptor *errMsg) {
const Descriptor &componentDesc{derived.component()}; if (original.IsPointer() || !original.IsAllocated()) {
std::size_t elements{orig.Elements()}; return StatOk; // nothing to do
int stat{StatOk}; } else {
WorkQueue workQueue{terminator};
int status{workQueue.BeginInitializeClone(
clone, original, derived, hasStat, errMsg)};
return status == StatContinue ? workQueue.Run() : status;
}
}
// Skip pointers and unallocated variables. RT_API_ATTRS int InitializeCloneTicket::Continue(WorkQueue &workQueue) {
if (orig.IsPointer() || !orig.IsAllocated()) { while (!IsComplete()) {
if (component_->genre() == typeInfo::Component::Genre::Allocatable) {
Descriptor &origDesc{*instance_.ElementComponent<Descriptor>(
subscripts_, component_->offset())};
if (origDesc.IsAllocated()) {
Descriptor &cloneDesc{*clone_.ElementComponent<Descriptor>(
subscripts_, component_->offset())};
if (phase_ == 0) {
++phase_;
cloneDesc.ApplyMold(origDesc, origDesc.rank());
if (int stat{ReturnError(workQueue.terminator(),
cloneDesc.Allocate(kNoAsyncObject), errMsg_, hasStat_)};
stat != StatOk) {
return stat; return stat;
} }
// Initialize each data component.
std::size_t components{componentDesc.Elements()};
for (std::size_t i{0}; i < components; ++i) {
const typeInfo::Component &comp{
*componentDesc.ZeroBasedIndexedElement<typeInfo::Component>(i)};
SubscriptValue at[maxRank];
orig.GetLowerBounds(at);
// Allocate allocatable components that are also allocated in the original
// object.
if (comp.genre() == typeInfo::Component::Genre::Allocatable) {
// Initialize each element.
for (std::size_t j{0}; j < elements; ++j, orig.IncrementSubscripts(at)) {
Descriptor &origDesc{
*orig.ElementComponent<Descriptor>(at, comp.offset())};
Descriptor &cloneDesc{
*clone.ElementComponent<Descriptor>(at, comp.offset())};
if (origDesc.IsAllocated()) {
cloneDesc.ApplyMold(origDesc, origDesc.rank());
stat = ReturnError(
terminator, cloneDesc.Allocate(kNoAsyncObject), errMsg, hasStat);
if (stat == StatOk) {
if (const DescriptorAddendum *addendum{cloneDesc.Addendum()}) { if (const DescriptorAddendum *addendum{cloneDesc.Addendum()}) {
if (const typeInfo::DerivedType * if (const typeInfo::DerivedType *derived{addendum->derivedType()}) {
derived{addendum->derivedType()}) {
if (!derived->noInitializationNeeded()) { if (!derived->noInitializationNeeded()) {
// Perform default initialization for the allocated element. // Perform default initialization for the allocated element.
stat = Initialize( if (int status{workQueue.BeginInitialize(cloneDesc, *derived)};
cloneDesc, *derived, terminator, hasStat, errMsg); status != StatOk) {
return status;
} }
}
}
}
}
if (phase_ == 1) {
++phase_;
if (const DescriptorAddendum *addendum{cloneDesc.Addendum()}) {
if (const typeInfo::DerivedType *derived{addendum->derivedType()}) {
// Initialize derived type's allocatables. // Initialize derived type's allocatables.
if (stat == StatOk) { if (int status{workQueue.BeginInitializeClone(
stat = InitializeClone(cloneDesc, origDesc, *derived, cloneDesc, origDesc, *derived, hasStat_, errMsg_)};
terminator, hasStat, errMsg); status != StatOk) {
return status;
} }
} }
} }
} }
} }
if (stat != StatOk) { Advance();
break; } else if (component_->genre() == typeInfo::Component::Genre::Data) {
} if (component_->derivedType()) {
}
} else if (comp.genre() == typeInfo::Component::Genre::Data &&
comp.derivedType()) {
// Handle nested derived types. // Handle nested derived types.
const typeInfo::DerivedType &compType{*comp.derivedType()}; const typeInfo::DerivedType &compType{*component_->derivedType()};
SubscriptValue extents[maxRank]; SubscriptValue extents[maxRank];
GetComponentExtents(extents, comp, orig); GetComponentExtents(extents, *component_, instance_);
// Data components don't have descriptors, allocate them. Descriptor &origDesc{componentDescriptor_.descriptor()};
StaticDescriptor<maxRank, true, 0> origStaticDesc; Descriptor &cloneDesc{cloneComponentDescriptor_.descriptor()};
StaticDescriptor<maxRank, true, 0> cloneStaticDesc;
Descriptor &origDesc{origStaticDesc.descriptor()};
Descriptor &cloneDesc{cloneStaticDesc.descriptor()};
// Initialize each element.
for (std::size_t j{0}; j < elements; ++j, orig.IncrementSubscripts(at)) {
origDesc.Establish(compType, origDesc.Establish(compType,
orig.ElementComponent<char>(at, comp.offset()), comp.rank(), instance_.ElementComponent<char>(subscripts_, component_->offset()),
extents); component_->rank(), extents);
cloneDesc.Establish(compType, cloneDesc.Establish(compType,
clone.ElementComponent<char>(at, comp.offset()), comp.rank(), clone_.ElementComponent<char>(subscripts_, component_->offset()),
extents); component_->rank(), extents);
stat = InitializeClone( Advance();
cloneDesc, origDesc, compType, terminator, hasStat, errMsg); if (int status{workQueue.BeginInitializeClone(
if (stat != StatOk) { cloneDesc, origDesc, compType, hasStat_, errMsg_)};
break; status != StatOk) {
return status;
}
} else {
SkipToNextComponent();
}
} else {
SkipToNextComponent();
} }
} }
return StatOk;
}
// Fortran 2018 subclause 7.5.6.2
RT_API_ATTRS void Finalize(const Descriptor &descriptor,
const typeInfo::DerivedType &derived, Terminator *terminator) {
if (!derived.noFinalizationNeeded() && descriptor.IsAllocated()) {
Terminator stubTerminator{"Finalize() in Fortran runtime", 0};
WorkQueue workQueue{terminator ? *terminator : stubTerminator};
if (workQueue.BeginFinalize(descriptor, derived) == StatContinue) {
workQueue.Run();
} }
} }
return stat;
} }
static RT_API_ATTRS const typeInfo::SpecialBinding *FindFinal( static RT_API_ATTRS const typeInfo::SpecialBinding *FindFinal(
@ -221,7 +234,7 @@ static RT_API_ATTRS const typeInfo::SpecialBinding *FindFinal(
} }
static RT_API_ATTRS void CallFinalSubroutine(const Descriptor &descriptor, static RT_API_ATTRS void CallFinalSubroutine(const Descriptor &descriptor,
const typeInfo::DerivedType &derived, Terminator *terminator) { const typeInfo::DerivedType &derived, Terminator &terminator) {
if (const auto *special{FindFinal(derived, descriptor.rank())}) { if (const auto *special{FindFinal(derived, descriptor.rank())}) {
if (special->which() == typeInfo::SpecialBinding::Which::ElementalFinal) { if (special->which() == typeInfo::SpecialBinding::Which::ElementalFinal) {
std::size_t elements{descriptor.Elements()}; std::size_t elements{descriptor.Elements()};
@ -258,9 +271,7 @@ static RT_API_ATTRS void CallFinalSubroutine(const Descriptor &descriptor,
copy = descriptor; copy = descriptor;
copy.set_base_addr(nullptr); copy.set_base_addr(nullptr);
copy.raw().attribute = CFI_attribute_allocatable; copy.raw().attribute = CFI_attribute_allocatable;
Terminator stubTerminator{"CallFinalProcedure() in Fortran runtime", 0}; RUNTIME_CHECK(terminator, copy.Allocate(kNoAsyncObject) == CFI_SUCCESS);
RUNTIME_CHECK(terminator ? *terminator : stubTerminator,
copy.Allocate(kNoAsyncObject) == CFI_SUCCESS);
ShallowCopyDiscontiguousToContiguous(copy, descriptor); ShallowCopyDiscontiguousToContiguous(copy, descriptor);
argDescriptor = &copy; argDescriptor = &copy;
} }
@ -284,87 +295,94 @@ static RT_API_ATTRS void CallFinalSubroutine(const Descriptor &descriptor,
} }
} }
// Fortran 2018 subclause 7.5.6.2 RT_API_ATTRS int FinalizeTicket::Begin(WorkQueue &workQueue) {
RT_API_ATTRS void Finalize(const Descriptor &descriptor, CallFinalSubroutine(instance_, derived_, workQueue.terminator());
const typeInfo::DerivedType &derived, Terminator *terminator) {
if (derived.noFinalizationNeeded() || !descriptor.IsAllocated()) {
return;
}
CallFinalSubroutine(descriptor, derived, terminator);
const auto *parentType{derived.GetParentType()};
bool recurse{parentType && !parentType->noFinalizationNeeded()};
// If there's a finalizable parent component, handle it last, as required // If there's a finalizable parent component, handle it last, as required
// by the Fortran standard (7.5.6.2), and do so recursively with the same // by the Fortran standard (7.5.6.2), and do so recursively with the same
// descriptor so that the rank is preserved. // descriptor so that the rank is preserved.
const Descriptor &componentDesc{derived.component()}; finalizableParentType_ = derived_.GetParentType();
std::size_t myComponents{componentDesc.Elements()}; if (finalizableParentType_) {
std::size_t elements{descriptor.Elements()}; if (finalizableParentType_->noFinalizationNeeded()) {
for (auto k{recurse ? std::size_t{1} finalizableParentType_ = nullptr;
/* skip first component, it's the parent */ } else {
: 0}; SkipToNextComponent();
k < myComponents; ++k) { }
const auto &comp{ }
*componentDesc.ZeroBasedIndexedElement<typeInfo::Component>(k)}; return StatContinue;
SubscriptValue at[maxRank]; }
descriptor.GetLowerBounds(at);
if (comp.genre() == typeInfo::Component::Genre::Allocatable && RT_API_ATTRS int FinalizeTicket::Continue(WorkQueue &workQueue) {
comp.category() == TypeCategory::Derived) { while (!IsComplete()) {
if (component_->genre() == typeInfo::Component::Genre::Allocatable &&
component_->category() == TypeCategory::Derived) {
// Component may be polymorphic or unlimited polymorphic. Need to use the // Component may be polymorphic or unlimited polymorphic. Need to use the
// dynamic type to check whether finalization is needed. // dynamic type to check whether finalization is needed.
for (std::size_t j{0}; j++ < elements; const Descriptor &compDesc{*instance_.ElementComponent<Descriptor>(
descriptor.IncrementSubscripts(at)) { subscripts_, component_->offset())};
const Descriptor &compDesc{ Advance();
*descriptor.ElementComponent<Descriptor>(at, comp.offset())};
if (compDesc.IsAllocated()) { if (compDesc.IsAllocated()) {
if (const DescriptorAddendum *addendum{compDesc.Addendum()}) { if (const DescriptorAddendum *addendum{compDesc.Addendum()}) {
if (const typeInfo::DerivedType * if (const typeInfo::DerivedType *compDynamicType{
compDynamicType{addendum->derivedType()}) { addendum->derivedType()}) {
if (!compDynamicType->noFinalizationNeeded()) { if (!compDynamicType->noFinalizationNeeded()) {
Finalize(compDesc, *compDynamicType, terminator); if (int status{
workQueue.BeginFinalize(compDesc, *compDynamicType)};
status != StatOk) {
return status;
} }
} }
} }
} }
} }
} else if (comp.genre() == typeInfo::Component::Genre::Allocatable || } else if (component_->genre() == typeInfo::Component::Genre::Allocatable ||
comp.genre() == typeInfo::Component::Genre::Automatic) { component_->genre() == typeInfo::Component::Genre::Automatic) {
if (const typeInfo::DerivedType * compType{comp.derivedType()}) { if (const typeInfo::DerivedType *compType{component_->derivedType()};
if (!compType->noFinalizationNeeded()) { compType && !compType->noFinalizationNeeded()) {
for (std::size_t j{0}; j++ < elements; const Descriptor &compDesc{*instance_.ElementComponent<Descriptor>(
descriptor.IncrementSubscripts(at)) { subscripts_, component_->offset())};
const Descriptor &compDesc{ Advance();
*descriptor.ElementComponent<Descriptor>(at, comp.offset())};
if (compDesc.IsAllocated()) { if (compDesc.IsAllocated()) {
Finalize(compDesc, *compType, terminator); if (int status{workQueue.BeginFinalize(compDesc, *compType)};
status != StatOk) {
return status;
} }
} }
} else {
SkipToNextComponent();
} }
} } else if (component_->genre() == typeInfo::Component::Genre::Data &&
} else if (comp.genre() == typeInfo::Component::Genre::Data && component_->derivedType() &&
comp.derivedType() && !comp.derivedType()->noFinalizationNeeded()) { !component_->derivedType()->noFinalizationNeeded()) {
SubscriptValue extents[maxRank]; SubscriptValue extents[maxRank];
GetComponentExtents(extents, comp, descriptor); GetComponentExtents(extents, *component_, instance_);
StaticDescriptor<maxRank, true, 0> staticDescriptor; Descriptor &compDesc{componentDescriptor_.descriptor()};
Descriptor &compDesc{staticDescriptor.descriptor()}; const typeInfo::DerivedType &compType{*component_->derivedType()};
const typeInfo::DerivedType &compType{*comp.derivedType()};
for (std::size_t j{0}; j++ < elements;
descriptor.IncrementSubscripts(at)) {
compDesc.Establish(compType, compDesc.Establish(compType,
descriptor.ElementComponent<char>(at, comp.offset()), comp.rank(), instance_.ElementComponent<char>(subscripts_, component_->offset()),
extents); component_->rank(), extents);
Finalize(compDesc, compType, terminator); Advance();
if (int status{workQueue.BeginFinalize(compDesc, compType)};
status != StatOk) {
return status;
}
} else {
SkipToNextComponent();
} }
} }
} // Last, do the parent component, if any and finalizable.
if (recurse) { if (finalizableParentType_) {
StaticDescriptor<maxRank, true, 8 /*?*/> statDesc; Descriptor &tmpDesc{componentDescriptor_.descriptor()};
Descriptor &tmpDesc{statDesc.descriptor()}; tmpDesc = instance_;
tmpDesc = descriptor;
tmpDesc.raw().attribute = CFI_attribute_pointer; tmpDesc.raw().attribute = CFI_attribute_pointer;
tmpDesc.Addendum()->set_derivedType(parentType); tmpDesc.Addendum()->set_derivedType(finalizableParentType_);
tmpDesc.raw().elem_len = parentType->sizeInBytes(); tmpDesc.raw().elem_len = finalizableParentType_->sizeInBytes();
Finalize(tmpDesc, *parentType, terminator); const auto &parentType{*finalizableParentType_};
finalizableParentType_ = nullptr;
// Don't return StatOk here if the nested FInalize is still running;
// it needs this->componentDescriptor_.
return workQueue.BeginFinalize(tmpDesc, parentType);
} }
return StatOk;
} }
// The order of finalization follows Fortran 2018 7.5.6.2, with // The order of finalization follows Fortran 2018 7.5.6.2, with
@ -373,52 +391,72 @@ RT_API_ATTRS void Finalize(const Descriptor &descriptor,
// preceding any deallocation. // preceding any deallocation.
RT_API_ATTRS void Destroy(const Descriptor &descriptor, bool finalize, RT_API_ATTRS void Destroy(const Descriptor &descriptor, bool finalize,
const typeInfo::DerivedType &derived, Terminator *terminator) { const typeInfo::DerivedType &derived, Terminator *terminator) {
if (derived.noDestructionNeeded() || !descriptor.IsAllocated()) { if (descriptor.IsAllocated() && !derived.noDestructionNeeded()) {
return; Terminator stubTerminator{"Destroy() in Fortran runtime", 0};
WorkQueue workQueue{terminator ? *terminator : stubTerminator};
if (workQueue.BeginDestroy(descriptor, derived, finalize) == StatContinue) {
workQueue.Run();
} }
if (finalize && !derived.noFinalizationNeeded()) {
Finalize(descriptor, derived, terminator);
} }
}
RT_API_ATTRS int DestroyTicket::Begin(WorkQueue &workQueue) {
if (finalize_ && !derived_.noFinalizationNeeded()) {
if (int status{workQueue.BeginFinalize(instance_, derived_)};
status != StatOk && status != StatContinue) {
return status;
}
}
return StatContinue;
}
RT_API_ATTRS int DestroyTicket::Continue(WorkQueue &workQueue) {
// Deallocate all direct and indirect allocatable and automatic components. // Deallocate all direct and indirect allocatable and automatic components.
// Contrary to finalization, the order of deallocation does not matter. // Contrary to finalization, the order of deallocation does not matter.
const Descriptor &componentDesc{derived.component()}; while (!IsComplete()) {
std::size_t myComponents{componentDesc.Elements()}; const auto *componentDerived{component_->derivedType()};
std::size_t elements{descriptor.Elements()}; if (component_->genre() == typeInfo::Component::Genre::Allocatable ||
SubscriptValue at[maxRank]; component_->genre() == typeInfo::Component::Genre::Automatic) {
descriptor.GetLowerBounds(at); Descriptor *d{instance_.ElementComponent<Descriptor>(
for (std::size_t k{0}; k < myComponents; ++k) { subscripts_, component_->offset())};
const auto &comp{ if (d->IsAllocated()) {
*componentDesc.ZeroBasedIndexedElement<typeInfo::Component>(k)}; if (phase_ == 0) {
const bool destroyComp{ ++phase_;
comp.derivedType() && !comp.derivedType()->noDestructionNeeded()}; if (componentDerived && !componentDerived->noDestructionNeeded()) {
if (comp.genre() == typeInfo::Component::Genre::Allocatable || if (int status{workQueue.BeginDestroy(
comp.genre() == typeInfo::Component::Genre::Automatic) { *d, *componentDerived, /*finalize=*/false)};
for (std::size_t j{0}; j < elements; ++j) { status != StatOk) {
Descriptor *d{ return status;
descriptor.ElementComponent<Descriptor>(at, comp.offset())}; }
if (destroyComp) { }
Destroy(*d, /*finalize=*/false, *comp.derivedType(), terminator);
} }
d->Deallocate(); d->Deallocate();
descriptor.IncrementSubscripts(at);
} }
} else if (destroyComp && Advance();
comp.genre() == typeInfo::Component::Genre::Data) { } else if (component_->genre() == typeInfo::Component::Genre::Data) {
if (!componentDerived || componentDerived->noDestructionNeeded()) {
SkipToNextComponent();
} else {
SubscriptValue extents[maxRank]; SubscriptValue extents[maxRank];
GetComponentExtents(extents, comp, descriptor); GetComponentExtents(extents, *component_, instance_);
StaticDescriptor<maxRank, true, 0> staticDescriptor; Descriptor &compDesc{componentDescriptor_.descriptor()};
Descriptor &compDesc{staticDescriptor.descriptor()}; const typeInfo::DerivedType &compType{*componentDerived};
const typeInfo::DerivedType &compType{*comp.derivedType()};
for (std::size_t j{0}; j++ < elements;
descriptor.IncrementSubscripts(at)) {
compDesc.Establish(compType, compDesc.Establish(compType,
descriptor.ElementComponent<char>(at, comp.offset()), comp.rank(), instance_.ElementComponent<char>(subscripts_, component_->offset()),
extents); component_->rank(), extents);
Destroy(compDesc, /*finalize=*/false, *comp.derivedType(), terminator); Advance();
if (int status{workQueue.BeginDestroy(
compDesc, *componentDerived, /*finalize=*/false)};
status != StatOk) {
return status;
} }
} }
} else {
SkipToNextComponent();
} }
} }
return StatOk;
}
RT_API_ATTRS bool HasDynamicComponent(const Descriptor &descriptor) { RT_API_ATTRS bool HasDynamicComponent(const Descriptor &descriptor) {
if (const DescriptorAddendum * addendum{descriptor.Addendum()}) { if (const DescriptorAddendum * addendum{descriptor.Addendum()}) {

View File

@ -7,15 +7,44 @@
//===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===//
#include "descriptor-io.h" #include "descriptor-io.h"
#include "edit-input.h"
#include "edit-output.h"
#include "unit.h"
#include "flang-rt/runtime/descriptor.h"
#include "flang-rt/runtime/io-stmt.h"
#include "flang-rt/runtime/namelist.h"
#include "flang-rt/runtime/terminator.h"
#include "flang-rt/runtime/type-info.h"
#include "flang-rt/runtime/work-queue.h"
#include "flang/Common/optional.h"
#include "flang/Common/restorer.h" #include "flang/Common/restorer.h"
#include "flang/Common/uint128.h"
#include "flang/Runtime/cpp-type.h"
#include "flang/Runtime/freestanding-tools.h" #include "flang/Runtime/freestanding-tools.h"
// Implementation of I/O data list item transfers based on descriptors.
// (All I/O items come through here so that the code is exercised for test;
// some scalar I/O data transfer APIs could be changed to bypass their use
// of descriptors in the future for better efficiency.)
namespace Fortran::runtime::io::descr { namespace Fortran::runtime::io::descr {
RT_OFFLOAD_API_GROUP_BEGIN RT_OFFLOAD_API_GROUP_BEGIN
template <typename A>
inline RT_API_ATTRS A &ExtractElement(IoStatementState &io,
const Descriptor &descriptor, const SubscriptValue subscripts[]) {
A *p{descriptor.Element<A>(subscripts)};
if (!p) {
io.GetIoErrorHandler().Crash("Bad address for I/O item -- null base "
"address or subscripts out of range");
}
return *p;
}
// Defined formatted I/O (maybe) // Defined formatted I/O (maybe)
Fortran::common::optional<bool> DefinedFormattedIo(IoStatementState &io, static RT_API_ATTRS Fortran::common::optional<bool> DefinedFormattedIo(
const Descriptor &descriptor, const typeInfo::DerivedType &derived, IoStatementState &io, const Descriptor &descriptor,
const typeInfo::DerivedType &derived,
const typeInfo::SpecialBinding &special, const typeInfo::SpecialBinding &special,
const SubscriptValue subscripts[]) { const SubscriptValue subscripts[]) {
Fortran::common::optional<DataEdit> peek{ Fortran::common::optional<DataEdit> peek{
@ -65,10 +94,13 @@ Fortran::common::optional<bool> DefinedFormattedIo(IoStatementState &io,
// I/O subroutine reads counts towards READ(SIZE=). // I/O subroutine reads counts towards READ(SIZE=).
startPos = io.InquirePos(); startPos = io.InquirePos();
} }
const auto *bindings{
derived.binding().OffsetElement<const typeInfo::Binding>()};
if (special.IsArgDescriptor(0)) { if (special.IsArgDescriptor(0)) {
// "dtv" argument is "class(t)", pass a descriptor // "dtv" argument is "class(t)", pass a descriptor
auto *p{special.GetProc<void (*)(const Descriptor &, int &, char *, auto *p{special.GetProc<void (*)(const Descriptor &, int &, char *,
const Descriptor &, int &, char *, std::size_t, std::size_t)>()}; const Descriptor &, int &, char *, std::size_t, std::size_t)>(
bindings)};
StaticDescriptor<1, true, 10 /*?*/> elementStatDesc; StaticDescriptor<1, true, 10 /*?*/> elementStatDesc;
Descriptor &elementDesc{elementStatDesc.descriptor()}; Descriptor &elementDesc{elementStatDesc.descriptor()};
elementDesc.Establish( elementDesc.Establish(
@ -79,7 +111,8 @@ Fortran::common::optional<bool> DefinedFormattedIo(IoStatementState &io,
} else { } else {
// "dtv" argument is "type(t)", pass a raw pointer // "dtv" argument is "type(t)", pass a raw pointer
auto *p{special.GetProc<void (*)(const void *, int &, char *, auto *p{special.GetProc<void (*)(const void *, int &, char *,
const Descriptor &, int &, char *, std::size_t, std::size_t)>()}; const Descriptor &, int &, char *, std::size_t, std::size_t)>(
bindings)};
p(descriptor.Element<char>(subscripts), unit, ioType, vListDesc, ioStat, p(descriptor.Element<char>(subscripts), unit, ioType, vListDesc, ioStat,
ioMsg, ioTypeLen, sizeof ioMsg); ioMsg, ioTypeLen, sizeof ioMsg);
} }
@ -104,8 +137,8 @@ Fortran::common::optional<bool> DefinedFormattedIo(IoStatementState &io,
} }
// Defined unformatted I/O // Defined unformatted I/O
bool DefinedUnformattedIo(IoStatementState &io, const Descriptor &descriptor, static RT_API_ATTRS bool DefinedUnformattedIo(IoStatementState &io,
const typeInfo::DerivedType &derived, const Descriptor &descriptor, const typeInfo::DerivedType &derived,
const typeInfo::SpecialBinding &special) { const typeInfo::SpecialBinding &special) {
// Unformatted I/O must have an external unit (or child thereof). // Unformatted I/O must have an external unit (or child thereof).
IoErrorHandler &handler{io.GetIoErrorHandler()}; IoErrorHandler &handler{io.GetIoErrorHandler()};
@ -121,10 +154,12 @@ bool DefinedUnformattedIo(IoStatementState &io, const Descriptor &descriptor,
std::size_t numElements{descriptor.Elements()}; std::size_t numElements{descriptor.Elements()};
SubscriptValue subscripts[maxRank]; SubscriptValue subscripts[maxRank];
descriptor.GetLowerBounds(subscripts); descriptor.GetLowerBounds(subscripts);
const auto *bindings{
derived.binding().OffsetElement<const typeInfo::Binding>()};
if (special.IsArgDescriptor(0)) { if (special.IsArgDescriptor(0)) {
// "dtv" argument is "class(t)", pass a descriptor // "dtv" argument is "class(t)", pass a descriptor
auto *p{special.GetProc<void (*)( auto *p{special.GetProc<void (*)(
const Descriptor &, int &, int &, char *, std::size_t)>()}; const Descriptor &, int &, int &, char *, std::size_t)>(bindings)};
StaticDescriptor<1, true, 10 /*?*/> elementStatDesc; StaticDescriptor<1, true, 10 /*?*/> elementStatDesc;
Descriptor &elementDesc{elementStatDesc.descriptor()}; Descriptor &elementDesc{elementStatDesc.descriptor()};
elementDesc.Establish(derived, nullptr, 0, nullptr, CFI_attribute_pointer); elementDesc.Establish(derived, nullptr, 0, nullptr, CFI_attribute_pointer);
@ -137,8 +172,9 @@ bool DefinedUnformattedIo(IoStatementState &io, const Descriptor &descriptor,
} }
} else { } else {
// "dtv" argument is "type(t)", pass a raw pointer // "dtv" argument is "type(t)", pass a raw pointer
auto *p{special.GetProc<void (*)( auto *p{special
const void *, int &, int &, char *, std::size_t)>()}; .GetProc<void (*)(const void *, int &, int &, char *, std::size_t)>(
bindings)};
for (; numElements-- > 0; descriptor.IncrementSubscripts(subscripts)) { for (; numElements-- > 0; descriptor.IncrementSubscripts(subscripts)) {
p(descriptor.Element<char>(subscripts), unit, ioStat, ioMsg, p(descriptor.Element<char>(subscripts), unit, ioStat, ioMsg,
sizeof ioMsg); sizeof ioMsg);
@ -152,5 +188,619 @@ bool DefinedUnformattedIo(IoStatementState &io, const Descriptor &descriptor,
return handler.GetIoStat() == IostatOk; return handler.GetIoStat() == IostatOk;
} }
// Per-category descriptor-based I/O templates
// TODO (perhaps as a nontrivial but small starter project): implement
// automatic repetition counts, like "10*3.14159", for list-directed and
// NAMELIST array output.
template <int KIND, Direction DIR>
inline RT_API_ATTRS bool FormattedIntegerIO(IoStatementState &io,
const Descriptor &descriptor, [[maybe_unused]] bool isSigned) {
std::size_t numElements{descriptor.Elements()};
SubscriptValue subscripts[maxRank];
descriptor.GetLowerBounds(subscripts);
using IntType = CppTypeFor<common::TypeCategory::Integer, KIND>;
bool anyInput{false};
for (std::size_t j{0}; j < numElements; ++j) {
if (auto edit{io.GetNextDataEdit()}) {
IntType &x{ExtractElement<IntType>(io, descriptor, subscripts)};
if constexpr (DIR == Direction::Output) {
if (!EditIntegerOutput<KIND>(io, *edit, x, isSigned)) {
return false;
}
} else if (edit->descriptor != DataEdit::ListDirectedNullValue) {
if (EditIntegerInput(
io, *edit, reinterpret_cast<void *>(&x), KIND, isSigned)) {
anyInput = true;
} else {
return anyInput && edit->IsNamelist();
}
}
if (!descriptor.IncrementSubscripts(subscripts) && j + 1 < numElements) {
io.GetIoErrorHandler().Crash(
"FormattedIntegerIO: subscripts out of bounds");
}
} else {
return false;
}
}
return true;
}
template <int KIND, Direction DIR>
inline RT_API_ATTRS bool FormattedRealIO(
IoStatementState &io, const Descriptor &descriptor) {
std::size_t numElements{descriptor.Elements()};
SubscriptValue subscripts[maxRank];
descriptor.GetLowerBounds(subscripts);
using RawType = typename RealOutputEditing<KIND>::BinaryFloatingPoint;
bool anyInput{false};
for (std::size_t j{0}; j < numElements; ++j) {
if (auto edit{io.GetNextDataEdit()}) {
RawType &x{ExtractElement<RawType>(io, descriptor, subscripts)};
if constexpr (DIR == Direction::Output) {
if (!RealOutputEditing<KIND>{io, x}.Edit(*edit)) {
return false;
}
} else if (edit->descriptor != DataEdit::ListDirectedNullValue) {
if (EditRealInput<KIND>(io, *edit, reinterpret_cast<void *>(&x))) {
anyInput = true;
} else {
return anyInput && edit->IsNamelist();
}
}
if (!descriptor.IncrementSubscripts(subscripts) && j + 1 < numElements) {
io.GetIoErrorHandler().Crash(
"FormattedRealIO: subscripts out of bounds");
}
} else {
return false;
}
}
return true;
}
template <int KIND, Direction DIR>
inline RT_API_ATTRS bool FormattedComplexIO(
IoStatementState &io, const Descriptor &descriptor) {
std::size_t numElements{descriptor.Elements()};
SubscriptValue subscripts[maxRank];
descriptor.GetLowerBounds(subscripts);
bool isListOutput{
io.get_if<ListDirectedStatementState<Direction::Output>>() != nullptr};
using RawType = typename RealOutputEditing<KIND>::BinaryFloatingPoint;
bool anyInput{false};
for (std::size_t j{0}; j < numElements; ++j) {
RawType *x{&ExtractElement<RawType>(io, descriptor, subscripts)};
if (isListOutput) {
DataEdit rEdit, iEdit;
rEdit.descriptor = DataEdit::ListDirectedRealPart;
iEdit.descriptor = DataEdit::ListDirectedImaginaryPart;
rEdit.modes = iEdit.modes = io.mutableModes();
if (!RealOutputEditing<KIND>{io, x[0]}.Edit(rEdit) ||
!RealOutputEditing<KIND>{io, x[1]}.Edit(iEdit)) {
return false;
}
} else {
for (int k{0}; k < 2; ++k, ++x) {
auto edit{io.GetNextDataEdit()};
if (!edit) {
return false;
} else if constexpr (DIR == Direction::Output) {
if (!RealOutputEditing<KIND>{io, *x}.Edit(*edit)) {
return false;
}
} else if (edit->descriptor == DataEdit::ListDirectedNullValue) {
break;
} else if (EditRealInput<KIND>(
io, *edit, reinterpret_cast<void *>(x))) {
anyInput = true;
} else {
return anyInput && edit->IsNamelist();
}
}
}
if (!descriptor.IncrementSubscripts(subscripts) && j + 1 < numElements) {
io.GetIoErrorHandler().Crash(
"FormattedComplexIO: subscripts out of bounds");
}
}
return true;
}
template <typename A, Direction DIR>
inline RT_API_ATTRS bool FormattedCharacterIO(
IoStatementState &io, const Descriptor &descriptor) {
std::size_t numElements{descriptor.Elements()};
SubscriptValue subscripts[maxRank];
descriptor.GetLowerBounds(subscripts);
std::size_t length{descriptor.ElementBytes() / sizeof(A)};
auto *listOutput{io.get_if<ListDirectedStatementState<Direction::Output>>()};
bool anyInput{false};
for (std::size_t j{0}; j < numElements; ++j) {
A *x{&ExtractElement<A>(io, descriptor, subscripts)};
if (listOutput) {
if (!ListDirectedCharacterOutput(io, *listOutput, x, length)) {
return false;
}
} else if (auto edit{io.GetNextDataEdit()}) {
if constexpr (DIR == Direction::Output) {
if (!EditCharacterOutput(io, *edit, x, length)) {
return false;
}
} else { // input
if (edit->descriptor != DataEdit::ListDirectedNullValue) {
if (EditCharacterInput(io, *edit, x, length)) {
anyInput = true;
} else {
return anyInput && edit->IsNamelist();
}
}
}
} else {
return false;
}
if (!descriptor.IncrementSubscripts(subscripts) && j + 1 < numElements) {
io.GetIoErrorHandler().Crash(
"FormattedCharacterIO: subscripts out of bounds");
}
}
return true;
}
template <int KIND, Direction DIR>
inline RT_API_ATTRS bool FormattedLogicalIO(
IoStatementState &io, const Descriptor &descriptor) {
std::size_t numElements{descriptor.Elements()};
SubscriptValue subscripts[maxRank];
descriptor.GetLowerBounds(subscripts);
auto *listOutput{io.get_if<ListDirectedStatementState<Direction::Output>>()};
using IntType = CppTypeFor<TypeCategory::Integer, KIND>;
bool anyInput{false};
for (std::size_t j{0}; j < numElements; ++j) {
IntType &x{ExtractElement<IntType>(io, descriptor, subscripts)};
if (listOutput) {
if (!ListDirectedLogicalOutput(io, *listOutput, x != 0)) {
return false;
}
} else if (auto edit{io.GetNextDataEdit()}) {
if constexpr (DIR == Direction::Output) {
if (!EditLogicalOutput(io, *edit, x != 0)) {
return false;
}
} else {
if (edit->descriptor != DataEdit::ListDirectedNullValue) {
bool truth{};
if (EditLogicalInput(io, *edit, truth)) {
x = truth;
anyInput = true;
} else {
return anyInput && edit->IsNamelist();
}
}
}
} else {
return false;
}
if (!descriptor.IncrementSubscripts(subscripts) && j + 1 < numElements) {
io.GetIoErrorHandler().Crash(
"FormattedLogicalIO: subscripts out of bounds");
}
}
return true;
}
template <Direction DIR>
RT_API_ATTRS int DerivedIoTicket<DIR>::Continue(WorkQueue &workQueue) {
while (!IsComplete()) {
if (component_->genre() == typeInfo::Component::Genre::Data) {
// Create a descriptor for the component
Descriptor &compDesc{componentDescriptor_.descriptor()};
component_->CreatePointerDescriptor(
compDesc, instance_, io_.GetIoErrorHandler(), subscripts_);
Advance();
if (int status{workQueue.BeginDescriptorIo<DIR>(
io_, compDesc, table_, anyIoTookPlace_)};
status != StatOk) {
return status;
}
} else {
// Component is itself a descriptor
char *pointer{
instance_.Element<char>(subscripts_) + component_->offset()};
const Descriptor &compDesc{
*reinterpret_cast<const Descriptor *>(pointer)};
Advance();
if (compDesc.IsAllocated()) {
if (int status{workQueue.BeginDescriptorIo<DIR>(
io_, compDesc, table_, anyIoTookPlace_)};
status != StatOk) {
return status;
}
}
}
}
return StatOk;
}
template RT_API_ATTRS int DerivedIoTicket<Direction::Output>::Continue(
WorkQueue &);
template RT_API_ATTRS int DerivedIoTicket<Direction::Input>::Continue(
WorkQueue &);
template <Direction DIR>
RT_API_ATTRS int DescriptorIoTicket<DIR>::Begin(WorkQueue &workQueue) {
IoErrorHandler &handler{io_.GetIoErrorHandler()};
if (handler.InError()) {
return handler.GetIoStat();
}
if (!io_.get_if<IoDirectionState<DIR>>()) {
handler.Crash("DescriptorIO() called for wrong I/O direction");
return handler.GetIoStat();
}
if constexpr (DIR == Direction::Input) {
if (!io_.BeginReadingRecord()) {
return StatOk;
}
}
if (!io_.get_if<FormattedIoStatementState<DIR>>()) {
// Unformatted I/O
IoErrorHandler &handler{io_.GetIoErrorHandler()};
const DescriptorAddendum *addendum{instance_.Addendum()};
if (const typeInfo::DerivedType *type{
addendum ? addendum->derivedType() : nullptr}) {
// derived type unformatted I/O
if (table_) {
if (const auto *definedIo{table_->Find(*type,
DIR == Direction::Input
? common::DefinedIo::ReadUnformatted
: common::DefinedIo::WriteUnformatted)}) {
if (definedIo->subroutine) {
typeInfo::SpecialBinding special{DIR == Direction::Input
? typeInfo::SpecialBinding::Which::ReadUnformatted
: typeInfo::SpecialBinding::Which::WriteUnformatted,
definedIo->subroutine, definedIo->isDtvArgPolymorphic, false,
false};
if (DefinedUnformattedIo(io_, instance_, *type, special)) {
anyIoTookPlace_ = true;
return StatOk;
}
} else {
int status{workQueue.BeginDerivedIo<DIR>(
io_, instance_, *type, table_, anyIoTookPlace_)};
return status == StatContinue ? StatOk : status; // done here
}
}
}
if (const typeInfo::SpecialBinding *special{
type->FindSpecialBinding(DIR == Direction::Input
? typeInfo::SpecialBinding::Which::ReadUnformatted
: typeInfo::SpecialBinding::Which::WriteUnformatted)}) {
if (!table_ || !table_->ignoreNonTbpEntries || special->IsTypeBound()) {
// defined derived type unformatted I/O
if (DefinedUnformattedIo(io_, instance_, *type, *special)) {
anyIoTookPlace_ = true;
return StatOk;
} else {
return IostatEnd;
}
}
}
// Default derived type unformatted I/O
// TODO: If no component at any level has defined READ or WRITE
// (as appropriate), the elements are contiguous, and no byte swapping
// is active, do a block transfer via the code below.
int status{workQueue.BeginDerivedIo<DIR>(
io_, instance_, *type, table_, anyIoTookPlace_)};
return status == StatContinue ? StatOk : status; // done here
} else {
// intrinsic type unformatted I/O
auto *externalUnf{io_.get_if<ExternalUnformattedIoStatementState<DIR>>()};
ChildUnformattedIoStatementState<DIR> *childUnf{nullptr};
InquireIOLengthState *inq{nullptr};
bool swapEndianness{false};
if (externalUnf) {
swapEndianness = externalUnf->unit().swapEndianness();
} else {
childUnf = io_.get_if<ChildUnformattedIoStatementState<DIR>>();
if (!childUnf) {
inq = DIR == Direction::Output ? io_.get_if<InquireIOLengthState>()
: nullptr;
RUNTIME_CHECK(handler, inq != nullptr);
}
}
std::size_t elementBytes{instance_.ElementBytes()};
std::size_t swappingBytes{elementBytes};
if (auto maybeCatAndKind{instance_.type().GetCategoryAndKind()}) {
// Byte swapping units can be smaller than elements, namely
// for COMPLEX and CHARACTER.
if (maybeCatAndKind->first == TypeCategory::Character) {
// swap each character position independently
swappingBytes = maybeCatAndKind->second; // kind
} else if (maybeCatAndKind->first == TypeCategory::Complex) {
// swap real and imaginary components independently
swappingBytes /= 2;
}
}
using CharType =
std::conditional_t<DIR == Direction::Output, const char, char>;
auto Transfer{[=](CharType &x, std::size_t totalBytes) -> bool {
if constexpr (DIR == Direction::Output) {
return externalUnf ? externalUnf->Emit(&x, totalBytes, swappingBytes)
: childUnf ? childUnf->Emit(&x, totalBytes, swappingBytes)
: inq->Emit(&x, totalBytes, swappingBytes);
} else {
return externalUnf
? externalUnf->Receive(&x, totalBytes, swappingBytes)
: childUnf->Receive(&x, totalBytes, swappingBytes);
}
}};
if (!swapEndianness &&
instance_.IsContiguous()) { // contiguous unformatted I/O
char &x{ExtractElement<char>(io_, instance_, subscripts_)};
if (Transfer(x, elements_ * elementBytes)) {
anyIoTookPlace_ = true;
} else {
return IostatEnd;
}
} else { // non-contiguous or byte-swapped intrinsic type unformatted I/O
for (; !IsComplete(); Advance()) {
char &x{ExtractElement<char>(io_, instance_, subscripts_)};
if (Transfer(x, elementBytes)) {
anyIoTookPlace_ = true;
} else {
return IostatEnd;
}
}
}
}
// Unformatted I/O never needs to call Continue().
return StatOk;
}
// Formatted I/O
if (auto catAndKind{instance_.type().GetCategoryAndKind()}) {
TypeCategory cat{catAndKind->first};
int kind{catAndKind->second};
bool any{false};
switch (cat) {
case TypeCategory::Integer:
switch (kind) {
case 1:
any = FormattedIntegerIO<1, DIR>(io_, instance_, true);
break;
case 2:
any = FormattedIntegerIO<2, DIR>(io_, instance_, true);
break;
case 4:
any = FormattedIntegerIO<4, DIR>(io_, instance_, true);
break;
case 8:
any = FormattedIntegerIO<8, DIR>(io_, instance_, true);
break;
case 16:
any = FormattedIntegerIO<16, DIR>(io_, instance_, true);
break;
default:
handler.Crash(
"not yet implemented: INTEGER(KIND=%d) in formatted IO", kind);
return IostatEnd;
}
break;
case TypeCategory::Unsigned:
switch (kind) {
case 1:
any = FormattedIntegerIO<1, DIR>(io_, instance_, false);
break;
case 2:
any = FormattedIntegerIO<2, DIR>(io_, instance_, false);
break;
case 4:
any = FormattedIntegerIO<4, DIR>(io_, instance_, false);
break;
case 8:
any = FormattedIntegerIO<8, DIR>(io_, instance_, false);
break;
case 16:
any = FormattedIntegerIO<16, DIR>(io_, instance_, false);
break;
default:
handler.Crash(
"not yet implemented: UNSIGNED(KIND=%d) in formatted IO", kind);
return IostatEnd;
}
break;
case TypeCategory::Real:
switch (kind) {
case 2:
any = FormattedRealIO<2, DIR>(io_, instance_);
break;
case 3:
any = FormattedRealIO<3, DIR>(io_, instance_);
break;
case 4:
any = FormattedRealIO<4, DIR>(io_, instance_);
break;
case 8:
any = FormattedRealIO<8, DIR>(io_, instance_);
break;
case 10:
any = FormattedRealIO<10, DIR>(io_, instance_);
break;
// TODO: case double/double
case 16:
any = FormattedRealIO<16, DIR>(io_, instance_);
break;
default:
handler.Crash(
"not yet implemented: REAL(KIND=%d) in formatted IO", kind);
return IostatEnd;
}
break;
case TypeCategory::Complex:
switch (kind) {
case 2:
any = FormattedComplexIO<2, DIR>(io_, instance_);
break;
case 3:
any = FormattedComplexIO<3, DIR>(io_, instance_);
break;
case 4:
any = FormattedComplexIO<4, DIR>(io_, instance_);
break;
case 8:
any = FormattedComplexIO<8, DIR>(io_, instance_);
break;
case 10:
any = FormattedComplexIO<10, DIR>(io_, instance_);
break;
// TODO: case double/double
case 16:
any = FormattedComplexIO<16, DIR>(io_, instance_);
break;
default:
handler.Crash(
"not yet implemented: COMPLEX(KIND=%d) in formatted IO", kind);
return IostatEnd;
}
break;
case TypeCategory::Character:
switch (kind) {
case 1:
any = FormattedCharacterIO<char, DIR>(io_, instance_);
break;
case 2:
any = FormattedCharacterIO<char16_t, DIR>(io_, instance_);
break;
case 4:
any = FormattedCharacterIO<char32_t, DIR>(io_, instance_);
break;
default:
handler.Crash(
"not yet implemented: CHARACTER(KIND=%d) in formatted IO", kind);
return IostatEnd;
}
break;
case TypeCategory::Logical:
switch (kind) {
case 1:
any = FormattedLogicalIO<1, DIR>(io_, instance_);
break;
case 2:
any = FormattedLogicalIO<2, DIR>(io_, instance_);
break;
case 4:
any = FormattedLogicalIO<4, DIR>(io_, instance_);
break;
case 8:
any = FormattedLogicalIO<8, DIR>(io_, instance_);
break;
default:
handler.Crash(
"not yet implemented: LOGICAL(KIND=%d) in formatted IO", kind);
return IostatEnd;
}
break;
case TypeCategory::Derived: {
// Derived type information must be present for formatted I/O.
IoErrorHandler &handler{io_.GetIoErrorHandler()};
const DescriptorAddendum *addendum{instance_.Addendum()};
RUNTIME_CHECK(handler, addendum != nullptr);
derived_ = addendum->derivedType();
RUNTIME_CHECK(handler, derived_ != nullptr);
if (table_) {
if (const auto *definedIo{table_->Find(*derived_,
DIR == Direction::Input ? common::DefinedIo::ReadFormatted
: common::DefinedIo::WriteFormatted)}) {
if (definedIo->subroutine) {
nonTbpSpecial_.emplace(DIR == Direction::Input
? typeInfo::SpecialBinding::Which::ReadFormatted
: typeInfo::SpecialBinding::Which::WriteFormatted,
definedIo->subroutine, definedIo->isDtvArgPolymorphic, false,
false);
special_ = &*nonTbpSpecial_;
}
}
}
if (!special_) {
if (const typeInfo::SpecialBinding *binding{
derived_->FindSpecialBinding(DIR == Direction::Input
? typeInfo::SpecialBinding::Which::ReadFormatted
: typeInfo::SpecialBinding::Which::WriteFormatted)}) {
if (!table_ || !table_->ignoreNonTbpEntries ||
binding->IsTypeBound()) {
special_ = binding;
}
}
}
return StatContinue;
}
}
if (any) {
anyIoTookPlace_ = true;
} else {
return IostatEnd;
}
} else {
handler.Crash("DescriptorIO: bad type code (%d) in descriptor",
static_cast<int>(instance_.type().raw()));
return handler.GetIoStat();
}
return StatOk;
}
template RT_API_ATTRS int DescriptorIoTicket<Direction::Output>::Begin(
WorkQueue &);
template RT_API_ATTRS int DescriptorIoTicket<Direction::Input>::Begin(
WorkQueue &);
template <Direction DIR>
RT_API_ATTRS int DescriptorIoTicket<DIR>::Continue(WorkQueue &workQueue) {
// Only derived type formatted I/O gets here.
while (!IsComplete()) {
if (special_) {
if (auto defined{DefinedFormattedIo(
io_, instance_, *derived_, *special_, subscripts_)}) {
anyIoTookPlace_ |= *defined;
Advance();
continue;
}
}
Descriptor &elementDesc{elementDescriptor_.descriptor()};
elementDesc.Establish(
*derived_, nullptr, 0, nullptr, CFI_attribute_pointer);
elementDesc.set_base_addr(instance_.Element<char>(subscripts_));
Advance();
if (int status{workQueue.BeginDerivedIo<DIR>(
io_, elementDesc, *derived_, table_, anyIoTookPlace_)};
status != StatOk) {
return status;
}
}
return StatOk;
}
template RT_API_ATTRS int DescriptorIoTicket<Direction::Output>::Continue(
WorkQueue &);
template RT_API_ATTRS int DescriptorIoTicket<Direction::Input>::Continue(
WorkQueue &);
template <Direction DIR>
RT_API_ATTRS bool DescriptorIO(IoStatementState &io,
const Descriptor &descriptor, const NonTbpDefinedIoTable *table) {
bool anyIoTookPlace{false};
WorkQueue workQueue{io.GetIoErrorHandler()};
if (workQueue.BeginDescriptorIo<DIR>(io, descriptor, table, anyIoTookPlace) ==
StatContinue) {
workQueue.Run();
}
return anyIoTookPlace;
}
template RT_API_ATTRS bool DescriptorIO<Direction::Output>(
IoStatementState &, const Descriptor &, const NonTbpDefinedIoTable *);
template RT_API_ATTRS bool DescriptorIO<Direction::Input>(
IoStatementState &, const Descriptor &, const NonTbpDefinedIoTable *);
RT_OFFLOAD_API_GROUP_END RT_OFFLOAD_API_GROUP_END
} // namespace Fortran::runtime::io::descr } // namespace Fortran::runtime::io::descr

View File

@ -9,619 +9,27 @@
#ifndef FLANG_RT_RUNTIME_DESCRIPTOR_IO_H_ #ifndef FLANG_RT_RUNTIME_DESCRIPTOR_IO_H_
#define FLANG_RT_RUNTIME_DESCRIPTOR_IO_H_ #define FLANG_RT_RUNTIME_DESCRIPTOR_IO_H_
// Implementation of I/O data list item transfers based on descriptors. #include "flang-rt/runtime/connection.h"
// (All I/O items come through here so that the code is exercised for test;
// some scalar I/O data transfer APIs could be changed to bypass their use
// of descriptors in the future for better efficiency.)
#include "edit-input.h" namespace Fortran::runtime {
#include "edit-output.h" class Descriptor;
#include "unit.h" } // namespace Fortran::runtime
#include "flang-rt/runtime/descriptor.h"
#include "flang-rt/runtime/io-stmt.h" namespace Fortran::runtime::io {
#include "flang-rt/runtime/namelist.h" class IoStatementState;
#include "flang-rt/runtime/terminator.h" struct NonTbpDefinedIoTable;
#include "flang-rt/runtime/type-info.h" } // namespace Fortran::runtime::io
#include "flang/Common/optional.h"
#include "flang/Common/uint128.h"
#include "flang/Runtime/cpp-type.h"
namespace Fortran::runtime::io::descr { namespace Fortran::runtime::io::descr {
template <typename A>
inline RT_API_ATTRS A &ExtractElement(IoStatementState &io,
const Descriptor &descriptor, const SubscriptValue subscripts[]) {
A *p{descriptor.Element<A>(subscripts)};
if (!p) {
io.GetIoErrorHandler().Crash("Bad address for I/O item -- null base "
"address or subscripts out of range");
}
return *p;
}
// Per-category descriptor-based I/O templates
// TODO (perhaps as a nontrivial but small starter project): implement
// automatic repetition counts, like "10*3.14159", for list-directed and
// NAMELIST array output.
template <int KIND, Direction DIR>
inline RT_API_ATTRS bool FormattedIntegerIO(IoStatementState &io,
const Descriptor &descriptor, [[maybe_unused]] bool isSigned) {
std::size_t numElements{descriptor.Elements()};
SubscriptValue subscripts[maxRank];
descriptor.GetLowerBounds(subscripts);
using IntType = CppTypeFor<common::TypeCategory::Integer, KIND>;
bool anyInput{false};
for (std::size_t j{0}; j < numElements; ++j) {
if (auto edit{io.GetNextDataEdit()}) {
IntType &x{ExtractElement<IntType>(io, descriptor, subscripts)};
if constexpr (DIR == Direction::Output) {
if (!EditIntegerOutput<KIND>(io, *edit, x, isSigned)) {
return false;
}
} else if (edit->descriptor != DataEdit::ListDirectedNullValue) {
if (EditIntegerInput(
io, *edit, reinterpret_cast<void *>(&x), KIND, isSigned)) {
anyInput = true;
} else {
return anyInput && edit->IsNamelist();
}
}
if (!descriptor.IncrementSubscripts(subscripts) && j + 1 < numElements) {
io.GetIoErrorHandler().Crash(
"FormattedIntegerIO: subscripts out of bounds");
}
} else {
return false;
}
}
return true;
}
template <int KIND, Direction DIR>
inline RT_API_ATTRS bool FormattedRealIO(
IoStatementState &io, const Descriptor &descriptor) {
std::size_t numElements{descriptor.Elements()};
SubscriptValue subscripts[maxRank];
descriptor.GetLowerBounds(subscripts);
using RawType = typename RealOutputEditing<KIND>::BinaryFloatingPoint;
bool anyInput{false};
for (std::size_t j{0}; j < numElements; ++j) {
if (auto edit{io.GetNextDataEdit()}) {
RawType &x{ExtractElement<RawType>(io, descriptor, subscripts)};
if constexpr (DIR == Direction::Output) {
if (!RealOutputEditing<KIND>{io, x}.Edit(*edit)) {
return false;
}
} else if (edit->descriptor != DataEdit::ListDirectedNullValue) {
if (EditRealInput<KIND>(io, *edit, reinterpret_cast<void *>(&x))) {
anyInput = true;
} else {
return anyInput && edit->IsNamelist();
}
}
if (!descriptor.IncrementSubscripts(subscripts) && j + 1 < numElements) {
io.GetIoErrorHandler().Crash(
"FormattedRealIO: subscripts out of bounds");
}
} else {
return false;
}
}
return true;
}
template <int KIND, Direction DIR>
inline RT_API_ATTRS bool FormattedComplexIO(
IoStatementState &io, const Descriptor &descriptor) {
std::size_t numElements{descriptor.Elements()};
SubscriptValue subscripts[maxRank];
descriptor.GetLowerBounds(subscripts);
bool isListOutput{
io.get_if<ListDirectedStatementState<Direction::Output>>() != nullptr};
using RawType = typename RealOutputEditing<KIND>::BinaryFloatingPoint;
bool anyInput{false};
for (std::size_t j{0}; j < numElements; ++j) {
RawType *x{&ExtractElement<RawType>(io, descriptor, subscripts)};
if (isListOutput) {
DataEdit rEdit, iEdit;
rEdit.descriptor = DataEdit::ListDirectedRealPart;
iEdit.descriptor = DataEdit::ListDirectedImaginaryPart;
rEdit.modes = iEdit.modes = io.mutableModes();
if (!RealOutputEditing<KIND>{io, x[0]}.Edit(rEdit) ||
!RealOutputEditing<KIND>{io, x[1]}.Edit(iEdit)) {
return false;
}
} else {
for (int k{0}; k < 2; ++k, ++x) {
auto edit{io.GetNextDataEdit()};
if (!edit) {
return false;
} else if constexpr (DIR == Direction::Output) {
if (!RealOutputEditing<KIND>{io, *x}.Edit(*edit)) {
return false;
}
} else if (edit->descriptor == DataEdit::ListDirectedNullValue) {
break;
} else if (EditRealInput<KIND>(
io, *edit, reinterpret_cast<void *>(x))) {
anyInput = true;
} else {
return anyInput && edit->IsNamelist();
}
}
}
if (!descriptor.IncrementSubscripts(subscripts) && j + 1 < numElements) {
io.GetIoErrorHandler().Crash(
"FormattedComplexIO: subscripts out of bounds");
}
}
return true;
}
template <typename A, Direction DIR>
inline RT_API_ATTRS bool FormattedCharacterIO(
IoStatementState &io, const Descriptor &descriptor) {
std::size_t numElements{descriptor.Elements()};
SubscriptValue subscripts[maxRank];
descriptor.GetLowerBounds(subscripts);
std::size_t length{descriptor.ElementBytes() / sizeof(A)};
auto *listOutput{io.get_if<ListDirectedStatementState<Direction::Output>>()};
bool anyInput{false};
for (std::size_t j{0}; j < numElements; ++j) {
A *x{&ExtractElement<A>(io, descriptor, subscripts)};
if (listOutput) {
if (!ListDirectedCharacterOutput(io, *listOutput, x, length)) {
return false;
}
} else if (auto edit{io.GetNextDataEdit()}) {
if constexpr (DIR == Direction::Output) {
if (!EditCharacterOutput(io, *edit, x, length)) {
return false;
}
} else { // input
if (edit->descriptor != DataEdit::ListDirectedNullValue) {
if (EditCharacterInput(io, *edit, x, length)) {
anyInput = true;
} else {
return anyInput && edit->IsNamelist();
}
}
}
} else {
return false;
}
if (!descriptor.IncrementSubscripts(subscripts) && j + 1 < numElements) {
io.GetIoErrorHandler().Crash(
"FormattedCharacterIO: subscripts out of bounds");
}
}
return true;
}
template <int KIND, Direction DIR>
inline RT_API_ATTRS bool FormattedLogicalIO(
IoStatementState &io, const Descriptor &descriptor) {
std::size_t numElements{descriptor.Elements()};
SubscriptValue subscripts[maxRank];
descriptor.GetLowerBounds(subscripts);
auto *listOutput{io.get_if<ListDirectedStatementState<Direction::Output>>()};
using IntType = CppTypeFor<TypeCategory::Integer, KIND>;
bool anyInput{false};
for (std::size_t j{0}; j < numElements; ++j) {
IntType &x{ExtractElement<IntType>(io, descriptor, subscripts)};
if (listOutput) {
if (!ListDirectedLogicalOutput(io, *listOutput, x != 0)) {
return false;
}
} else if (auto edit{io.GetNextDataEdit()}) {
if constexpr (DIR == Direction::Output) {
if (!EditLogicalOutput(io, *edit, x != 0)) {
return false;
}
} else {
if (edit->descriptor != DataEdit::ListDirectedNullValue) {
bool truth{};
if (EditLogicalInput(io, *edit, truth)) {
x = truth;
anyInput = true;
} else {
return anyInput && edit->IsNamelist();
}
}
}
} else {
return false;
}
if (!descriptor.IncrementSubscripts(subscripts) && j + 1 < numElements) {
io.GetIoErrorHandler().Crash(
"FormattedLogicalIO: subscripts out of bounds");
}
}
return true;
}
template <Direction DIR> template <Direction DIR>
static RT_API_ATTRS bool DescriptorIO(IoStatementState &, const Descriptor &, RT_API_ATTRS bool DescriptorIO(IoStatementState &, const Descriptor &,
const NonTbpDefinedIoTable * = nullptr); const NonTbpDefinedIoTable * = nullptr);
// For intrinsic (not defined) derived type I/O, formatted & unformatted extern template RT_API_ATTRS bool DescriptorIO<Direction::Output>(
template <Direction DIR> IoStatementState &, const Descriptor &, const NonTbpDefinedIoTable *);
static RT_API_ATTRS bool DefaultComponentIO(IoStatementState &io, extern template RT_API_ATTRS bool DescriptorIO<Direction::Input>(
const typeInfo::Component &component, const Descriptor &origDescriptor, IoStatementState &, const Descriptor &, const NonTbpDefinedIoTable *);
const SubscriptValue origSubscripts[], Terminator &terminator,
const NonTbpDefinedIoTable *table) {
#if !defined(RT_DEVICE_AVOID_RECURSION)
if (component.genre() == typeInfo::Component::Genre::Data) {
// Create a descriptor for the component
StaticDescriptor<maxRank, true, 16 /*?*/> statDesc;
Descriptor &desc{statDesc.descriptor()};
component.CreatePointerDescriptor(
desc, origDescriptor, terminator, origSubscripts);
return DescriptorIO<DIR>(io, desc, table);
} else {
// Component is itself a descriptor
char *pointer{
origDescriptor.Element<char>(origSubscripts) + component.offset()};
const Descriptor &compDesc{*reinterpret_cast<const Descriptor *>(pointer)};
return compDesc.IsAllocated() && DescriptorIO<DIR>(io, compDesc, table);
}
#else
terminator.Crash("not yet implemented: component IO");
#endif
}
template <Direction DIR>
static RT_API_ATTRS bool DefaultComponentwiseFormattedIO(IoStatementState &io,
const Descriptor &descriptor, const typeInfo::DerivedType &type,
const NonTbpDefinedIoTable *table, const SubscriptValue subscripts[]) {
IoErrorHandler &handler{io.GetIoErrorHandler()};
const Descriptor &compArray{type.component()};
RUNTIME_CHECK(handler, compArray.rank() == 1);
std::size_t numComponents{compArray.Elements()};
SubscriptValue at[maxRank];
compArray.GetLowerBounds(at);
for (std::size_t k{0}; k < numComponents;
++k, compArray.IncrementSubscripts(at)) {
const typeInfo::Component &component{
*compArray.Element<typeInfo::Component>(at)};
if (!DefaultComponentIO<DIR>(
io, component, descriptor, subscripts, handler, table)) {
// Return true for NAMELIST input if any component appeared.
auto *listInput{
io.get_if<ListDirectedStatementState<Direction::Input>>()};
return DIR == Direction::Input && k > 0 && listInput &&
listInput->inNamelistSequence();
}
}
return true;
}
template <Direction DIR>
static RT_API_ATTRS bool DefaultComponentwiseUnformattedIO(IoStatementState &io,
const Descriptor &descriptor, const typeInfo::DerivedType &type,
const NonTbpDefinedIoTable *table) {
IoErrorHandler &handler{io.GetIoErrorHandler()};
const Descriptor &compArray{type.component()};
RUNTIME_CHECK(handler, compArray.rank() == 1);
std::size_t numComponents{compArray.Elements()};
std::size_t numElements{descriptor.Elements()};
SubscriptValue subscripts[maxRank];
descriptor.GetLowerBounds(subscripts);
for (std::size_t j{0}; j < numElements;
++j, descriptor.IncrementSubscripts(subscripts)) {
SubscriptValue at[maxRank];
compArray.GetLowerBounds(at);
for (std::size_t k{0}; k < numComponents;
++k, compArray.IncrementSubscripts(at)) {
const typeInfo::Component &component{
*compArray.Element<typeInfo::Component>(at)};
if (!DefaultComponentIO<DIR>(
io, component, descriptor, subscripts, handler, table)) {
return false;
}
}
}
return true;
}
RT_API_ATTRS Fortran::common::optional<bool> DefinedFormattedIo(
IoStatementState &, const Descriptor &, const typeInfo::DerivedType &,
const typeInfo::SpecialBinding &, const SubscriptValue[]);
template <Direction DIR>
static RT_API_ATTRS bool FormattedDerivedTypeIO(IoStatementState &io,
const Descriptor &descriptor, const NonTbpDefinedIoTable *table) {
IoErrorHandler &handler{io.GetIoErrorHandler()};
// Derived type information must be present for formatted I/O.
const DescriptorAddendum *addendum{descriptor.Addendum()};
RUNTIME_CHECK(handler, addendum != nullptr);
const typeInfo::DerivedType *type{addendum->derivedType()};
RUNTIME_CHECK(handler, type != nullptr);
Fortran::common::optional<typeInfo::SpecialBinding> nonTbpSpecial;
const typeInfo::SpecialBinding *special{nullptr};
if (table) {
if (const auto *definedIo{table->Find(*type,
DIR == Direction::Input ? common::DefinedIo::ReadFormatted
: common::DefinedIo::WriteFormatted)}) {
if (definedIo->subroutine) {
nonTbpSpecial.emplace(DIR == Direction::Input
? typeInfo::SpecialBinding::Which::ReadFormatted
: typeInfo::SpecialBinding::Which::WriteFormatted,
definedIo->subroutine, definedIo->isDtvArgPolymorphic, false,
false);
special = &*nonTbpSpecial;
}
}
}
if (!special) {
if (const typeInfo::SpecialBinding *
binding{type->FindSpecialBinding(DIR == Direction::Input
? typeInfo::SpecialBinding::Which::ReadFormatted
: typeInfo::SpecialBinding::Which::WriteFormatted)}) {
if (!table || !table->ignoreNonTbpEntries || binding->isTypeBound()) {
special = binding;
}
}
}
SubscriptValue subscripts[maxRank];
descriptor.GetLowerBounds(subscripts);
std::size_t numElements{descriptor.Elements()};
for (std::size_t j{0}; j < numElements;
++j, descriptor.IncrementSubscripts(subscripts)) {
Fortran::common::optional<bool> result;
if (special) {
result = DefinedFormattedIo(io, descriptor, *type, *special, subscripts);
}
if (!result) {
result = DefaultComponentwiseFormattedIO<DIR>(
io, descriptor, *type, table, subscripts);
}
if (!result.value()) {
// Return true for NAMELIST input if we got anything.
auto *listInput{
io.get_if<ListDirectedStatementState<Direction::Input>>()};
return DIR == Direction::Input && j > 0 && listInput &&
listInput->inNamelistSequence();
}
}
return true;
}
RT_API_ATTRS bool DefinedUnformattedIo(IoStatementState &, const Descriptor &,
const typeInfo::DerivedType &, const typeInfo::SpecialBinding &);
// Unformatted I/O
template <Direction DIR>
static RT_API_ATTRS bool UnformattedDescriptorIO(IoStatementState &io,
const Descriptor &descriptor, const NonTbpDefinedIoTable *table = nullptr) {
IoErrorHandler &handler{io.GetIoErrorHandler()};
const DescriptorAddendum *addendum{descriptor.Addendum()};
if (const typeInfo::DerivedType *
type{addendum ? addendum->derivedType() : nullptr}) {
// derived type unformatted I/O
if (table) {
if (const auto *definedIo{table->Find(*type,
DIR == Direction::Input ? common::DefinedIo::ReadUnformatted
: common::DefinedIo::WriteUnformatted)}) {
if (definedIo->subroutine) {
typeInfo::SpecialBinding special{DIR == Direction::Input
? typeInfo::SpecialBinding::Which::ReadUnformatted
: typeInfo::SpecialBinding::Which::WriteUnformatted,
definedIo->subroutine, definedIo->isDtvArgPolymorphic, false,
false};
if (Fortran::common::optional<bool> wasDefined{
DefinedUnformattedIo(io, descriptor, *type, special)}) {
return *wasDefined;
}
} else {
return DefaultComponentwiseUnformattedIO<DIR>(
io, descriptor, *type, table);
}
}
}
if (const typeInfo::SpecialBinding *
special{type->FindSpecialBinding(DIR == Direction::Input
? typeInfo::SpecialBinding::Which::ReadUnformatted
: typeInfo::SpecialBinding::Which::WriteUnformatted)}) {
if (!table || !table->ignoreNonTbpEntries || special->isTypeBound()) {
// defined derived type unformatted I/O
return DefinedUnformattedIo(io, descriptor, *type, *special);
}
}
// Default derived type unformatted I/O
// TODO: If no component at any level has defined READ or WRITE
// (as appropriate), the elements are contiguous, and no byte swapping
// is active, do a block transfer via the code below.
return DefaultComponentwiseUnformattedIO<DIR>(io, descriptor, *type, table);
} else {
// intrinsic type unformatted I/O
auto *externalUnf{io.get_if<ExternalUnformattedIoStatementState<DIR>>()};
auto *childUnf{io.get_if<ChildUnformattedIoStatementState<DIR>>()};
auto *inq{
DIR == Direction::Output ? io.get_if<InquireIOLengthState>() : nullptr};
RUNTIME_CHECK(handler, externalUnf || childUnf || inq);
std::size_t elementBytes{descriptor.ElementBytes()};
std::size_t numElements{descriptor.Elements()};
std::size_t swappingBytes{elementBytes};
if (auto maybeCatAndKind{descriptor.type().GetCategoryAndKind()}) {
// Byte swapping units can be smaller than elements, namely
// for COMPLEX and CHARACTER.
if (maybeCatAndKind->first == TypeCategory::Character) {
// swap each character position independently
swappingBytes = maybeCatAndKind->second; // kind
} else if (maybeCatAndKind->first == TypeCategory::Complex) {
// swap real and imaginary components independently
swappingBytes /= 2;
}
}
SubscriptValue subscripts[maxRank];
descriptor.GetLowerBounds(subscripts);
using CharType =
std::conditional_t<DIR == Direction::Output, const char, char>;
auto Transfer{[=](CharType &x, std::size_t totalBytes) -> bool {
if constexpr (DIR == Direction::Output) {
return externalUnf ? externalUnf->Emit(&x, totalBytes, swappingBytes)
: childUnf ? childUnf->Emit(&x, totalBytes, swappingBytes)
: inq->Emit(&x, totalBytes, swappingBytes);
} else {
return externalUnf ? externalUnf->Receive(&x, totalBytes, swappingBytes)
: childUnf->Receive(&x, totalBytes, swappingBytes);
}
}};
bool swapEndianness{externalUnf && externalUnf->unit().swapEndianness()};
if (!swapEndianness &&
descriptor.IsContiguous()) { // contiguous unformatted I/O
char &x{ExtractElement<char>(io, descriptor, subscripts)};
return Transfer(x, numElements * elementBytes);
} else { // non-contiguous or byte-swapped intrinsic type unformatted I/O
for (std::size_t j{0}; j < numElements; ++j) {
char &x{ExtractElement<char>(io, descriptor, subscripts)};
if (!Transfer(x, elementBytes)) {
return false;
}
if (!descriptor.IncrementSubscripts(subscripts) &&
j + 1 < numElements) {
handler.Crash("DescriptorIO: subscripts out of bounds");
}
}
return true;
}
}
}
template <Direction DIR>
static RT_API_ATTRS bool DescriptorIO(IoStatementState &io,
const Descriptor &descriptor, const NonTbpDefinedIoTable *table) {
IoErrorHandler &handler{io.GetIoErrorHandler()};
if (handler.InError()) {
return false;
}
if (!io.get_if<IoDirectionState<DIR>>()) {
handler.Crash("DescriptorIO() called for wrong I/O direction");
return false;
}
if constexpr (DIR == Direction::Input) {
if (!io.BeginReadingRecord()) {
return false;
}
}
if (!io.get_if<FormattedIoStatementState<DIR>>()) {
return UnformattedDescriptorIO<DIR>(io, descriptor, table);
}
if (auto catAndKind{descriptor.type().GetCategoryAndKind()}) {
TypeCategory cat{catAndKind->first};
int kind{catAndKind->second};
switch (cat) {
case TypeCategory::Integer:
switch (kind) {
case 1:
return FormattedIntegerIO<1, DIR>(io, descriptor, true);
case 2:
return FormattedIntegerIO<2, DIR>(io, descriptor, true);
case 4:
return FormattedIntegerIO<4, DIR>(io, descriptor, true);
case 8:
return FormattedIntegerIO<8, DIR>(io, descriptor, true);
case 16:
return FormattedIntegerIO<16, DIR>(io, descriptor, true);
default:
handler.Crash(
"not yet implemented: INTEGER(KIND=%d) in formatted IO", kind);
return false;
}
case TypeCategory::Unsigned:
switch (kind) {
case 1:
return FormattedIntegerIO<1, DIR>(io, descriptor, false);
case 2:
return FormattedIntegerIO<2, DIR>(io, descriptor, false);
case 4:
return FormattedIntegerIO<4, DIR>(io, descriptor, false);
case 8:
return FormattedIntegerIO<8, DIR>(io, descriptor, false);
case 16:
return FormattedIntegerIO<16, DIR>(io, descriptor, false);
default:
handler.Crash(
"not yet implemented: UNSIGNED(KIND=%d) in formatted IO", kind);
return false;
}
case TypeCategory::Real:
switch (kind) {
case 2:
return FormattedRealIO<2, DIR>(io, descriptor);
case 3:
return FormattedRealIO<3, DIR>(io, descriptor);
case 4:
return FormattedRealIO<4, DIR>(io, descriptor);
case 8:
return FormattedRealIO<8, DIR>(io, descriptor);
case 10:
return FormattedRealIO<10, DIR>(io, descriptor);
// TODO: case double/double
case 16:
return FormattedRealIO<16, DIR>(io, descriptor);
default:
handler.Crash(
"not yet implemented: REAL(KIND=%d) in formatted IO", kind);
return false;
}
case TypeCategory::Complex:
switch (kind) {
case 2:
return FormattedComplexIO<2, DIR>(io, descriptor);
case 3:
return FormattedComplexIO<3, DIR>(io, descriptor);
case 4:
return FormattedComplexIO<4, DIR>(io, descriptor);
case 8:
return FormattedComplexIO<8, DIR>(io, descriptor);
case 10:
return FormattedComplexIO<10, DIR>(io, descriptor);
// TODO: case double/double
case 16:
return FormattedComplexIO<16, DIR>(io, descriptor);
default:
handler.Crash(
"not yet implemented: COMPLEX(KIND=%d) in formatted IO", kind);
return false;
}
case TypeCategory::Character:
switch (kind) {
case 1:
return FormattedCharacterIO<char, DIR>(io, descriptor);
case 2:
return FormattedCharacterIO<char16_t, DIR>(io, descriptor);
case 4:
return FormattedCharacterIO<char32_t, DIR>(io, descriptor);
default:
handler.Crash(
"not yet implemented: CHARACTER(KIND=%d) in formatted IO", kind);
return false;
}
case TypeCategory::Logical:
switch (kind) {
case 1:
return FormattedLogicalIO<1, DIR>(io, descriptor);
case 2:
return FormattedLogicalIO<2, DIR>(io, descriptor);
case 4:
return FormattedLogicalIO<4, DIR>(io, descriptor);
case 8:
return FormattedLogicalIO<8, DIR>(io, descriptor);
default:
handler.Crash(
"not yet implemented: LOGICAL(KIND=%d) in formatted IO", kind);
return false;
}
case TypeCategory::Derived:
return FormattedDerivedTypeIO<DIR>(io, descriptor, table);
}
}
handler.Crash("DescriptorIO: bad type code (%d) in descriptor",
static_cast<int>(descriptor.type().raw()));
return false;
}
} // namespace Fortran::runtime::io::descr } // namespace Fortran::runtime::io::descr
#endif // FLANG_RT_RUNTIME_DESCRIPTOR_IO_H_ #endif // FLANG_RT_RUNTIME_DESCRIPTOR_IO_H_

View File

@ -143,6 +143,10 @@ void ExecutionEnvironment::Configure(int ac, const char *av[],
} }
} }
if (auto *x{std::getenv("FLANG_RT_DEBUG")}) {
internalDebugging = std::strtol(x, nullptr, 10);
}
if (auto *x{std::getenv("ACC_OFFLOAD_STACK_SIZE")}) { if (auto *x{std::getenv("ACC_OFFLOAD_STACK_SIZE")}) {
char *end; char *end;
auto n{std::strtoul(x, &end, 10)}; auto n{std::strtoul(x, &end, 10)};

View File

@ -10,6 +10,7 @@
#include "descriptor-io.h" #include "descriptor-io.h"
#include "flang-rt/runtime/emit-encoded.h" #include "flang-rt/runtime/emit-encoded.h"
#include "flang-rt/runtime/io-stmt.h" #include "flang-rt/runtime/io-stmt.h"
#include "flang-rt/runtime/type-info.h"
#include "flang/Runtime/io-api.h" #include "flang/Runtime/io-api.h"
#include <algorithm> #include <algorithm>
#include <cstring> #include <cstring>

View File

@ -205,7 +205,7 @@ RT_API_ATTRS void ShallowCopyInner(const Descriptor &to, const Descriptor &from,
// Doing the recursion upwards instead of downwards puts the more common // Doing the recursion upwards instead of downwards puts the more common
// cases earlier in the if-chain and has a tangible impact on performance. // cases earlier in the if-chain and has a tangible impact on performance.
template <typename P, int RANK> struct ShallowCopyRankSpecialize { template <typename P, int RANK> struct ShallowCopyRankSpecialize {
static bool execute(const Descriptor &to, const Descriptor &from, static RT_API_ATTRS bool execute(const Descriptor &to, const Descriptor &from,
bool toIsContiguous, bool fromIsContiguous) { bool toIsContiguous, bool fromIsContiguous) {
if (to.rank() == RANK && from.rank() == RANK) { if (to.rank() == RANK && from.rank() == RANK) {
ShallowCopyInner<P, RANK>(to, from, toIsContiguous, fromIsContiguous); ShallowCopyInner<P, RANK>(to, from, toIsContiguous, fromIsContiguous);
@ -217,7 +217,7 @@ template <typename P, int RANK> struct ShallowCopyRankSpecialize {
}; };
template <typename P> struct ShallowCopyRankSpecialize<P, maxRank + 1> { template <typename P> struct ShallowCopyRankSpecialize<P, maxRank + 1> {
static bool execute(const Descriptor &to, const Descriptor &from, static RT_API_ATTRS bool execute(const Descriptor &to, const Descriptor &from,
bool toIsContiguous, bool fromIsContiguous) { bool toIsContiguous, bool fromIsContiguous) {
return false; return false;
} }

View File

@ -140,11 +140,11 @@ RT_API_ATTRS void Component::CreatePointerDescriptor(Descriptor &descriptor,
const SubscriptValue *subscripts) const { const SubscriptValue *subscripts) const {
RUNTIME_CHECK(terminator, genre_ == Genre::Data); RUNTIME_CHECK(terminator, genre_ == Genre::Data);
EstablishDescriptor(descriptor, container, terminator); EstablishDescriptor(descriptor, container, terminator);
std::size_t offset{offset_};
if (subscripts) { if (subscripts) {
descriptor.set_base_addr(container.Element<char>(subscripts) + offset_); offset += container.SubscriptsToByteOffset(subscripts);
} else {
descriptor.set_base_addr(container.OffsetElement<char>() + offset_);
} }
descriptor.set_base_addr(container.OffsetElement<char>() + offset);
descriptor.raw().attribute = CFI_attribute_pointer; descriptor.raw().attribute = CFI_attribute_pointer;
} }
@ -279,6 +279,10 @@ FILE *Component::Dump(FILE *f) const {
} }
std::fprintf(f, " category %d kind %d rank %d offset 0x%zx\n", category_, std::fprintf(f, " category %d kind %d rank %d offset 0x%zx\n", category_,
kind_, rank_, static_cast<std::size_t>(offset_)); kind_, rank_, static_cast<std::size_t>(offset_));
const auto &dtDesc{derivedType_.descriptor()};
if (dtDesc.raw().base_addr) {
std::fprintf(f, " derivedType_ %p\n", dtDesc.raw().base_addr);
}
if (initialization_) { if (initialization_) {
std::fprintf(f, " initialization @ %p:\n", std::fprintf(f, " initialization @ %p:\n",
reinterpret_cast<const void *>(initialization_)); reinterpret_cast<const void *>(initialization_));
@ -325,7 +329,7 @@ FILE *SpecialBinding::Dump(FILE *f) const {
break; break;
} }
std::fprintf(f, " isArgDescriptorSet: 0x%x\n", isArgDescriptorSet_); std::fprintf(f, " isArgDescriptorSet: 0x%x\n", isArgDescriptorSet_);
std::fprintf(f, " isTypeBound: 0x%x\n", isTypeBound_); std::fprintf(f, " isTypeBound: %d\n", isTypeBound_);
std::fprintf(f, " isArgContiguousSet: 0x%x\n", isArgContiguousSet_); std::fprintf(f, " isArgContiguousSet: 0x%x\n", isArgContiguousSet_);
std::fprintf(f, " proc: %p\n", reinterpret_cast<void *>(proc_)); std::fprintf(f, " proc: %p\n", reinterpret_cast<void *>(proc_));
return f; return f;

View File

@ -0,0 +1,161 @@
//===-- lib/runtime/work-queue.cpp ------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "flang-rt/runtime/work-queue.h"
#include "flang-rt/runtime/environment.h"
#include "flang-rt/runtime/memory.h"
#include "flang-rt/runtime/type-info.h"
#include "flang/Common/visit.h"
namespace Fortran::runtime {
#if !defined(RT_DEVICE_COMPILATION)
// FLANG_RT_DEBUG code is disabled when false.
static constexpr bool enableDebugOutput{false};
#endif
RT_OFFLOAD_API_GROUP_BEGIN
RT_API_ATTRS Componentwise::Componentwise(const typeInfo::DerivedType &derived)
: derived_{derived}, components_{derived_.component().Elements()} {
GetComponent();
}
RT_API_ATTRS void Componentwise::GetComponent() {
if (IsComplete()) {
component_ = nullptr;
} else {
const Descriptor &componentDesc{derived_.component()};
component_ = componentDesc.ZeroBasedIndexedElement<typeInfo::Component>(
componentAt_);
}
}
RT_API_ATTRS int Ticket::Continue(WorkQueue &workQueue) {
if (!begun) {
begun = true;
return common::visit(
[&workQueue](
auto &specificTicket) { return specificTicket.Begin(workQueue); },
u);
} else {
return common::visit(
[&workQueue](auto &specificTicket) {
return specificTicket.Continue(workQueue);
},
u);
}
}
RT_API_ATTRS WorkQueue::~WorkQueue() {
if (last_) {
if ((last_->next = firstFree_)) {
last_->next->previous = last_;
}
firstFree_ = first_;
first_ = last_ = nullptr;
}
while (firstFree_) {
TicketList *next{firstFree_->next};
if (!firstFree_->isStatic) {
FreeMemory(firstFree_);
}
firstFree_ = next;
}
}
RT_API_ATTRS Ticket &WorkQueue::StartTicket() {
if (!firstFree_) {
void *p{AllocateMemoryOrCrash(terminator_, sizeof(TicketList))};
firstFree_ = new (p) TicketList;
firstFree_->isStatic = false;
}
TicketList *newTicket{firstFree_};
if ((firstFree_ = newTicket->next)) {
firstFree_->previous = nullptr;
}
TicketList *after{insertAfter_ ? insertAfter_->next : nullptr};
if ((newTicket->previous = insertAfter_ ? insertAfter_ : last_)) {
newTicket->previous->next = newTicket;
} else {
first_ = newTicket;
}
if ((newTicket->next = after)) {
after->previous = newTicket;
} else {
last_ = newTicket;
}
newTicket->ticket.begun = false;
#if !defined(RT_DEVICE_COMPILATION)
if (enableDebugOutput &&
(executionEnvironment.internalDebugging &
ExecutionEnvironment::WorkQueue)) {
std::fprintf(stderr, "WQ: new ticket\n");
}
#endif
return newTicket->ticket;
}
RT_API_ATTRS int WorkQueue::Run() {
while (last_) {
TicketList *at{last_};
insertAfter_ = last_;
#if !defined(RT_DEVICE_COMPILATION)
if (enableDebugOutput &&
(executionEnvironment.internalDebugging &
ExecutionEnvironment::WorkQueue)) {
std::fprintf(stderr, "WQ: %zd %s\n", at->ticket.u.index(),
at->ticket.begun ? "Continue" : "Begin");
}
#endif
int stat{at->ticket.Continue(*this)};
#if !defined(RT_DEVICE_COMPILATION)
if (enableDebugOutput &&
(executionEnvironment.internalDebugging &
ExecutionEnvironment::WorkQueue)) {
std::fprintf(stderr, "WQ: ... stat %d\n", stat);
}
#endif
insertAfter_ = nullptr;
if (stat == StatOk) {
if (at->previous) {
at->previous->next = at->next;
} else {
first_ = at->next;
}
if (at->next) {
at->next->previous = at->previous;
} else {
last_ = at->previous;
}
if ((at->next = firstFree_)) {
at->next->previous = at;
}
at->previous = nullptr;
firstFree_ = at;
} else if (stat != StatContinue) {
Stop();
return stat;
}
}
return StatOk;
}
RT_API_ATTRS void WorkQueue::Stop() {
if (last_) {
if ((last_->next = firstFree_)) {
last_->next->previous = last_;
}
firstFree_ = first_;
first_ = last_ = nullptr;
}
}
RT_OFFLOAD_API_GROUP_END
} // namespace Fortran::runtime

View File

@ -184,7 +184,7 @@ TEST(ExternalIOTests, TestSequentialFixedUnformatted) {
io = IONAME(BeginInquireIoLength)(__FILE__, __LINE__); io = IONAME(BeginInquireIoLength)(__FILE__, __LINE__);
for (int j{1}; j <= 3; ++j) { for (int j{1}; j <= 3; ++j) {
ASSERT_TRUE(IONAME(OutputDescriptor)(io, desc)) ASSERT_TRUE(IONAME(OutputDescriptor)(io, desc))
<< "OutputDescriptor() for InquireIoLength"; << "OutputDescriptor() for InquireIoLength " << j;
} }
ASSERT_EQ(IONAME(GetIoLength)(io), 3 * recl) << "GetIoLength"; ASSERT_EQ(IONAME(GetIoLength)(io), 3 * recl) << "GetIoLength";
ASSERT_EQ(IONAME(EndIoStatement)(io), IostatOk) ASSERT_EQ(IONAME(EndIoStatement)(io), IostatOk)

View File

@ -858,6 +858,16 @@ print *, [(j,j=1,10)]
warning since such values may have become defined by the time the nested warning since such values may have become defined by the time the nested
expression's value is required. expression's value is required.
* Intrinsic assignment of arrays is defined elementally, and intrinsic
assignment of derived type components is defined componentwise.
However, when intrinsic assignment takes place for an array of derived
type, the order of the loop nesting is not defined.
Some compilers will loop over the elements, assigning all of the components
of each element before proceeding to the next element.
This compiler loops over all of the components, and assigns all of
the elements for each component before proceeding to the next component.
A program using defined assignment might be able to detect the difference.
## De Facto Standard Features ## De Facto Standard Features
* `EXTENDS_TYPE_OF()` returns `.TRUE.` if both of its arguments have the * `EXTENDS_TYPE_OF()` returns `.TRUE.` if both of its arguments have the

View File

@ -38,7 +38,8 @@ enum AssignFlags {
ComponentCanBeDefinedAssignment = 1 << 3, ComponentCanBeDefinedAssignment = 1 << 3,
ExplicitLengthCharacterLHS = 1 << 4, ExplicitLengthCharacterLHS = 1 << 4,
PolymorphicLHS = 1 << 5, PolymorphicLHS = 1 << 5,
DeallocateLHS = 1 << 6 DeallocateLHS = 1 << 6,
UpdateLHSBounds = 1 << 7,
}; };
#ifdef RT_DEVICE_COMPILATION #ifdef RT_DEVICE_COMPILATION

View File

@ -182,9 +182,12 @@ const Symbol *HasImpureFinal(
const Symbol &, std::optional<int> rank = std::nullopt); const Symbol &, std::optional<int> rank = std::nullopt);
// Is this type finalizable or does it contain any polymorphic allocatable // Is this type finalizable or does it contain any polymorphic allocatable
// ultimate components? // ultimate components?
bool MayRequireFinalization(const DerivedTypeSpec &derived); bool MayRequireFinalization(const DerivedTypeSpec &);
// Does this type have an allocatable direct component? // Does this type have an allocatable direct component?
bool HasAllocatableDirectComponent(const DerivedTypeSpec &derived); bool HasAllocatableDirectComponent(const DerivedTypeSpec &);
// Does this type have any defined assignment at any level (or any polymorphic
// allocatable)?
bool MayHaveDefinedAssignment(const DerivedTypeSpec &);
bool IsInBlankCommon(const Symbol &); bool IsInBlankCommon(const Symbol &);
bool IsAssumedLengthCharacter(const Symbol &); bool IsAssumedLengthCharacter(const Symbol &);

View File

@ -82,17 +82,17 @@ private:
const SomeExpr &genre, std::int64_t = 0) const; const SomeExpr &genre, std::int64_t = 0) const;
SomeExpr PackageIntValueExpr(const SomeExpr &genre, std::int64_t = 0) const; SomeExpr PackageIntValueExpr(const SomeExpr &genre, std::int64_t = 0) const;
std::vector<evaluate::StructureConstructor> DescribeBindings( std::vector<evaluate::StructureConstructor> DescribeBindings(
const Scope &dtScope, Scope &); const Scope &dtScope, Scope &, const SymbolVector &bindings);
std::map<int, evaluate::StructureConstructor> DescribeSpecialGenerics( std::map<int, evaluate::StructureConstructor> DescribeSpecialGenerics(
const Scope &dtScope, const Scope &thisScope, const Scope &dtScope, const Scope &thisScope, const DerivedTypeSpec *,
const DerivedTypeSpec *) const; const SymbolVector &bindings) const;
void DescribeSpecialGeneric(const GenericDetails &, void DescribeSpecialGeneric(const GenericDetails &,
std::map<int, evaluate::StructureConstructor> &, const Scope &, std::map<int, evaluate::StructureConstructor> &, const Scope &,
const DerivedTypeSpec *) const; const DerivedTypeSpec *, const SymbolVector &bindings) const;
void DescribeSpecialProc(std::map<int, evaluate::StructureConstructor> &, void DescribeSpecialProc(std::map<int, evaluate::StructureConstructor> &,
const Symbol &specificOrBinding, bool isAssignment, bool isFinal, const Symbol &specificOrBinding, bool isAssignment, bool isFinal,
std::optional<common::DefinedIo>, const Scope *, const DerivedTypeSpec *, std::optional<common::DefinedIo>, const Scope *, const DerivedTypeSpec *,
bool isTypeBound) const; const SymbolVector *bindings) const;
void IncorporateDefinedIoGenericInterfaces( void IncorporateDefinedIoGenericInterfaces(
std::map<int, evaluate::StructureConstructor> &, common::DefinedIo, std::map<int, evaluate::StructureConstructor> &, common::DefinedIo,
const Scope *, const DerivedTypeSpec *); const Scope *, const DerivedTypeSpec *);
@ -595,8 +595,9 @@ const Symbol *RuntimeTableBuilder::DescribeType(
// Compile the "vtable" of type-bound procedure bindings // Compile the "vtable" of type-bound procedure bindings
std::uint32_t specialBitSet{0}; std::uint32_t specialBitSet{0};
if (!dtSymbol->attrs().test(Attr::ABSTRACT)) { if (!dtSymbol->attrs().test(Attr::ABSTRACT)) {
SymbolVector boundProcedures{CollectBindings(dtScope)};
std::vector<evaluate::StructureConstructor> bindings{ std::vector<evaluate::StructureConstructor> bindings{
DescribeBindings(dtScope, scope)}; DescribeBindings(dtScope, scope, boundProcedures)};
AddValue(dtValues, derivedTypeSchema_, bindingDescCompName, AddValue(dtValues, derivedTypeSchema_, bindingDescCompName,
SaveDerivedPointerTarget(scope, SaveDerivedPointerTarget(scope,
SaveObjectName( SaveObjectName(
@ -609,12 +610,14 @@ const Symbol *RuntimeTableBuilder::DescribeType(
// subroutines override any parent bindings, but FINAL subroutines do not // subroutines override any parent bindings, but FINAL subroutines do not
// (the runtime will call all of them). // (the runtime will call all of them).
std::map<int, evaluate::StructureConstructor> specials{ std::map<int, evaluate::StructureConstructor> specials{
DescribeSpecialGenerics(dtScope, dtScope, derivedTypeSpec)}; DescribeSpecialGenerics(
dtScope, dtScope, derivedTypeSpec, boundProcedures)};
if (derivedTypeSpec) { if (derivedTypeSpec) {
for (auto &ref : FinalsForDerivedTypeInstantiation(*derivedTypeSpec)) { for (const Symbol &symbol :
DescribeSpecialProc(specials, *ref, /*isAssignment-*/ false, FinalsForDerivedTypeInstantiation(*derivedTypeSpec)) {
DescribeSpecialProc(specials, symbol, /*isAssignment-*/ false,
/*isFinal=*/true, std::nullopt, nullptr, derivedTypeSpec, /*isFinal=*/true, std::nullopt, nullptr, derivedTypeSpec,
/*isTypeBound=*/true); &boundProcedures);
} }
IncorporateDefinedIoGenericInterfaces(specials, IncorporateDefinedIoGenericInterfaces(specials,
common::DefinedIo::ReadFormatted, &scope, derivedTypeSpec); common::DefinedIo::ReadFormatted, &scope, derivedTypeSpec);
@ -661,6 +664,10 @@ const Symbol *RuntimeTableBuilder::DescribeType(
AddValue(dtValues, derivedTypeSchema_, "nofinalizationneeded"s, AddValue(dtValues, derivedTypeSchema_, "nofinalizationneeded"s,
IntExpr<1>( IntExpr<1>(
derivedTypeSpec && !MayRequireFinalization(*derivedTypeSpec))); derivedTypeSpec && !MayRequireFinalization(*derivedTypeSpec)));
// Similarly, a flag to enable optimized runtime assignment.
AddValue(dtValues, derivedTypeSchema_, "nodefinedassignment"s,
IntExpr<1>(
derivedTypeSpec && !MayHaveDefinedAssignment(*derivedTypeSpec)));
} }
dtObject.get<ObjectEntityDetails>().set_init(MaybeExpr{ dtObject.get<ObjectEntityDetails>().set_init(MaybeExpr{
StructureExpr(Structure(derivedTypeSchema_, std::move(dtValues)))}); StructureExpr(Structure(derivedTypeSchema_, std::move(dtValues)))});
@ -1041,15 +1048,16 @@ SymbolVector CollectBindings(const Scope &dtScope) {
} }
std::vector<evaluate::StructureConstructor> std::vector<evaluate::StructureConstructor>
RuntimeTableBuilder::DescribeBindings(const Scope &dtScope, Scope &scope) { RuntimeTableBuilder::DescribeBindings(
const Scope &dtScope, Scope &scope, const SymbolVector &bindings) {
std::vector<evaluate::StructureConstructor> result; std::vector<evaluate::StructureConstructor> result;
for (const SymbolRef &ref : CollectBindings(dtScope)) { for (const Symbol &symbol : bindings) {
evaluate::StructureConstructorValues values; evaluate::StructureConstructorValues values;
AddValue(values, bindingSchema_, procCompName, AddValue(values, bindingSchema_, procCompName,
SomeExpr{evaluate::ProcedureDesignator{ SomeExpr{evaluate::ProcedureDesignator{
ref.get().get<ProcBindingDetails>().symbol()}}); symbol.get<ProcBindingDetails>().symbol()}});
AddValue(values, bindingSchema_, "name"s, AddValue(values, bindingSchema_, "name"s,
SaveNameAsPointerTarget(scope, ref.get().name().ToString())); SaveNameAsPointerTarget(scope, symbol.name().ToString()));
result.emplace_back(DEREF(bindingSchema_.AsDerived()), std::move(values)); result.emplace_back(DEREF(bindingSchema_.AsDerived()), std::move(values));
} }
return result; return result;
@ -1057,16 +1065,18 @@ RuntimeTableBuilder::DescribeBindings(const Scope &dtScope, Scope &scope) {
std::map<int, evaluate::StructureConstructor> std::map<int, evaluate::StructureConstructor>
RuntimeTableBuilder::DescribeSpecialGenerics(const Scope &dtScope, RuntimeTableBuilder::DescribeSpecialGenerics(const Scope &dtScope,
const Scope &thisScope, const DerivedTypeSpec *derivedTypeSpec) const { const Scope &thisScope, const DerivedTypeSpec *derivedTypeSpec,
const SymbolVector &bindings) const {
std::map<int, evaluate::StructureConstructor> specials; std::map<int, evaluate::StructureConstructor> specials;
if (const Scope * parentScope{dtScope.GetDerivedTypeParent()}) { if (const Scope * parentScope{dtScope.GetDerivedTypeParent()}) {
specials = specials = DescribeSpecialGenerics(
DescribeSpecialGenerics(*parentScope, thisScope, derivedTypeSpec); *parentScope, thisScope, derivedTypeSpec, bindings);
} }
for (const auto &pair : dtScope) { for (const auto &pair : dtScope) {
const Symbol &symbol{*pair.second}; const Symbol &symbol{*pair.second};
if (const auto *generic{symbol.detailsIf<GenericDetails>()}) { if (const auto *generic{symbol.detailsIf<GenericDetails>()}) {
DescribeSpecialGeneric(*generic, specials, thisScope, derivedTypeSpec); DescribeSpecialGeneric(
*generic, specials, thisScope, derivedTypeSpec, bindings);
} }
} }
return specials; return specials;
@ -1074,15 +1084,16 @@ RuntimeTableBuilder::DescribeSpecialGenerics(const Scope &dtScope,
void RuntimeTableBuilder::DescribeSpecialGeneric(const GenericDetails &generic, void RuntimeTableBuilder::DescribeSpecialGeneric(const GenericDetails &generic,
std::map<int, evaluate::StructureConstructor> &specials, std::map<int, evaluate::StructureConstructor> &specials,
const Scope &dtScope, const DerivedTypeSpec *derivedTypeSpec) const { const Scope &dtScope, const DerivedTypeSpec *derivedTypeSpec,
const SymbolVector &bindings) const {
common::visit( common::visit(
common::visitors{ common::visitors{
[&](const GenericKind::OtherKind &k) { [&](const GenericKind::OtherKind &k) {
if (k == GenericKind::OtherKind::Assignment) { if (k == GenericKind::OtherKind::Assignment) {
for (auto ref : generic.specificProcs()) { for (const Symbol &specific : generic.specificProcs()) {
DescribeSpecialProc(specials, *ref, /*isAssignment=*/true, DescribeSpecialProc(specials, specific, /*isAssignment=*/true,
/*isFinal=*/false, std::nullopt, &dtScope, derivedTypeSpec, /*isFinal=*/false, std::nullopt, &dtScope, derivedTypeSpec,
/*isTypeBound=*/true); &bindings);
} }
} }
}, },
@ -1092,10 +1103,10 @@ void RuntimeTableBuilder::DescribeSpecialGeneric(const GenericDetails &generic,
case common::DefinedIo::ReadUnformatted: case common::DefinedIo::ReadUnformatted:
case common::DefinedIo::WriteFormatted: case common::DefinedIo::WriteFormatted:
case common::DefinedIo::WriteUnformatted: case common::DefinedIo::WriteUnformatted:
for (auto ref : generic.specificProcs()) { for (const Symbol &specific : generic.specificProcs()) {
DescribeSpecialProc(specials, *ref, /*isAssignment=*/false, DescribeSpecialProc(specials, specific, /*isAssignment=*/false,
/*isFinal=*/false, io, &dtScope, derivedTypeSpec, /*isFinal=*/false, io, &dtScope, derivedTypeSpec,
/*isTypeBound=*/true); &bindings);
} }
break; break;
} }
@ -1109,7 +1120,8 @@ void RuntimeTableBuilder::DescribeSpecialProc(
std::map<int, evaluate::StructureConstructor> &specials, std::map<int, evaluate::StructureConstructor> &specials,
const Symbol &specificOrBinding, bool isAssignment, bool isFinal, const Symbol &specificOrBinding, bool isAssignment, bool isFinal,
std::optional<common::DefinedIo> io, const Scope *dtScope, std::optional<common::DefinedIo> io, const Scope *dtScope,
const DerivedTypeSpec *derivedTypeSpec, bool isTypeBound) const { const DerivedTypeSpec *derivedTypeSpec,
const SymbolVector *bindings) const {
const auto *binding{specificOrBinding.detailsIf<ProcBindingDetails>()}; const auto *binding{specificOrBinding.detailsIf<ProcBindingDetails>()};
if (binding && dtScope) { // use most recent override if (binding && dtScope) { // use most recent override
binding = &DEREF(dtScope->FindComponent(specificOrBinding.name())) binding = &DEREF(dtScope->FindComponent(specificOrBinding.name()))
@ -1128,6 +1140,9 @@ void RuntimeTableBuilder::DescribeSpecialProc(
// component assignment as part of intrinsic assignment. // component assignment as part of intrinsic assignment.
// Non-type-bound generic INTERFACEs and assignments from incompatible // Non-type-bound generic INTERFACEs and assignments from incompatible
// types must not be used for component intrinsic assignment. // types must not be used for component intrinsic assignment.
if (!binding) {
return;
}
CHECK(proc->dummyArguments.size() == 2); CHECK(proc->dummyArguments.size() == 2);
const auto t1{ const auto t1{
DEREF(std::get_if<evaluate::characteristics::DummyDataObject>( DEREF(std::get_if<evaluate::characteristics::DummyDataObject>(
@ -1137,7 +1152,7 @@ void RuntimeTableBuilder::DescribeSpecialProc(
DEREF(std::get_if<evaluate::characteristics::DummyDataObject>( DEREF(std::get_if<evaluate::characteristics::DummyDataObject>(
&proc->dummyArguments[1].u)) &proc->dummyArguments[1].u))
.type.type()}; .type.type()};
if (!binding || t1.category() != TypeCategory::Derived || if (t1.category() != TypeCategory::Derived ||
t2.category() != TypeCategory::Derived || t2.category() != TypeCategory::Derived ||
t1.IsUnlimitedPolymorphic() || t2.IsUnlimitedPolymorphic()) { t1.IsUnlimitedPolymorphic() || t2.IsUnlimitedPolymorphic()) {
return; return;
@ -1149,7 +1164,7 @@ void RuntimeTableBuilder::DescribeSpecialProc(
} }
which = proc->IsElemental() ? elementalAssignmentEnum_ which = proc->IsElemental() ? elementalAssignmentEnum_
: scalarAssignmentEnum_; : scalarAssignmentEnum_;
if (binding && binding->passName() && if (binding->passName() &&
*binding->passName() == proc->dummyArguments[1].name) { *binding->passName() == proc->dummyArguments[1].name) {
argThatMightBeDescriptor = 1; argThatMightBeDescriptor = 1;
isArgDescriptorSet |= 2; isArgDescriptorSet |= 2;
@ -1234,8 +1249,19 @@ void RuntimeTableBuilder::DescribeSpecialProc(
values, specialSchema_, "which"s, SomeExpr{std::move(which.value())}); values, specialSchema_, "which"s, SomeExpr{std::move(which.value())});
AddValue(values, specialSchema_, "isargdescriptorset"s, AddValue(values, specialSchema_, "isargdescriptorset"s,
IntExpr<1>(isArgDescriptorSet)); IntExpr<1>(isArgDescriptorSet));
AddValue(values, specialSchema_, "istypebound"s, int bindingIndex{0};
IntExpr<1>(isTypeBound ? 1 : 0)); if (bindings) {
int j{0};
for (const Symbol &bind : DEREF(bindings)) {
++j;
if (&bind.get<ProcBindingDetails>().symbol() == &specific) {
bindingIndex = j; // index offset by 1
break;
}
}
}
CHECK(bindingIndex <= 255);
AddValue(values, specialSchema_, "istypebound"s, IntExpr<1>(bindingIndex));
AddValue(values, specialSchema_, "isargcontiguousset"s, AddValue(values, specialSchema_, "isargcontiguousset"s,
IntExpr<1>(isArgContiguousSet)); IntExpr<1>(isArgContiguousSet));
AddValue(values, specialSchema_, procCompName, AddValue(values, specialSchema_, procCompName,
@ -1260,7 +1286,7 @@ void RuntimeTableBuilder::IncorporateDefinedIoGenericInterfaces(
CHECK(std::get<common::DefinedIo>(genericDetails.kind().u) == definedIo); CHECK(std::get<common::DefinedIo>(genericDetails.kind().u) == definedIo);
for (auto ref : genericDetails.specificProcs()) { for (auto ref : genericDetails.specificProcs()) {
DescribeSpecialProc(specials, *ref, false, false, definedIo, nullptr, DescribeSpecialProc(specials, *ref, false, false, definedIo, nullptr,
derivedTypeSpec, false); derivedTypeSpec, /*bindings=*/nullptr);
} }
} }
} }

View File

@ -814,6 +814,38 @@ bool HasAllocatableDirectComponent(const DerivedTypeSpec &derived) {
return std::any_of(directs.begin(), directs.end(), IsAllocatable); return std::any_of(directs.begin(), directs.end(), IsAllocatable);
} }
static bool MayHaveDefinedAssignment(
const DerivedTypeSpec &derived, std::set<const Scope *> &checked) {
if (const Scope *scope{derived.GetScope()};
scope && checked.find(scope) == checked.end()) {
checked.insert(scope);
for (const auto &[_, symbolRef] : *scope) {
if (const auto *generic{symbolRef->detailsIf<GenericDetails>()}) {
if (generic->kind().IsAssignment()) {
return true;
}
} else if (symbolRef->has<ObjectEntityDetails>() &&
!IsPointer(*symbolRef)) {
if (const DeclTypeSpec *type{symbolRef->GetType()}) {
if (type->IsPolymorphic()) {
return true;
} else if (const DerivedTypeSpec *derived{type->AsDerived()}) {
if (MayHaveDefinedAssignment(*derived, checked)) {
return true;
}
}
}
}
}
}
return false;
}
bool MayHaveDefinedAssignment(const DerivedTypeSpec &derived) {
std::set<const Scope *> checked;
return MayHaveDefinedAssignment(derived, checked);
}
bool IsAssumedLengthCharacter(const Symbol &symbol) { bool IsAssumedLengthCharacter(const Symbol &symbol) {
if (const DeclTypeSpec * type{symbol.GetType()}) { if (const DeclTypeSpec * type{symbol.GetType()}) {
return type->category() == DeclTypeSpec::Character && return type->category() == DeclTypeSpec::Character &&

View File

@ -52,7 +52,8 @@ module __fortran_type_info
integer(1) :: noInitializationNeeded ! 1 if no component w/ init integer(1) :: noInitializationNeeded ! 1 if no component w/ init
integer(1) :: noDestructionNeeded ! 1 if no component w/ dealloc/final integer(1) :: noDestructionNeeded ! 1 if no component w/ dealloc/final
integer(1) :: noFinalizationNeeded ! 1 if nothing finalizeable integer(1) :: noFinalizationNeeded ! 1 if nothing finalizeable
integer(1) :: __padding0(4) integer(1) :: noDefinedAssignment ! 1 if no defined ASSIGNMENT(=)
integer(1) :: __padding0(3)
end type end type
type :: Binding type :: Binding
@ -116,7 +117,7 @@ module __fortran_type_info
type, bind(c) :: SpecialBinding type, bind(c) :: SpecialBinding
integer(1) :: which ! SpecialBinding::Which integer(1) :: which ! SpecialBinding::Which
integer(1) :: isArgDescriptorSet integer(1) :: isArgDescriptorSet
integer(1) :: isTypeBound integer(1) :: isTypeBound ! binding index + 1, if any
integer(1) :: isArgContiguousSet integer(1) :: isArgContiguousSet
integer(1) :: __padding0(4) integer(1) :: __padding0(4)
type(__builtin_c_funptr) :: proc type(__builtin_c_funptr) :: proc

File diff suppressed because one or more lines are too long

View File

@ -8,7 +8,7 @@ module m01
end type end type
!CHECK: Module scope: m01 !CHECK: Module scope: m01
!CHECK: .c.t1, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(component) shape: 0_8:0_8 init:[component::component(name=.n.n,genre=1_1,category=0_1,kind=4_1,rank=0_1,offset=0_8,characterlen=value(genre=1_1,value=0_8),derived=NULL(),lenvalue=NULL(),bounds=NULL(),initialization=NULL())] !CHECK: .c.t1, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(component) shape: 0_8:0_8 init:[component::component(name=.n.n,genre=1_1,category=0_1,kind=4_1,rank=0_1,offset=0_8,characterlen=value(genre=1_1,value=0_8),derived=NULL(),lenvalue=NULL(),bounds=NULL(),initialization=NULL())]
!CHECK: .dt.t1, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.t1,sizeinbytes=4_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.t1,procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1) !CHECK: .dt.t1, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.t1,sizeinbytes=4_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.t1,procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1,nodefinedassignment=1_1)
!CHECK: .n.n, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: CHARACTER(1_8,1) init:"n" !CHECK: .n.n, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: CHARACTER(1_8,1) init:"n"
!CHECK: .n.t1, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: CHARACTER(2_8,1) init:"t1" !CHECK: .n.t1, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: CHARACTER(2_8,1) init:"t1"
!CHECK: DerivedType scope: t1 !CHECK: DerivedType scope: t1
@ -23,8 +23,8 @@ module m02
end type end type
!CHECK: .c.child, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(component) shape: 0_8:1_8 init:[component::component(name=.n.parent,genre=1_1,category=6_1,kind=0_1,rank=0_1,offset=0_8,characterlen=value(genre=1_1,value=0_8),derived=.dt.parent,lenvalue=NULL(),bounds=NULL(),initialization=NULL()),component(name=.n.cn,genre=1_1,category=0_1,kind=4_1,rank=0_1,offset=4_8,characterlen=value(genre=1_1,value=0_8),derived=NULL(),lenvalue=NULL(),bounds=NULL(),initialization=NULL())] !CHECK: .c.child, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(component) shape: 0_8:1_8 init:[component::component(name=.n.parent,genre=1_1,category=6_1,kind=0_1,rank=0_1,offset=0_8,characterlen=value(genre=1_1,value=0_8),derived=.dt.parent,lenvalue=NULL(),bounds=NULL(),initialization=NULL()),component(name=.n.cn,genre=1_1,category=0_1,kind=4_1,rank=0_1,offset=4_8,characterlen=value(genre=1_1,value=0_8),derived=NULL(),lenvalue=NULL(),bounds=NULL(),initialization=NULL())]
!CHECK: .c.parent, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(component) shape: 0_8:0_8 init:[component::component(name=.n.pn,genre=1_1,category=0_1,kind=4_1,rank=0_1,offset=0_8,characterlen=value(genre=1_1,value=0_8),derived=NULL(),lenvalue=NULL(),bounds=NULL(),initialization=NULL())] !CHECK: .c.parent, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(component) shape: 0_8:0_8 init:[component::component(name=.n.pn,genre=1_1,category=0_1,kind=4_1,rank=0_1,offset=0_8,characterlen=value(genre=1_1,value=0_8),derived=NULL(),lenvalue=NULL(),bounds=NULL(),initialization=NULL())]
!CHECK: .dt.child, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.child,sizeinbytes=8_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.child,procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=1_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1) !CHECK: .dt.child, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.child,sizeinbytes=8_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.child,procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=1_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1,nodefinedassignment=1_1)
!CHECK: .dt.parent, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.parent,sizeinbytes=4_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.parent,procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1) !CHECK: .dt.parent, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.parent,sizeinbytes=4_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.parent,procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1,nodefinedassignment=1_1)
end module end module
module m03 module m03
@ -35,7 +35,7 @@ module m03
type(kpdt(4)) :: x type(kpdt(4)) :: x
!CHECK: .c.kpdt.4, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(component) shape: 0_8:0_8 init:[component::component(name=.n.a,genre=1_1,category=2_1,kind=4_1,rank=0_1,offset=0_8,characterlen=value(genre=1_1,value=0_8),derived=NULL(),lenvalue=NULL(),bounds=NULL(),initialization=NULL())] !CHECK: .c.kpdt.4, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(component) shape: 0_8:0_8 init:[component::component(name=.n.a,genre=1_1,category=2_1,kind=4_1,rank=0_1,offset=0_8,characterlen=value(genre=1_1,value=0_8),derived=NULL(),lenvalue=NULL(),bounds=NULL(),initialization=NULL())]
!CHECK: .dt.kpdt, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(name=.n.kpdt,uninstantiated=NULL(),kindparameter=.kp.kpdt,lenparameterkind=NULL()) !CHECK: .dt.kpdt, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(name=.n.kpdt,uninstantiated=NULL(),kindparameter=.kp.kpdt,lenparameterkind=NULL())
!CHECK: .dt.kpdt.4, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.kpdt,sizeinbytes=4_8,uninstantiated=.dt.kpdt,kindparameter=.kp.kpdt.4,lenparameterkind=NULL(),component=.c.kpdt.4,procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1) !CHECK: .dt.kpdt.4, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.kpdt,sizeinbytes=4_8,uninstantiated=.dt.kpdt,kindparameter=.kp.kpdt.4,lenparameterkind=NULL(),component=.c.kpdt.4,procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1,nodefinedassignment=1_1)
!CHECK: .kp.kpdt.4, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: INTEGER(8) shape: 0_8:0_8 init:[INTEGER(8)::4_8] !CHECK: .kp.kpdt.4, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: INTEGER(8) shape: 0_8:0_8 init:[INTEGER(8)::4_8]
end module end module
@ -49,7 +49,7 @@ module m04
subroutine s1(x) subroutine s1(x)
class(tbps), intent(in) :: x class(tbps), intent(in) :: x
end subroutine end subroutine
!CHECK: .dt.tbps, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=.v.tbps,name=.n.tbps,sizeinbytes=0_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=NULL(),procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1) !CHECK: .dt.tbps, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=.v.tbps,name=.n.tbps,sizeinbytes=0_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=NULL(),procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1,nodefinedassignment=1_1)
!CHECK: .v.tbps, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(binding) shape: 0_8:1_8 init:[binding::binding(proc=s1,name=.n.b1),binding(proc=s1,name=.n.b2)] !CHECK: .v.tbps, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(binding) shape: 0_8:1_8 init:[binding::binding(proc=s1,name=.n.b1),binding(proc=s1,name=.n.b2)]
end module end module
@ -61,7 +61,7 @@ module m05
subroutine s1(x) subroutine s1(x)
class(t), intent(in) :: x class(t), intent(in) :: x
end subroutine end subroutine
!CHECK: .dt.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.t,sizeinbytes=8_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=NULL(),procptr=.p.t,special=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=0_1,nodestructionneeded=1_1,nofinalizationneeded=1_1) !CHECK: .dt.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.t,sizeinbytes=8_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=NULL(),procptr=.p.t,special=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=0_1,nodestructionneeded=1_1,nofinalizationneeded=1_1,nodefinedassignment=1_1)
!CHECK: .p.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(procptrcomponent) shape: 0_8:0_8 init:[procptrcomponent::procptrcomponent(name=.n.p1,offset=0_8,initialization=s1)] !CHECK: .p.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(procptrcomponent) shape: 0_8:0_8 init:[procptrcomponent::procptrcomponent(name=.n.p1,offset=0_8,initialization=s1)]
end module end module
@ -85,8 +85,8 @@ module m06
class(t), intent(in) :: y class(t), intent(in) :: y
end subroutine end subroutine
!CHECK: .c.t2, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(component) shape: 0_8:0_8 init:[component::component(name=.n.t,genre=1_1,category=6_1,kind=0_1,rank=0_1,offset=0_8,characterlen=value(genre=1_1,value=0_8),derived=.dt.t,lenvalue=NULL(),bounds=NULL(),initialization=NULL())] !CHECK: .c.t2, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(component) shape: 0_8:0_8 init:[component::component(name=.n.t,genre=1_1,category=6_1,kind=0_1,rank=0_1,offset=0_8,characterlen=value(genre=1_1,value=0_8),derived=.dt.t,lenvalue=NULL(),bounds=NULL(),initialization=NULL())]
!CHECK: .dt.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=.v.t,name=.n.t,sizeinbytes=0_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=NULL(),procptr=NULL(),special=.s.t,specialbitset=2_4,hasparent=0_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1) !CHECK: .dt.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=.v.t,name=.n.t,sizeinbytes=0_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=NULL(),procptr=NULL(),special=.s.t,specialbitset=2_4,hasparent=0_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1,nodefinedassignment=0_1)
!CHECK: .dt.t2, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=.v.t2,name=.n.t2,sizeinbytes=0_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.t2,procptr=NULL(),special=.s.t2,specialbitset=2_4,hasparent=1_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1) !CHECK: .dt.t2, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=.v.t2,name=.n.t2,sizeinbytes=0_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.t2,procptr=NULL(),special=.s.t2,specialbitset=2_4,hasparent=1_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1,nodefinedassignment=0_1)
!CHECK: .s.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(specialbinding) shape: 0_8:0_8 init:[specialbinding::specialbinding(which=1_1,isargdescriptorset=3_1,istypebound=1_1,isargcontiguousset=0_1,proc=s1)] !CHECK: .s.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(specialbinding) shape: 0_8:0_8 init:[specialbinding::specialbinding(which=1_1,isargdescriptorset=3_1,istypebound=1_1,isargcontiguousset=0_1,proc=s1)]
!CHECK: .s.t2, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(specialbinding) shape: 0_8:0_8 init:[specialbinding::specialbinding(which=1_1,isargdescriptorset=3_1,istypebound=1_1,isargcontiguousset=0_1,proc=s2)] !CHECK: .s.t2, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(specialbinding) shape: 0_8:0_8 init:[specialbinding::specialbinding(which=1_1,isargdescriptorset=3_1,istypebound=1_1,isargcontiguousset=0_1,proc=s2)]
!CHECK: .v.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(binding) shape: 0_8:0_8 init:[binding::binding(proc=s1,name=.n.s1)] !CHECK: .v.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(binding) shape: 0_8:0_8 init:[binding::binding(proc=s1,name=.n.s1)]
@ -113,8 +113,8 @@ module m06a
class(t2), intent(in) :: y class(t2), intent(in) :: y
end subroutine end subroutine
!CHECK: .c.t2, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(component) shape: 0_8:0_8 init:[component::component(name=.n.t,genre=1_1,category=6_1,kind=0_1,rank=0_1,offset=0_8,characterlen=value(genre=1_1,value=0_8),derived=.dt.t,lenvalue=NULL(),bounds=NULL(),initialization=NULL())] !CHECK: .c.t2, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(component) shape: 0_8:0_8 init:[component::component(name=.n.t,genre=1_1,category=6_1,kind=0_1,rank=0_1,offset=0_8,characterlen=value(genre=1_1,value=0_8),derived=.dt.t,lenvalue=NULL(),bounds=NULL(),initialization=NULL())]
!CHECK: .dt.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=.v.t,name=.n.t,sizeinbytes=0_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=NULL(),procptr=NULL(),special=.s.t,specialbitset=2_4,hasparent=0_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1) !CHECK: .dt.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=.v.t,name=.n.t,sizeinbytes=0_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=NULL(),procptr=NULL(),special=.s.t,specialbitset=2_4,hasparent=0_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1,nodefinedassignment=0_1)
!CHECK: .dt.t2, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=.v.t2,name=.n.t2,sizeinbytes=0_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.t2,procptr=NULL(),special=.s.t2,specialbitset=2_4,hasparent=1_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1) !CHECK: .dt.t2, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=.v.t2,name=.n.t2,sizeinbytes=0_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.t2,procptr=NULL(),special=.s.t2,specialbitset=2_4,hasparent=1_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1,nodefinedassignment=0_1)
!CHECK: .s.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(specialbinding) shape: 0_8:0_8 init:[specialbinding::specialbinding(which=1_1,isargdescriptorset=3_1,istypebound=1_1,isargcontiguousset=0_1,proc=s1)] !CHECK: .s.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(specialbinding) shape: 0_8:0_8 init:[specialbinding::specialbinding(which=1_1,isargdescriptorset=3_1,istypebound=1_1,isargcontiguousset=0_1,proc=s1)]
!CHECK: .s.t2, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(specialbinding) shape: 0_8:0_8 init:[specialbinding::specialbinding(which=1_1,isargdescriptorset=3_1,istypebound=1_1,isargcontiguousset=0_1,proc=s2)] !CHECK: .s.t2, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(specialbinding) shape: 0_8:0_8 init:[specialbinding::specialbinding(which=1_1,isargdescriptorset=3_1,istypebound=1_1,isargcontiguousset=0_1,proc=s2)]
!CHECK: .v.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(binding) shape: 0_8:0_8 init:[binding::binding(proc=s1,name=.n.s1)] !CHECK: .v.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(binding) shape: 0_8:0_8 init:[binding::binding(proc=s1,name=.n.s1)]
@ -132,7 +132,7 @@ module m07
class(t), intent(out) :: x class(t), intent(out) :: x
class(t), intent(in) :: y class(t), intent(in) :: y
end subroutine end subroutine
!CHECK: .dt.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=.v.t,name=.n.t,sizeinbytes=0_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=NULL(),procptr=NULL(),special=.s.t,specialbitset=4_4,hasparent=0_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1) !CHECK: .dt.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=.v.t,name=.n.t,sizeinbytes=0_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=NULL(),procptr=NULL(),special=.s.t,specialbitset=4_4,hasparent=0_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1,nodefinedassignment=0_1)
!CHECK: .s.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(specialbinding) shape: 0_8:0_8 init:[specialbinding::specialbinding(which=2_1,isargdescriptorset=3_1,istypebound=1_1,isargcontiguousset=0_1,proc=s1)] !CHECK: .s.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(specialbinding) shape: 0_8:0_8 init:[specialbinding::specialbinding(which=2_1,isargdescriptorset=3_1,istypebound=1_1,isargcontiguousset=0_1,proc=s1)]
!CHECK: .v.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(binding) shape: 0_8:0_8 init:[binding::binding(proc=s1,name=.n.s1)] !CHECK: .v.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(binding) shape: 0_8:0_8 init:[binding::binding(proc=s1,name=.n.s1)]
end module end module
@ -155,8 +155,8 @@ module m08
subroutine s4(x) subroutine s4(x)
type(t), contiguous :: x(:,:,:) type(t), contiguous :: x(:,:,:)
end subroutine end subroutine
!CHECK: .dt.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.t,sizeinbytes=0_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=NULL(),procptr=NULL(),special=.s.t,specialbitset=7296_4,hasparent=0_1,noinitializationneeded=1_1,nodestructionneeded=0_1,nofinalizationneeded=0_1) !CHECK: .dt.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.t,sizeinbytes=0_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=NULL(),procptr=NULL(),special=.s.t,specialbitset=7296_4,hasparent=0_1,noinitializationneeded=1_1,nodestructionneeded=0_1,nofinalizationneeded=0_1,nodefinedassignment=1_1)
!CHECK: .s.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(specialbinding) shape: 0_8:3_8 init:[specialbinding::specialbinding(which=7_1,isargdescriptorset=0_1,istypebound=1_1,isargcontiguousset=0_1,proc=s3),specialbinding(which=10_1,isargdescriptorset=1_1,istypebound=1_1,isargcontiguousset=0_1,proc=s1),specialbinding(which=11_1,isargdescriptorset=0_1,istypebound=1_1,isargcontiguousset=1_1,proc=s2),specialbinding(which=12_1,isargdescriptorset=1_1,istypebound=1_1,isargcontiguousset=1_1,proc=s4)] !CHECK: .s.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(specialbinding) shape: 0_8:3_8 init:[specialbinding::specialbinding(which=7_1,isargdescriptorset=0_1,istypebound=0_1,isargcontiguousset=0_1,proc=s3),specialbinding(which=10_1,isargdescriptorset=1_1,istypebound=0_1,isargcontiguousset=0_1,proc=s1),specialbinding(which=11_1,isargdescriptorset=0_1,istypebound=0_1,isargcontiguousset=1_1,proc=s2),specialbinding(which=12_1,isargdescriptorset=1_1,istypebound=0_1,isargcontiguousset=1_1,proc=s4)]
end module end module
module m09 module m09
@ -197,8 +197,8 @@ module m09
integer, intent(out) :: iostat integer, intent(out) :: iostat
character(len=*), intent(inout) :: iomsg character(len=*), intent(inout) :: iomsg
end subroutine end subroutine
!CHECK: .dt.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=.v.t,name=.n.t,sizeinbytes=0_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=NULL(),procptr=NULL(),special=.s.t,specialbitset=120_4,hasparent=0_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1) !CHECK: .dt.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=.v.t,name=.n.t,sizeinbytes=0_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=NULL(),procptr=NULL(),special=.s.t,specialbitset=120_4,hasparent=0_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1,nodefinedassignment=1_1)
!CHECK: .s.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(specialbinding) shape: 0_8:3_8 init:[specialbinding::specialbinding(which=3_1,isargdescriptorset=1_1,istypebound=1_1,isargcontiguousset=0_1,proc=rf),specialbinding(which=4_1,isargdescriptorset=1_1,istypebound=1_1,isargcontiguousset=0_1,proc=ru),specialbinding(which=5_1,isargdescriptorset=1_1,istypebound=1_1,isargcontiguousset=0_1,proc=wf),specialbinding(which=6_1,isargdescriptorset=1_1,istypebound=1_1,isargcontiguousset=0_1,proc=wu)] !CHECK: .s.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(specialbinding) shape: 0_8:3_8 init:[specialbinding::specialbinding(which=3_1,isargdescriptorset=1_1,istypebound=1_1,isargcontiguousset=0_1,proc=rf),specialbinding(which=4_1,isargdescriptorset=1_1,istypebound=2_1,isargcontiguousset=0_1,proc=ru),specialbinding(which=5_1,isargdescriptorset=1_1,istypebound=3_1,isargcontiguousset=0_1,proc=wf),specialbinding(which=6_1,isargdescriptorset=1_1,istypebound=4_1,isargcontiguousset=0_1,proc=wu)]
!CHECK: .v.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(binding) shape: 0_8:3_8 init:[binding::binding(proc=rf,name=.n.rf),binding(proc=ru,name=.n.ru),binding(proc=wf,name=.n.wf),binding(proc=wu,name=.n.wu)] !CHECK: .v.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(binding) shape: 0_8:3_8 init:[binding::binding(proc=rf,name=.n.rf),binding(proc=ru,name=.n.ru),binding(proc=wf,name=.n.wf),binding(proc=wu,name=.n.wu)]
end module end module
@ -246,7 +246,7 @@ module m10
integer, intent(out) :: iostat integer, intent(out) :: iostat
character(len=*), intent(inout) :: iomsg character(len=*), intent(inout) :: iomsg
end subroutine end subroutine
!CHECK: .dt.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.t,sizeinbytes=0_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=NULL(),procptr=NULL(),special=.s.t,specialbitset=120_4,hasparent=0_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1) !CHECK: .dt.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.t,sizeinbytes=0_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=NULL(),procptr=NULL(),special=.s.t,specialbitset=120_4,hasparent=0_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1,nodefinedassignment=1_1)
!CHECK: .s.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(specialbinding) shape: 0_8:3_8 init:[specialbinding::specialbinding(which=3_1,isargdescriptorset=0_1,istypebound=0_1,isargcontiguousset=0_1,proc=rf),specialbinding(which=4_1,isargdescriptorset=0_1,istypebound=0_1,isargcontiguousset=0_1,proc=ru),specialbinding(which=5_1,isargdescriptorset=0_1,istypebound=0_1,isargcontiguousset=0_1,proc=wf),specialbinding(which=6_1,isargdescriptorset=0_1,istypebound=0_1,isargcontiguousset=0_1,proc=wu)] !CHECK: .s.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(specialbinding) shape: 0_8:3_8 init:[specialbinding::specialbinding(which=3_1,isargdescriptorset=0_1,istypebound=0_1,isargcontiguousset=0_1,proc=rf),specialbinding(which=4_1,isargdescriptorset=0_1,istypebound=0_1,isargcontiguousset=0_1,proc=ru),specialbinding(which=5_1,isargdescriptorset=0_1,istypebound=0_1,isargcontiguousset=0_1,proc=wf),specialbinding(which=6_1,isargdescriptorset=0_1,istypebound=0_1,isargcontiguousset=0_1,proc=wu)]
end module end module
@ -263,7 +263,7 @@ module m11
!CHECK: .c.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(component) shape: 0_8:3_8 init:[component::component(name=.n.allocatable,genre=3_1,category=2_1,kind=4_1,rank=1_1,offset=0_8,characterlen=value(genre=1_1,value=0_8),derived=NULL(),lenvalue=NULL(),bounds=NULL(),initialization=NULL()),component(name=.n.pointer,genre=2_1,category=2_1,kind=4_1,rank=0_1,offset=48_8,characterlen=value(genre=1_1,value=0_8),derived=NULL(),lenvalue=NULL(),bounds=NULL(),initialization=.di.t.pointer),component(name=.n.chauto,genre=4_1,category=4_1,kind=1_1,rank=0_1,offset=72_8,characterlen=value(genre=3_1,value=0_8),derived=NULL(),lenvalue=NULL(),bounds=NULL(),initialization=NULL()),component(name=.n.automatic,genre=4_1,category=2_1,kind=4_1,rank=1_1,offset=96_8,characterlen=value(genre=1_1,value=0_8),derived=NULL(),lenvalue=NULL(),bounds=.b.t.automatic,initialization=NULL())] !CHECK: .c.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(component) shape: 0_8:3_8 init:[component::component(name=.n.allocatable,genre=3_1,category=2_1,kind=4_1,rank=1_1,offset=0_8,characterlen=value(genre=1_1,value=0_8),derived=NULL(),lenvalue=NULL(),bounds=NULL(),initialization=NULL()),component(name=.n.pointer,genre=2_1,category=2_1,kind=4_1,rank=0_1,offset=48_8,characterlen=value(genre=1_1,value=0_8),derived=NULL(),lenvalue=NULL(),bounds=NULL(),initialization=.di.t.pointer),component(name=.n.chauto,genre=4_1,category=4_1,kind=1_1,rank=0_1,offset=72_8,characterlen=value(genre=3_1,value=0_8),derived=NULL(),lenvalue=NULL(),bounds=NULL(),initialization=NULL()),component(name=.n.automatic,genre=4_1,category=2_1,kind=4_1,rank=1_1,offset=96_8,characterlen=value(genre=1_1,value=0_8),derived=NULL(),lenvalue=NULL(),bounds=.b.t.automatic,initialization=NULL())]
!CHECK: .di.t.pointer, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(.dp.t.pointer) init:.dp.t.pointer(pointer=target) !CHECK: .di.t.pointer, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(.dp.t.pointer) init:.dp.t.pointer(pointer=target)
!CHECK: .dp.t.pointer (CompilerCreated): DerivedType components: pointer !CHECK: .dp.t.pointer (CompilerCreated): DerivedType components: pointer
!CHECK: .dt.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.t,sizeinbytes=144_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=.lpk.t,component=.c.t,procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=0_1,nodestructionneeded=0_1,nofinalizationneeded=1_1) !CHECK: .dt.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.t,sizeinbytes=144_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=.lpk.t,component=.c.t,procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=0_1,nodestructionneeded=0_1,nofinalizationneeded=1_1,nodefinedassignment=1_1)
!CHECK: .lpk.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: INTEGER(1) shape: 0_8:0_8 init:[INTEGER(1)::8_1] !CHECK: .lpk.t, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: INTEGER(1) shape: 0_8:0_8 init:[INTEGER(1)::8_1]
!CHECK: DerivedType scope: .dp.t.pointer size=24 alignment=8 instantiation of .dp.t.pointer !CHECK: DerivedType scope: .dp.t.pointer size=24 alignment=8 instantiation of .dp.t.pointer
!CHECK: pointer, POINTER size=24 offset=0: ObjectEntity type: REAL(4) !CHECK: pointer, POINTER size=24 offset=0: ObjectEntity type: REAL(4)

View File

@ -6,4 +6,4 @@ module m
class(*), pointer :: sp, ap(:) class(*), pointer :: sp, ap(:)
end type end type
end module end module
!CHECK: .dt.haspointer, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.haspointer,sizeinbytes=104_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.haspointer,procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=0_1,nodestructionneeded=1_1,nofinalizationneeded=1_1) !CHECK: .dt.haspointer, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.haspointer,sizeinbytes=104_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.haspointer,procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=0_1,nodestructionneeded=1_1,nofinalizationneeded=1_1,nodefinedassignment=1_1)

View File

@ -7,18 +7,18 @@ module m
contains contains
final :: final final :: final
end type end type
!CHECK: .dt.finalizable, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.finalizable,sizeinbytes=0_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=NULL(),procptr=NULL(),special=.s.finalizable,specialbitset=128_4,hasparent=0_1,noinitializationneeded=1_1,nodestructionneeded=0_1,nofinalizationneeded=0_1) !CHECK: .dt.finalizable, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.finalizable,sizeinbytes=0_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=NULL(),procptr=NULL(),special=.s.finalizable,specialbitset=128_4,hasparent=0_1,noinitializationneeded=1_1,nodestructionneeded=0_1,nofinalizationneeded=0_1,nodefinedassignment=1_1)
type, abstract :: t1 type, abstract :: t1
end type end type
!CHECK: .dt.t1, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(name=.n.t1,sizeinbytes=0_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=NULL(),procptr=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1) !CHECK: .dt.t1, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(name=.n.t1,sizeinbytes=0_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=NULL(),procptr=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1,nodefinedassignment=1_1)
type, abstract :: t2 type, abstract :: t2
real, allocatable :: a(:) real, allocatable :: a(:)
end type end type
!CHECK: .dt.t2, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(name=.n.t2,sizeinbytes=48_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.t2,procptr=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=0_1,nodestructionneeded=0_1,nofinalizationneeded=1_1) !CHECK: .dt.t2, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(name=.n.t2,sizeinbytes=48_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.t2,procptr=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=0_1,nodestructionneeded=0_1,nofinalizationneeded=1_1,nodefinedassignment=1_1)
type, abstract :: t3 type, abstract :: t3
type(finalizable) :: x type(finalizable) :: x
end type end type
!CHECK: .dt.t3, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(name=.n.t3,sizeinbytes=0_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.t3,procptr=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=1_1,nodestructionneeded=0_1,nofinalizationneeded=0_1) !CHECK: .dt.t3, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(name=.n.t3,sizeinbytes=0_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.t3,procptr=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=1_1,nodestructionneeded=0_1,nofinalizationneeded=0_1,nodefinedassignment=1_1)
contains contains
impure elemental subroutine final(x) impure elemental subroutine final(x)
type(finalizable), intent(in out) :: x type(finalizable), intent(in out) :: x

View File

@ -7,10 +7,10 @@ program main
type t1 type t1
type(t2), pointer :: b type(t2), pointer :: b
end type t1 end type t1
!CHECK: .dt.t1, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.t1,sizeinbytes=40_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.t1,procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=0_1,nodestructionneeded=1_1,nofinalizationneeded=1_1) !CHECK: .dt.t1, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.t1,sizeinbytes=40_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.t1,procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=0_1,nodestructionneeded=1_1,nofinalizationneeded=1_1,nodefinedassignment=1_1)
type :: t2 type :: t2
type(t1) :: a type(t1) :: a
end type t2 end type t2
! CHECK: .dt.t2, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.t2,sizeinbytes=40_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.t2,procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=0_1,nodestructionneeded=1_1,nofinalizationneeded=1_1) ! CHECK: .dt.t2, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.t2,sizeinbytes=40_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.t2,procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=0_1,nodestructionneeded=1_1,nofinalizationneeded=1_1,nodefinedassignment=1_1)
end program main end program main

View File

@ -7,10 +7,10 @@ program main
type t1 type t1
type(t2), allocatable :: b type(t2), allocatable :: b
end type t1 end type t1
!CHECK: .dt.t1, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.t1,sizeinbytes=40_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.t1,procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=0_1,nodestructionneeded=0_1,nofinalizationneeded=1_1) !CHECK: .dt.t1, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.t1,sizeinbytes=40_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.t1,procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=0_1,nodestructionneeded=0_1,nofinalizationneeded=1_1,nodefinedassignment=1_1)
type :: t2 type :: t2
type(t1) :: a type(t1) :: a
end type t2 end type t2
! CHECK: .dt.t2, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.t2,sizeinbytes=40_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.t2,procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=0_1,nodestructionneeded=0_1,nofinalizationneeded=1_1) ! CHECK: .dt.t2, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.t2,sizeinbytes=40_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.t2,procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=0_1,nodestructionneeded=0_1,nofinalizationneeded=1_1,nodefinedassignment=1_1)
end program main end program main

View File

@ -16,7 +16,7 @@
type(t_container_extension) :: wrapper type(t_container_extension) :: wrapper
end type end type
end end
! CHECK: .dt.t_container, SAVE, TARGET (CompilerCreated, ReadOnly): {{.*}}noinitializationneeded=0_1,nodestructionneeded=0_1,nofinalizationneeded=0_1) ! CHECK: .dt.t_container, SAVE, TARGET (CompilerCreated, ReadOnly): {{.*}}noinitializationneeded=0_1,nodestructionneeded=0_1,nofinalizationneeded=0_1,nodefinedassignment=0_1)
! CHECK: .dt.t_container_extension, SAVE, TARGET (CompilerCreated, ReadOnly): {{.*}}noinitializationneeded=0_1,nodestructionneeded=0_1,nofinalizationneeded=0_1) ! CHECK: .dt.t_container_extension, SAVE, TARGET (CompilerCreated, ReadOnly): {{.*}}noinitializationneeded=0_1,nodestructionneeded=0_1,nofinalizationneeded=0_1,nodefinedassignment=0_1)
! CHECK: .dt.t_container_not_polymorphic, SAVE, TARGET (CompilerCreated, ReadOnly): {{.*}}noinitializationneeded=0_1,nodestructionneeded=0_1,nofinalizationneeded=1_1) ! CHECK: .dt.t_container_not_polymorphic, SAVE, TARGET (CompilerCreated, ReadOnly): {{.*}}noinitializationneeded=0_1,nodestructionneeded=0_1,nofinalizationneeded=1_1,nodefinedassignment=1_1)
! CHECK: .dt.t_container_wrapper, SAVE, TARGET (CompilerCreated, ReadOnly): {{.*}}noinitializationneeded=0_1,nodestructionneeded=0_1,nofinalizationneeded=0_1) ! CHECK: .dt.t_container_wrapper, SAVE, TARGET (CompilerCreated, ReadOnly): {{.*}}noinitializationneeded=0_1,nodestructionneeded=0_1,nofinalizationneeded=0_1,nodefinedassignment=0_1)

View File

@ -13,7 +13,7 @@ end module
!CHECK: Module scope: m size=0 alignment=1 sourceRange=113 bytes !CHECK: Module scope: m size=0 alignment=1 sourceRange=113 bytes
!CHECK: .c.s, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(component) shape: 0_8:0_8 init:[component::component(name=.n.t1,genre=1_1,category=6_1,kind=0_1,rank=0_1,offset=0_8,characterlen=value(genre=1_1,value=0_8),lenvalue=NULL(),bounds=NULL(),initialization=NULL())] !CHECK: .c.s, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(component) shape: 0_8:0_8 init:[component::component(name=.n.t1,genre=1_1,category=6_1,kind=0_1,rank=0_1,offset=0_8,characterlen=value(genre=1_1,value=0_8),lenvalue=NULL(),bounds=NULL(),initialization=NULL())]
!CHECK: .dt.s, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.s,sizeinbytes=0_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=.lpk.s,component=.c.s,procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1) !CHECK: .dt.s, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.s,sizeinbytes=0_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=.lpk.s,component=.c.s,procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1,nodefinedassignment=1_1)
!CHECK: .lpk.s, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: INTEGER(1) shape: 0_8:0_8 init:[INTEGER(1)::4_1] !CHECK: .lpk.s, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: INTEGER(1) shape: 0_8:0_8 init:[INTEGER(1)::4_1]
!CHECK: .n.s, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: CHARACTER(1_8,1) init:"s" !CHECK: .n.s, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: CHARACTER(1_8,1) init:"s"
!CHECK: .n.t1, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: CHARACTER(2_8,1) init:"t1" !CHECK: .n.t1, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: CHARACTER(2_8,1) init:"t1"

View File

@ -14,4 +14,4 @@ end type
type(t2) x type(t2) x
end end
!CHECK: .dt.t2, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.t2,sizeinbytes=40_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.t2,procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=0_1,nodestructionneeded=0_1,nofinalizationneeded=0_1) !CHECK: .dt.t2, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.t2,sizeinbytes=40_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.t2,procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=0_1,nodestructionneeded=0_1,nofinalizationneeded=0_1,nodefinedassignment=0_1)

View File

@ -0,0 +1,67 @@
!RUN: bbc --dump-symbols %s | FileCheck %s
!Check "nodefinedassignment" settings.
module m01
type hasAsst1
contains
procedure asst1
generic :: assignment(=) => asst1
end type
!CHECK: .dt.hasasst1, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=.v.hasasst1,name=.n.hasasst1,sizeinbytes=0_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=NULL(),procptr=NULL(),special=.s.hasasst1,specialbitset=4_4,hasparent=0_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1,nodefinedassignment=0_1)
type hasAsst2 ! no defined assignment relevant to the runtime
end type
interface assignment(=)
procedure asst2
end interface
!CHECK: .dt.hasasst2, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.hasasst2,sizeinbytes=0_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=NULL(),procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1,nodefinedassignment=1_1)
type test1
type(hasAsst1) c
end type
!CHECK: .dt.test1, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.test1,sizeinbytes=0_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.test1,procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1,nodefinedassignment=0_1)
type test2
type(hasAsst2) c
end type
!CHECK: .dt.test2, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.test2,sizeinbytes=0_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.test2,procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1,nodefinedassignment=1_1)
type test3
type(hasAsst1), pointer :: p
end type
!CHECK: .dt.test3, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.test3,sizeinbytes=40_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.test3,procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=0_1,nodestructionneeded=1_1,nofinalizationneeded=1_1,nodefinedassignment=1_1)
type test4
type(hasAsst2), pointer :: p
end type
!CHECK: .dt.test4, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.test4,sizeinbytes=40_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.test4,procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=0_1,nodestructionneeded=1_1,nofinalizationneeded=1_1,nodefinedassignment=1_1)
type, extends(hasAsst1) :: test5
end type
!CHECK: .dt.test5, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=.v.test5,name=.n.test5,sizeinbytes=0_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.test5,procptr=NULL(),special=.s.test5,specialbitset=4_4,hasparent=1_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1,nodefinedassignment=0_1)
type, extends(hasAsst2) :: test6
end type
!CHECK: .dt.test6, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.test6,sizeinbytes=0_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.test6,procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=1_1,noinitializationneeded=1_1,nodestructionneeded=1_1,nofinalizationneeded=1_1,nodefinedassignment=1_1)
type test7
type(test7), allocatable :: c
end type
!CHECK: .dt.test7, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.test7,sizeinbytes=40_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.test7,procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=0_1,nodestructionneeded=0_1,nofinalizationneeded=1_1,nodefinedassignment=1_1)
type test8
class(test8), allocatable :: c
end type
!CHECK: .dt.test8, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(derivedtype) init:derivedtype(binding=NULL(),name=.n.test8,sizeinbytes=40_8,uninstantiated=NULL(),kindparameter=NULL(),lenparameterkind=NULL(),component=.c.test8,procptr=NULL(),special=NULL(),specialbitset=0_4,hasparent=0_1,noinitializationneeded=0_1,nodestructionneeded=0_1,nofinalizationneeded=0_1,nodefinedassignment=0_1)
contains
impure elemental subroutine asst1(left, right)
class(hasAsst1), intent(out) :: left
class(hasAsst1), intent(in) :: right
end
impure elemental subroutine asst2(left, right)
class(hasAsst2), intent(out) :: left
class(hasAsst2), intent(in) :: right
end
end

View File

@ -22,5 +22,5 @@ module m
end end
end end
!CHECK: .s.child, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(specialbinding) shape: 0_8:0_8 init:[specialbinding::specialbinding(which=2_1,isargdescriptorset=1_1,istypebound=1_1,isargcontiguousset=0_1,proc=override)] !CHECK: .s.child, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(specialbinding) shape: 0_8:0_8 init:[specialbinding::specialbinding(which=2_1,isargdescriptorset=1_1,istypebound=2_1,isargcontiguousset=0_1,proc=override)]
!CHECK: .v.child, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(binding) shape: 0_8:1_8 init:[binding::binding(proc=baseassign,name=.n.baseassign),binding(proc=override,name=.n.override)] !CHECK: .v.child, SAVE, TARGET (CompilerCreated, ReadOnly): ObjectEntity type: TYPE(binding) shape: 0_8:1_8 init:[binding::binding(proc=baseassign,name=.n.baseassign),binding(proc=override,name=.n.override)]