1 //===- ToolUtilities.cpp - MLIR Tool Utilities ----------------------------===// 2 // 3 // Copyright 2019 The MLIR Authors. 4 // 5 // Licensed under the Apache License, Version 2.0 (the "License"); 6 // you may not use this file except in compliance with the License. 7 // You may obtain a copy of the License at 8 // 9 // http://www.apache.org/licenses/LICENSE-2.0 10 // 11 // Unless required by applicable law or agreed to in writing, software 12 // distributed under the License is distributed on an "AS IS" BASIS, 13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 // See the License for the specific language governing permissions and 15 // limitations under the License. 16 // ============================================================================= 17 // 18 // This file defines common utilities for implementing MLIR tools. 19 // 20 //===----------------------------------------------------------------------===// 21 22 #include "mlir/Support/ToolUtilities.h" 23 #include "mlir/Support/LLVM.h" 24 #include "mlir/Support/LogicalResult.h" 25 #include "llvm/Support/SourceMgr.h" 26 27 using namespace mlir; 28 29 LogicalResult 30 mlir::splitAndProcessBuffer(std::unique_ptr<llvm::MemoryBuffer> originalBuffer, 31 ChunkBufferHandler processChunkBuffer, 32 raw_ostream &os) { 33 const char splitMarker[] = "// -----"; 34 35 auto *origMemBuffer = originalBuffer.get(); 36 SmallVector<StringRef, 8> sourceBuffers; 37 origMemBuffer->getBuffer().split(sourceBuffers, splitMarker); 38 39 // Add the original buffer to the source manager. 40 llvm::SourceMgr fileSourceMgr; 41 fileSourceMgr.AddNewSourceBuffer(std::move(originalBuffer), llvm::SMLoc()); 42 43 // Process each chunk in turn. 44 bool hadFailure = false; 45 for (auto &subBuffer : sourceBuffers) { 46 auto splitLoc = llvm::SMLoc::getFromPointer(subBuffer.data()); 47 unsigned splitLine = fileSourceMgr.getLineAndColumn(splitLoc).first; 48 auto subMemBuffer = llvm::MemoryBuffer::getMemBufferCopy( 49 subBuffer, origMemBuffer->getBufferIdentifier() + 50 Twine(" split at line #") + Twine(splitLine)); 51 if (failed(processChunkBuffer(std::move(subMemBuffer), os))) 52 hadFailure = true; 53 } 54 55 // If any fails, then return a failure of the tool. 56 return failure(hadFailure); 57 } 58