1 //===-- FIRAttr.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 // Coding style: https://mlir.llvm.org/getting_started/DeveloperGuide/
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "flang/Optimizer/Dialect/FIRAttr.h"
14 #include "flang/Optimizer/Dialect/FIRDialect.h"
15 #include "flang/Optimizer/Support/KindMapping.h"
16 #include "mlir/IR/AttributeSupport.h"
17 #include "mlir/IR/DialectImplementation.h"
18 #include "mlir/IR/BuiltinTypes.h"
19 #include "llvm/ADT/SmallString.h"
20 
21 using namespace fir;
22 
23 namespace fir::detail {
24 
25 struct RealAttributeStorage : public mlir::AttributeStorage {
26   using KeyTy = std::pair<int, llvm::APFloat>;
27 
28   RealAttributeStorage(int kind, const llvm::APFloat &value)
29       : kind(kind), value(value) {}
30   RealAttributeStorage(const KeyTy &key)
31       : RealAttributeStorage(key.first, key.second) {}
32 
33   static unsigned hashKey(const KeyTy &key) { return llvm::hash_value(key); }
34 
35   bool operator==(const KeyTy &key) const {
36     return key.first == kind &&
37            key.second.compare(value) == llvm::APFloatBase::cmpEqual;
38   }
39 
40   static RealAttributeStorage *
41   construct(mlir::AttributeStorageAllocator &allocator, const KeyTy &key) {
42     return new (allocator.allocate<RealAttributeStorage>())
43         RealAttributeStorage(key);
44   }
45 
46   KindTy getFKind() const { return kind; }
47   llvm::APFloat getValue() const { return value; }
48 
49 private:
50   int kind;
51   llvm::APFloat value;
52 };
53 
54 /// An attribute representing a reference to a type.
55 struct TypeAttributeStorage : public mlir::AttributeStorage {
56   using KeyTy = mlir::Type;
57 
58   TypeAttributeStorage(mlir::Type value) : value(value) {
59     assert(value && "must not be of Type null");
60   }
61 
62   /// Key equality function.
63   bool operator==(const KeyTy &key) const { return key == value; }
64 
65   /// Construct a new storage instance.
66   static TypeAttributeStorage *
67   construct(mlir::AttributeStorageAllocator &allocator, KeyTy key) {
68     return new (allocator.allocate<TypeAttributeStorage>())
69         TypeAttributeStorage(key);
70   }
71 
72   mlir::Type getType() const { return value; }
73 
74 private:
75   mlir::Type value;
76 };
77 
78 /// An attribute representing a raw pointer.
79 struct OpaqueAttributeStorage : public mlir::AttributeStorage {
80   using KeyTy = void *;
81 
82   OpaqueAttributeStorage(void *value) : value(value) {}
83 
84   /// Key equality function.
85   bool operator==(const KeyTy &key) const { return key == value; }
86 
87   /// Construct a new storage instance.
88   static OpaqueAttributeStorage *
89   construct(mlir::AttributeStorageAllocator &allocator, KeyTy key) {
90     return new (allocator.allocate<OpaqueAttributeStorage>())
91         OpaqueAttributeStorage(key);
92   }
93 
94   void *getPointer() const { return value; }
95 
96 private:
97   void *value;
98 };
99 } // namespace fir::detail
100 
101 //===----------------------------------------------------------------------===//
102 // Attributes for SELECT TYPE
103 //===----------------------------------------------------------------------===//
104 
105 ExactTypeAttr fir::ExactTypeAttr::get(mlir::Type value) {
106   return Base::get(value.getContext(), value);
107 }
108 
109 mlir::Type fir::ExactTypeAttr::getType() const { return getImpl()->getType(); }
110 
111 SubclassAttr fir::SubclassAttr::get(mlir::Type value) {
112   return Base::get(value.getContext(), value);
113 }
114 
115 mlir::Type fir::SubclassAttr::getType() const { return getImpl()->getType(); }
116 
117 //===----------------------------------------------------------------------===//
118 // Attributes for SELECT CASE
119 //===----------------------------------------------------------------------===//
120 
121 using AttributeUniquer = mlir::detail::AttributeUniquer;
122 
123 ClosedIntervalAttr fir::ClosedIntervalAttr::get(mlir::MLIRContext *ctxt) {
124   return AttributeUniquer::get<ClosedIntervalAttr>(ctxt);
125 }
126 
127 UpperBoundAttr fir::UpperBoundAttr::get(mlir::MLIRContext *ctxt) {
128   return AttributeUniquer::get<UpperBoundAttr>(ctxt);
129 }
130 
131 LowerBoundAttr fir::LowerBoundAttr::get(mlir::MLIRContext *ctxt) {
132   return AttributeUniquer::get<LowerBoundAttr>(ctxt);
133 }
134 
135 PointIntervalAttr fir::PointIntervalAttr::get(mlir::MLIRContext *ctxt) {
136   return AttributeUniquer::get<PointIntervalAttr>(ctxt);
137 }
138 
139 //===----------------------------------------------------------------------===//
140 // RealAttr
141 //===----------------------------------------------------------------------===//
142 
143 RealAttr fir::RealAttr::get(mlir::MLIRContext *ctxt,
144                             const RealAttr::ValueType &key) {
145   return Base::get(ctxt, key);
146 }
147 
148 KindTy fir::RealAttr::getFKind() const { return getImpl()->getFKind(); }
149 
150 llvm::APFloat fir::RealAttr::getValue() const { return getImpl()->getValue(); }
151 
152 //===----------------------------------------------------------------------===//
153 // OpaqueAttr
154 //===----------------------------------------------------------------------===//
155 
156 OpaqueAttr fir::OpaqueAttr::get(mlir::MLIRContext *ctxt, void *key) {
157   return Base::get(ctxt, key);
158 }
159 
160 void *fir::OpaqueAttr::getPointer() const { return getImpl()->getPointer(); }
161 
162 //===----------------------------------------------------------------------===//
163 // FIR attribute parsing
164 //===----------------------------------------------------------------------===//
165 
166 static mlir::Attribute parseFirRealAttr(FIROpsDialect *dialect,
167                                         mlir::DialectAsmParser &parser,
168                                         mlir::Type type) {
169   int kind = 0;
170   if (parser.parseLess() || parser.parseInteger(kind) || parser.parseComma()) {
171     parser.emitError(parser.getNameLoc(), "expected '<' kind ','");
172     return {};
173   }
174   KindMapping kindMap(dialect->getContext());
175   llvm::APFloat value(0.);
176   if (parser.parseOptionalKeyword("i")) {
177     // `i` not present, so literal float must be present
178     double dontCare;
179     if (parser.parseFloat(dontCare) || parser.parseGreater()) {
180       parser.emitError(parser.getNameLoc(), "expected real constant '>'");
181       return {};
182     }
183     auto fltStr = parser.getFullSymbolSpec()
184                       .drop_until([](char c) { return c == ','; })
185                       .drop_front()
186                       .drop_while([](char c) { return c == ' ' || c == '\t'; })
187                       .take_until([](char c) {
188                         return c == '>' || c == ' ' || c == '\t';
189                       });
190     value = llvm::APFloat(kindMap.getFloatSemantics(kind), fltStr);
191   } else {
192     // `i` is present, so literal bitstring (hex) must be present
193     llvm::StringRef hex;
194     if (parser.parseKeyword(&hex) || parser.parseGreater()) {
195       parser.emitError(parser.getNameLoc(), "expected real constant '>'");
196       return {};
197     }
198     auto bits = llvm::APInt(kind * 8, hex.drop_front(), 16);
199     value = llvm::APFloat(kindMap.getFloatSemantics(kind), bits);
200   }
201   return RealAttr::get(dialect->getContext(), {kind, value});
202 }
203 
204 mlir::Attribute fir::parseFirAttribute(FIROpsDialect *dialect,
205                                        mlir::DialectAsmParser &parser,
206                                        mlir::Type type) {
207   auto loc = parser.getNameLoc();
208   llvm::StringRef attrName;
209   if (parser.parseKeyword(&attrName)) {
210     parser.emitError(loc, "expected an attribute name");
211     return {};
212   }
213 
214   if (attrName == ExactTypeAttr::getAttrName()) {
215     mlir::Type type;
216     if (parser.parseLess() || parser.parseType(type) || parser.parseGreater()) {
217       parser.emitError(loc, "expected a type");
218       return {};
219     }
220     return ExactTypeAttr::get(type);
221   }
222   if (attrName == SubclassAttr::getAttrName()) {
223     mlir::Type type;
224     if (parser.parseLess() || parser.parseType(type) || parser.parseGreater()) {
225       parser.emitError(loc, "expected a subtype");
226       return {};
227     }
228     return SubclassAttr::get(type);
229   }
230   if (attrName == OpaqueAttr::getAttrName()) {
231     if (parser.parseLess() || parser.parseGreater()) {
232       parser.emitError(loc, "expected <>");
233       return {};
234     }
235     // NB: opaque pointers are always parsed in as nullptrs. The tool must
236     // rebuild the context.
237     return OpaqueAttr::get(dialect->getContext(), nullptr);
238   }
239   if (attrName == PointIntervalAttr::getAttrName())
240     return PointIntervalAttr::get(dialect->getContext());
241   if (attrName == LowerBoundAttr::getAttrName())
242     return LowerBoundAttr::get(dialect->getContext());
243   if (attrName == UpperBoundAttr::getAttrName())
244     return UpperBoundAttr::get(dialect->getContext());
245   if (attrName == ClosedIntervalAttr::getAttrName())
246     return ClosedIntervalAttr::get(dialect->getContext());
247   if (attrName == RealAttr::getAttrName())
248     return parseFirRealAttr(dialect, parser, type);
249 
250   parser.emitError(loc, "unknown FIR attribute: ") << attrName;
251   return {};
252 }
253 
254 //===----------------------------------------------------------------------===//
255 // FIR attribute pretty printer
256 //===----------------------------------------------------------------------===//
257 
258 void fir::printFirAttribute(FIROpsDialect *dialect, mlir::Attribute attr,
259                             mlir::DialectAsmPrinter &p) {
260   auto &os = p.getStream();
261   if (auto exact = attr.dyn_cast<fir::ExactTypeAttr>()) {
262     os << fir::ExactTypeAttr::getAttrName() << '<';
263     p.printType(exact.getType());
264     os << '>';
265   } else if (auto sub = attr.dyn_cast<fir::SubclassAttr>()) {
266     os << fir::SubclassAttr::getAttrName() << '<';
267     p.printType(sub.getType());
268     os << '>';
269   } else if (attr.dyn_cast_or_null<fir::PointIntervalAttr>()) {
270     os << fir::PointIntervalAttr::getAttrName();
271   } else if (attr.dyn_cast_or_null<fir::ClosedIntervalAttr>()) {
272     os << fir::ClosedIntervalAttr::getAttrName();
273   } else if (attr.dyn_cast_or_null<fir::LowerBoundAttr>()) {
274     os << fir::LowerBoundAttr::getAttrName();
275   } else if (attr.dyn_cast_or_null<fir::UpperBoundAttr>()) {
276     os << fir::UpperBoundAttr::getAttrName();
277   } else if (auto a = attr.dyn_cast_or_null<fir::RealAttr>()) {
278     os << fir::RealAttr::getAttrName() << '<' << a.getFKind() << ", i x";
279     llvm::SmallString<40> ss;
280     a.getValue().bitcastToAPInt().toStringUnsigned(ss, 16);
281     os << ss << '>';
282   } else if (attr.isa<fir::OpaqueAttr>()) {
283     os << fir::OpaqueAttr::getAttrName() << "<>";
284   } else {
285     // don't know how to print the attribute, so use a default
286     os << "<(unknown attribute)>";
287   }
288 }
289