Compiler.cpp revision 1e321862daea867b44700360c4827bcb7b97968a
1/* 2 * Copyright 2010-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 "bcc/Compiler.h" 18 19#include <llvm/Analysis/Passes.h> 20#include <llvm/Analysis/TargetTransformInfo.h> 21#include <llvm/CodeGen/RegAllocRegistry.h> 22#include <llvm/IR/LegacyPassManager.h> 23#include <llvm/IR/Module.h> 24#include <llvm/Support/TargetRegistry.h> 25#include <llvm/Support/raw_ostream.h> 26#include <llvm/IR/DataLayout.h> 27#include <llvm/Target/TargetSubtargetInfo.h> 28#include <llvm/Target/TargetMachine.h> 29#include <llvm/Transforms/IPO.h> 30#include <llvm/Transforms/IPO/PassManagerBuilder.h> 31#include <llvm/Transforms/Scalar.h> 32#include <llvm/Transforms/Vectorize.h> 33 34#include "bcc/Assert.h" 35#include "bcc/Renderscript/RSScript.h" 36#include "bcc/Renderscript/RSTransforms.h" 37#include "bcc/Script.h" 38#include "bcc/Source.h" 39#include "bcc/Support/CompilerConfig.h" 40#include "bcc/Support/Log.h" 41#include "bcc/Support/OutputFile.h" 42#include "bcinfo/MetadataExtractor.h" 43#include "rsDefines.h" 44 45#include <string> 46 47using namespace bcc; 48 49const char *Compiler::GetErrorString(enum ErrorCode pErrCode) { 50 switch (pErrCode) { 51 case kSuccess: 52 return "Successfully compiled."; 53 case kInvalidConfigNoTarget: 54 return "Invalid compiler config supplied (getTarget() returns nullptr.) " 55 "(missing call to CompilerConfig::initialize()?)"; 56 case kErrCreateTargetMachine: 57 return "Failed to create llvm::TargetMachine."; 58 case kErrSwitchTargetMachine: 59 return "Failed to switch llvm::TargetMachine."; 60 case kErrNoTargetMachine: 61 return "Failed to compile the script since there's no available " 62 "TargetMachine. (missing call to Compiler::config()?)"; 63 case kErrMaterialization: 64 return "Failed to materialize the module."; 65 case kErrInvalidOutputFileState: 66 return "Supplied output file was invalid (in the error state.)"; 67 case kErrPrepareOutput: 68 return "Failed to prepare file for output."; 69 case kPrepareCodeGenPass: 70 return "Failed to construct pass list for code-generation."; 71 case kErrCustomPasses: 72 return "Error occurred while adding custom passes."; 73 case kErrInvalidSource: 74 return "Error loading input bitcode"; 75 case kIllegalGlobalFunction: 76 return "Use of undefined external function"; 77 } 78 79 // This assert should never be reached as the compiler verifies that the 80 // above switch coveres all enum values. 81 bccAssert(false && "Unknown error code encountered"); 82 return ""; 83} 84 85//===----------------------------------------------------------------------===// 86// Instance Methods 87//===----------------------------------------------------------------------===// 88Compiler::Compiler() : mTarget(nullptr), mEnableOpt(true) { 89 return; 90} 91 92Compiler::Compiler(const CompilerConfig &pConfig) : mTarget(nullptr), 93 mEnableOpt(true) { 94 const std::string &triple = pConfig.getTriple(); 95 96 enum ErrorCode err = config(pConfig); 97 if (err != kSuccess) { 98 ALOGE("%s (%s, features: %s)", GetErrorString(err), 99 triple.c_str(), pConfig.getFeatureString().c_str()); 100 return; 101 } 102 103 return; 104} 105 106enum Compiler::ErrorCode Compiler::config(const CompilerConfig &pConfig) { 107 if (pConfig.getTarget() == nullptr) { 108 return kInvalidConfigNoTarget; 109 } 110 111 llvm::TargetMachine *new_target = 112 (pConfig.getTarget())->createTargetMachine(pConfig.getTriple(), 113 pConfig.getCPU(), 114 pConfig.getFeatureString(), 115 pConfig.getTargetOptions(), 116 pConfig.getRelocationModel(), 117 pConfig.getCodeModel(), 118 pConfig.getOptimizationLevel()); 119 120 if (new_target == nullptr) { 121 return ((mTarget != nullptr) ? kErrSwitchTargetMachine : 122 kErrCreateTargetMachine); 123 } 124 125 // Replace the old TargetMachine. 126 delete mTarget; 127 mTarget = new_target; 128 129 // Adjust register allocation policy according to the optimization level. 130 // createFastRegisterAllocator: fast but bad quality 131 // createLinearScanRegisterAllocator: not so fast but good quality 132 if ((pConfig.getOptimizationLevel() == llvm::CodeGenOpt::None)) { 133 llvm::RegisterRegAlloc::setDefault(llvm::createFastRegisterAllocator); 134 } else { 135 llvm::RegisterRegAlloc::setDefault(llvm::createGreedyRegisterAllocator); 136 } 137 138 return kSuccess; 139} 140 141Compiler::~Compiler() { 142 delete mTarget; 143} 144 145 146// This function has complete responsibility for creating and executing the 147// exact list of compiler passes. 148enum Compiler::ErrorCode Compiler::runPasses(Script &pScript, 149 llvm::raw_pwrite_stream &pResult) { 150 // Pass manager for link-time optimization 151 llvm::legacy::PassManager transformPasses; 152 153 // Empty MCContext. 154 llvm::MCContext *mc_context = nullptr; 155 156 transformPasses.add( 157 createTargetTransformInfoWrapperPass(mTarget->getTargetIRAnalysis())); 158 159 // Add some initial custom passes. 160 addInvokeHelperPass(transformPasses); 161 addExpandKernelPass(transformPasses); 162 addInvariantPass(transformPasses); 163 if (!addInternalizeSymbolsPass(pScript, transformPasses)) 164 return kErrCustomPasses; 165 addGlobalInfoPass(pScript, transformPasses); 166 167 if (mTarget->getOptLevel() == llvm::CodeGenOpt::None) { 168 transformPasses.add(llvm::createGlobalOptimizerPass()); 169 transformPasses.add(llvm::createConstantMergePass()); 170 171 } else { 172 // FIXME: Figure out which passes should be executed. 173 llvm::PassManagerBuilder Builder; 174 Builder.Inliner = llvm::createFunctionInliningPass(); 175 Builder.populateLTOPassManager(transformPasses); 176 177 /* FIXME: Reenable autovectorization after rebase. 178 bug 19324423 179 // Add vectorization passes after LTO passes are in 180 // additional flag: -unroll-runtime 181 transformPasses.add(llvm::createLoopUnrollPass(-1, 16, 0, 1)); 182 // Need to pass appropriate flags here: -scalarize-load-store 183 transformPasses.add(llvm::createScalarizerPass()); 184 transformPasses.add(llvm::createCFGSimplificationPass()); 185 transformPasses.add(llvm::createScopedNoAliasAAPass()); 186 transformPasses.add(llvm::createScalarEvolutionAliasAnalysisPass()); 187 // additional flags: -slp-vectorize-hor -slp-vectorize-hor-store (unnecessary?) 188 transformPasses.add(llvm::createSLPVectorizerPass()); 189 transformPasses.add(llvm::createDeadCodeEliminationPass()); 190 transformPasses.add(llvm::createInstructionCombiningPass()); 191 */ 192 } 193 194 // These passes have to come after LTO, since we don't want to examine 195 // functions that are never actually called. 196 if (llvm::Triple(getTargetMachine().getTargetTriple()).getArch() == llvm::Triple::x86_64) 197 transformPasses.add(createRSX86_64CallConvPass()); // Add pass to correct calling convention for X86-64. 198 transformPasses.add(createRSIsThreadablePass()); // Add pass to mark script as threadable. 199 200 // RSEmbedInfoPass needs to come after we have scanned for non-threadable 201 // functions. 202 // Script passed to RSCompiler must be a RSScript. 203 RSScript &script = static_cast<RSScript &>(pScript); 204 if (script.getEmbedInfo()) 205 transformPasses.add(createRSEmbedInfoPass()); 206 207 // Execute the passes. 208 transformPasses.run(pScript.getSource().getModule()); 209 210 // Run backend separately to avoid interference between debug metadata 211 // generation and backend initialization. 212 llvm::legacy::PassManager codeGenPasses; 213 214 // Add passes to the pass manager to emit machine code through MC layer. 215 if (mTarget->addPassesToEmitMC(codeGenPasses, mc_context, pResult, 216 /* DisableVerify */false)) { 217 return kPrepareCodeGenPass; 218 } 219 220 // Execute the passes. 221 codeGenPasses.run(pScript.getSource().getModule()); 222 223 return kSuccess; 224} 225 226enum Compiler::ErrorCode Compiler::compile(Script &pScript, 227 llvm::raw_pwrite_stream &pResult, 228 llvm::raw_ostream *IRStream) { 229 llvm::Module &module = pScript.getSource().getModule(); 230 enum ErrorCode err; 231 232 if (mTarget == nullptr) { 233 return kErrNoTargetMachine; 234 } 235 236 const std::string &triple = module.getTargetTriple(); 237 const llvm::DataLayout *dl = getTargetMachine().getDataLayout(); 238 unsigned int pointerSize = dl->getPointerSizeInBits(); 239 if (triple == "armv7-none-linux-gnueabi") { 240 if (pointerSize != 32) { 241 return kErrInvalidSource; 242 } 243 } else if (triple == "aarch64-none-linux-gnueabi") { 244 if (pointerSize != 64) { 245 return kErrInvalidSource; 246 } 247 } else { 248 return kErrInvalidSource; 249 } 250 251 // Sanitize module's target information. 252 module.setTargetTriple(getTargetMachine().getTargetTriple()); 253 module.setDataLayout(*getTargetMachine().getDataLayout()); 254 255 // Materialize the bitcode module. 256 if (module.getMaterializer() != nullptr) { 257 // A module with non-null materializer means that it is a lazy-load module. 258 // Materialize it now via invoking MaterializeAllPermanently(). This 259 // function returns false when the materialization is successful. 260 std::error_code ec = module.materializeAllPermanently(); 261 if (ec) { 262 ALOGE("Failed to materialize the module `%s'! (%s)", 263 module.getModuleIdentifier().c_str(), ec.message().c_str()); 264 return kErrMaterialization; 265 } 266 } 267 268 if ((err = runPasses(pScript, pResult)) != kSuccess) { 269 return err; 270 } 271 272 if (IRStream) { 273 *IRStream << module; 274 } 275 276 return kSuccess; 277} 278 279enum Compiler::ErrorCode Compiler::compile(Script &pScript, 280 OutputFile &pResult, 281 llvm::raw_ostream *IRStream) { 282 // Check the state of the specified output file. 283 if (pResult.hasError()) { 284 return kErrInvalidOutputFileState; 285 } 286 287 // Open the output file decorated in llvm::raw_ostream. 288 llvm::raw_pwrite_stream *out = pResult.dup(); 289 if (out == nullptr) { 290 return kErrPrepareOutput; 291 } 292 293 // Delegate the request. 294 enum Compiler::ErrorCode err = compile(pScript, *out, IRStream); 295 296 // Close the output before return. 297 delete out; 298 299 return err; 300} 301 302bool Compiler::addInternalizeSymbolsPass(Script &pScript, llvm::legacy::PassManager &pPM) { 303 // Add a pass to internalize the symbols that don't need to have global 304 // visibility. 305 RSScript &script = static_cast<RSScript &>(pScript); 306 llvm::Module &module = script.getSource().getModule(); 307 bcinfo::MetadataExtractor me(&module); 308 if (!me.extract()) { 309 bccAssert(false && "Could not extract metadata for module!"); 310 return false; 311 } 312 313 // The vector contains the symbols that should not be internalized. 314 std::vector<const char *> export_symbols; 315 316 const char *sf[] = { 317 kRoot, // Graphics drawing function or compute kernel. 318 kInit, // Initialization routine called implicitly on startup. 319 kRsDtor, // Static global destructor for a script instance. 320 kRsInfo, // Variable containing string of RS metadata info. 321 kRsGlobalEntries, // Optional number of global variables. 322 kRsGlobalNames, // Optional global variable name info. 323 kRsGlobalAddresses, // Optional global variable address info. 324 kRsGlobalSizes, // Optional global variable size info. 325 kRsGlobalProperties, // Optional global variable properties. 326 nullptr // Must be nullptr-terminated. 327 }; 328 const char **special_functions = sf; 329 // Special RS functions should always be global symbols. 330 while (*special_functions != nullptr) { 331 export_symbols.push_back(*special_functions); 332 special_functions++; 333 } 334 335 // Visibility of symbols appeared in rs_export_var and rs_export_func should 336 // also be preserved. 337 size_t exportVarCount = me.getExportVarCount(); 338 size_t exportFuncCount = me.getExportFuncCount(); 339 size_t exportForEachCount = me.getExportForEachSignatureCount(); 340 size_t exportReduceCount = me.getExportReduceCount(); 341 size_t exportReduceNewCount = me.getExportReduceNewCount(); 342 const char **exportVarNameList = me.getExportVarNameList(); 343 const char **exportFuncNameList = me.getExportFuncNameList(); 344 const char **exportForEachNameList = me.getExportForEachNameList(); 345 const char **exportReduceNameList = me.getExportReduceNameList(); 346 const bcinfo::MetadataExtractor::ReduceNew *exportReduceNewList = me.getExportReduceNewList(); 347 size_t i; 348 349 for (i = 0; i < exportVarCount; ++i) { 350 export_symbols.push_back(exportVarNameList[i]); 351 } 352 353 for (i = 0; i < exportFuncCount; ++i) { 354 export_symbols.push_back(exportFuncNameList[i]); 355 } 356 357 // Expanded foreach and reduce functions should not be 358 // internalized. expanded_funcs keeps the names of the expanded 359 // functions around until createInternalizePass() is finished making 360 // its own copy of the visible symbols. 361 std::vector<std::string> expanded_funcs; 362 expanded_funcs.reserve(exportForEachCount + exportReduceCount + exportReduceNewCount); 363 364 for (i = 0; i < exportForEachCount; ++i) { 365 expanded_funcs.push_back(std::string(exportForEachNameList[i]) + ".expand"); 366 } 367 for (i = 0; i < exportReduceCount; ++i) { 368 expanded_funcs.push_back(std::string(exportReduceNameList[i]) + ".expand"); 369 } 370 for (i = 0; i < exportReduceNewCount; ++i) { 371 expanded_funcs.push_back(std::string(exportReduceNewList[i].mAccumulatorName) + ".expand"); 372 } 373 374 for (auto &symbol_name : expanded_funcs) { 375 export_symbols.push_back(symbol_name.c_str()); 376 } 377 378 pPM.add(llvm::createInternalizePass(export_symbols)); 379 380 return true; 381} 382 383void Compiler::addInvokeHelperPass(llvm::legacy::PassManager &pPM) { 384 llvm::Triple arch(getTargetMachine().getTargetTriple()); 385 if (arch.isArch64Bit()) { 386 pPM.add(createRSInvokeHelperPass()); 387 } 388} 389 390void Compiler::addExpandKernelPass(llvm::legacy::PassManager &pPM) { 391 // Expand ForEach and reduce on CPU path to reduce launch overhead. 392 bool pEnableStepOpt = true; 393 pPM.add(createRSKernelExpandPass(pEnableStepOpt)); 394} 395 396void Compiler::addGlobalInfoPass(Script &pScript, llvm::legacy::PassManager &pPM) { 397 // Add additional information about RS global variables inside the Module. 398 RSScript &script = static_cast<RSScript &>(pScript); 399 if (script.getEmbedGlobalInfo()) { 400 pPM.add(createRSGlobalInfoPass(script.getEmbedGlobalInfoSkipConstant())); 401 } 402} 403 404void Compiler::addInvariantPass(llvm::legacy::PassManager &pPM) { 405 // Mark Loads from RsExpandKernelDriverInfo as "load.invariant". 406 // Should run after ExpandForEach and before inlining. 407 pPM.add(createRSInvariantPass()); 408} 409 410enum Compiler::ErrorCode Compiler::screenGlobalFunctions(Script &pScript) { 411 llvm::Module &module = pScript.getSource().getModule(); 412 413 // Materialize the bitcode module in case this is a lazy-load module. Do not 414 // clear the materializer by calling materializeAllPermanently since the 415 // runtime library has not been merged into the module yet. 416 if (module.getMaterializer() != nullptr) { 417 std::error_code ec = module.materializeAll(); 418 if (ec) { 419 ALOGE("Failed to materialize module `%s' when screening globals! (%s)", 420 module.getModuleIdentifier().c_str(), ec.message().c_str()); 421 return kErrMaterialization; 422 } 423 } 424 425 // Add pass to check for illegal function calls. 426 llvm::legacy::PassManager pPM; 427 pPM.add(createRSScreenFunctionsPass()); 428 pPM.run(module); 429 430 return kSuccess; 431 432} 433