write.rs 87.9 KB
Newer Older
A
Akos Kiss 已提交
1
// Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT
2 3 4 5 6 7 8 9 10
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

11 12
use back::bytecode::{self, RLIB_BYTECODE_EXTENSION};
use back::lto::{self, ModuleBuffer, ThinBuffer};
13
use back::link::{self, get_linker, remove};
14
use back::linker::LinkerInfo;
15
use back::symbol_export::ExportedSymbols;
16 17
use base;
use consts;
18
use rustc_incremental::{save_trans_partition, in_incr_comp_dir};
19
use rustc::dep_graph::{DepGraph, WorkProductFileKind};
20
use rustc::middle::cstore::{LinkMeta, EncodedMetadata};
21 22 23
use rustc::session::config::{self, OutputFilenames, OutputType, OutputTypes, Passes, SomePasses,
                             AllPasses, Sanitizer};
use rustc::session::Session;
24
use rustc::util::nodemap::FxHashMap;
A
Alex Crichton 已提交
25
use time_graph::{self, TimeGraph, Timeline};
26
use llvm;
27
use llvm::{ModuleRef, TargetMachineRef, PassManagerRef, DiagnosticInfoRef};
28
use llvm::{SMDiagnosticRef, ContextRef};
29
use {CrateTranslation, ModuleSource, ModuleTranslation, CompiledModule, ModuleKind};
30
use CrateInfo;
31 32
use rustc::hir::def_id::{CrateNum, LOCAL_CRATE};
use rustc::ty::TyCtxt;
33
use rustc::util::common::{time, time_depth, set_time_depth, path2cstr, print_time_passes_entry};
34
use rustc::util::fs::{link_or_copy, rename_or_copy_remove};
35
use errors::{self, Handler, Level, DiagnosticBuilder, FatalError};
36
use errors::emitter::{Emitter};
37
use syntax::attr;
38
use syntax::ext::hygiene::Mark;
39
use syntax_pos::MultiSpan;
40
use syntax_pos::symbol::Symbol;
41
use type_::Type;
42
use context::{is_pie_binary, get_reloc_model};
43
use jobserver::{Client, Acquired};
44
use rustc_demangle;
45

46
use std::any::Any;
47
use std::ffi::{CString, CStr};
48
use std::fs::{self, File};
49
use std::io;
50
use std::io::Write;
51
use std::mem;
52
use std::path::{Path, PathBuf};
53
use std::str;
54
use std::sync::Arc;
55
use std::sync::mpsc::{channel, Sender, Receiver};
56
use std::slice;
57
use std::time::Instant;
58
use std::thread;
59
use libc::{c_uint, c_void, c_char, size_t};
60

61
pub const RELOC_MODEL_ARGS : [(&'static str, llvm::RelocMode); 7] = [
62 63 64 65
    ("pic", llvm::RelocMode::PIC),
    ("static", llvm::RelocMode::Static),
    ("default", llvm::RelocMode::Default),
    ("dynamic-no-pic", llvm::RelocMode::DynamicNoPic),
66 67 68
    ("ropi", llvm::RelocMode::ROPI),
    ("rwpi", llvm::RelocMode::RWPI),
    ("ropi-rwpi", llvm::RelocMode::ROPI_RWPI),
69 70
];

71 72 73 74 75 76
pub const CODE_GEN_MODEL_ARGS : [(&'static str, llvm::CodeModel); 5] = [
    ("default", llvm::CodeModel::Default),
    ("small", llvm::CodeModel::Small),
    ("kernel", llvm::CodeModel::Kernel),
    ("medium", llvm::CodeModel::Medium),
    ("large", llvm::CodeModel::Large),
77 78
];

79
pub fn llvm_err(handler: &errors::Handler, msg: String) -> FatalError {
A
Alex Crichton 已提交
80
    match llvm::last_error() {
81 82
        Some(err) => handler.fatal(&format!("{}: {}", msg, err)),
        None => handler.fatal(&msg),
83 84 85 86
    }
}

pub fn write_output_file(
87
        handler: &errors::Handler,
88 89 90 91
        target: llvm::TargetMachineRef,
        pm: llvm::PassManagerRef,
        m: ModuleRef,
        output: &Path,
92
        file_type: llvm::FileType) -> Result<(), FatalError> {
93
    unsafe {
A
Alex Crichton 已提交
94
        let output_c = path2cstr(output);
A
Alex Crichton 已提交
95
        let result = llvm::LLVMRustWriteOutputFile(
96
                target, pm, m, output_c.as_ptr(), file_type);
97
        if result.into_result().is_err() {
98 99 100 101
            let msg = format!("could not write output to {}", output.display());
            Err(llvm_err(handler, msg))
        } else {
            Ok(())
102
        }
103 104 105
    }
}

106 107 108 109 110 111 112 113 114 115 116 117
// On android, we by default compile for armv7 processors. This enables
// things like double word CAS instructions (rather than emulating them)
// which are *far* more efficient. This is obviously undesirable in some
// cases, so if any sort of target feature is specified we don't append v7
// to the feature list.
//
// On iOS only armv7 and newer are supported. So it is useful to
// get all hardware potential via VFP3 (hardware floating point)
// and NEON (SIMD) instructions supported by LLVM.
// Note that without those flags various linking errors might
// arise as some of intrinsics are converted into function calls
// and nobody provides implementations those functions
118
fn target_feature(sess: &Session) -> String {
119 120 121 122 123 124 125 126 127 128
    let rustc_features = [
        "crt-static",
    ];
    let requested_features = sess.opts.cg.target_feature.split(',');
    let llvm_features = requested_features.filter(|f| {
        !rustc_features.iter().any(|s| f.contains(s))
    });
    format!("{},{}",
            sess.target.target.options.features,
            llvm_features.collect::<Vec<_>>().join(","))
129 130
}

131 132
fn get_llvm_opt_level(optimize: config::OptLevel) -> llvm::CodeGenOptLevel {
    match optimize {
133 134 135 136 137
      config::OptLevel::No => llvm::CodeGenOptLevel::None,
      config::OptLevel::Less => llvm::CodeGenOptLevel::Less,
      config::OptLevel::Default => llvm::CodeGenOptLevel::Default,
      config::OptLevel::Aggressive => llvm::CodeGenOptLevel::Aggressive,
      _ => llvm::CodeGenOptLevel::Default,
138 139 140 141 142 143 144 145
    }
}

fn get_llvm_opt_size(optimize: config::OptLevel) -> llvm::CodeGenOptSize {
    match optimize {
      config::OptLevel::Size => llvm::CodeGenOptSizeDefault,
      config::OptLevel::SizeMin => llvm::CodeGenOptSizeAggressive,
      _ => llvm::CodeGenOptSizeNone,
146 147
    }
}
148

149
pub fn create_target_machine(sess: &Session) -> TargetMachineRef {
150 151 152 153 154 155 156 157
    target_machine_factory(sess)().unwrap_or_else(|err| {
        panic!(llvm_err(sess.diagnostic(), err))
    })
}

pub fn target_machine_factory(sess: &Session)
    -> Arc<Fn() -> Result<TargetMachineRef, String> + Send + Sync>
{
158
    let reloc_model = get_reloc_model(sess);
159

160 161 162
    let opt_level = get_llvm_opt_level(sess.opts.optimize);
    let use_softfp = sess.opts.cg.soft_float;

163
    let ffunction_sections = sess.target.target.options.function_sections;
164 165
    let fdata_sections = ffunction_sections;

166
    let code_model_arg = match sess.opts.cg.code_model {
167 168
        Some(ref s) => &s,
        None => &sess.target.target.options.code_model,
169 170
    };

171 172 173
    let code_model = match CODE_GEN_MODEL_ARGS.iter().find(
        |&&arg| arg.0 == code_model_arg) {
        Some(x) => x.1,
174
        _ => {
J
Jorge Aparicio 已提交
175
            sess.err(&format!("{:?} is not a valid code model",
176 177
                             sess.opts
                                 .cg
178
                                 .code_model));
179
            sess.abort_if_errors();
180
            bug!();
181 182 183
        }
    };

184
    let triple = &sess.target.target.llvm_target;
185

186 187 188 189
    let triple = CString::new(triple.as_bytes()).unwrap();
    let cpu = match sess.opts.cg.target_cpu {
        Some(ref s) => &**s,
        None => &*sess.target.target.options.cpu
190
    };
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
    let cpu = CString::new(cpu.as_bytes()).unwrap();
    let features = CString::new(target_feature(sess).as_bytes()).unwrap();
    let is_pie_binary = is_pie_binary(sess);

    Arc::new(move || {
        let tm = unsafe {
            llvm::LLVMRustCreateTargetMachine(
                triple.as_ptr(), cpu.as_ptr(), features.as_ptr(),
                code_model,
                reloc_model,
                opt_level,
                use_softfp,
                is_pie_binary,
                ffunction_sections,
                fdata_sections,
            )
        };
208

209 210 211 212 213 214 215
        if tm.is_null() {
            Err(format!("Could not create LLVM TargetMachine for triple: {}",
                        triple.to_str().unwrap()))
        } else {
            Ok(tm)
        }
    })
216 217 218
}

/// Module-specific configuration for `optimize_and_codegen`.
219
pub struct ModuleConfig {
220 221 222 223
    /// Names of additional optimization passes to run.
    passes: Vec<String>,
    /// Some(level) to optimize at a certain level, or None to run
    /// absolutely no optimizations (used for the metadata module).
224
    pub opt_level: Option<llvm::CodeGenOptLevel>,
225

226 227 228
    /// Some(level) to optimize binary size, or None to not affect program size.
    opt_size: Option<llvm::CodeGenOptSize>,

229 230 231
    // Flags indicating which outputs to produce.
    emit_no_opt_bc: bool,
    emit_bc: bool,
232
    emit_bc_compressed: bool,
233 234 235 236 237 238 239 240 241 242
    emit_lto_bc: bool,
    emit_ir: bool,
    emit_asm: bool,
    emit_obj: bool,
    // Miscellaneous flags.  These are mostly copied from command-line
    // options.
    no_verify: bool,
    no_prepopulate_passes: bool,
    no_builtins: bool,
    time_passes: bool,
A
Alex Crichton 已提交
243 244 245
    vectorize_loop: bool,
    vectorize_slp: bool,
    merge_functions: bool,
246 247 248 249 250
    inline_threshold: Option<usize>,
    // Instead of creating an object file by doing LLVM codegen, just
    // make the object file bitcode. Provides easy compatibility with
    // emscripten's ecc compiler, when used as the linker.
    obj_is_bitcode: bool,
251 252 253
}

impl ModuleConfig {
A
Alex Crichton 已提交
254
    fn new(passes: Vec<String>) -> ModuleConfig {
255
        ModuleConfig {
256
            passes,
257
            opt_level: None,
258
            opt_size: None,
259 260 261

            emit_no_opt_bc: false,
            emit_bc: false,
262
            emit_bc_compressed: false,
263 264 265 266
            emit_lto_bc: false,
            emit_ir: false,
            emit_asm: false,
            emit_obj: false,
267
            obj_is_bitcode: false,
268 269 270 271 272

            no_verify: false,
            no_prepopulate_passes: false,
            no_builtins: false,
            time_passes: false,
A
Alex Crichton 已提交
273 274 275
            vectorize_loop: false,
            vectorize_slp: false,
            merge_functions: false,
B
Brian Anderson 已提交
276
            inline_threshold: None
277
        }
278
    }
279

280
    fn set_flags(&mut self, sess: &Session, no_builtins: bool) {
281 282
        self.no_verify = sess.no_verify();
        self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
283
        self.no_builtins = no_builtins;
284
        self.time_passes = sess.time_passes();
B
Brian Anderson 已提交
285
        self.inline_threshold = sess.opts.cg.inline_threshold;
286
        self.obj_is_bitcode = sess.target.target.options.obj_is_bitcode;
A
Alex Crichton 已提交
287 288 289 290

        // Copy what clang does by turning on loop vectorization at O2 and
        // slp vectorization at O3. Otherwise configure other optimization aspects
        // of this pass manager builder.
291
        // Turn off vectorization for emscripten, as it's not very well supported.
A
Alex Crichton 已提交
292
        self.vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
293
                             (sess.opts.optimize == config::OptLevel::Default ||
294 295 296
                              sess.opts.optimize == config::OptLevel::Aggressive) &&
                             !sess.target.target.options.is_like_emscripten;

A
Alex Crichton 已提交
297
        self.vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
298 299
                            sess.opts.optimize == config::OptLevel::Aggressive &&
                            !sess.target.target.options.is_like_emscripten;
A
Alex Crichton 已提交
300

301 302
        self.merge_functions = sess.opts.optimize == config::OptLevel::Default ||
                               sess.opts.optimize == config::OptLevel::Aggressive;
303 304 305 306
    }
}

/// Additional resources used by optimize_and_codegen (not module specific)
307
#[derive(Clone)]
308
pub struct CodegenContext {
309 310 311
    // Resouces needed when running LTO
    pub time_passes: bool,
    pub lto: bool,
A
Alex Crichton 已提交
312
    pub thinlto: bool,
313
    pub no_landing_pads: bool,
314
    pub save_temps: bool,
315 316
    pub exported_symbols: Arc<ExportedSymbols>,
    pub opts: Arc<config::Options>,
317 318
    pub crate_types: Vec<config::CrateType>,
    pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
A
Alex Crichton 已提交
319 320 321 322
    output_filenames: Arc<OutputFilenames>,
    regular_module_config: Arc<ModuleConfig>,
    metadata_module_config: Arc<ModuleConfig>,
    allocator_module_config: Arc<ModuleConfig>,
323
    pub tm_factory: Arc<Fn() -> Result<TargetMachineRef, String> + Send + Sync>,
324 325
    pub msvc_imps_needed: bool,
    pub target_pointer_width: String,
A
Alex Crichton 已提交
326

A
Alex Crichton 已提交
327 328
    // Number of cgus excluding the allocator/metadata modules
    pub total_cgus: usize,
329
    // Handler to use for diagnostics produced during codegen.
330
    pub diag_emitter: SharedEmitter,
331
    // LLVM passes added by plugins.
332
    pub plugin_passes: Vec<String>,
333
    // LLVM optimizations for which we want to print remarks.
334
    pub remark: Passes,
335
    // Worker thread number
336
    pub worker: usize,
337 338
    // The incremental compilation session directory, or None if we are not
    // compiling incrementally
339 340
    pub incr_comp_session_dir: Option<PathBuf>,
    // Channel back to the main control thread to send messages to
341
    coordinator_send: Sender<Box<Any + Send>>,
342 343 344
    // A reference to the TimeGraph so we can register timings. None means that
    // measuring is disabled.
    time_graph: Option<TimeGraph>,
345
}
346

347
impl CodegenContext {
348
    pub fn create_diag_handler(&self) -> Handler {
349 350
        Handler::with_emitter(true, false, Box::new(self.diag_emitter.clone()))
    }
A
Alex Crichton 已提交
351

352
    pub fn config(&self, kind: ModuleKind) -> &ModuleConfig {
A
Alex Crichton 已提交
353 354 355 356 357 358
        match kind {
            ModuleKind::Regular => &self.regular_module_config,
            ModuleKind::Metadata => &self.metadata_module_config,
            ModuleKind::Allocator => &self.allocator_module_config,
        }
    }
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394

    pub fn save_temp_bitcode(&self, trans: &ModuleTranslation, name: &str) {
        if !self.save_temps {
            return
        }
        unsafe {
            let ext = format!("{}.bc", name);
            let cgu = Some(&trans.name[..]);
            let path = self.output_filenames.temp_path_ext(&ext, cgu);
            let cstr = path2cstr(&path);
            let llmod = trans.llvm().unwrap().llmod;
            llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
        }
    }
}

struct DiagnosticHandlers<'a> {
    inner: Box<(&'a CodegenContext, &'a Handler)>,
    llcx: ContextRef,
}

impl<'a> DiagnosticHandlers<'a> {
    fn new(cgcx: &'a CodegenContext,
           handler: &'a Handler,
           llcx: ContextRef) -> DiagnosticHandlers<'a> {
        let data = Box::new((cgcx, handler));
        unsafe {
            let arg = &*data as &(_, _) as *const _ as *mut _;
            llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, arg);
            llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, arg);
        }
        DiagnosticHandlers {
            inner: data,
            llcx: llcx,
        }
    }
