blob: 166d2f610bd3cbbfff8a825be560ff61880d7c95 [file] [log] [blame]
Logan Chien8b977d32012-02-21 19:14:55 +08001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "compilation_unit.h"
18
Logan Chien110bcba2012-04-16 19:11:28 +080019#include "compiled_method.h"
Shih-wei Liaod7726e42012-04-20 15:23:36 -070020#include "file.h"
Elliott Hughes0f3c5532012-03-30 14:51:51 -070021#include "instruction_set.h"
Logan Chien8b977d32012-02-21 19:14:55 +080022#include "ir_builder.h"
23#include "logging.h"
Shih-wei Liaod7726e42012-04-20 15:23:36 -070024#include "os.h"
Logan Chien8b977d32012-02-21 19:14:55 +080025
TDYa127d668a062012-04-13 12:36:57 -070026#include "runtime_support_builder_arm.h"
27#include "runtime_support_builder_x86.h"
28
Logan Chien8b977d32012-02-21 19:14:55 +080029#include <llvm/ADT/OwningPtr.h>
30#include <llvm/ADT/StringSet.h>
31#include <llvm/ADT/Triple.h>
32#include <llvm/Analysis/CallGraph.h>
33#include <llvm/Analysis/DebugInfo.h>
34#include <llvm/Analysis/LoopPass.h>
35#include <llvm/Analysis/RegionPass.h>
36#include <llvm/Analysis/Verifier.h>
37#include <llvm/Assembly/PrintModulePass.h>
38#include <llvm/Bitcode/ReaderWriter.h>
39#include <llvm/CallGraphSCCPass.h>
Logan Chien110bcba2012-04-16 19:11:28 +080040#include <llvm/CodeGen/MachineFrameInfo.h>
41#include <llvm/CodeGen/MachineFunction.h>
42#include <llvm/CodeGen/MachineFunctionPass.h>
Logan Chien8b977d32012-02-21 19:14:55 +080043#include <llvm/DerivedTypes.h>
44#include <llvm/LLVMContext.h>
Logan Chien8b977d32012-02-21 19:14:55 +080045#include <llvm/Module.h>
46#include <llvm/PassManager.h>
47#include <llvm/Support/Debug.h>
48#include <llvm/Support/FormattedStream.h>
49#include <llvm/Support/ManagedStatic.h>
Shih-wei Liaod7726e42012-04-20 15:23:36 -070050#include <llvm/Support/MemoryBuffer.h>
Logan Chien8b977d32012-02-21 19:14:55 +080051#include <llvm/Support/PassNameParser.h>
52#include <llvm/Support/PluginLoader.h>
53#include <llvm/Support/PrettyStackTrace.h>
54#include <llvm/Support/Signals.h>
55#include <llvm/Support/SystemUtils.h>
56#include <llvm/Support/TargetRegistry.h>
57#include <llvm/Support/TargetSelect.h>
58#include <llvm/Support/ToolOutputFile.h>
59#include <llvm/Support/raw_ostream.h>
Shih-wei Liaod7726e42012-04-20 15:23:36 -070060#include <llvm/Support/system_error.h>
Logan Chien8b977d32012-02-21 19:14:55 +080061#include <llvm/Target/TargetData.h>
62#include <llvm/Target/TargetLibraryInfo.h>
63#include <llvm/Target/TargetMachine.h>
Shih-wei Liaof1cb9a52012-04-20 01:49:18 -070064#include <llvm/Transforms/IPO.h>
Logan Chien8b977d32012-02-21 19:14:55 +080065#include <llvm/Transforms/IPO/PassManagerBuilder.h>
66
Shih-wei Liaod7726e42012-04-20 15:23:36 -070067#include <sys/types.h>
68#include <sys/wait.h>
69#include <unistd.h>
70
Logan Chien8b977d32012-02-21 19:14:55 +080071#include <string>
72
Logan Chien110bcba2012-04-16 19:11:28 +080073namespace {
74
75class UpdateFrameSizePass : public llvm::MachineFunctionPass {
76 public:
77 static char ID;
78
79 UpdateFrameSizePass() : llvm::MachineFunctionPass(ID), cunit_(NULL) {
80 LOG(FATAL) << "Unexpected instantiation of UpdateFrameSizePass";
81 // NOTE: We have to declare this constructor for llvm::RegisterPass, but
82 // this constructor won't work because we have no information on
83 // CompilationUnit. Thus, we should place a LOG(FATAL) here.
84 }
85
86 UpdateFrameSizePass(art::compiler_llvm::CompilationUnit* cunit)
87 : llvm::MachineFunctionPass(ID), cunit_(cunit) {
88 }
89
90 virtual bool runOnMachineFunction(llvm::MachineFunction &MF) {
91 cunit_->UpdateFrameSizeInBytes(MF.getFunction(),
92 MF.getFrameInfo()->getStackSize());
93 return false;
94 }
95
96 private:
97 art::compiler_llvm::CompilationUnit* cunit_;
98};
99
100char UpdateFrameSizePass::ID = 0;
101
102llvm::RegisterPass<UpdateFrameSizePass> reg_update_frame_size_pass_(
103 "update-frame-size", "Update frame size pass", false, false);
104
105} // end anonymous namespace
106
Logan Chien8b977d32012-02-21 19:14:55 +0800107namespace art {
108namespace compiler_llvm {
109
110llvm::Module* makeLLVMModuleContents(llvm::Module* module);
111
112
Logan Chien6546ec52012-03-17 20:08:29 +0800113CompilationUnit::CompilationUnit(InstructionSet insn_set, size_t elf_idx)
114: insn_set_(insn_set), elf_idx_(elf_idx), context_(new llvm::LLVMContext()),
Logan Chien937105a2012-04-02 02:37:37 +0800115 mem_usage_(0), num_elf_funcs_(0) {
Logan Chien8b977d32012-02-21 19:14:55 +0800116
117 // Create the module and include the runtime function declaration
118 module_ = new llvm::Module("art", *context_);
119 makeLLVMModuleContents(module_);
120
121 // Create IRBuilder
122 irb_.reset(new IRBuilder(*context_, *module_));
TDYa127d668a062012-04-13 12:36:57 -0700123
124 // We always need a switch case, so just use a normal function.
125 switch(insn_set_) {
126 default:
127 runtime_support_.reset(new RuntimeSupportBuilder(*context_, *module_, *irb_));
128 break;
129 case kArm:
130 case kThumb2:
131 runtime_support_.reset(new RuntimeSupportBuilderARM(*context_, *module_, *irb_));
132 break;
133 case kX86:
134 runtime_support_.reset(new RuntimeSupportBuilderX86(*context_, *module_, *irb_));
135 break;
136 }
137
138 runtime_support_->OptimizeRuntimeSupport();
139
140 irb_->SetRuntimeSupport(runtime_support_.get());
Logan Chien8b977d32012-02-21 19:14:55 +0800141}
142
143
144CompilationUnit::~CompilationUnit() {
145}
146
147
Shih-wei Liaodbd00342012-04-20 14:27:29 -0700148bool CompilationUnit::WriteBitcodeToFile(const std::string& bitcode_filename) {
Logan Chien8b977d32012-02-21 19:14:55 +0800149 std::string errmsg;
150
151 llvm::OwningPtr<llvm::tool_output_file> out_file(
Shih-wei Liaodbd00342012-04-20 14:27:29 -0700152 new llvm::tool_output_file(bitcode_filename.c_str(), errmsg,
Logan Chien8b977d32012-02-21 19:14:55 +0800153 llvm::raw_fd_ostream::F_Binary));
154
155
156 if (!errmsg.empty()) {
157 LOG(ERROR) << "Failed to create bitcode output file: " << errmsg;
158 return false;
159 }
160
161 llvm::WriteBitcodeToFile(module_, out_file->os());
162 out_file->keep();
163
164 return true;
165}
166
Shih-wei Liaod7726e42012-04-20 15:23:36 -0700167// TODO: Move to scoped_temp_file.h
168class ScopedTempFile {
169 public:
170 ScopedTempFile(const std::string& filename_template)
171 : filename_(filename_template), file_(NULL) {
172 int fd = mkstemp(&filename_[0]);
173 CHECK_NE(-1, fd);
174 file_ = OS::FileFromFd(filename_.c_str(), fd);
Logan Chien8b977d32012-02-21 19:14:55 +0800175 }
176
Shih-wei Liaod7726e42012-04-20 15:23:36 -0700177 ~ScopedTempFile() {
178 delete file_;
179 TEMP_FAILURE_RETRY(unlink(filename_.c_str()));
180 }
Logan Chien8b977d32012-02-21 19:14:55 +0800181
Shih-wei Liaod7726e42012-04-20 15:23:36 -0700182 int GetFd() {
183 return file_->Fd();
184 }
Logan Chien8b977d32012-02-21 19:14:55 +0800185
Shih-wei Liaod7726e42012-04-20 15:23:36 -0700186 const std::string &GetName() const {
187 return filename_;
188 }
Logan Chien8b977d32012-02-21 19:14:55 +0800189
Shih-wei Liaod7726e42012-04-20 15:23:36 -0700190 bool ReadToString(std::string &buffer) {
191 off_t file_size = file_->Length();
192 if (file_size <= 0) {
193 buffer.clear();
194 return true;
195 }
Logan Chien8b977d32012-02-21 19:14:55 +0800196
Shih-wei Liaod7726e42012-04-20 15:23:36 -0700197 buffer.reserve(file_size);
198 buffer.resize(file_size);
199 return file_->ReadFully(&buffer[0], file_size);
200 }
Logan Chien8b977d32012-02-21 19:14:55 +0800201
Shih-wei Liaod7726e42012-04-20 15:23:36 -0700202 private:
203 std::string filename_;
204 File *file_;
205};
Logan Chien8b977d32012-02-21 19:14:55 +0800206
Shih-wei Liaod7726e42012-04-20 15:23:36 -0700207bool CompilationUnit::Materialize() {
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700208 const std::string tmp_file("/tmp/art-llvm-XXXXXX");
Logan Chien8b977d32012-02-21 19:14:55 +0800209
Shih-wei Liaod7726e42012-04-20 15:23:36 -0700210 // Prepare the input
211 ScopedTempFile input(tmp_file);
212 if (input.GetFd() < 0) {
213 PLOG(ERROR) << "Failed to save the module to the file " << tmp_file;
214 return false;
215 }
Logan Chien8b977d32012-02-21 19:14:55 +0800216
Shih-wei Liaod7726e42012-04-20 15:23:36 -0700217 // Write the bitcode to the file
218 if (!WriteBitcodeToFile(input.GetName())) {
219 return false;
220 }
Logan Chien8b977d32012-02-21 19:14:55 +0800221
Shih-wei Liaod7726e42012-04-20 15:23:36 -0700222 // Prepare the output
223 ScopedTempFile output(tmp_file);
224 if (output.GetFd() < 0) {
225 PLOG(ERROR) << "Failed to prepare the output file " << tmp_file;
226 return false;
227 }
Shih-wei Liao17765722012-04-17 16:42:19 -0700228
Shih-wei Liaod7726e42012-04-20 15:23:36 -0700229 // Fork a process to do the compilation
230 pid_t pid = fork();
231 if (pid == 0) {
232 // change process groups, so we don't get ripped by ProcessManager
233 setpgid(0, 0);
Logan Chienb9eaeea2012-03-17 19:45:01 +0800234
Shih-wei Liaod7726e42012-04-20 15:23:36 -0700235 // TODO: Should use exec* family instead of invoking a function.
236 // Forward our compilation request to bcc.
237 exit(static_cast<int>(!MaterializeFile(input.GetFd(), output.GetFd(),
238 insn_set_)));
239 } else {
240 if (pid < 0) {
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700241 PLOG(FATAL) << "Failed to fork a process to do the compilation";
Shih-wei Liaod7726e42012-04-20 15:23:36 -0700242 }
243
244 // Free the resources
245 context_.reset(NULL);
246 irb_.reset(NULL);
247 module_ = NULL;
248
249 int status;
250
251 // Wait for child to finish
252 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
253 if (got_pid != pid) {
254 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
Logan Chienb9eaeea2012-03-17 19:45:01 +0800255 return false;
256 }
257
Shih-wei Liaod7726e42012-04-20 15:23:36 -0700258 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
259 LOG(ERROR) << "Failed to compile the bitcode: " << WEXITSTATUS(status);
260 return false;
Shih-wei Liao17765722012-04-17 16:42:19 -0700261 }
Shih-wei Liaod7726e42012-04-20 15:23:36 -0700262 }
Shih-wei Liao17765722012-04-17 16:42:19 -0700263
Shih-wei Liaod7726e42012-04-20 15:23:36 -0700264 // Read the result out from the output file
265 TEMP_FAILURE_RETRY(lseek(output.GetFd(), 0, SEEK_SET));
266 if (!output.ReadToString(elf_image_)) {
267 LOG(ERROR) << "Failed to read the result file";
268 return false;
Logan Chienb9eaeea2012-03-17 19:45:01 +0800269 }
270
Logan Chiende08e842012-03-21 00:34:12 +0800271 LOG(INFO) << "Compilation Unit: " << elf_idx_ << " (done)";
Logan Chien7f767612012-03-01 18:54:49 +0800272
Logan Chien8b977d32012-02-21 19:14:55 +0800273 return true;
274}
275
276
Logan Chien110bcba2012-04-16 19:11:28 +0800277void CompilationUnit::RegisterCompiledMethod(const llvm::Function* func,
278 CompiledMethod* compiled_method) {
279 compiled_methods_map_.Put(func, compiled_method);
280}
281
282
283void CompilationUnit::UpdateFrameSizeInBytes(const llvm::Function* func,
284 size_t frame_size_in_bytes) {
285 SafeMap<const llvm::Function*, CompiledMethod*>::iterator iter =
286 compiled_methods_map_.find(func);
287
288 if (iter != compiled_methods_map_.end()) {
289 CompiledMethod* compiled_method = iter->second;
290 compiled_method->SetFrameSizeInBytes(frame_size_in_bytes);
291
292 if (frame_size_in_bytes > 1728u) {
293 LOG(WARNING) << "Huge frame size: " << frame_size_in_bytes
294 << " elf_idx=" << compiled_method->GetElfIndex()
295 << " elf_func_idx=" << compiled_method->GetElfFuncIndex();
296 }
297 }
298}
299
Shih-wei Liaod7726e42012-04-20 15:23:36 -0700300bool CompilationUnit::MaterializeFile(int input_fd, int output_fd,
301 InstructionSet insn_set) {
302 // Initialize the LLVM first
303 llvm::InitializeAllTargets();
304 llvm::InitializeAllTargetMCs();
305 llvm::InitializeAllAsmPrinters();
306 llvm::InitializeAllAsmParsers();
307
308 // Read the LLVM module from input_fd
309 llvm::OwningPtr<llvm::MemoryBuffer> memory_buffer;
310 llvm::error_code load_input_err =
311 llvm::MemoryBuffer::getOpenFile(input_fd, "<art-llvm-module>",
312 memory_buffer);
313
314 if (load_input_err) {
315 LOG(ERROR) << "Failed to load input for compiler into memory: "
316 << load_input_err.message();
317 return false;
318 }
319
320 // It's safe to use the global context now
321 std::string load_module_errmsg;
322 llvm::Module *module = ParseBitcodeFile(memory_buffer.get(),
323 llvm::getGlobalContext(),
324 &load_module_errmsg);
325 if (module == NULL) {
326 LOG(ERROR) << "Failed to load LLVM module to compiler: "
327 << load_module_errmsg;
328 return false;
329 }
330
331 // Lookup the LLVM target
332 char const* target_triple = NULL;
333 char const* target_attr = NULL;
334
335 switch (insn_set) {
336 case kThumb2:
337 target_triple = "thumb-none-linux-gnueabi";
338 target_attr = "+thumb2,+neon,+neonfp,+vfp3";
339 break;
340
341 case kArm:
342 target_triple = "armv7-none-linux-gnueabi";
343 // TODO: Fix for Xoom.
344 target_attr = "+v7,+neon,+neonfp,+vfp3";
345 break;
346
347 case kX86:
348 target_triple = "i386-pc-linux-gnu";
349 target_attr = "";
350 break;
351
352 case kMips:
353 target_triple = "mipsel-unknown-linux";
354 target_attr = "mips32r2";
355 break;
356
357 default:
358 LOG(FATAL) << "Unknown instruction set: " << insn_set;
359 }
360
361 std::string errmsg;
362 llvm::Target const* target =
363 llvm::TargetRegistry::lookupTarget(target_triple, errmsg);
364
365 CHECK(target != NULL) << errmsg;
366
367 // Target options
368 llvm::TargetOptions target_options;
369 target_options.FloatABIType = llvm::FloatABI::Soft;
370 target_options.NoFramePointerElim = true;
371 target_options.NoFramePointerElimNonLeaf = true;
372 target_options.UseSoftFloat = false;
373 target_options.EnableFastISel = true;
374
375 // Create the llvm::TargetMachine
376 llvm::TargetMachine* target_machine =
377 target->createTargetMachine(target_triple, "", target_attr, target_options,
378 llvm::Reloc::Static, llvm::CodeModel::Small,
379 llvm::CodeGenOpt::Less);
380
381 CHECK(target_machine != NULL) << "Failed to create target machine";
382
383 // Add target data
384 llvm::TargetData const* target_data = target_machine->getTargetData();
385
386 // PassManager for code generation passes
387 llvm::PassManager pm;
388 pm.add(new llvm::TargetData(*target_data));
389
390 // FunctionPassManager for optimization pass
391 llvm::FunctionPassManager fpm(module);
392 fpm.add(new llvm::TargetData(*target_data));
393
394 // Add optimization pass
395 llvm::PassManagerBuilder pm_builder;
396 pm_builder.Inliner = llvm::createAlwaysInlinerPass();
397 pm_builder.OptLevel = 1;
398 pm_builder.DisableSimplifyLibCalls = 1;
399 pm_builder.populateModulePassManager(pm);
400 pm_builder.populateFunctionPassManager(fpm);
401
402 // Add passes to emit ELF image
403 {
404 llvm::formatted_raw_ostream formatted_os(
405 *(new llvm::raw_fd_ostream(output_fd, /* shouldClose */false)), true);
406
407 // Ask the target to add backend passes as necessary.
408 if (target_machine->addPassesToEmitFile(pm,
409 formatted_os,
410 llvm::TargetMachine::CGFT_ObjectFile,
411 true)) {
412 LOG(FATAL) << "Unable to generate ELF for this target";
413 return false;
414 }
415
416 // FIXME: Unable to run the UpdateFrameSizePass pass since it tries to
417 // update the value reside in the different address space.
418 // Add pass to update the frame_size_in_bytes_
419 //pm.add(new ::UpdateFrameSizePass(this));
420
421 // Run the per-function optimization
422 fpm.doInitialization();
423 for (llvm::Module::iterator F = module->begin(), E = module->end();
424 F != E; ++F) {
425 fpm.run(*F);
426 }
427 fpm.doFinalization();
428
429 // Run the code generation passes
430 pm.run(*module);
431 }
432
433 return true;
434}
Logan Chien110bcba2012-04-16 19:11:28 +0800435
Logan Chien8b977d32012-02-21 19:14:55 +0800436} // namespace compiler_llvm
437} // namespace art