xref: /llvm-project/flang/lib/Semantics/pointer-assignment.cpp (revision bcb2591b6ca00365cb9f99efafeb3bfe8682f002)
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 std::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 std::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", false /*elemental*/,
176             evaluate::CheckConformanceFlags::BothDeferredShape)) {
177       return false; // IsCompatibleWith() emitted message
178     }
179   }
180   if (msg) {
181     auto restorer{common::ScopedSet(lhs_, symbol)};
182     Say(*msg, description_, funcName);
183     return false;
184   }
185   return true;
186 }
187 
188 template <typename T>
189 bool PointerAssignmentChecker::Check(const evaluate::Designator<T> &d) {
190   const Symbol *last{d.GetLastSymbol()};
191   const Symbol *base{d.GetBaseObject().symbol()};
192   if (!last || !base) {
193     // P => "character literal"(1:3)
194     context_.messages().Say("Pointer target is not a named entity"_err_en_US);
195     return false;
196   }
197   std::optional<std::variant<MessageFixedText, MessageFormattedText>> msg;
198   if (procedure_) {
199     // Shouldn't be here in this function unless lhs is an object pointer.
200     msg = "In assignment to procedure %s, the target is not a procedure or"
201           " procedure pointer"_err_en_US;
202   } else if (!evaluate::GetLastTarget(GetSymbolVector(d))) { // C1025
203     msg = "In assignment to object %s, the target '%s' is not an object with"
204           " POINTER or TARGET attributes"_err_en_US;
205   } else if (auto rhsType{TypeAndShape::Characterize(d, context_)}) {
206     if (!lhsType_) {
207       msg = "%s associated with object '%s' with incompatible type or"
208             " shape"_err_en_US;
209     } else if (rhsType->corank() > 0 &&
210         (isVolatile_ != last->attrs().test(Attr::VOLATILE))) { // C1020
211       // TODO: what if A is VOLATILE in A%B%C?  need a better test here
212       if (isVolatile_) {
213         msg = "Pointer may not be VOLATILE when target is a"
214               " non-VOLATILE coarray"_err_en_US;
215       } else {
216         msg = "Pointer must be VOLATILE when target is a"
217               " VOLATILE coarray"_err_en_US;
218       }
219     } else if (rhsType->type().IsUnlimitedPolymorphic()) {
220       if (!LhsOkForUnlimitedPoly()) {
221         msg = "Pointer type must be unlimited polymorphic or non-extensible"
222               " derived type when target is unlimited polymorphic"_err_en_US;
223       }
224     } else {
225       if (!lhsType_->type().IsTkCompatibleWith(rhsType->type())) {
226         msg = MessageFormattedText{
227             "Target type %s is not compatible with pointer type %s"_err_en_US,
228             rhsType->type().AsFortran(), lhsType_->type().AsFortran()};
229 
230       } else if (!isBoundsRemapping_) {
231         int lhsRank{evaluate::GetRank(lhsType_->shape())};
232         int rhsRank{evaluate::GetRank(rhsType->shape())};
233         if (lhsRank != rhsRank) {
234           msg = MessageFormattedText{
235               "Pointer has rank %d but target has rank %d"_err_en_US, lhsRank,
236               rhsRank};
237         }
238       }
239     }
240   }
241   if (msg) {
242     auto restorer{common::ScopedSet(lhs_, last)};
243     if (auto *m{std::get_if<MessageFixedText>(&*msg)}) {
244       std::string buf;
245       llvm::raw_string_ostream ss{buf};
246       d.AsFortran(ss);
247       Say(*m, description_, ss.str());
248     } else {
249       Say(std::get<MessageFormattedText>(*msg));
250     }
251     return false;
252   }
253   return true;
254 }
255 
256 // Common handling for procedure pointer right-hand sides
257 bool PointerAssignmentChecker::Check(
258     parser::CharBlock rhsName, bool isCall, const Procedure *rhsProcedure) {
259   if (std::optional<MessageFixedText> msg{
260           evaluate::CheckProcCompatibility(isCall, procedure_, rhsProcedure)}) {
261     Say(std::move(*msg), description_, rhsName);
262     return false;
263   }
264   return true;
265 }
266 
267 bool PointerAssignmentChecker::Check(const evaluate::ProcedureDesignator &d) {
268   if (auto chars{Procedure::Characterize(d, context_)}) {
269     return Check(d.GetName(), false, &*chars);
270   } else {
271     return Check(d.GetName(), false);
272   }
273 }
274 
275 bool PointerAssignmentChecker::Check(const evaluate::ProcedureRef &ref) {
276   const Procedure *procedure{nullptr};
277   auto chars{Procedure::Characterize(ref, context_)};
278   if (chars) {
279     procedure = &*chars;
280     if (chars->functionResult) {
281       if (const auto *proc{chars->functionResult->IsProcedurePointer()}) {
282         procedure = proc;
283       }
284     }
285   }
286   return Check(ref.proc().GetName(), true, procedure);
287 }
288 
289 // The target can be unlimited polymorphic if the pointer is, or if it is
290 // a non-extensible derived type.
291 bool PointerAssignmentChecker::LhsOkForUnlimitedPoly() const {
292   const auto &type{lhsType_->type()};
293   if (type.category() != TypeCategory::Derived || type.IsAssumedType()) {
294     return false;
295   } else if (type.IsUnlimitedPolymorphic()) {
296     return true;
297   } else {
298     return !IsExtensibleType(&type.GetDerivedTypeSpec());
299   }
300 }
301 
302 template <typename... A>
303 parser::Message *PointerAssignmentChecker::Say(A &&...x) {
304   auto *msg{context_.messages().Say(std::forward<A>(x)...)};
305   if (msg) {
306     if (lhs_) {
307       return evaluate::AttachDeclaration(msg, *lhs_);
308     }
309     if (!source_.empty()) {
310       msg->Attach(source_, "Declaration of %s"_en_US, description_);
311     }
312   }
313   return msg;
314 }
315 
316 // Verify that any bounds on the LHS of a pointer assignment are valid.
317 // Return true if it is a bound-remapping so we can perform further checks.
318 static bool CheckPointerBounds(
319     evaluate::FoldingContext &context, const evaluate::Assignment &assignment) {
320   auto &messages{context.messages()};
321   const SomeExpr &lhs{assignment.lhs};
322   const SomeExpr &rhs{assignment.rhs};
323   bool isBoundsRemapping{false};
324   std::size_t numBounds{std::visit(
325       common::visitors{
326           [&](const evaluate::Assignment::BoundsSpec &bounds) {
327             return bounds.size();
328           },
329           [&](const evaluate::Assignment::BoundsRemapping &bounds) {
330             isBoundsRemapping = true;
331             evaluate::ExtentExpr lhsSizeExpr{1};
332             for (const auto &bound : bounds) {
333               lhsSizeExpr = std::move(lhsSizeExpr) *
334                   (common::Clone(bound.second) - common::Clone(bound.first) +
335                       evaluate::ExtentExpr{1});
336             }
337             if (std::optional<std::int64_t> lhsSize{evaluate::ToInt64(
338                     evaluate::Fold(context, std::move(lhsSizeExpr)))}) {
339               if (auto shape{evaluate::GetShape(context, rhs)}) {
340                 if (std::optional<std::int64_t> rhsSize{
341                         evaluate::ToInt64(evaluate::Fold(
342                             context, evaluate::GetSize(std::move(*shape))))}) {
343                   if (*lhsSize > *rhsSize) {
344                     messages.Say(
345                         "Pointer bounds require %d elements but target has"
346                         " only %d"_err_en_US,
347                         *lhsSize, *rhsSize); // 10.2.2.3(9)
348                   }
349                 }
350               }
351             }
352             return bounds.size();
353           },
354           [](const auto &) -> std::size_t {
355             DIE("not valid for pointer assignment");
356           },
357       },
358       assignment.u)};
359   if (numBounds > 0) {
360     if (lhs.Rank() != static_cast<int>(numBounds)) {
361       messages.Say("Pointer '%s' has rank %d but the number of bounds specified"
362                    " is %d"_err_en_US,
363           lhs.AsFortran(), lhs.Rank(), numBounds); // C1018
364     }
365   }
366   if (isBoundsRemapping && rhs.Rank() != 1 &&
367       !evaluate::IsSimplyContiguous(rhs, context)) {
368     messages.Say("Pointer bounds remapping target must have rank 1 or be"
369                  " simply contiguous"_err_en_US); // 10.2.2.3(9)
370   }
371   return isBoundsRemapping;
372 }
373 
374 bool CheckPointerAssignment(
375     evaluate::FoldingContext &context, const evaluate::Assignment &assignment) {
376   return CheckPointerAssignment(context, assignment.lhs, assignment.rhs,
377       CheckPointerBounds(context, assignment));
378 }
379 
380 bool CheckPointerAssignment(evaluate::FoldingContext &context,
381     const SomeExpr &lhs, const SomeExpr &rhs, bool isBoundsRemapping) {
382   const Symbol *pointer{GetLastSymbol(lhs)};
383   if (!pointer) {
384     return false; // error was reported
385   }
386   if (!IsPointer(*pointer)) {
387     evaluate::SayWithDeclaration(context.messages(), *pointer,
388         "'%s' is not a pointer"_err_en_US, pointer->name());
389     return false;
390   }
391   if (pointer->has<ProcEntityDetails>() && evaluate::ExtractCoarrayRef(lhs)) {
392     context.messages().Say( // C1027
393         "Procedure pointer may not be a coindexed object"_err_en_US);
394     return false;
395   }
396   return PointerAssignmentChecker{context, *pointer}
397       .set_isBoundsRemapping(isBoundsRemapping)
398       .Check(rhs);
399 }
400 
401 bool CheckPointerAssignment(
402     evaluate::FoldingContext &context, const Symbol &lhs, const SomeExpr &rhs) {
403   CHECK(IsPointer(lhs));
404   return PointerAssignmentChecker{context, lhs}.Check(rhs);
405 }
406 
407 bool CheckPointerAssignment(evaluate::FoldingContext &context,
408     parser::CharBlock source, const std::string &description,
409     const DummyDataObject &lhs, const SomeExpr &rhs) {
410   return PointerAssignmentChecker{context, source, description}
411       .set_lhsType(common::Clone(lhs.type))
412       .set_isContiguous(lhs.attrs.test(DummyDataObject::Attr::Contiguous))
413       .set_isVolatile(lhs.attrs.test(DummyDataObject::Attr::Volatile))
414       .Check(rhs);
415 }
416 
417 bool CheckInitialTarget(evaluate::FoldingContext &context,
418     const SomeExpr &pointer, const SomeExpr &init) {
419   return evaluate::IsInitialDataTarget(init, &context.messages()) &&
420       CheckPointerAssignment(context, pointer, init);
421 }
422 
423 } // namespace Fortran::semantics
424