395 396
}

397 398 399 400 401 402 403
impl<'a> Drop for DiagnosticHandlers<'a> {
    fn drop(&mut self) {
        unsafe {
            llvm::LLVMRustSetInlineAsmDiagnosticHandler(self.llcx, inline_asm_handler, 0 as *mut _);
            llvm::LLVMContextSetDiagnosticHandler(self.llcx, diagnostic_handler, 0 as *mut _);
        }
    }
404 405
}

406
unsafe extern "C" fn report_inline_asm<'a, 'b>(cgcx: &'a CodegenContext,
407 408
                                               msg: &'b str,
                                               cookie: c_uint) {
409
    cgcx.diag_emitter.inline_asm_error(cookie as u32, msg.to_string());
410 411
}

412 413 414
unsafe extern "C" fn inline_asm_handler(diag: SMDiagnosticRef,
                                        user: *const c_void,
                                        cookie: c_uint) {
415 416 417 418
    if user.is_null() {
        return
    }
    let (cgcx, _) = *(user as *const (&CodegenContext, &Handler));
419

420
    let msg = llvm::build_string(|s| llvm::LLVMRustWriteSMDiagnosticToString(diag, s))
421 422
        .expect("non-UTF8 SMDiagnostic");

423
    report_inline_asm(cgcx, &msg, cookie);
424 425
}

426
unsafe extern "C" fn diagnostic_handler(info: DiagnosticInfoRef, user: *mut c_void) {
427 428 429 430
    if user.is_null() {
        return
    }
    let (cgcx, diag_handler) = *(user as *const (&CodegenContext, &Handler));
431 432

    match llvm::diagnostic::Diagnostic::unpack(info) {
433 434
        llvm::diagnostic::InlineAsm(inline) => {
            report_inline_asm(cgcx,
J
Jonas Schievink 已提交
435
                              &llvm::twine_to_string(inline.message),
436 437 438
                              inline.cookie);
        }

439 440 441
        llvm::diagnostic::Optimization(opt) => {
            let enabled = match cgcx.remark {
                AllPasses => true,
442
                SomePasses(ref v) => v.iter().any(|s| *s == opt.pass_name),
443 444 445
            };

            if enabled {
446
                diag_handler.note_without_error(&format!("optimization {} for {} at {}:{}:{}: {}",
N
Nick Cameron 已提交
447
                                                opt.kind.describe(),
448
                                                opt.pass_name,
449 450 451
                                                opt.filename,
                                                opt.line,
                                                opt.column,
452
                                                opt.message));
453
            }
454
        }
455 456

        _ => (),
457 458 459 460
    }
}

// Unsafe due to LLVM calls.
461 462 463
unsafe fn optimize(cgcx: &CodegenContext,
                   diag_handler: &Handler,
                   mtrans: &ModuleTranslation,
A
Alex Crichton 已提交
464 465
                   config: &ModuleConfig,
                   timeline: &mut Timeline)
466
    -> Result<(), FatalError>
