1//===- FileUtilities.cpp - utilities for working with files ---------------===//
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// Definitions of common utilities for working with files.
10//
11//===----------------------------------------------------------------------===//
12
13#include "mlir/Support/FileUtilities.h"
14#include "mlir/Support/LLVM.h"
15#include "llvm/Support/Alignment.h"
16#include "llvm/Support/FileUtilities.h"
17#include "llvm/Support/MemoryBuffer.h"
18#include "llvm/Support/ToolOutputFile.h"
19
20using namespace mlir;
21
22static std::unique_ptr<llvm::MemoryBuffer>
23openInputFileImpl(StringRef inputFilename, std::string *errorMessage,
24 std::optional<llvm::Align> alignment) {
25 auto fileOrErr = llvm::MemoryBuffer::getFileOrSTDIN(
26 Filename: inputFilename, /*IsText=*/false, /*RequiresNullTerminator=*/true,
27 Alignment: alignment);
28 if (std::error_code error = fileOrErr.getError()) {
29 if (errorMessage)
30 *errorMessage = "cannot open input file '" + inputFilename.str() +
31 "': " + error.message();
32 return nullptr;
33 }
34
35 return std::move(*fileOrErr);
36}
37std::unique_ptr<llvm::MemoryBuffer>
38mlir::openInputFile(StringRef inputFilename, std::string *errorMessage) {
39 return openInputFileImpl(inputFilename, errorMessage,
40 /*alignment=*/std::nullopt);
41}
42std::unique_ptr<llvm::MemoryBuffer>
43mlir::openInputFile(llvm::StringRef inputFilename, llvm::Align alignment,
44 std::string *errorMessage) {
45 return openInputFileImpl(inputFilename, errorMessage, alignment);
46}
47
48std::unique_ptr<llvm::ToolOutputFile>
49mlir::openOutputFile(StringRef outputFilename, std::string *errorMessage) {
50 std::error_code error;
51 auto result = std::make_unique<llvm::ToolOutputFile>(args&: outputFilename, args&: error,
52 args: llvm::sys::fs::OF_None);
53 if (error) {
54 if (errorMessage)
55 *errorMessage = "cannot open output file '" + outputFilename.str() +
56 "': " + error.message();
57 return nullptr;
58 }
59
60 return result;
61}
62

source code of mlir/lib/Support/FileUtilities.cpp