1 //===- FileUtilities.cpp - utilities for working with files ---------------===//
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
7 //===----------------------------------------------------------------------===//
9 // Definitions of common utilities for working with files.
11 //===----------------------------------------------------------------------===//
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"
22 static std::unique_ptr
<llvm::MemoryBuffer
>
23 openInputFileImpl(StringRef inputFilename
, std::string
*errorMessage
,
24 std::optional
<llvm::Align
> alignment
) {
25 auto fileOrErr
= llvm::MemoryBuffer::getFileOrSTDIN(
26 inputFilename
, /*IsText=*/false, /*RequiresNullTerminator=*/true,
28 if (std::error_code error
= fileOrErr
.getError()) {
30 *errorMessage
= "cannot open input file '" + inputFilename
.str() +
31 "': " + error
.message();
35 return std::move(*fileOrErr
);
37 std::unique_ptr
<llvm::MemoryBuffer
>
38 mlir::openInputFile(StringRef inputFilename
, std::string
*errorMessage
) {
39 return openInputFileImpl(inputFilename
, errorMessage
,
40 /*alignment=*/std::nullopt
);
42 std::unique_ptr
<llvm::MemoryBuffer
>
43 mlir::openInputFile(llvm::StringRef inputFilename
, llvm::Align alignment
,
44 std::string
*errorMessage
) {
45 return openInputFileImpl(inputFilename
, errorMessage
, alignment
);
48 std::unique_ptr
<llvm::ToolOutputFile
>
49 mlir::openOutputFile(StringRef outputFilename
, std::string
*errorMessage
) {
50 std::error_code error
;
51 auto result
= std::make_unique
<llvm::ToolOutputFile
>(outputFilename
, error
,
52 llvm::sys::fs::OF_None
);
55 *errorMessage
= "cannot open output file '" + outputFilename
.str() +
56 "': " + error
.message();