467
{
468 469
    let (llmod, llcx, tm) = match mtrans.source {
        ModuleSource::Translated(ref llvm) => (llvm.llmod, llvm.llcx, llvm.tm),
470 471 472 473 474
        ModuleSource::Preexisting(_) => {
            bug!("optimize_and_codegen: called with ModuleSource::Preexisting")
        }
    };

475
    let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
476

477 478
    let module_name = mtrans.name.clone();
    let module_name = Some(&module_name[..]);
479

480
    if config.emit_no_opt_bc {
A
Alex Crichton 已提交
481
        let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
A
Alex Crichton 已提交
482
        let out = path2cstr(&out);
A
Alex Crichton 已提交
483
        llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
484 485
    }

486 487 488 489 490 491 492 493 494 495
    if config.opt_level.is_some() {
        // Create the two optimizing pass managers. These mirror what clang
        // does, and are by populated by LLVM's default PassManagerBuilder.
        // Each manager has a different set of passes, but they also share
        // some common passes.
        let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
        let mpm = llvm::LLVMCreatePassManager();

        // If we're verifying or linting, add them to the function pass
        // manager.
496 497 498 499 500 501 502
        let addpass = |pass_name: &str| {
            let pass_name = CString::new(pass_name).unwrap();
            let pass = llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr());
            if pass.is_null() {
                return false;
            }
            let pass_manager = match llvm::LLVMRustPassKind(pass) {
503 504 505
                llvm::PassKind::Function => fpm,
                llvm::PassKind::Module => mpm,
                llvm::PassKind::Other => {
506
                    diag_handler.err("Encountered LLVM pass kind we can't handle");
507 508 509 510 511
                    return true
                },
            };
            llvm::LLVMRustAddPass(pass_manager, pass);
            true
512
        };
513

514 515 516 517
        if !config.no_verify { assert!(addpass("verify")); }
        if !config.no_prepopulate_passes {
            llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
            llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
518 519
            let opt_level = config.opt_level.unwrap_or(llvm::CodeGenOptLevel::None);
            with_llvm_pmb(llmod, &config, opt_level, &mut |b| {
520 521 522 523
                llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
                llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
            })
        }
524

525 526
        for pass in &config.passes {
            if !addpass(pass) {
527
                diag_handler.warn(&format!("unknown pass `{}`, ignoring",
528
                                           pass));
529
            }
530
        }
531

532 533
        for pass in &cgcx.plugin_passes {
            if !addpass(pass) {
534
                diag_handler.err(&format!("a plugin asked for LLVM pass \
535 536
                                           `{}` but LLVM does not \
                                           recognize it", pass));
537
            }
538
        }
539

540
        diag_handler.abort_if_errors();
541

542
        // Finally, run the actual optimization passes
543
        time(config.time_passes, &format!("llvm function passes [{}]", module_name.unwrap()), ||
544
             llvm::LLVMRustRunFunctionPassManager(fpm, llmod));
A
Alex Crichton 已提交
545
        timeline.record("fpm");
546
        time(config.time_passes, &format!("llvm module passes [{}]", module_name.unwrap()), ||
547
             llvm::LLVMRunPassManager(mpm, llmod));
548

549 550 551
        // Deallocate managers that we're now done with
        llvm::LLVMDisposePassManager(fpm);
        llvm::LLVMDisposePassManager(mpm);
552 553 554
    }
    Ok(())
}
555

556 557 558 559
fn generate_lto_work(cgcx: &CodegenContext,
                     modules: Vec<ModuleTranslation>)
    -> Vec<(WorkItem, u64)>
{
A
Alex Crichton 已提交
560 561 562 563 564 565 566 567 568 569 570 571
    let mut timeline = cgcx.time_graph.as_ref().map(|tg| {
        tg.start(TRANS_WORKER_TIMELINE,
                 TRANS_WORK_PACKAGE_KIND,
                 "generate lto")
    }).unwrap_or(Timeline::noop());
    let mode = if cgcx.lto {
        lto::LTOMode::WholeCrateGraph
    } else {
        lto::LTOMode::JustThisCrate
    };
    let lto_modules = lto::run(cgcx, modules, mode, &mut timeline)
        .unwrap_or_else(|e| panic!(e));
572 573 574 575 576 577 578 579 580 581

    lto_modules.into_iter().map(|module| {
        let cost = module.cost();
        (WorkItem::LTO(module), cost)
    }).collect()
}

unsafe fn codegen(cgcx: &CodegenContext,
                  diag_handler: &Handler,
                  mtrans: ModuleTranslation,
A
Alex Crichton 已提交
582 583
                  config: &ModuleConfig,
                  timeline: &mut Timeline)
584 585
    -> Result<CompiledModule, FatalError>
{
A
Alex Crichton 已提交
586
    timeline.record("codegen");
587 588 589 590
    let (llmod, llcx, tm) = match mtrans.source {
        ModuleSource::Translated(ref llvm) => (llvm.llmod, llvm.llcx, llvm.tm),
        ModuleSource::Preexisting(_) => {
            bug!("codegen: called with ModuleSource::Preexisting")
591
        }
592 593 594 595
    };
    let module_name = mtrans.name.clone();
    let module_name = Some(&module_name[..]);
    let handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
596

597 598 599 600
    if cgcx.msvc_imps_needed {
        create_msvc_imps(cgcx, llcx, llmod);
    }

601 602 603 604 605 606 607 608
    // A codegen-specific pass manager is used to generate object
    // files for an LLVM module.
    //
    // Apparently each of these pass managers is a one-shot kind of
    // thing, so we create a new one for each type of output. The
    // pass manager passed to the closure should be ensured to not
    // escape the closure itself, and the manager should only be
    // used once.
609 610 611 612 613
    unsafe fn with_codegen<F, R>(tm: TargetMachineRef,
                                 llmod: ModuleRef,
                                 no_builtins: bool,
                                 f: F) -> R
        where F: FnOnce(PassManagerRef) -> R,
614
    {
615 616 617
        let cpm = llvm::LLVMCreatePassManager();
        llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
        llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
618
        f(cpm)
619 620
    }

621 622 623 624 625 626 627 628 629
    // Change what we write and cleanup based on whether obj files are
    // just llvm bitcode. In that case write bitcode, and possibly
    // delete the bitcode if it wasn't requested. Don't generate the
    // machine code, instead copy the .o file from the .bc
    let write_bc = config.emit_bc || config.obj_is_bitcode;
    let rm_bc = !config.emit_bc && config.obj_is_bitcode;
    let write_obj = config.emit_obj && !config.obj_is_bitcode;
    let copy_bc_to_obj = config.emit_obj && config.obj_is_bitcode;

A
Alex Crichton 已提交
630 631
    let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name);
    let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name);
632

633 634 635 636 637 638 639

    if write_bc || config.emit_bc_compressed {
        let thin;
        let old;
        let data = if llvm::LLVMRustThinLTOAvailable() {
            thin = ThinBuffer::new(llmod);
            thin.data()
A
Alex Crichton 已提交
640
        } else {
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
            old = ModuleBuffer::new(llmod);
            old.data()
        };
        timeline.record("make-bc");

        if write_bc {
            if let Err(e) = File::create(&bc_out).and_then(|mut f| f.write_all(data)) {
                diag_handler.err(&format!("failed to write bytecode: {}", e));
            }
            timeline.record("write-bc");
        }

        if config.emit_bc_compressed {
            let dst = bc_out.with_extension(RLIB_BYTECODE_EXTENSION);
            let data = bytecode::encode(&mtrans.llmod_id, data);
            if let Err(e) = File::create(&dst).and_then(|mut f| f.write_all(&data)) {
                diag_handler.err(&format!("failed to write bytecode: {}", e));
            }
            timeline.record("compress-bc");
A
Alex Crichton 已提交
660
        }
661 662
    }

663
    time(config.time_passes, &format!("codegen passes [{}]", module_name.unwrap()),
664
         || -> Result<(), FatalError> {
665
        if config.emit_ir {
A
Alex Crichton 已提交
666
            let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
A
Alex Crichton 已提交
667
            let out = path2cstr(&out);
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699

            extern "C" fn demangle_callback(input_ptr: *const c_char,
                                            input_len: size_t,
                                            output_ptr: *mut c_char,
                                            output_len: size_t) -> size_t {
                let input = unsafe {
                    slice::from_raw_parts(input_ptr as *const u8, input_len as usize)
                };

                let input = match str::from_utf8(input) {
                    Ok(s) => s,
                    Err(_) => return 0,
                };

                let output = unsafe {
                    slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
                };
                let mut cursor = io::Cursor::new(output);

                let demangled = match rustc_demangle::try_demangle(input) {
                    Ok(d) => d,
                    Err(_) => return 0,
                };

                if let Err(_) = write!(cursor, "{:#}", demangled) {
                    // Possible only if provided buffer is not big enough
                    return 0;
                }

                cursor.position() as size_t
            }

A
Alex Crichton 已提交
700
            with_codegen(tm, llmod, config.no_builtins, |cpm| {
701
                llvm::LLVMRustPrintModule(cpm, llmod, out.as_ptr(), demangle_callback);
A
Alex Crichton 已提交
702
                llvm::LLVMDisposePassManager(cpm);
A
Alex Crichton 已提交
703 704
            });
            timeline.record("ir");
705 706
        }

707
        if config.emit_asm {
A
Alex Crichton 已提交
708
            let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
709 710 711 712 713 714 715 716 717

            // We can't use the same module for asm and binary output, because that triggers
            // various errors like invalid IR or broken binaries, so we might have to clone the
            // module to produce the asm output
            let llmod = if config.emit_obj {
                llvm::LLVMCloneModule(llmod)
            } else {
                llmod
            };
718
            with_codegen(tm, llmod, config.no_builtins, |cpm| {
719
                write_output_file(diag_handler, tm, cpm, llmod, &path,
720 721
                                  llvm::FileType::AssemblyFile)
            })?;
722 723 724
            if config.emit_obj {
                llvm::LLVMDisposeModule(llmod);
            }
A
Alex Crichton 已提交
725
            timeline.record("asm");
726 727
        }

728
        if write_obj {
729
            with_codegen(tm, llmod, config.no_builtins, |cpm| {
730
                write_output_file(diag_handler, tm, cpm, llmod, &obj_out,
731 732
                                  llvm::FileType::ObjectFile)
            })?;
A
Alex Crichton 已提交
733
            timeline.record("obj");
734
        }
735 736 737

        Ok(())
    })?;
738

739 740
    if copy_bc_to_obj {
        debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
741
        if let Err(e) = link_or_copy(&bc_out, &obj_out) {
742
            diag_handler.err(&format!("failed to copy bitcode to object file: {}", e));
743 744 745 746 747 748
        }
    }

    if rm_bc {
        debug!("removing_bitcode {:?}", bc_out);
        if let Err(e) = fs::remove_file(&bc_out) {
749
            diag_handler.err(&format!("failed to remove bitcode: {}", e));
750 751 752
        }
    }

753 754 755
    drop(handlers);
    Ok(mtrans.into_compiled_module(config.emit_obj,
                                   config.emit_bc,
756
                                   config.emit_bc_compressed,
757
                                   &cgcx.output_filenames))
758 759
}

760 761 762 763
pub struct CompiledModules {
    pub modules: Vec<CompiledModule>,
    pub metadata_module: CompiledModule,
    pub allocator_module: Option<CompiledModule>,
764 765
}

766 767 768 769 770
fn need_crate_bitcode_for_rlib(sess: &Session) -> bool {
    sess.crate_types.borrow().contains(&config::CrateTypeRlib) &&
    sess.opts.output_types.contains_key(&OutputType::Exe)
}

771
pub fn start_async_translation(tcx: TyCtxt,
772
                               time_graph: Option<TimeGraph>,
773
                               link: LinkMeta,
774
                               metadata: EncodedMetadata,
A
Alex Crichton 已提交
775 776
                               coordinator_receive: Receiver<Box<Any + Send>>,
                               total_cgus: usize)
777
                               -> OngoingCrateTranslation {
778
    let sess = tcx.sess;
A
Alex Crichton 已提交
779
    let crate_output = tcx.output_filenames(LOCAL_CRATE);
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
    let crate_name = tcx.crate_name(LOCAL_CRATE);
    let no_builtins = attr::contains_name(&tcx.hir.krate().attrs, "no_builtins");
    let subsystem = attr::first_attr_value_str_by_name(&tcx.hir.krate().attrs,
                                                       "windows_subsystem");
    let windows_subsystem = subsystem.map(|subsystem| {
        if subsystem != "windows" && subsystem != "console" {
            tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
                                     `windows` and `console` are allowed",
                                    subsystem));
        }
        subsystem.to_string()
    });

    let no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
        (tcx.sess.target.target.options.no_integrated_as &&
         (crate_output.outputs.contains_key(&OutputType::Object) ||
          crate_output.outputs.contains_key(&OutputType::Exe)));
    let linker_info = LinkerInfo::new(tcx);
    let crate_info = CrateInfo::new(tcx);

800 801 802 803 804 805
    let output_types_override = if no_integrated_as {
        OutputTypes::new(&[(OutputType::Assembly, None)])
    } else {
        sess.opts.output_types.clone()
    };

806
    // Figure out what we actually need to build.
A
Alex Crichton 已提交
807 808 809
    let mut modules_config = ModuleConfig::new(sess.opts.cg.passes.clone());
    let mut metadata_config = ModuleConfig::new(vec![]);
    let mut allocator_config = ModuleConfig::new(vec![]);
810

J
Jorge Aparicio 已提交
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
    if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
        match *sanitizer {
            Sanitizer::Address => {
                modules_config.passes.push("asan".to_owned());
                modules_config.passes.push("asan-module".to_owned());
            }
            Sanitizer::Memory => {
                modules_config.passes.push("msan".to_owned())
            }
            Sanitizer::Thread => {
                modules_config.passes.push("tsan".to_owned())
            }
            _ => {}
        }
    }

827 828 829 830
    if sess.opts.debugging_opts.profile {
        modules_config.passes.push("insert-gcov-profiling".to_owned())
    }

831
    modules_config.opt_level = Some(get_llvm_opt_level(sess.opts.optimize));
832
    modules_config.opt_size = Some(get_llvm_opt_size(sess.opts.optimize));
