1 //===-- runtime/misc-intrinsic.cpp ----------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "misc-intrinsic.h"
10 #include "descriptor.h"
11 #include "terminator.h"
12 #include <algorithm>
13 #include <cstring>
14 
15 namespace Fortran::runtime {
16 extern "C" {
17 
18 void RTNAME(Transfer)(Descriptor &result, const Descriptor &source,
19     const Descriptor &mold, const char *sourceFile, int line) {
20   if (mold.rank() > 0) {
21     std::size_t moldElementBytes{mold.ElementBytes()};
22     std::size_t elements{
23         (source.Elements() * source.ElementBytes() + moldElementBytes - 1) /
24         moldElementBytes};
25     return RTNAME(TransferSize)(result, source, mold, sourceFile, line,
26         static_cast<std::int64_t>(elements));
27   } else {
28     return RTNAME(TransferSize)(result, source, mold, sourceFile, line, 1);
29   }
30 }
31 
32 void RTNAME(TransferSize)(Descriptor &result, const Descriptor &source,
33     const Descriptor &mold, const char *sourceFile, int line,
34     std::int64_t size) {
35   int rank{mold.rank() > 0 ? 1 : 0};
36   std::size_t elementBytes{mold.ElementBytes()};
37   result.Establish(mold.type(), elementBytes, nullptr, rank, nullptr,
38       CFI_attribute_allocatable, mold.Addendum() != nullptr);
39   if (rank > 0) {
40     result.GetDimension(0).SetBounds(1, size);
41   }
42   if (const DescriptorAddendum * addendum{mold.Addendum()}) {
43     *result.Addendum() = *addendum;
44   }
45   if (int stat{result.Allocate()}) {
46     Terminator{sourceFile, line}.Crash(
47         "TRANSFER: could not allocate memory for result; STAT=%d", stat);
48   }
49   char *to{result.OffsetElement<char>()};
50   std::size_t resultBytes{size * elementBytes};
51   const std::size_t sourceElementBytes{source.ElementBytes()};
52   std::size_t sourceElements{source.Elements()};
53   SubscriptValue sourceAt[maxRank];
54   source.GetLowerBounds(sourceAt);
55   while (resultBytes > 0 && sourceElements > 0) {
56     std::size_t toMove{std::min(resultBytes, sourceElementBytes)};
57     std::memcpy(to, source.Element<char>(sourceAt), toMove);
58     to += toMove;
59     resultBytes -= toMove;
60     --sourceElements;
61     source.IncrementSubscripts(sourceAt);
62   }
63   if (resultBytes > 0) {
64     std::memset(to, 0, resultBytes);
65   }
66 }
67 
68 } // extern "C"
69 } // namespace Fortran::runtime
70