1 // 2 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 3 // See https://llvm.org/LICENSE.txt for license information. 4 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 5 // 6 //===----------------------------------------------------------------------===// 7 // 8 // This file defines common utilities for generating C++ from tablegen 9 // structures. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #ifndef MLIR_TABLEGEN_CODEGENHELPERS_H 14 #define MLIR_TABLEGEN_CODEGENHELPERS_H 15 16 #include "mlir/TableGen/Dialect.h" 17 #include "llvm/ADT/StringExtras.h" 18 #include "llvm/ADT/StringRef.h" 19 20 namespace mlir { 21 namespace tblgen { 22 23 // Simple RAII helper for defining ifdef-undef-endif scopes. 24 class IfDefScope { 25 public: IfDefScope(llvm::StringRef name,llvm::raw_ostream & os)26 IfDefScope(llvm::StringRef name, llvm::raw_ostream &os) : name(name), os(os) { 27 os << "#ifdef " << name << "\n" 28 << "#undef " << name << "\n\n"; 29 } ~IfDefScope()30 ~IfDefScope() { os << "\n#endif // " << name << "\n\n"; } 31 32 private: 33 llvm::StringRef name; 34 llvm::raw_ostream &os; 35 }; 36 37 // A helper RAII class to emit nested namespaces for this op. 38 class NamespaceEmitter { 39 public: NamespaceEmitter(raw_ostream & os,const Dialect & dialect)40 NamespaceEmitter(raw_ostream &os, const Dialect &dialect) : os(os) { 41 if (!dialect) 42 return; 43 llvm::SplitString(dialect.getCppNamespace(), namespaces, "::"); 44 for (StringRef ns : namespaces) 45 os << "namespace " << ns << " {\n"; 46 } 47 ~NamespaceEmitter()48 ~NamespaceEmitter() { 49 for (StringRef ns : llvm::reverse(namespaces)) 50 os << "} // namespace " << ns << "\n"; 51 } 52 53 private: 54 raw_ostream &os; 55 SmallVector<StringRef, 2> namespaces; 56 }; 57 58 } // namespace tblgen 59 } // namespace mlir 60 61 #endif // MLIR_TABLEGEN_CODEGENHELPERS_H 62