833 834 835 836 837 838 839

    // Save all versions of the bytecode if we're saving our temporaries.
    if sess.opts.cg.save_temps {
        modules_config.emit_no_opt_bc = true;
        modules_config.emit_bc = true;
        modules_config.emit_lto_bc = true;
        metadata_config.emit_bc = true;
840
        allocator_config.emit_bc = true;
841 842
    }

843 844 845
    // Emit compressed bitcode files for the crate if we're emitting an rlib.
    // Whenever an rlib is created, the bitcode is inserted into the archive in
    // order to allow LTO against it.
846
    if need_crate_bitcode_for_rlib(sess) {
847 848
        modules_config.emit_bc_compressed = true;
        allocator_config.emit_bc_compressed = true;
849 850
    }

851
    for output_type in output_types_override.keys() {
852
        match *output_type {
853 854
            OutputType::Bitcode => { modules_config.emit_bc = true; }
            OutputType::LlvmAssembly => { modules_config.emit_ir = true; }
855
            OutputType::Assembly => {
856 857 858 859
                modules_config.emit_asm = true;
                // If we're not using the LLVM assembler, this function
                // could be invoked specially with output_type_assembly, so
                // in this case we still want the metadata object file.
860
                if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
861
                    metadata_config.emit_obj = true;
862
                    allocator_config.emit_obj = true;
863
                }
864 865 866
            }
            OutputType::Object => { modules_config.emit_obj = true; }
            OutputType::Metadata => { metadata_config.emit_obj = true; }
867
            OutputType::Exe => {
868 869
                modules_config.emit_obj = true;
                metadata_config.emit_obj = true;
870
                allocator_config.emit_obj = true;
871
            },
J
Jake Goulding 已提交
872
            OutputType::Mir => {}
873
            OutputType::DepInfo => {}
874 875 876
        }
    }

877 878 879
    modules_config.set_flags(sess, no_builtins);
    metadata_config.set_flags(sess, no_builtins);
    allocator_config.set_flags(sess, no_builtins);
880

881 882 883 884 885
    // Exclude metadata and allocator modules from time_passes output, since
    // they throw off the "LLVM passes" measurement.
    metadata_config.time_passes = false;
    allocator_config.time_passes = false;

886 887 888 889
    let client = sess.jobserver_from_env.clone().unwrap_or_else(|| {
        // Pick a "reasonable maximum" if we don't otherwise have a jobserver in
        // our environment, capping out at 32 so we don't take everything down
        // by hogging the process run queue.
890
        Client::new(32).expect("failed to create jobserver")
891
    });
892

893
    let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
894
    let (trans_worker_send, trans_worker_receive) = channel();
895

A
Alex Crichton 已提交
896
    let coordinator_thread = start_executing_work(tcx,
897
                                                  &crate_info,
898 899
                                                  shared_emitter,
                                                  trans_worker_send,
900
                                                  coordinator_receive,
A
Alex Crichton 已提交
901
                                                  total_cgus,
902
                                                  client,
903
                                                  time_graph.clone(),
A
Alex Crichton 已提交
904 905 906 907
                                                  Arc::new(modules_config),
                                                  Arc::new(metadata_config),
                                                  Arc::new(allocator_config));

908 909 910 911 912 913 914
    OngoingCrateTranslation {
        crate_name,
        link,
        metadata,
        windows_subsystem,
        linker_info,
        no_integrated_as,
915
        crate_info,
916

917
        time_graph,
918
        coordinator_send: tcx.tx_to_llvm_workers.clone(),
919
        trans_worker_receive,
920
        shared_emitter_main,
A
Alex Crichton 已提交
921 922
        future: coordinator_thread,
        output_filenames: tcx.output_filenames(LOCAL_CRATE),
923 924 925 926
    }
}

fn copy_module_artifacts_into_incr_comp_cache(sess: &Session,
927
                                              dep_graph: &DepGraph,
928
                                              compiled_modules: &CompiledModules) {
929 930 931 932
    if sess.opts.incremental.is_none() {
        return;
    }

933
    for module in compiled_modules.modules.iter() {
934 935
        let mut files = vec![];

936 937
        if let Some(ref path) = module.object {
            files.push((WorkProductFileKind::Object, path.clone()));
938
        }
939 940 941 942 943
        if let Some(ref path) = module.bytecode {
            files.push((WorkProductFileKind::Bytecode, path.clone()));
        }
        if let Some(ref path) = module.bytecode_compressed {
            files.push((WorkProductFileKind::BytecodeCompressed, path.clone()));
944 945
        }

946
        save_trans_partition(sess, dep_graph, &module.name, &files);
947
    }
948
}
949

950 951 952
fn produce_final_output_artifacts(sess: &Session,
                                  compiled_modules: &CompiledModules,
                                  crate_output: &OutputFilenames) {
953
    let mut user_wants_bitcode = false;
A
Alex Crichton 已提交
954
    let mut user_wants_objects = false;
955

956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993
    // Produce final compile outputs.
    let copy_gracefully = |from: &Path, to: &Path| {
        if let Err(e) = fs::copy(from, to) {
            sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
        }
    };

    let copy_if_one_unit = |output_type: OutputType,
                            keep_numbered: bool| {
        if compiled_modules.modules.len() == 1 {
            // 1) Only one codegen unit.  In this case it's no difficulty
            //    to copy `foo.0.x` to `foo.x`.
            let module_name = Some(&compiled_modules.modules[0].name[..]);
            let path = crate_output.temp_path(output_type, module_name);
            copy_gracefully(&path,
                            &crate_output.path(output_type));
            if !sess.opts.cg.save_temps && !keep_numbered {
                // The user just wants `foo.x`, not `foo.#module-name#.x`.
                remove(sess, &path);
            }
        } else {
            let ext = crate_output.temp_path(output_type, None)
                                  .extension()
                                  .unwrap()
                                  .to_str()
                                  .unwrap()
                                  .to_owned();

            if crate_output.outputs.contains_key(&output_type) {
                // 2) Multiple codegen units, with `--emit foo=some_name`.  We have
                //    no good solution for this case, so warn the user.
                sess.warn(&format!("ignoring emit path because multiple .{} files \
                                    were produced", ext));
            } else if crate_output.single_output_file.is_some() {
                // 3) Multiple codegen units, with `-o some_name`.  We have
                //    no good solution for this case, so warn the user.
                sess.warn(&format!("ignoring -o because multiple .{} files \
                                    were produced", ext));
994
            } else {
995 996 997
                // 4) Multiple codegen units, but no explicit name.  We
                //    just leave the `foo.0.x` files in place.
                // (We don't have to do any work in this case.)
998
            }
999 1000
        }
    };
1001

1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
    // Flag to indicate whether the user explicitly requested bitcode.
    // Otherwise, we produced it only as a temporary output, and will need
    // to get rid of it.
    for output_type in crate_output.outputs.keys() {
        match *output_type {
            OutputType::Bitcode => {
                user_wants_bitcode = true;
                // Copy to .bc, but always keep the .0.bc.  There is a later
                // check to figure out if we should delete .0.bc files, or keep
                // them for making an rlib.
                copy_if_one_unit(OutputType::Bitcode, true);
            }
            OutputType::LlvmAssembly => {
                copy_if_one_unit(OutputType::LlvmAssembly, false);
            }
            OutputType::Assembly => {
                copy_if_one_unit(OutputType::Assembly, false);
            }
            OutputType::Object => {
                user_wants_objects = true;
                copy_if_one_unit(OutputType::Object, true);
1023
            }
1024 1025 1026 1027
            OutputType::Mir |
            OutputType::Metadata |
            OutputType::Exe |
            OutputType::DepInfo => {}
1028 1029 1030 1031 1032 1033
        }
    }

    // Clean up unwanted temporary files.

    // We create the following files by default:
1034 1035 1036 1037 1038 1039
    //  - #crate#.#module-name#.bc
    //  - #crate#.#module-name#.o
    //  - #crate#.crate.metadata.bc
    //  - #crate#.crate.metadata.o
    //  - #crate#.o (linked from crate.##.o)
    //  - #crate#.bc (copied from crate.##.bc)
1040 1041 1042 1043
    // We may create additional files if requested by the user (through
    // `-C save-temps` or `--emit=` flags).

    if !sess.opts.cg.save_temps {
1044
        // Remove the temporary .#module-name#.o objects.  If the user didn't
1045
        // explicitly request bitcode (with --emit=bc), and the bitcode is not
1046 1047
        // needed for building an rlib, then we must remove .#module-name#.bc as
        // well.
1048

1049
        // Specific rules for keeping .#module-name#.bc:
1050 1051 1052
        //  - If the user requested bitcode (`user_wants_bitcode`), and
        //    codegen_units > 1, then keep it.
        //  - If the user requested bitcode but codegen_units == 1, then we
1053
        //    can toss .#module-name#.bc because we copied it to .bc earlier.
1054
        //  - If we're not building an rlib and the user didn't request
1055
        //    bitcode, then delete .#module-name#.bc.
1056
        // If you change how this works, also update back::link::link_rlib,
1057 1058
        // where .#module-name#.bc files are (maybe) deleted after making an
        // rlib.
1059 1060
        let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);

1061
        let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
1062

A
Alex Crichton 已提交
1063
        let keep_numbered_objects = needs_crate_object ||
1064
                (user_wants_objects && sess.codegen_units() > 1);
A
Alex Crichton 已提交
1065

1066
        for module in compiled_modules.modules.iter() {
1067 1068 1069 1070
            if let Some(ref path) = module.object {
                if !keep_numbered_objects {
                    remove(sess, path);
                }
1071
            }
1072

1073 1074 1075 1076
            if let Some(ref path) = module.bytecode {
                if !keep_numbered_bitcode {
                    remove(sess, path);
                }
1077 1078 1079
            }
        }

1080 1081
        if !user_wants_bitcode {
            if let Some(ref path) = compiled_modules.metadata_module.bytecode {
1082 1083
                remove(sess, &path);
            }
1084 1085 1086 1087 1088 1089

            if let Some(ref allocator_module) = compiled_modules.allocator_module {
                if let Some(ref path) = allocator_module.bytecode {
                    remove(sess, path);
                }
            }
1090
        }
1091 1092 1093
    }

    // We leave the following files around by default:
1094 1095 1096
    //  - #crate#.o
    //  - #crate#.crate.metadata.o
    //  - #crate#.bc
1097 1098 1099
    // These are used in linking steps and will be cleaned up afterward.
}

1100
pub fn dump_incremental_data(trans: &CrateTranslation) {
1101 1102 1103
    println!("[incremental] Re-using {} out of {} modules",
              trans.modules.iter().filter(|m| m.pre_existing).count(),
              trans.modules.len());
1104 1105
}

1106 1107 1108
enum WorkItem {
    Optimize(ModuleTranslation),
    LTO(lto::LtoModuleTranslation),
1109
}
1110

1111 1112 1113 1114 1115 1116
impl WorkItem {
    fn kind(&self) -> ModuleKind {
        match *self {
            WorkItem::Optimize(ref m) => m.kind,
            WorkItem::LTO(_) => ModuleKind::Regular,
        }
1117
    }
A
Alex Crichton 已提交
1118

1119 1120 1121 1122
    fn name(&self) -> String {
        match *self {
            WorkItem::Optimize(ref m) => format!("optimize: {}", m.name),
            WorkItem::LTO(ref m) => format!("lto: {}", m.name()),
A
Alex Crichton 已提交
1123
        }
1124
    }
1125
}
1126

