xref: /aosp_15_r20/external/tensorflow/tensorflow/compiler/xla/service/gpu/llvm_gpu_backend/utils.cc (revision b6fb3261f9314811a0f4371741dbb8839866f948)
1 /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 
16 #include "tensorflow/compiler/xla/service/gpu/llvm_gpu_backend/utils.h"
17 
18 #include "absl/strings/str_cat.h"
19 #include "absl/strings/string_view.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/IRReader/IRReader.h"
23 #include "llvm/Support/SourceMgr.h"
24 #include "tensorflow/compiler/xla/types.h"
25 #include "tensorflow/core/platform/logging.h"
26 
27 namespace {
28 
DieWithSMDiagnosticError(llvm::SMDiagnostic * diagnostic)29 static void DieWithSMDiagnosticError(llvm::SMDiagnostic* diagnostic) {
30   LOG(FATAL) << diagnostic->getFilename().str() << ":"
31              << diagnostic->getLineNo() << ":" << diagnostic->getColumnNo()
32              << ": " << diagnostic->getMessage().str();
33 }
34 
35 }  // namespace
36 
37 namespace xla {
38 namespace gpu {
39 
LoadIRModule(const std::string & filename,llvm::LLVMContext * llvm_context)40 std::unique_ptr<llvm::Module> LoadIRModule(const std::string& filename,
41                                            llvm::LLVMContext* llvm_context) {
42   llvm::SMDiagnostic diagnostic_err;
43   std::unique_ptr<llvm::Module> module(
44       llvm::parseIRFile(llvm::StringRef(filename.data(), filename.size()),
45                         diagnostic_err, *llvm_context));
46 
47   if (module == nullptr) {
48     DieWithSMDiagnosticError(&diagnostic_err);
49   }
50 
51   return module;
52 }
53 
ReplaceFilenameExtension(absl::string_view filename,absl::string_view new_extension)54 std::string ReplaceFilenameExtension(absl::string_view filename,
55                                      absl::string_view new_extension) {
56   auto pos = filename.rfind('.');
57   absl::string_view stem = pos == absl::string_view::npos
58                                ? filename
59                                : absl::string_view(filename.data(), pos);
60   return absl::StrCat(stem, ".", new_extension);
61 }
62 
63 }  // namespace gpu
64 }  // namespace xla
65