xref: /llvm-project/flang/lib/Semantics/pointer-assignment.cpp (revision 2ab9990c9eb79682a4d4b183dfbc7612d3e55328)
1 //===-- lib/Semantics/pointer-assignment.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 "pointer-assignment.h"
10 #include "flang/Common/idioms.h"
11 #include "flang/Common/restorer.h"
12 #include "flang/Evaluate/characteristics.h"
13 #include "flang/Evaluate/expression.h"
14 #include "flang/Evaluate/fold.h"
15 #include "flang/Evaluate/tools.h"
16 #include "flang/Parser/message.h"
17 #include "flang/Parser/parse-tree-visitor.h"
18 #include "flang/Parser/parse-tree.h"
19 #include "flang/Semantics/expression.h"
20 #include "flang/Semantics/symbol.h"
21 #include "flang/Semantics/tools.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include <optional>
24 #include <set>
25 #include <string>
26 #include <type_traits>
27 
28 // Semantic checks for pointer assignment.
29 
30 namespace Fortran::semantics {
31 
32 using namespace parser::literals;
33 using evaluate::characteristics::DummyDataObject;
34 using evaluate::characteristics::FunctionResult;
35 using evaluate::characteristics::Procedure;
36 using evaluate::characteristics::TypeAndShape;
37 using parser::MessageFixedText;
38 using parser::MessageFormattedText;
39 
40 class PointerAssignmentChecker {
41 public:
42   PointerAssignmentChecker(evaluate::FoldingContext &context,
43       parser::CharBlock source, const std::string &description)
44       : context_{context}, source_{source}, description_{description} {}
45   PointerAssignmentChecker(evaluate::FoldingContext &context, const Symbol &lhs)
46       : context_{context}, source_{lhs.name()},
47         description_{"pointer '"s + lhs.name().ToString() + '\''}, lhs_{&lhs} {
48     set_lhsType(TypeAndShape::Characterize(lhs, context));
49     set_isContiguous(lhs.attrs().test(Attr::CONTIGUOUS));
50     set_isVolatile(lhs.attrs().test(Attr::VOLATILE));
51     if (IsProcedure(lhs)) {
52       procedure_ = Procedure::Characterize(lhs, context);
53     }
54   }
55   PointerAssignmentChecker &set_lhsType(std::optional<TypeAndShape> &&);
56   PointerAssignmentChecker &set_isContiguous(bool);
57   PointerAssignmentChecker &set_isVolatile(bool);
58   PointerAssignmentChecker &set_isBoundsRemapping(bool);
59   bool Check(const SomeExpr &);
60 
61 private:
62   template <typename T> bool Check(const T &);
63   template <typename T> bool Check(const evaluate::Expr<T> &);
64   template <typename T> bool Check(const evaluate::FunctionRef<T> &);
65   template <typename T> bool Check(const evaluate::Designator<T> &);
66   bool Check(const evaluate::NullPointer &);
67   bool Check(const evaluate::ProcedureDesignator &);
68   bool Check(const evaluate::ProcedureRef &);
69   // Target is a procedure
70   bool Check(
71       parser::CharBlock rhsName, bool isCall, const Procedure * = nullptr);
72   bool LhsOkForUnlimitedPoly() const;
73   template <typename... A> parser::Message *Say(A &&...);
74 
75   evaluate::FoldingContext &context_;
76   const parser::CharBlock source_;
77   const std::string description_;
78   const Symbol *lhs_{nullptr};
79   std::optional<TypeAndShape> lhsType_;
80   std::optional<Procedure> procedure_;
81   bool isContiguous_{false};
82   bool isVolatile_{false};
83   bool isBoundsRemapping_{false};
84 };
85 
86 PointerAssignmentChecker &PointerAssignmentChecker::set_lhsType(
87     std::optional<TypeAndShape> &&lhsType) {
88   lhsType_ = std::move(lhsType);
89   return *this;
90 }
91 
92 PointerAssignmentChecker &PointerAssignmentChecker::set_isContiguous(
93     bool isContiguous) {
94   isContiguous_ = isContiguous;
95   return *this;
96 }
97 
98 PointerAssignmentChecker &PointerAssignmentChecker::set_isVolatile(
99     bool isVolatile) {
100   isVolatile_ = isVolatile;
101   return *this;
102 }
103 
104 PointerAssignmentChecker &PointerAssignmentChecker::set_isBoundsRemapping(
105     bool isBoundsRemapping) {
106   isBoundsRemapping_ = isBoundsRemapping;
107   return *this;
108 }
109 
110 template <typename T> bool PointerAssignmentChecker::Check(const T &) {
111   // Catch-all case for really bad target expression
112   Say("Target associated with %s must be a designator or a call to a"
113       " pointer-valued function"_err_en_US,
114       description_);
115   return false;
116 }
117 
118 template <typename T>
119 bool PointerAssignmentChecker::Check(const evaluate::Expr<T> &x) {
120   return common::visit([&](const auto &x) { return Check(x); }, x.u);
121 }
122 
123 bool PointerAssignmentChecker::Check(const SomeExpr &rhs) {
124   if (HasVectorSubscript(rhs)) { // C1025
125     Say("An array section with a vector subscript may not be a pointer target"_err_en_US);
126     return false;
127   } else if (ExtractCoarrayRef(rhs)) { // C1026
128     Say("A coindexed object may not be a pointer target"_err_en_US);
129     return false;
130   } else {
131     return common::visit([&](const auto &x) { return Check(x); }, rhs.u);
132   }
133 }
134 
135 bool PointerAssignmentChecker::Check(const evaluate::NullPointer &) {
136   return true; // P => NULL() without MOLD=; always OK
137 }
138 
139 template <typename T>
140 bool PointerAssignmentChecker::Check(const evaluate::FunctionRef<T> &f) {
141   std::string funcName;
142   const auto *symbol{f.proc().GetSymbol()};
143   if (symbol) {
144     funcName = symbol->name().ToString();
145   } else if (const auto *intrinsic{f.proc().GetSpecificIntrinsic()}) {
146     funcName = intrinsic->name;
147   }
148   auto proc{Procedure::Characterize(f.proc(), context_)};
149   if (!proc) {
150     return false;
151   }
152   std::optional<MessageFixedText> msg;
153   const auto &funcResult{proc->functionResult}; // C1025
154   if (!funcResult) {
155     msg = "%s is associated with the non-existent result of reference to"
156           " procedure"_err_en_US;
157   } else if (procedure_) {
158     // Shouldn't be here in this function unless lhs is an object pointer.
159     msg = "Procedure %s is associated with the result of a reference to"
160           " function '%s' that does not return a procedure pointer"_err_en_US;
161   } else if (funcResult->IsProcedurePointer()) {
162     msg = "Object %s is associated with the result of a reference to"
163           " function '%s' that is a procedure pointer"_err_en_US;
164   } else if (!funcResult->attrs.test(FunctionResult::Attr::Pointer)) {
165     msg = "%s is associated with the result of a reference to function '%s'"
166           " that is a not a pointer"_err_en_US;
167   } else if (isContiguous_ &&
168       !funcResult->attrs.test(FunctionResult::Attr::Contiguous)) {
169     msg = "CONTIGUOUS %s is associated with the result of reference to"
170           " function '%s' that is not contiguous"_err_en_US;
171   } else if (lhsType_) {
172     const auto *frTypeAndShape{funcResult->GetTypeAndShape()};
173     CHECK(frTypeAndShape);
174     if (!lhsType_->IsCompatibleWith(context_.messages(), *frTypeAndShape,
175             "pointer", "function result",
176             isBoundsRemapping_ /*omit shape check*/,
177             evaluate::CheckConformanceFlags::BothDeferredShape)) {
178       return false; // IsCompatibleWith() emitted message
179     }
180   }
181   if (msg) {
182     auto restorer{common::ScopedSet(lhs_, symbol)};
183     Say(*msg, description_, funcName);
184     return false;
185   }
186   return true;
187 }
188 
189 template <typename T>
190 bool PointerAssignmentChecker::Check(const evaluate::Designator<T> &d) {
191   const Symbol *last{d.GetLastSymbol()};
192   const Symbol *base{d.GetBaseObject().symbol()};
193   if (!last || !base) {
194     // P => "character literal"(1:3)
195     context_.messages().Say("Pointer target is not a named entity"_err_en_US);
196     return false;
197   }
198   std::optional<std::variant<MessageFixedText, MessageFormattedText>> msg;
199   if (procedure_) {
200     // Shouldn't be here in this function unless lhs is an object pointer.
201     msg = "In assignment to procedure %s, the target is not a procedure or"
202           " procedure pointer"_err_en_US;
203   } else if (!evaluate::GetLastTarget(GetSymbolVector(d))) { // C1025
204     msg = "In assignment to object %s, the target '%s' is not an object with"
205           " POINTER or TARGET attributes"_err_en_US;
206   } else if (auto rhsType{TypeAndShape::Characterize(d, context_)}) {
207     if (!lhsType_) {
208       msg = "%s associated with object '%s' with incompatible type or"
209             " shape"_err_en_US;
210     } else if (rhsType->corank() > 0 &&
211         (isVolatile_ != last->attrs().test(Attr::VOLATILE))) { // C1020
212       // TODO: what if A is VOLATILE in A%B%C?  need a better test here
213       if (isVolatile_) {
214         msg = "Pointer may not be VOLATILE when target is a"
215               " non-VOLATILE coarray"_err_en_US;
216       } else {
217         msg = "Pointer must be VOLATILE when target is a"
218               " VOLATILE coarray"_err_en_US;
219       }
220     } else if (rhsType->type().IsUnlimitedPolymorphic()) {
221       if (!LhsOkForUnlimitedPoly()) {
222         msg = "Pointer type must be unlimited polymorphic or non-extensible"
223               " derived type when target is unlimited polymorphic"_err_en_US;
224       }
225     } else {
226       if (!lhsType_->type().IsTkCompatibleWith(rhsType->type())) {
227         msg = MessageFormattedText{
228             "Target type %s is not compatible with pointer type %s"_err_en_US,
229             rhsType->type().AsFortran(), lhsType_->type().AsFortran()};
230 
231       } else if (!isBoundsRemapping_) {
232         int lhsRank{evaluate::GetRank(lhsType_->shape())};
233         int rhsRank{evaluate::GetRank(rhsType->shape())};
234         if (lhsRank != rhsRank) {
235           msg = MessageFormattedText{
236               "Pointer has rank %d but target has rank %d"_err_en_US, lhsRank,
237               rhsRank};
238         }
239       }
240     }
241   }
242   if (msg) {
243     auto restorer{common::ScopedSet(lhs_, last)};
244     if (auto *m{std::get_if<MessageFixedText>(&*msg)}) {
245       std::string buf;
246       llvm::raw_string_ostream ss{buf};
247       d.AsFortran(ss);
248       Say(*m, description_, ss.str());
249     } else {
250       Say(std::get<MessageFormattedText>(*msg));
251     }
252     return false;
253   }
254   return true;
255 }
256 
257 // Common handling for procedure pointer right-hand sides
258 bool PointerAssignmentChecker::Check(
259     parser::CharBlock rhsName, bool isCall, const Procedure *rhsProcedure) {
260   if (std::optional<MessageFixedText> msg{
261           evaluate::CheckProcCompatibility(isCall, procedure_, rhsProcedure)}) {
262     Say(std::move(*msg), description_, rhsName);
263     return false;
264   }
265   return true;
266 }
267 
268 bool PointerAssignmentChecker::Check(const evaluate::ProcedureDesignator &d) {
269   if (auto chars{Procedure::Characterize(d, context_)}) {
270     return Check(d.GetName(), false, &*chars);
271   } else {
272     return Check(d.GetName(), false);
273   }
274 }
275 
276 bool PointerAssignmentChecker::Check(const evaluate::ProcedureRef &ref) {
277   const Procedure *procedure{nullptr};
278   auto chars{Procedure::Characterize(ref, context_)};
279   if (chars) {
280     procedure = &*chars;
281     if (chars->functionResult) {
282       if (const auto *proc{chars->functionResult->IsProcedurePointer()}) {
283         procedure = proc;
284       }
285     }
286   }
287   return Check(ref.proc().GetName(), true, procedure);
288 }
289 
290 // The target can be unlimited polymorphic if the pointer is, or if it is
291 // a non-extensible derived type.
292 bool PointerAssignmentChecker::LhsOkForUnlimitedPoly() const {
293   const auto &type{lhsType_->type()};
294   if (type.category() != TypeCategory::Derived || type.IsAssumedType()) {
295     return false;
296   } else if (type.IsUnlimitedPolymorphic()) {
297     return true;
298   } else {
299     return !IsExtensibleType(&type.GetDerivedTypeSpec());
300   }
301 }
302 
303 template <typename... A>
304 parser::Message *PointerAssignmentChecker::Say(A &&...x) {
305   auto *msg{context_.messages().Say(std::forward<A>(x)...)};
306   if (msg) {
307     if (lhs_) {
308       return evaluate::AttachDeclaration(msg, *lhs_);
309     }
310     if (!source_.empty()) {
311       msg->Attach(source_, "Declaration of %s"_en_US, description_);
312     }
313   }
314   return msg;
315 }
316 
317 // Verify that any bounds on the LHS of a pointer assignment are valid.
318 // Return true if it is a bound-remapping so we can perform further checks.
319 static bool CheckPointerBounds(
320     evaluate::FoldingContext &context, const evaluate::Assignment &assignment) {
321   auto &messages{context.messages()};
322   const SomeExpr &lhs{assignment.lhs};
323   const SomeExpr &rhs{assignment.rhs};
324   bool isBoundsRemapping{false};
325   std::size_t numBounds{common::visit(
326       common::visitors{
327           [&](const evaluate::Assignment::BoundsSpec &bounds) {
328             return bounds.size();
329           },
330           [&](const evaluate::Assignment::BoundsRemapping &bounds) {
331             isBoundsRemapping = true;
332             evaluate::ExtentExpr lhsSizeExpr{1};
333             for (const auto &bound : bounds) {
334               lhsSizeExpr = std::move(lhsSizeExpr) *
335                   (common::Clone(bound.second) - common::Clone(bound.first) +
336                       evaluate::ExtentExpr{1});
337             }
338             if (std::optional<std::int64_t> lhsSize{evaluate::ToInt64(
339                     evaluate::Fold(context, std::move(lhsSizeExpr)))}) {
340               if (auto shape{evaluate::GetShape(context, rhs)}) {
341                 if (std::optional<std::int64_t> rhsSize{
342                         evaluate::ToInt64(evaluate::Fold(
343                             context, evaluate::GetSize(std::move(*shape))))}) {
344                   if (*lhsSize > *rhsSize) {
345                     messages.Say(
346                         "Pointer bounds require %d elements but target has"
347                         " only %d"_err_en_US,
348                         *lhsSize, *rhsSize); // 10.2.2.3(9)
349                   }
350                 }
351               }
352             }
353             return bounds.size();
354           },
355           [](const auto &) -> std::size_t {
356             DIE("not valid for pointer assignment");
357           },
358       },
359       assignment.u)};
360   if (numBounds > 0) {
361     if (lhs.Rank() != static_cast<int>(numBounds)) {
362       messages.Say("Pointer '%s' has rank %d but the number of bounds specified"
363                    " is %d"_err_en_US,
364           lhs.AsFortran(), lhs.Rank(), numBounds); // C1018
365     }
366   }
367   if (isBoundsRemapping && rhs.Rank() != 1 &&
368       !evaluate::IsSimplyContiguous(rhs, context)) {
369     messages.Say("Pointer bounds remapping target must have rank 1 or be"
370                  " simply contiguous"_err_en_US); // 10.2.2.3(9)
371   }
372   return isBoundsRemapping;
373 }
374 
375 bool CheckPointerAssignment(
376     evaluate::FoldingContext &context, const evaluate::Assignment &assignment) {
377   return CheckPointerAssignment(context, assignment.lhs, assignment.rhs,
378       CheckPointerBounds(context, assignment));
379 }
380 
381 bool CheckPointerAssignment(evaluate::FoldingContext &context,
382     const SomeExpr &lhs, const SomeExpr &rhs, bool isBoundsRemapping) {
383   const Symbol *pointer{GetLastSymbol(lhs)};
384   if (!pointer) {
385     return false; // error was reported
386   }
387   if (!IsPointer(pointer->GetUltimate())) {
388     evaluate::SayWithDeclaration(context.messages(), *pointer,
389         "'%s' is not a pointer"_err_en_US, pointer->name());
390     return false;
391   }
392   if (pointer->has<ProcEntityDetails>() && evaluate::ExtractCoarrayRef(lhs)) {
393     context.messages().Say( // C1027
394         "Procedure pointer may not be a coindexed object"_err_en_US);
395     return false;
396   }
397   return PointerAssignmentChecker{context, *pointer}
398       .set_isBoundsRemapping(isBoundsRemapping)
399       .Check(rhs);
400 }
401 
402 bool CheckPointerAssignment(
403     evaluate::FoldingContext &context, const Symbol &lhs, const SomeExpr &rhs) {
404   CHECK(IsPointer(lhs));
405   return PointerAssignmentChecker{context, lhs}.Check(rhs);
406 }
407 
408 bool CheckPointerAssignment(evaluate::FoldingContext &context,
409     parser::CharBlock source, const std::string &description,
410     const DummyDataObject &lhs, const SomeExpr &rhs) {
411   return PointerAssignmentChecker{context, source, description}
412       .set_lhsType(common::Clone(lhs.type))
413       .set_isContiguous(lhs.attrs.test(DummyDataObject::Attr::Contiguous))
414       .set_isVolatile(lhs.attrs.test(DummyDataObject::Attr::Volatile))
415       .Check(rhs);
416 }
417 
418 bool CheckInitialTarget(evaluate::FoldingContext &context,
419     const SomeExpr &pointer, const SomeExpr &init) {
420   return evaluate::IsInitialDataTarget(init, &context.messages()) &&
421       CheckPointerAssignment(context, pointer, init);
422 }
423 
424 } // namespace Fortran::semantics
425