1127 1128 1129 1130 1131
enum WorkItemResult {
    Compiled(CompiledModule),
    NeedsLTO(ModuleTranslation),
}

A
Alex Crichton 已提交
1132 1133 1134
fn execute_work_item(cgcx: &CodegenContext,
                     work_item: WorkItem,
                     timeline: &mut Timeline)
1135
    -> Result<WorkItemResult, FatalError>
1136
{
1137
    let diag_handler = cgcx.create_diag_handler();
1138 1139 1140 1141 1142
    let config = cgcx.config(work_item.kind());
    let mtrans = match work_item {
        WorkItem::Optimize(mtrans) => mtrans,
        WorkItem::LTO(mut lto) => {
            unsafe {
A
Alex Crichton 已提交
1143 1144
                let module = lto.optimize(cgcx, timeline)?;
                let module = codegen(cgcx, &diag_handler, module, config, timeline)?;
1145 1146 1147 1148 1149
                return Ok(WorkItemResult::Compiled(module))
            }
        }
    };
    let module_name = mtrans.name.clone();
1150

1151
    let pre_existing = match mtrans.source {
1152 1153 1154 1155 1156 1157 1158 1159
        ModuleSource::Translated(_) => None,
        ModuleSource::Preexisting(ref wp) => Some(wp.clone()),
    };

    if let Some(wp) = pre_existing {
        let incr_comp_session_dir = cgcx.incr_comp_session_dir
                                        .as_ref()
                                        .unwrap();
1160
        let name = &mtrans.name;
1161 1162 1163
        let mut object = None;
        let mut bytecode = None;
        let mut bytecode_compressed = None;
1164
        for (kind, saved_file) in wp.saved_files {
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
            let obj_out = match kind {
                WorkProductFileKind::Object => {
                    let path = cgcx.output_filenames.temp_path(OutputType::Object, Some(name));
                    object = Some(path.clone());
                    path
                }
                WorkProductFileKind::Bytecode => {
                    let path = cgcx.output_filenames.temp_path(OutputType::Bitcode, Some(name));
                    bytecode = Some(path.clone());
                    path
                }
                WorkProductFileKind::BytecodeCompressed => {
                    let path = cgcx.output_filenames.temp_path(OutputType::Bitcode, Some(name))
                        .with_extension(RLIB_BYTECODE_EXTENSION);
                    bytecode_compressed = Some(path.clone());
                    path
                }
            };
1183 1184 1185
            let source_file = in_incr_comp_dir(&incr_comp_session_dir,
                                               &saved_file);
            debug!("copying pre-existing module `{}` from {:?} to {}",
1186
                   mtrans.name,
1187 1188 1189 1190 1191 1192 1193 1194 1195
                   source_file,
                   obj_out.display());
            match link_or_copy(&source_file, &obj_out) {
                Ok(_) => { }
                Err(err) => {
                    diag_handler.err(&format!("unable to copy {} to {}: {}",
                                              source_file.display(),
                                              obj_out.display(),
                                              err));
1196 1197 1198
                }
            }
        }
1199 1200 1201
        assert_eq!(object.is_some(), config.emit_obj);
        assert_eq!(bytecode.is_some(), config.emit_bc);
        assert_eq!(bytecode_compressed.is_some(), config.emit_bc_compressed);
1202

1203 1204
        Ok(WorkItemResult::Compiled(CompiledModule {
            llmod_id: mtrans.llmod_id.clone(),
1205 1206 1207
            name: module_name,
            kind: ModuleKind::Regular,
            pre_existing: true,
1208 1209 1210
            object,
            bytecode,
            bytecode_compressed,
1211
        }))
1212 1213 1214 1215
    } else {
        debug!("llvm-optimizing {:?}", module_name);

        unsafe {
A
Alex Crichton 已提交
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
            optimize(cgcx, &diag_handler, &mtrans, config, timeline)?;

            let lto = cgcx.lto;

            let auto_thin_lto =
                cgcx.thinlto &&
                cgcx.total_cgus > 1 &&
                mtrans.kind != ModuleKind::Allocator;

            // If we're a metadata module we never participate in LTO.
            //
            // If LTO was explicitly requested on the command line, we always
            // LTO everything else.
            //
            // If LTO *wasn't* explicitly requested and we're not a metdata
            // module, then we may automatically do ThinLTO if we've got
            // multiple codegen units. Note, however, that the allocator module
            // doesn't participate here automatically because of linker
            // shenanigans later on.
            if mtrans.kind == ModuleKind::Metadata || (!lto && !auto_thin_lto) {
                let module = codegen(cgcx, &diag_handler, mtrans, config, timeline)?;
1237 1238 1239 1240
                Ok(WorkItemResult::Compiled(module))
            } else {
                Ok(WorkItemResult::NeedsLTO(mtrans))
            }
1241 1242
        }
    }
1243 1244
}

1245
enum Message {
1246
    Token(io::Result<Acquired>),
1247 1248 1249 1250
    NeedsLTO {
        result: ModuleTranslation,
        worker_id: usize,
    },
1251 1252 1253 1254
    Done {
        result: Result<CompiledModule, ()>,
        worker_id: usize,
    },
1255 1256
    TranslationDone {
        llvm_work_item: WorkItem,
1257
        cost: u64,
1258
    },
A
Alex Crichton 已提交
1259
    TranslationComplete,
1260
    TranslateItem,
1261
}
1262

1263
struct Diagnostic {
1264 1265 1266
    msg: String,
    code: Option<String>,
    lvl: Level,
1267 1268
}

1269
#[derive(PartialEq, Clone, Copy, Debug)]
1270
enum MainThreadWorkerState {
1271 1272 1273 1274 1275
    Idle,
    Translating,
    LLVMing,
}

A
Alex Crichton 已提交
1276
fn start_executing_work(tcx: TyCtxt,
1277
                        crate_info: &CrateInfo,
1278 1279
                        shared_emitter: SharedEmitter,
                        trans_worker_send: Sender<Message>,
1280
                        coordinator_receive: Receiver<Box<Any + Send>>,
A
Alex Crichton 已提交
1281
                        total_cgus: usize,
1282
                        jobserver: Client,
1283
                        time_graph: Option<TimeGraph>,
A
Alex Crichton 已提交
1284 1285 1286
                        modules_config: Arc<ModuleConfig>,
                        metadata_config: Arc<ModuleConfig>,
                        allocator_config: Arc<ModuleConfig>)
