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