xref: /aosp_15_r20/external/tensorflow/tensorflow/compiler/xla/service/llvm_ir/kernel_support_library.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/llvm_ir/kernel_support_library.h"
17 
18 #include "tensorflow/compiler/xla/service/llvm_ir/llvm_type_conversion_util.h"
19 #include "tensorflow/compiler/xla/service/llvm_ir/llvm_util.h"
20 
21 namespace xla {
ForWithStatus(absl::string_view name,llvm::Value * start,llvm::Value * end,llvm::Value * step,const std::function<Status (llvm::Value *,bool)> & for_body_generator)22 Status KernelSupportLibrary::ForWithStatus(
23     absl::string_view name, llvm::Value* start, llvm::Value* end,
24     llvm::Value* step,
25     const std::function<Status(llvm::Value*, bool)>& for_body_generator) {
26   return IfWithStatus(b_->CreateICmpSLT(start, end), [&]() -> Status {
27     TF_RETURN_IF_ERROR(for_body_generator(start, /*is_first_iteration=*/true));
28     return ForWithStatus(
29         name, b_->CreateAdd(start, step), end, step,
30         [&](llvm::Value* iv) { return for_body_generator(iv, false); });
31   });
32 }
33 
ForWithStatus(absl::string_view name,llvm::Value * start,llvm::Value * end,llvm::Value * step,bool peel_first_iteration,const std::function<Status (llvm::Value *,llvm::Value *)> & for_body_generator)34 Status KernelSupportLibrary::ForWithStatus(
35     absl::string_view name, llvm::Value* start, llvm::Value* end,
36     llvm::Value* step, bool peel_first_iteration,
37     const std::function<Status(llvm::Value*, llvm::Value*)>&
38         for_body_generator) {
39   if (peel_first_iteration) {
40     return ForWithStatus(
41         name, start, end, step, true,
42         [&](llvm::Value* indvar, bool is_first_iteration) -> Status {
43           return for_body_generator(indvar, b_->getInt1(is_first_iteration));
44         });
45   } else {
46     std::unique_ptr<llvm_ir::ForLoop> loop = llvm_ir::ForLoop::EmitForLoop(
47         name, start, end, step, b_,
48         /*unroll_mode=*/unroll_mode_,
49         /*prevent_vectorization=*/prevent_vectorization_);
50     b_->SetInsertPoint(&loop->GetBodyBasicBlock()->back());
51     TF_RETURN_IF_ERROR(
52         for_body_generator(loop->GetIndVarValue(),
53                            /*is_first_iteration=*/b_->CreateICmpEQ(
54                                loop->GetIndVarValue(), start)));
55     llvm_ir::SetToLastInsertPoint(loop->GetExitBasicBlock(), b_);
56     return OkStatus();
57   }
58 }
59 
IfWithStatus(absl::string_view name,llvm::Value * condition,const std::function<Status ()> & true_block_generator,const std::function<Status ()> & false_block_generator)60 Status KernelSupportLibrary::IfWithStatus(
61     absl::string_view name, llvm::Value* condition,
62     const std::function<Status()>& true_block_generator,
63     const std::function<Status()>& false_block_generator) {
64   llvm_ir::LlvmIfData if_data =
65       llvm_ir::EmitIfThenElse(condition, name, b_,
66                               /*emit_else=*/false_block_generator != nullptr);
67   b_->SetInsertPoint(&if_data.true_block->back());
68   TF_RETURN_IF_ERROR(true_block_generator());
69   if (false_block_generator != nullptr) {
70     b_->SetInsertPoint(&if_data.false_block->back());
71     TF_RETURN_IF_ERROR(false_block_generator());
72   }
73   llvm_ir::SetToLastInsertPoint(if_data.after_block, b_);
74   return OkStatus();
75 }
76 
EmitAndCallOutlinedKernel(const HloModuleConfig & module_config,llvm::IRBuilder<> * b,absl::string_view kernel_name,KernelSupportLibrary::ArgumentVector arguments,const std::function<void (KernelSupportLibrary::ArgumentVector)> & kernel_body_generator)77 void KernelSupportLibrary::EmitAndCallOutlinedKernel(
78     const HloModuleConfig& module_config, llvm::IRBuilder<>* b,
79     absl::string_view kernel_name,
80     KernelSupportLibrary::ArgumentVector arguments,
81     const std::function<void(KernelSupportLibrary::ArgumentVector)>&
82         kernel_body_generator) {
83   llvm::Module* module = b->GetInsertBlock()->getModule();
84   llvm::Function* function =
85       module->getFunction(llvm_ir::AsStringRef(kernel_name));
86 
87   int64_t null_arg_idx = -1;
88   std::vector<llvm::Value*> sanitized_args;
89   sanitized_args.reserve(arguments.size());
90   for (int64_t i = 0, e = arguments.size(); i < e; i++) {
91     if (arguments[i]) {
92       sanitized_args.push_back(arguments[i]);
93     } else {
94       CHECK_EQ(null_arg_idx, -1);
95       null_arg_idx = i;
96     }
97   }
98 
99   if (!function) {
100     VLOG(2) << "Generating kernel for " << kernel_name;
101     std::vector<llvm::Type*> arg_types;
102     std::transform(sanitized_args.begin(), sanitized_args.end(),
103                    std::back_inserter(arg_types),
104                    [](llvm::Value* arg) { return arg->getType(); });
105 
106     auto* function_type =
107         llvm::FunctionType::get(b->getVoidTy(), arg_types, /*isVarArg=*/false);
108 
109     function = llvm_ir::CreateCpuFunction(function_type,
110                                           llvm::GlobalValue::InternalLinkage,
111                                           module_config, kernel_name, module);
112 
113     llvm::IRBuilder<>::InsertPointGuard guard(*b);
114 
115     auto* entry_bb =
116         llvm::BasicBlock::Create(b->getContext(), "entry", function);
117     auto* return_inst = llvm::ReturnInst::Create(b->getContext(),
118                                                  /*retVal=*/nullptr, entry_bb);
119     // Set the insert point to before return_inst.
120     b->SetInsertPoint(return_inst);
121 
122     std::vector<llvm::Value*> arg_values;
123     /*
124      * clang on OSX doesn't like std::transform or range for loop here.
125      * See https://github.com/tensorflow/tensorflow/issues/15196
126      */
127     for (llvm::Function::arg_iterator arg = function->arg_begin(),
128                                       arg_e = function->arg_end();
129          arg != arg_e; ++arg) {
130       arg_values.push_back(arg);
131     }
132     if (null_arg_idx != -1) {
133       arg_values.insert(arg_values.begin() + null_arg_idx, nullptr);
134     }
135     kernel_body_generator(arg_values);
136   } else {
137     VLOG(3) << "Re-using kernel for " << kernel_name;
138   }
139 
140   b->CreateCall(function, llvm_ir::AsArrayRef(sanitized_args));
141 }
142 
143 }  // namespace xla
144