1287
                        -> thread::JoinHandle<Result<CompiledModules, ()>> {
A
Alex Crichton 已提交
1288 1289 1290 1291 1292 1293 1294 1295 1296
    let coordinator_send = tcx.tx_to_llvm_workers.clone();
    let mut exported_symbols = FxHashMap();
    exported_symbols.insert(LOCAL_CRATE, tcx.exported_symbols(LOCAL_CRATE));
    for &cnum in tcx.crates().iter() {
        exported_symbols.insert(cnum, tcx.exported_symbols(cnum));
    }
    let exported_symbols = Arc::new(exported_symbols);
    let sess = tcx.sess;

1297 1298 1299 1300 1301 1302 1303 1304 1305 1306
    // First up, convert our jobserver into a helper thread so we can use normal
    // mpsc channels to manage our messages and such. Once we've got the helper
    // thread then request `n-1` tokens because all of our work items are ready
    // to go.
    //
    // Note that the `n-1` is here because we ourselves have a token (our
    // process) and we'll use that token to execute at least one unit of work.
    //
    // After we've requested all these tokens then we'll, when we can, get
    // tokens on `rx` above which will get managed in the main loop below.
1307
    let coordinator_send2 = coordinator_send.clone();
1308
    let helper = jobserver.into_helper_thread(move |token| {
1309
        drop(coordinator_send2.send(Box::new(Message::Token(token))));
1310 1311
    }).expect("failed to spawn helper thread");

1312
    let mut each_linked_rlib_for_lto = Vec::new();
1313
    drop(link::each_linked_rlib(sess, crate_info, &mut |cnum, path| {
1314
        if link::ignored_for_lto(crate_info, cnum) {
1315 1316 1317 1318 1319 1320 1321
            return
        }
        each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
    }));

    let cgcx = CodegenContext {
        crate_types: sess.crate_types.borrow().clone(),
1322
        each_linked_rlib_for_lto,
1323
        lto: sess.lto(),
A
Alex Crichton 已提交
1324
        thinlto: sess.opts.debugging_opts.thinlto,
1325
        no_landing_pads: sess.no_landing_pads(),
1326
        save_temps: sess.opts.cg.save_temps,
1327
        opts: Arc::new(sess.opts.clone()),
1328
        time_passes: sess.time_passes(),
1329
        exported_symbols,
1330 1331 1332 1333
        plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
        remark: sess.opts.cg.remark.clone(),
        worker: 0,
        incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1334
        coordinator_send,
1335
        diag_emitter: shared_emitter.clone(),
1336
        time_graph,
A
Alex Crichton 已提交
1337 1338 1339 1340
        output_filenames: tcx.output_filenames(LOCAL_CRATE),
        regular_module_config: modules_config,
        metadata_module_config: metadata_config,
        allocator_module_config: allocator_config,
1341
        tm_factory: target_machine_factory(tcx.sess),
A
Alex Crichton 已提交
1342
        total_cgus,
1343 1344
        msvc_imps_needed: msvc_imps_needed(tcx),
        target_pointer_width: tcx.sess.target.target.target_pointer_width.clone(),
1345 1346
    };

1347 1348 1349 1350
    // This is the "main loop" of parallel work happening for parallel codegen.
    // It's here that we manage parallelism, schedule work, and work with
    // messages coming from clients.
    //
1351 1352
    // There are a few environmental pre-conditions that shape how the system
    // is set up:
1353
    //
1354 1355 1356 1357 1358 1359 1360 1361
    // - Error reporting only can happen on the main thread because that's the
    //   only place where we have access to the compiler `Session`.
    // - LLVM work can be done on any thread.
    // - Translation can only happen on the main thread.
    // - Each thread doing substantial work most be in possession of a `Token`
    //   from the `Jobserver`.
    // - The compiler process always holds one `Token`. Any additional `Tokens`
    //   have to be requested from the `Jobserver`.
1362
    //
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
    // Error Reporting
    // ===============
    // The error reporting restriction is handled separately from the rest: We
    // set up a `SharedEmitter` the holds an open channel to the main thread.
    // When an error occurs on any thread, the shared emitter will send the
    // error message to the receiver main thread (`SharedEmitterMain`). The
    // main thread will periodically query this error message queue and emit
    // any error messages it has received. It might even abort compilation if
    // has received a fatal error. In this case we rely on all other threads
    // being torn down automatically with the main thread.
    // Since the main thread will often be busy doing translation work, error
    // reporting will be somewhat delayed, since the message queue can only be
    // checked in between to work packages.
    //
    // Work Processing Infrastructure
    // ==============================
    // The work processing infrastructure knows three major actors:
    //
    // - the coordinator thread,
    // - the main thread, and
    // - LLVM worker threads
    //
    // The coordinator thread is running a message loop. It instructs the main
    // thread about what work to do when, and it will spawn off LLVM worker
    // threads as open LLVM WorkItems become available.
    //
    // The job of the main thread is to translate CGUs into LLVM work package
    // (since the main thread is the only thread that can do this). The main
    // thread will block until it receives a message from the coordinator, upon
    // which it will translate one CGU, send it to the coordinator and block
    // again. This way the coordinator can control what the main thread is
    // doing.
    //
    // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
    // available, it will spawn off a new LLVM worker thread and let it process
    // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
    // it will just shut down, which also frees all resources associated with
    // the given LLVM module, and sends a message to the coordinator that the
    // has been completed.
    //
    // Work Scheduling
    // ===============
    // The scheduler's goal is to minimize the time it takes to complete all
    // work there is, however, we also want to keep memory consumption low
    // if possible. These two goals are at odds with each other: If memory
    // consumption were not an issue, we could just let the main thread produce
    // LLVM WorkItems at full speed, assuring maximal utilization of
    // Tokens/LLVM worker threads. However, since translation usual is faster
    // than LLVM processing, the queue of LLVM WorkItems would fill up and each
    // WorkItem potentially holds on to a substantial amount of memory.
    //
    // So the actual goal is to always produce just enough LLVM WorkItems as
    // not to starve our LLVM worker threads. That means, once we have enough
    // WorkItems in our queue, we can block the main thread, so it does not
    // produce more until we need them.
    //
    // Doing LLVM Work on the Main Thread
    // ----------------------------------
    // Since the main thread owns the compiler processes implicit `Token`, it is
    // wasteful to keep it blocked without doing any work. Therefore, what we do
    // in this case is: We spawn off an additional LLVM worker thread that helps
    // reduce the queue. The work it is doing corresponds to the implicit
    // `Token`. The coordinator will mark the main thread as being busy with
    // LLVM work. (The actual work happens on another OS thread but we just care
    // about `Tokens`, not actual threads).
    //
    // When any LLVM worker thread finishes while the main thread is marked as
    // "busy with LLVM work", we can do a little switcheroo: We give the Token
    // of the just finished thread to the LLVM worker thread that is working on
    // behalf of the main thread's implicit Token, thus freeing up the main
    // thread again. The coordinator can then again decide what the main thread
    // should do. This allows the coordinator to make decisions at more points
    // in time.
    //
    // Striking a Balance between Throughput and Memory Consumption
    // ------------------------------------------------------------
    // Since our two goals, (1) use as many Tokens as possible and (2) keep
    // memory consumption as low as possible, are in conflict with each other,
    // we have to find a trade off between them. Right now, the goal is to keep
    // all workers busy, which means that no worker should find the queue empty
    // when it is ready to start.
    // How do we do achieve this? Good question :) We actually never know how
    // many `Tokens` are potentially available so it's hard to say how much to
    // fill up the queue before switching the main thread to LLVM work. Also we
    // currently don't have a means to estimate how long a running LLVM worker
    // will still be busy with it's current WorkItem. However, we know the
    // maximal count of available Tokens that makes sense (=the number of CPU
    // cores), so we can take a conservative guess. The heuristic we use here
    // is implemented in the `queue_full_enough()` function.
    //
    // Some Background on Jobservers
    // -----------------------------
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
    // It's worth also touching on the management of parallelism here. We don't
    // want to just spawn a thread per work item because while that's optimal
    // parallelism it may overload a system with too many threads or violate our
    // configuration for the maximum amount of cpu to use for this process. To
    // manage this we use the `jobserver` crate.
    //
    // Job servers are an artifact of GNU make and are used to manage
    // parallelism between processes. A jobserver is a glorified IPC semaphore
    // basically. Whenever we want to run some work we acquire the semaphore,
    // and whenever we're done with that work we release the semaphore. In this
    // manner we can ensure that the maximum number of parallel workers is
    // capped at any one point in time.
1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481
    //
    // LTO and the coordinator thread
    // ------------------------------
    //
    // The final job the coordinator thread is responsible for is managing LTO
    // and how that works. When LTO is requested what we'll to is collect all
    // optimized LLVM modules into a local vector on the coordinator. Once all
    // modules have been translated and optimized we hand this to the `lto`
    // module for further optimization. The `lto` module will return back a list
    // of more modules to work on, which the coordinator will continue to spawn
    // work for.
    //
    // Each LLVM module is automatically sent back to the coordinator for LTO if
    // necessary. There's already optimizations in place to avoid sending work
    // back to the coordinator if LTO isn't requested.
1482
    return thread::spawn(move || {
1483 1484 1485
        // We pretend to be within the top-level LLVM time-passes task here:
        set_time_depth(1);

1486
        let max_workers = ::num_cpus::get();
1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
        let mut worker_id_counter = 0;
        let mut free_worker_ids = Vec::new();
        let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
            if let Some(id) = free_worker_ids.pop() {
                id
            } else {
                let id = worker_id_counter;
                worker_id_counter += 1;
                id
            }
        };

1499 1500
        // This is where we collect codegen units that have gone all the way
        // through translation and LLVM.
1501 1502 1503
        let mut compiled_modules = vec![];
        let mut compiled_metadata_module = None;
        let mut compiled_allocator_module = None;
1504 1505
        let mut needs_lto = Vec::new();
        let mut started_lto = false;
1506

1507
        // This flag tracks whether all items have gone through translations
1508
        let mut translation_done = false;
1509 1510

        // This is the queue of LLVM work items that still need processing.
A
Alex Crichton 已提交
1511
        let mut work_items = Vec::<(WorkItem, u64)>::new();
1512 1513 1514

        // This are the Jobserver Tokens we currently hold. Does not include
        // the implicit Token the compiler process owns no matter what.
1515
        let mut tokens = Vec::new();
1516

1517
        let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1518
        let mut running = 0;
1519

1520 1521
        let mut llvm_start_time = None;

1522 1523
        // Run the message loop while there's still anything that needs message
        // processing:
1524 1525 1526
        while !translation_done ||
              work_items.len() > 0 ||
              running > 0 ||
1527
              needs_lto.len() > 0 ||
1528
              main_thread_worker_state != MainThreadWorkerState::Idle {
1529

1530 1531 1532
            // While there are still CGUs to be translated, the coordinator has
            // to decide how to utilize the compiler processes implicit Token:
            // For translating more CGU or for running them through LLVM.
1533
            if !translation_done {
1534 1535 1536
                if main_thread_worker_state == MainThreadWorkerState::Idle {
                    if !queue_full_enough(work_items.len(), running, max_workers) {
                        // The queue is not full enough, translate more items:
1537 1538 1539
                        if let Err(_) = trans_worker_send.send(Message::TranslateItem) {
                            panic!("Could not send Message::TranslateItem to main thread")
                        }
1540
                        main_thread_worker_state = MainThreadWorkerState::Translating;
1541
                    } else {
1542 1543 1544
                        // The queue is full enough to not let the worker
                        // threads starve. Use the implicit Token to do some
                        // LLVM work too.
1545 1546
                        let (item, _) = work_items.pop()
                            .expect("queue empty - queue_full_enough() broken?");
1547
                        let cgcx = CodegenContext {
1548
                            worker: get_worker_id(&mut free_worker_ids),
1549 1550
                            .. cgcx.clone()
                        };
1551
                        maybe_start_llvm_timer(cgcx.config(item.kind()),
A
Alex Crichton 已提交
1552
                                               &mut llvm_start_time);
1553
                        main_thread_worker_state = MainThreadWorkerState::LLVMing;
1554 1555 1556 1557
                        spawn_work(cgcx, item);
                    }
                }
            } else {
1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
                // If we've finished everything related to normal translation
                // then it must be the case that we've got some LTO work to do.
                // Perform the serial work here of figuring out what we're
                // going to LTO and then push a bunch of work items onto our
                // queue to do LTO
                if work_items.len() == 0 &&
                   running == 0 &&
                   main_thread_worker_state == MainThreadWorkerState::Idle {
                    assert!(!started_lto);
                    assert!(needs_lto.len() > 0);
                    started_lto = true;
                    let modules = mem::replace(&mut needs_lto, Vec::new());
                    for (work, cost) in generate_lto_work(&cgcx, modules) {
                        let insertion_index = work_items
                            .binary_search_by_key(&cost, |&(_, cost)| cost)
                            .unwrap_or_else(|e| e);
                        work_items.insert(insertion_index, (work, cost));
                        helper.request_token();
                    }
                }

1579 1580 1581 1582 1583 1584
                // In this branch, we know that everything has been translated,
                // so it's just a matter of determining whether the implicit
                // Token is free to use for LLVM work.
                match main_thread_worker_state {
                    MainThreadWorkerState::Idle => {
                        if let Some((item, _)) = work_items.pop() {
1585
                            let cgcx = CodegenContext {
1586
                                worker: get_worker_id(&mut free_worker_ids),
1587 1588
                                .. cgcx.clone()
                            };
1589
                            maybe_start_llvm_timer(cgcx.config(item.kind()),
A
Alex Crichton 已提交
1590
                                                   &mut llvm_start_time);
1591
                            main_thread_worker_state = MainThreadWorkerState::LLVMing;
1592
                            spawn_work(cgcx, item);
1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
                        } else {
                            // There is no unstarted work, so let the main thread
                            // take over for a running worker. Otherwise the
                            // implicit token would just go to waste.
                            // We reduce the `running` counter by one. The
                            // `tokens.truncate()` below will take care of
                            // giving the Token back.
                            debug_assert!(running > 0);
                            running -= 1;
                            main_thread_worker_state = MainThreadWorkerState::LLVMing;
1603 1604
                        }
                    }
1605
                    MainThreadWorkerState::Translating => {
1606 1607 1608
                        bug!("trans worker should not be translating after \
                              translation was already completed")
                    }
1609
                    MainThreadWorkerState::LLVMing => {
1610 1611 1612 1613
                        // Already making good use of that token
                    }
                }
            }
1614

1615 1616
            // Spin up what work we can, only doing this while we've got available
            // parallelism slots and work left to spawn.
1617
            while work_items.len() > 0 && running < tokens.len() {
1618
                let (item, _) = work_items.pop().unwrap();
1619

1620
                maybe_start_llvm_timer(cgcx.config(item.kind()),
A
Alex Crichton 已提交
1621
                                       &mut llvm_start_time);
1622

1623
                let cgcx = CodegenContext {
1624
                    worker: get_worker_id(&mut free_worker_ids),
1625 1626 1627 1628 1629
                    .. cgcx.clone()
                };

                spawn_work(cgcx, item);
                running += 1;
1630
            }
1631 1632

            // Relinquish accidentally acquired extra tokens
1633
            tokens.truncate(running);
1634

1635 1636
            let msg = coordinator_receive.recv().unwrap();
            match *msg.downcast::<Message>().ok().unwrap() {
1637 1638 1639 1640
                // Save the token locally and the next turn of the loop will use
                // this to spawn a new unit of work, or it may get dropped
                // immediately if we have no more work to spawn.
                Message::Token(token) => {
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657
                    match token {
                        Ok(token) => {
                            tokens.push(token);

                            if main_thread_worker_state == MainThreadWorkerState::LLVMing {
                                // If the main thread token is used for LLVM work
                                // at the moment, we turn that thread into a regular
                                // LLVM worker thread, so the main thread is free
                                // to react to translation demand.
                                main_thread_worker_state = MainThreadWorkerState::Idle;
                                running += 1;
                            }
                        }
                        Err(e) => {
                            let msg = &format!("failed to acquire jobserver token: {}", e);
                            shared_emitter.fatal(msg);
                            // Exit the coordinator thread
1658
                            panic!("{}", msg)
1659
                        }
1660
                    }
1661 1662
                }

A
Alex Crichton 已提交
1663
                Message::TranslationDone { llvm_work_item, cost } => {
1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677
                    // We keep the queue sorted by estimated processing cost,
                    // so that more expensive items are processed earlier. This
                    // is good for throughput as it gives the main thread more
                    // time to fill up the queue and it avoids scheduling
                    // expensive items to the end.
                    // Note, however, that this is not ideal for memory
                    // consumption, as LLVM module sizes are not evenly
                    // distributed.
                    let insertion_index =
                        work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
                    let insertion_index = match insertion_index {
                        Ok(idx) | Err(idx) => idx
                    };
                    work_items.insert(insertion_index, (llvm_work_item, cost));
1678

A
Alex Crichton 已提交
1679 1680 1681 1682 1683
                    helper.request_token();
                    assert_eq!(main_thread_worker_state,
                               MainThreadWorkerState::Translating);
                    main_thread_worker_state = MainThreadWorkerState::Idle;
                }
1684

A
Alex Crichton 已提交
1685 1686
                Message::TranslationComplete => {
                    translation_done = true;
1687 1688 1689
                    assert_eq!(main_thread_worker_state,
                               MainThreadWorkerState::Translating);
                    main_thread_worker_state = MainThreadWorkerState::Idle;
1690 1691
                }

1692 1693 1694 1695 1696 1697 1698 1699
                // If a thread exits successfully then we drop a token associated
                // with that worker and update our `running` count. We may later
                // re-acquire a token to continue running more work. We may also not
                // actually drop a token here if the worker was running with an
                // "ephemeral token"
                //
                // Note that if the thread failed that means it panicked, so we
                // abort immediately.
1700
                Message::Done { result: Ok(compiled_module), worker_id } => {
1701 1702
                    if main_thread_worker_state == MainThreadWorkerState::LLVMing {
                        main_thread_worker_state = MainThreadWorkerState::Idle;
1703 1704 1705
                    } else {
                        running -= 1;
                    }
1706

1707 1708
                    free_worker_ids.push(worker_id);

1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721
                    match compiled_module.kind {
                        ModuleKind::Regular => {
                            compiled_modules.push(compiled_module);
                        }
                        ModuleKind::Metadata => {
                            assert!(compiled_metadata_module.is_none());
                            compiled_metadata_module = Some(compiled_module);
                        }
                        ModuleKind::Allocator => {
                            assert!(compiled_allocator_module.is_none());
                            compiled_allocator_module = Some(compiled_module);
                        }
                    }
1722
                }
1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733
                Message::NeedsLTO { result, worker_id } => {
                    assert!(!started_lto);
                    if main_thread_worker_state == MainThreadWorkerState::LLVMing {
                        main_thread_worker_state = MainThreadWorkerState::Idle;
                    } else {
                        running -= 1;
                    }

                    free_worker_ids.push(worker_id);
                    needs_lto.push(result);
                }
1734
                Message::Done { result: Err(()), worker_id: _ } => {
1735
                    shared_emitter.fatal("aborting due to worker thread failure");
1736
                    // Exit the coordinator thread
1737
                    return Err(())
1738
                }
1739 1740
                Message::TranslateItem => {
                    bug!("the coordinator should not receive translation requests")
1741
                }
1742
            }
1743
        }
1744

1745 1746 1747 1748 1749 1750 1751 1752 1753 1754
        if let Some(llvm_start_time) = llvm_start_time {
            let total_llvm_time = Instant::now().duration_since(llvm_start_time);
            // This is the top-level timing for all of LLVM, set the time-depth
            // to zero.
            set_time_depth(0);
            print_time_passes_entry(cgcx.time_passes,
                                    "LLVM passes",
                                    total_llvm_time);
        }

1755 1756 1757 1758 1759
        // Regardless of what order these modules completed in, report them to
        // the backend in the same order every time to ensure that we're handing
        // out deterministic results.
        compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));

1760 1761 1762
        let compiled_metadata_module = compiled_metadata_module
            .expect("Metadata module not compiled?");

1763
        Ok(CompiledModules {
1764
            modules: compiled_modules,
1765
            metadata_module: compiled_metadata_module,
1766
            allocator_module: compiled_allocator_module,
1767
        })
1768 1769 1770 1771 1772 1773 1774 1775
    });

    // A heuristic that determines if we have enough LLVM WorkItems in the
    // queue so that the main thread can do LLVM work instead of translation
    fn queue_full_enough(items_in_queue: usize,
                         workers_running: usize,
                         max_workers: usize) -> bool {
        // Tune me, plz.
1776
        items_in_queue > 0 &&
1777 1778
        items_in_queue >= max_workers.saturating_sub(workers_running / 2)
    }
1779

A
Alex Crichton 已提交
1780
    fn maybe_start_llvm_timer(config: &ModuleConfig,
1781 1782 1783
                              llvm_start_time: &mut Option<Instant>) {
        // We keep track of the -Ztime-passes output manually,
        // since the closure-based interface does not fit well here.
A
Alex Crichton 已提交
1784
        if config.time_passes {
1785 1786 1787 1788 1789
            if llvm_start_time.is_none() {
                *llvm_start_time = Some(Instant::now());
            }
        }
    }
1790 1791
}

1792 1793 1794 1795 1796 1797 1798 1799
pub const TRANS_WORKER_ID: usize = ::std::usize::MAX;
pub const TRANS_WORKER_TIMELINE: time_graph::TimelineId =
    time_graph::TimelineId(TRANS_WORKER_ID);
pub const TRANS_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
    time_graph::WorkPackageKind(&["#DE9597", "#FED1D3", "#FDC5C7", "#B46668", "#88494B"]);
const LLVM_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
    time_graph::WorkPackageKind(&["#7DB67A", "#C6EEC4", "#ACDAAA", "#579354", "#3E6F3C"]);

1800
fn spawn_work(cgcx: CodegenContext, work: WorkItem) {
1801 1802
    let depth = time_depth();

1803
    thread::spawn(move || {
1804 1805 1806 1807 1808
        set_time_depth(depth);

        // Set up a destructor which will fire off a message that we're done as
        // we exit.
        struct Bomb {
1809
            coordinator_send: Sender<Box<Any + Send>>,
1810
            result: Option<WorkItemResult>,
1811
            worker_id: usize,
1812 1813 1814
        }
        impl Drop for Bomb {
            fn drop(&mut self) {
1815 1816 1817 1818 1819 1820 1821 1822 1823
                let worker_id = self.worker_id;
                let msg = match self.result.take() {
                    Some(WorkItemResult::Compiled(m)) => {
                        Message::Done { result: Ok(m), worker_id }
                    }
                    Some(WorkItemResult::NeedsLTO(m)) => {
                        Message::NeedsLTO { result: m, worker_id }
                    }
                    None => Message::Done { result: Err(()), worker_id }
1824
                };
1825
                drop(self.coordinator_send.send(Box::new(msg)));
1826 1827
            }
        }
1828

1829
        let mut bomb = Bomb {
1830
            coordinator_send: cgcx.coordinator_send.clone(),
1831
            result: None,
1832
            worker_id: cgcx.worker,
1833 1834 1835 1836 1837
        };

        // Execute the work itself, and if it finishes successfully then flag
        // ourselves as a success as well.
        //
1838 1839 1840
        // Note that we ignore any `FatalError` coming out of `execute_work_item`,
        // as a diagnostic was already sent off to the main thread - just
        // surface that there was an error in this worker.
1841
        bomb.result = {
A
Alex Crichton 已提交
1842
            let timeline = cgcx.time_graph.as_ref().map(|tg| {
1843 1844 1845 1846
                tg.start(time_graph::TimelineId(cgcx.worker),
                         LLVM_WORK_PACKAGE_KIND,
                         &work.name())
            });
A
Alex Crichton 已提交
1847 1848
            let mut timeline = timeline.unwrap_or(Timeline::noop());
            execute_work_item(&cgcx, work, &mut timeline).ok()
1849
        };
1850 1851 1852
    });
}

1853
pub fn run_assembler(sess: &Session, outputs: &OutputFilenames) {
1854
    let (pname, mut cmd, _) = get_linker(sess);
1855

1856 1857 1858 1859
    for arg in &sess.target.target.options.asm_args {
        cmd.arg(arg);
    }

1860
    cmd.arg("-c").arg("-o").arg(&outputs.path(OutputType::Object))
1861
                           .arg(&outputs.temp_path(OutputType::Assembly, None));
A
Alex Crichton 已提交
1862
    debug!("{:?}", cmd);
1863 1864 1865 1866

    match cmd.output() {
        Ok(prog) => {
            if !prog.status.success() {
A
Alex Crichton 已提交
1867
                let mut note = prog.stderr.clone();
1868
                note.extend_from_slice(&prog.stdout);
N
Nick Cameron 已提交
1869 1870 1871 1872 1873 1874 1875

                sess.struct_err(&format!("linking with `{}` failed: {}",
                                         pname,
                                         prog.status))
                    .note(&format!("{:?}", &cmd))
                    .note(str::from_utf8(&note[..]).unwrap())
                    .emit();
1876 1877 1878 1879
                sess.abort_if_errors();
            }
        },
        Err(e) => {
1880
            sess.err(&format!("could not exec the linker `{}`: {}", pname, e));
1881 1882 1883 1884 1885
            sess.abort_if_errors();
        }
    }
}

1886 1887
pub unsafe fn with_llvm_pmb(llmod: ModuleRef,
                            config: &ModuleConfig,
1888
                            opt_level: llvm::CodeGenOptLevel,
1889
                            f: &mut FnMut(llvm::PassManagerBuilderRef)) {
1890 1891 1892 1893
    // Create the PassManagerBuilder for LLVM. We configure it with
    // reasonable defaults and prepare it to actually populate the pass
    // manager.
    let builder = llvm::LLVMPassManagerBuilderCreate();
1894
    let opt_size = config.opt_size.unwrap_or(llvm::CodeGenOptSizeNone);
B
Brian Anderson 已提交
1895
    let inline_threshold = config.inline_threshold;
A
Alex Crichton 已提交
1896

1897 1898
    llvm::LLVMRustConfigurePassManagerBuilder(builder,
                                              opt_level,
A
Alex Crichton 已提交
1899 1900 1901
                                              config.merge_functions,
                                              config.vectorize_slp,
                                              config.vectorize_loop);
1902 1903 1904 1905 1906
    llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);

    if opt_size != llvm::CodeGenOptSizeNone {
        llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
    }
A
Alex Crichton 已提交
1907 1908 1909 1910 1911 1912 1913

    llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);

    // Here we match what clang does (kinda). For O0 we only inline
    // always-inline functions (but don't add lifetime intrinsics), at O1 we
    // inline with lifetime intrinsics, and O2+ we add an inliner with a
    // thresholds copied from clang.
1914
    match (opt_level, opt_size, inline_threshold) {
V
Vadim Petrochenkov 已提交
1915
        (.., Some(t)) => {
B
Brian Anderson 已提交
1916 1917
            llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
        }
V
Vadim Petrochenkov 已提交
1918
        (llvm::CodeGenOptLevel::Aggressive, ..) => {
1919 1920 1921 1922 1923 1924 1925 1926
            llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
        }
        (_, llvm::CodeGenOptSizeDefault, _) => {
            llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
        }
        (_, llvm::CodeGenOptSizeAggressive, _) => {
            llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
        }
V
Vadim Petrochenkov 已提交
1927
        (llvm::CodeGenOptLevel::None, ..) => {
1928 1929
            llvm::LLVMRustAddAlwaysInlinePass(builder, false);
        }
V
Vadim Petrochenkov 已提交
1930
        (llvm::CodeGenOptLevel::Less, ..) => {
1931 1932
            llvm::LLVMRustAddAlwaysInlinePass(builder, true);
        }
V
Vadim Petrochenkov 已提交
1933
        (llvm::CodeGenOptLevel::Default, ..) => {
A
Alex Crichton 已提交
1934
            llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
1935
        }
V
Vadim Petrochenkov 已提交
1936
        (llvm::CodeGenOptLevel::Other, ..) => {
1937 1938
            bug!("CodeGenOptLevel::Other selected")
        }
1939 1940
    }

1941
    f(builder);
1942 1943
    llvm::LLVMPassManagerBuilderDispose(builder);
}
1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972


enum SharedEmitterMessage {
    Diagnostic(Diagnostic),
    InlineAsmError(u32, String),
    AbortIfErrors,
    Fatal(String),
}

#[derive(Clone)]
pub struct SharedEmitter {
    sender: Sender<SharedEmitterMessage>,
}

pub struct SharedEmitterMain {
    receiver: Receiver<SharedEmitterMessage>,
}

impl SharedEmitter {
    pub fn new() -> (SharedEmitter, SharedEmitterMain) {
        let (sender, receiver) = channel();

        (SharedEmitter { sender }, SharedEmitterMain { receiver })
    }

    fn inline_asm_error(&self, cookie: u32, msg: String) {
        drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg)));
    }

1973 1974
    fn fatal(&self, msg: &str) {
        drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996
    }
}

impl Emitter for SharedEmitter {
    fn emit(&mut self, db: &DiagnosticBuilder) {
        drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
            msg: db.message(),
            code: db.code.clone(),
            lvl: db.level,
        })));
        for child in &db.children {
            drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
                msg: child.message(),
                code: None,
                lvl: child.level,
            })));
        }
        drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
    }
}

impl SharedEmitterMain {
1997
    pub fn check(&self, sess: &Session, blocking: bool) {
1998
        loop {
1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011
            let message = if blocking {
                match self.receiver.recv() {
                    Ok(message) => Ok(message),
                    Err(_) => Err(()),
                }
            } else {
                match self.receiver.try_recv() {
                    Ok(message) => Ok(message),
                    Err(_) => Err(()),
                }
            };

            match message {
2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047
                Ok(SharedEmitterMessage::Diagnostic(diag)) => {
                    let handler = sess.diagnostic();
                    match diag.code {
                        Some(ref code) => {
                            handler.emit_with_code(&MultiSpan::new(),
                                                   &diag.msg,
                                                   &code,
                                                   diag.lvl);
                        }
                        None => {
                            handler.emit(&MultiSpan::new(),
                                         &diag.msg,
                                         diag.lvl);
                        }
                    }
                }
                Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => {
                    match Mark::from_u32(cookie).expn_info() {
                        Some(ei) => sess.span_err(ei.call_site, &msg),
                        None     => sess.err(&msg),
                    }
                }
                Ok(SharedEmitterMessage::AbortIfErrors) => {
                    sess.abort_if_errors();
                }
                Ok(SharedEmitterMessage::Fatal(msg)) => {
                    sess.fatal(&msg);
                }
                Err(_) => {
                    break;
                }
            }

        }
    }
}
2048 2049

pub struct OngoingCrateTranslation {
2050 2051 2052 2053 2054 2055
    crate_name: Symbol,
    link: LinkMeta,
    metadata: EncodedMetadata,
    windows_subsystem: Option<String>,
    linker_info: LinkerInfo,
    no_integrated_as: bool,
2056
    crate_info: CrateInfo,
2057
    time_graph: Option<TimeGraph>,
2058
    coordinator_send: Sender<Box<Any + Send>>,
2059
    trans_worker_receive: Receiver<Message>,
2060
    shared_emitter_main: SharedEmitterMain,
2061
    future: thread::JoinHandle<Result<CompiledModules, ()>>,
A
Alex Crichton 已提交
2062
    output_filenames: Arc<OutputFilenames>,
2063 2064 2065
}

impl OngoingCrateTranslation {
2066
    pub fn join(self, sess: &Session, dep_graph: &DepGraph) -> CrateTranslation {
2067
        self.shared_emitter_main.check(sess, true);
2068
        let compiled_modules = match self.future.join() {
2069 2070 2071 2072 2073
            Ok(Ok(compiled_modules)) => compiled_modules,
            Ok(Err(())) => {
                sess.abort_if_errors();
                panic!("expected abort due to worker thread errors")
            },
2074 2075 2076 2077
            Err(_) => {
                sess.fatal("Error during translation/LLVM phase.");
            }
        };
2078 2079

        sess.abort_if_errors();
2080

2081 2082 2083 2084
        if let Some(time_graph) = self.time_graph {
            time_graph.dump(&format!("{}-timings", self.crate_name));
        }

2085
        copy_module_artifacts_into_incr_comp_cache(sess,
2086
                                                   dep_graph,
2087
                                                   &compiled_modules);
2088 2089 2090
        produce_final_output_artifacts(sess,
                                       &compiled_modules,
                                       &self.output_filenames);
2091 2092 2093

        // FIXME: time_llvm_passes support - does this use a global context or
        // something?
2094
        if sess.codegen_units() == 1 && sess.time_llvm_passes() {
2095 2096
            unsafe { llvm::LLVMRustPrintPassTimings(); }
        }
2097 2098 2099 2100 2101 2102 2103

        let trans = CrateTranslation {
            crate_name: self.crate_name,
            link: self.link,
            metadata: self.metadata,
            windows_subsystem: self.windows_subsystem,
            linker_info: self.linker_info,
2104
            crate_info: self.crate_info,
2105

2106 2107
            modules: compiled_modules.modules,
            allocator_module: compiled_modules.allocator_module,
2108
            metadata_module: compiled_modules.metadata_module,
2109 2110 2111
        };

        if self.no_integrated_as {
2112
            run_assembler(sess,  &self.output_filenames);
2113 2114 2115 2116 2117

            // HACK the linker expects the object file to be named foo.0.o but
            // `run_assembler` produces an object named just foo.o. Rename it if we
            // are going to build an executable
            if sess.opts.output_types.contains_key(&OutputType::Exe) {
2118
                let f =  self.output_filenames.path(OutputType::Object);
2119
                rename_or_copy_remove(&f,
2120 2121
                    f.with_file_name(format!("{}.0.o",
                                             f.file_stem().unwrap().to_string_lossy()))).unwrap();
2122 2123 2124 2125
            }

            // Remove assembly source, unless --save-temps was specified
            if !sess.opts.cg.save_temps {
2126 2127
                fs::remove_file(&self.output_filenames
                                     .temp_path(OutputType::Assembly, None)).unwrap();
2128 2129 2130 2131 2132
            }
        }

        trans
    }
2133

2134
    pub fn submit_pre_translated_module_to_llvm(&self,
A
Alex Crichton 已提交
2135 2136
                                                tcx: TyCtxt,
                                                mtrans: ModuleTranslation) {
2137
        self.wait_for_signal_to_translate_item();
A
Alex Crichton 已提交
2138
        self.check_for_errors(tcx.sess);
2139 2140 2141

        // These are generally cheap and won't through off scheduling.
        let cost = 0;
A
Alex Crichton 已提交
2142 2143 2144 2145 2146 2147 2148
        submit_translated_module_to_llvm(tcx, mtrans, cost);
    }

    pub fn translation_finished(&self, tcx: TyCtxt) {
        self.wait_for_signal_to_translate_item();
        self.check_for_errors(tcx.sess);
        drop(self.coordinator_send.send(Box::new(Message::TranslationComplete)));
2149
    }
2150 2151 2152 2153

    pub fn check_for_errors(&self, sess: &Session) {
        self.shared_emitter_main.check(sess, false);
    }
2154 2155 2156 2157 2158 2159

    pub fn wait_for_signal_to_translate_item(&self) {
        match self.trans_worker_receive.recv() {
            Ok(Message::TranslateItem) => {
                // Nothing to do
            }
2160
            Ok(_) => panic!("unexpected message"),
2161 2162 2163 2164 2165 2166
            Err(_) => {
                // One of the LLVM threads must have panicked, fall through so
                // error handling can be reached.
            }
        }
    }
2167
}
A
Alex Crichton 已提交
2168 2169 2170 2171

pub fn submit_translated_module_to_llvm(tcx: TyCtxt,
                                        mtrans: ModuleTranslation,
                                        cost: u64) {
2172
    let llvm_work_item = WorkItem::Optimize(mtrans);
A
Alex Crichton 已提交
2173 2174 2175 2176 2177
    drop(tcx.tx_to_llvm_workers.send(Box::new(Message::TranslationDone {
        llvm_work_item,
        cost,
    })));
}
2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225

fn msvc_imps_needed(tcx: TyCtxt) -> bool {
    tcx.sess.target.target.options.is_like_msvc &&
        tcx.sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateTypeRlib)
}

// Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
// This is required to satisfy `dllimport` references to static data in .rlibs
// when using MSVC linker.  We do this only for data, as linker can fix up
// code references on its own.
// See #26591, #27438
fn create_msvc_imps(cgcx: &CodegenContext, llcx: ContextRef, llmod: ModuleRef) {
    if !cgcx.msvc_imps_needed {
        return
    }
    // The x86 ABI seems to require that leading underscores are added to symbol
    // names, so we need an extra underscore on 32-bit. There's also a leading
    // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
    // underscores added in front).
    let prefix = if cgcx.target_pointer_width == "32" {
        "\x01__imp__"
    } else {
        "\x01__imp_"
    };
    unsafe {
        let i8p_ty = Type::i8p_llcx(llcx);
        let globals = base::iter_globals(llmod)
            .filter(|&val| {
                llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage &&
                    llvm::LLVMIsDeclaration(val) == 0
            })
            .map(move |val| {
                let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
                let mut imp_name = prefix.as_bytes().to_vec();
                imp_name.extend(name.to_bytes());
                let imp_name = CString::new(imp_name).unwrap();
                (imp_name, val)
            })
            .collect::<Vec<_>>();
        for (imp_name, val) in globals {
            let imp = llvm::LLVMAddGlobal(llmod,
                                          i8p_ty.to_ref(),
                                          imp_name.as_ptr() as *const _);
            llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
            llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
        }
    }
}