cmNinjaTargetGenerator.cxx 29.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*============================================================================
  CMake - Cross Platform Makefile Generator
  Copyright 2011 Peter Collingbourne <peter@pcc.me.uk>
  Copyright 2011 Nicolas Despres <nicolas.despres@gmail.com>

  Distributed under the OSI-approved BSD License (the "License");
  see accompanying file Copyright.txt for details.

  This software is distributed WITHOUT ANY WARRANTY; without even the
  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  See the License for more information.
============================================================================*/
#include "cmNinjaTargetGenerator.h"
#include "cmGlobalNinjaGenerator.h"
#include "cmLocalNinjaGenerator.h"
#include "cmGeneratedFileStream.h"
17
#include "cmGeneratorTarget.h"
18
19
20
21
22
23
24
#include "cmNinjaNormalTargetGenerator.h"
#include "cmNinjaUtilityTargetGenerator.h"
#include "cmSystemTools.h"
#include "cmMakefile.h"
#include "cmComputeLinkInformation.h"
#include "cmSourceFile.h"
#include "cmCustomCommandGenerator.h"
25
#include "cmAlgorithms.h"
26
27
28
29

#include <algorithm>

cmNinjaTargetGenerator *
30
cmNinjaTargetGenerator::New(cmGeneratorTarget* target)
31
32
33
34
35
36
37
{
  switch (target->GetType())
    {
      case cmTarget::EXECUTABLE:
      case cmTarget::SHARED_LIBRARY:
      case cmTarget::STATIC_LIBRARY:
      case cmTarget::MODULE_LIBRARY:
38
      case cmTarget::OBJECT_LIBRARY:
39
40
41
42
43
44
45
46
47
        return new cmNinjaNormalTargetGenerator(target);

      case cmTarget::UTILITY:
        return new cmNinjaUtilityTargetGenerator(target);;

      case cmTarget::GLOBAL_TARGET: {
        // We only want to process global targets that live in the home
        // (i.e. top-level) directory.  CMake creates copies of these targets
        // in every directory, which we don't need.
48
        cmMakefile *mf = target->Target->GetMakefile();
49
50
        if (strcmp(mf->GetCurrentSourceDirectory(),
                   mf->GetHomeDirectory()) == 0)
51
52
53
54
55
56
57
58
59
          return new cmNinjaUtilityTargetGenerator(target);
        // else fallthrough
      }

      default:
        return 0;
    }
}

60
cmNinjaTargetGenerator::cmNinjaTargetGenerator(cmGeneratorTarget* target)
61
  :
Peter Kümmel's avatar
Peter Kümmel committed
62
    MacOSXContentGenerator(0),
63
64
    OSXBundleGenerator(0),
    MacContentFolders(),
65
66
    Target(target->Target),
    Makefile(target->Makefile),
67
    LocalGenerator(
68
      static_cast<cmLocalNinjaGenerator*>(target->GetLocalGenerator())),
69
70
    Objects()
{
71
  this->GeneratorTarget = target;
Peter Kümmel's avatar
Peter Kümmel committed
72
  MacOSXContentGenerator = new MacOSXContentGeneratorType(this);
73
74
75
76
}

cmNinjaTargetGenerator::~cmNinjaTargetGenerator()
{
Nicolas Despres's avatar
Nicolas Despres committed
77
  delete this->MacOSXContentGenerator;
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
}

cmGeneratedFileStream& cmNinjaTargetGenerator::GetBuildFileStream() const
{
  return *this->GetGlobalGenerator()->GetBuildFileStream();
}

cmGeneratedFileStream& cmNinjaTargetGenerator::GetRulesFileStream() const
{
  return *this->GetGlobalGenerator()->GetRulesFileStream();
}

cmGlobalNinjaGenerator* cmNinjaTargetGenerator::GetGlobalGenerator() const
{
  return this->LocalGenerator->GetGlobalNinjaGenerator();
}

95
std::string const& cmNinjaTargetGenerator::GetConfigName() const
96
{
97
  return this->LocalGenerator->GetConfigName();
98
99
}

100
101
102
103
104
105
106
std::string cmNinjaTargetGenerator::LanguageCompilerRule(
  const std::string& lang) const
{
  return lang + "_COMPILER__" +
    cmGlobalNinjaGenerator::EncodeRuleName(this->Target->GetName());
}

107
// TODO: Picked up from cmMakefileTargetGenerator.  Refactor it.
108
const char* cmNinjaTargetGenerator::GetFeature(const std::string& feature)
109
{
110
  return this->GeneratorTarget->GetFeature(feature, this->GetConfigName());
111
112
113
}

// TODO: Picked up from cmMakefileTargetGenerator.  Refactor it.
114
bool cmNinjaTargetGenerator::GetFeatureAsBool(const std::string& feature)
115
{
116
117
  return this->GeneratorTarget->GetFeatureAsBool(feature,
                                                 this->GetConfigName());
118
119
120
121
}

// TODO: Picked up from cmMakefileTargetGenerator.  Refactor it.
void cmNinjaTargetGenerator::AddFeatureFlags(std::string& flags,
122
                                             const std::string& lang)
123
124
125
126
127
128
129
130
131
132
{
  // Add language-specific flags.
  this->LocalGenerator->AddLanguageFlags(flags, lang, this->GetConfigName());

  if(this->GetFeatureAsBool("INTERPROCEDURAL_OPTIMIZATION"))
    {
    this->LocalGenerator->AppendFeatureOptions(flags, lang, "IPO");
    }
}

133
134
135
136
137
138
std::string
cmNinjaTargetGenerator::OrderDependsTargetForTarget()
{
  return "cmake_order_depends_target_" + this->GetTargetName();
}

139
140
141
142
143
// TODO: Most of the code is picked up from
// void cmMakefileExecutableTargetGenerator::WriteExecutableRule(bool relink),
// void cmMakefileTargetGenerator::WriteTargetLanguageFlags()
// Refactor it.
std::string
144
cmNinjaTargetGenerator::ComputeFlagsForObject(cmSourceFile const* source,
145
146
147
148
149
150
151
152
153
                                              const std::string& language)
{
  // TODO: Fortran support.
  // // Fortran-specific flags computed for this target.
  // if(*l == "Fortran")
  //   {
  //   this->AddFortranFlags(flags);
  //   }

Ben Boeckel's avatar
Ben Boeckel committed
154
155
156
157
  bool hasLangCached = this->LanguageFlags.count(language) != 0;
  std::string& languageFlags = this->LanguageFlags[language];
  if(!hasLangCached)
    {
Stephen Kelly's avatar
Stephen Kelly committed
158
    this->AddFeatureFlags(languageFlags, language);
Ben Boeckel's avatar
Ben Boeckel committed
159
160
161

    this->GetLocalGenerator()->AddArchitectureFlags(languageFlags,
                                                    this->GeneratorTarget,
Stephen Kelly's avatar
Stephen Kelly committed
162
                                                    language,
Ben Boeckel's avatar
Ben Boeckel committed
163
164
165
166
167
168
169
170
                                                    this->GetConfigName());

    // Add shared-library flags if needed.
    this->LocalGenerator->AddCMP0018Flags(languageFlags, this->Target,
                                          language,
                                          this->GetConfigName());

    this->LocalGenerator->AddVisibilityPresetFlags(languageFlags, this->Target,
Stephen Kelly's avatar
Stephen Kelly committed
171
                                                   language);
Ben Boeckel's avatar
Ben Boeckel committed
172
173
174
175

    std::vector<std::string> includes;
    this->LocalGenerator->GetIncludeDirectories(includes,
                                                this->GeneratorTarget,
Stephen Kelly's avatar
Stephen Kelly committed
176
                                                language,
Ben Boeckel's avatar
Ben Boeckel committed
177
178
179
180
                                                this->GetConfigName());
    // Add include directory flags.
    std::string includeFlags =
      this->LocalGenerator->GetIncludeFlags(includes, this->GeneratorTarget,
Stephen Kelly's avatar
Stephen Kelly committed
181
                                            language,
182
      language == "RC" ? true : false,  // full include paths for RC
Ben Boeckel's avatar
Ben Boeckel committed
183
                                        // needed by cmcldeps
184
185
                                            false,
                                            this->GetConfigName());
186
    if (this->GetGlobalGenerator()->IsGCCOnWindows())
Ben Boeckel's avatar
Ben Boeckel committed
187
188
      cmSystemTools::ReplaceString(includeFlags, "\\", "/");

189
    this->LocalGenerator->AppendFlags(languageFlags, includeFlags);
Ben Boeckel's avatar
Ben Boeckel committed
190
191
192
193
194
195
196

    // Append old-style preprocessor definition flags.
    this->LocalGenerator->AppendFlags(languageFlags,
                                      this->Makefile->GetDefineFlags());

    // Add target-specific flags.
    this->LocalGenerator->AddCompileOptions(languageFlags, this->Target,
Stephen Kelly's avatar
Stephen Kelly committed
197
                                            language,
Ben Boeckel's avatar
Ben Boeckel committed
198
199
200
201
202
203
204
205
                                            this->GetConfigName());
    }

  std::string flags = languageFlags;

  // Add source file specific flags.
  this->LocalGenerator->AppendFlags(flags,
    source->GetProperty("COMPILE_FLAGS"));
206
207
208
209
210
211

  // TODO: Handle Apple frameworks.

  return flags;
}

212
bool cmNinjaTargetGenerator::NeedDepTypeMSVC(const std::string& lang) const
213
{
214
215
216
217
218
219
220
221
222
223
224
  if (lang == "C" || lang == "CXX")
    {
    cmMakefile* mf = this->GetMakefile();
    return (
      strcmp(mf->GetSafeDefinition("CMAKE_C_COMPILER_ID"), "MSVC") == 0 ||
      strcmp(mf->GetSafeDefinition("CMAKE_CXX_COMPILER_ID"), "MSVC") == 0 ||
      strcmp(mf->GetSafeDefinition("CMAKE_C_SIMULATE_ID"), "MSVC") == 0 ||
      strcmp(mf->GetSafeDefinition("CMAKE_CXX_SIMULATE_ID"), "MSVC") == 0
      );
    }
  return false;
225
226
}

227
228
229
230
// TODO: Refactor with
// void cmMakefileTargetGenerator::WriteTargetLanguageFlags().
std::string
cmNinjaTargetGenerator::
231
ComputeDefines(cmSourceFile const* source, const std::string& language)
232
{
233
  std::set<std::string> defines;
234
235
236
237

  // Add the export symbol definition for shared library objects.
  if(const char* exportMacro = this->Target->GetExportMacro())
    {
238
    this->LocalGenerator->AppendDefines(defines, exportMacro);
239
240
241
    }

  // Add preprocessor definitions for this target and configuration.
242
  this->LocalGenerator->AddCompileDefinitions(defines, this->Target,
243
                                             this->GetConfigName(), language);
244
245
  this->LocalGenerator->AppendDefines
    (defines,
246
     source->GetProperty("COMPILE_DEFINITIONS"));
247
248
249
250
251
  {
  std::string defPropName = "COMPILE_DEFINITIONS_";
  defPropName += cmSystemTools::UpperCase(this->GetConfigName());
  this->LocalGenerator->AppendDefines
    (defines,
Stephen Kelly's avatar
Stephen Kelly committed
252
     source->GetProperty(defPropName));
253
254
  }

255
256
  std::string definesString;
  this->LocalGenerator->JoinDefines(defines, definesString,
Stephen Kelly's avatar
Stephen Kelly committed
257
     language);
258
259

  return definesString;
260
261
262
263
264
}

cmNinjaDeps cmNinjaTargetGenerator::ComputeLinkDeps() const
{
  // Static libraries never depend on other targets for linking.
265
266
  if (this->Target->GetType() == cmTarget::STATIC_LIBRARY ||
      this->Target->GetType() == cmTarget::OBJECT_LIBRARY)
267
268
269
    return cmNinjaDeps();

  cmComputeLinkInformation* cli =
270
    this->Target->GetLinkInformation(this->GetConfigName());
271
272
273
274
275
276
  if(!cli)
    return cmNinjaDeps();

  const std::vector<std::string> &deps = cli->GetDepends();
  cmNinjaDeps result(deps.size());
  std::transform(deps.begin(), deps.end(), result.begin(), MapToNinjaPath());
Peter Kuemmel's avatar
Peter Kuemmel committed
277
278

  // Add a dependency on the link definitions file, if any.
279
  if(!this->ModuleDefinitionFile.empty())
Peter Kuemmel's avatar
Peter Kuemmel committed
280
    {
281
    result.push_back(this->ModuleDefinitionFile);
Peter Kuemmel's avatar
Peter Kuemmel committed
282
283
    }

284
285
286
287
288
  return result;
}

std::string
cmNinjaTargetGenerator
289
::GetSourceFilePath(cmSourceFile const* source) const
290
{
291
  return ConvertToNinjaPath(source->GetFullPath());
292
293
294
295
}

std::string
cmNinjaTargetGenerator
296
::GetObjectFilePath(cmSourceFile const* source) const
297
298
299
300
{
  std::string path = this->LocalGenerator->GetHomeRelativeOutputPath();
  if(!path.empty())
    path += "/";
301
302
  std::string const& objectName = this->GeneratorTarget
                                      ->GetObjectName(source);
303
304
305
  path += this->LocalGenerator->GetTargetDirectory(*this->Target);
  path += "/";
  path += objectName;
306
307
308
309
310
311
  return path;
}

std::string cmNinjaTargetGenerator::GetTargetOutputDir() const
{
  std::string dir = this->Target->GetDirectory(this->GetConfigName());
312
  return ConvertToNinjaPath(dir);
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
}

std::string
cmNinjaTargetGenerator
::GetTargetFilePath(const std::string& name) const
{
  std::string path = this->GetTargetOutputDir();
  if (path.empty() || path == ".")
    return name;
  path += "/";
  path += name;
  return path;
}

std::string cmNinjaTargetGenerator::GetTargetName() const
{
  return this->Target->GetName();
}

332

333
bool cmNinjaTargetGenerator::SetMsvcTargetPdbVariable(cmNinjaVars& vars) const
334
{
335
336
337
  cmMakefile* mf = this->GetMakefile();
  if (mf->GetDefinition("MSVC_C_ARCHITECTURE_ID") ||
      mf->GetDefinition("MSVC_CXX_ARCHITECTURE_ID"))
338
    {
339
    std::string pdbPath;
340
    std::string compilePdbPath;
341
342
343
344
345
    if(this->Target->GetType() == cmTarget::EXECUTABLE ||
       this->Target->GetType() == cmTarget::STATIC_LIBRARY ||
       this->Target->GetType() == cmTarget::SHARED_LIBRARY ||
       this->Target->GetType() == cmTarget::MODULE_LIBRARY)
      {
346
      pdbPath = this->Target->GetPDBDirectory(this->GetConfigName());
347
348
      pdbPath += "/";
      pdbPath += this->Target->GetPDBName(this->GetConfigName());
349
      }
350
351
352
353
354
355
356
357
    if(this->Target->GetType() <= cmTarget::OBJECT_LIBRARY)
      {
      compilePdbPath = this->Target->GetCompilePDBPath(this->GetConfigName());
      if(compilePdbPath.empty())
        {
        compilePdbPath = this->Target->GetSupportDirectory() + "/";
        }
      }
358

359
    vars["TARGET_PDB"] = this->GetLocalGenerator()->ConvertToOutputFormat(
360
                          ConvertToNinjaPath(pdbPath),
361
                          cmLocalGenerator::SHELL);
362
363
    vars["TARGET_COMPILE_PDB"] =
      this->GetLocalGenerator()->ConvertToOutputFormat(
364
        ConvertToNinjaPath(compilePdbPath),
365
366
        cmLocalGenerator::SHELL);

367
    EnsureParentDirectoryExists(pdbPath);
368
    EnsureParentDirectoryExists(compilePdbPath);
369
370
371
    return true;
    }
  return false;
372
373
}

374
375
376
377
void
cmNinjaTargetGenerator
::WriteLanguageRules(const std::string& language)
{
378
#ifdef NINJA_GEN_VERBOSE_FILES
379
380
  this->GetRulesFileStream()
    << "# Rules for language " << language << "\n\n";
381
#endif
382
383
384
385
386
  this->WriteCompileRule(language);
}

void
cmNinjaTargetGenerator
387
::WriteCompileRule(const std::string& lang)
388
389
390
391
392
393
394
395
{
  cmLocalGenerator::RuleVariables vars;
  vars.RuleLauncher = "RULE_LAUNCH_COMPILE";
  vars.CMTarget = this->GetTarget();
  vars.Language = lang.c_str();
  vars.Source = "$in";
  vars.Object = "$out";
  vars.Defines = "$DEFINES";
396
  vars.TargetPDB = "$TARGET_PDB";
397
  vars.TargetCompilePDB = "$TARGET_COMPILE_PDB";
398
  vars.ObjectDir = "$OBJECT_DIR";
399
  vars.ObjectFileDir = "$OBJECT_FILE_DIR";
400

401
  cmMakefile* mf = this->GetMakefile();
402

403
404
405
406
407
  // Tell ninja dependency format so all deps can be loaded into a database
  std::string deptype;
  std::string depfile;
  std::string cldeps;
  std::string flags = "$FLAGS";
408
  if (this->NeedDepTypeMSVC(lang))
409
    {
410
411
412
413
414
415
416
417
418
    deptype = "msvc";
    depfile = "";
    flags += " /showIncludes";
    }
  else if (lang == "RC" && this->NeedDepTypeMSVC("C"))
    {
    // For the MS resource compiler we need cmcldeps, but skip dependencies
    // for source-file try_compile cases because they are always fresh.
    if (!mf->GetIsSourceFileTryCompile())
419
      {
420
421
422
423
424
425
426
427
428
429
430
      deptype = "gcc";
      depfile = "$DEP_FILE";
      const std::string cl = mf->GetDefinition("CMAKE_C_COMPILER") ?
                        mf->GetSafeDefinition("CMAKE_C_COMPILER") :
                        mf->GetSafeDefinition("CMAKE_CXX_COMPILER");
      cldeps =  "\"";
      cldeps += mf->GetSafeDefinition("CMAKE_CMCLDEPS_EXECUTABLE");
      cldeps += "\" " + lang + " $in \"$DEP_FILE\" $out \"";
      cldeps += mf->GetSafeDefinition("CMAKE_CL_SHOWINCLUDES_PREFIX");
      cldeps += "\" \"" + cl + "\" ";
      }
431
    }
432
433
434
  else
    {
    deptype = "gcc";
435
436
437
438
439
    const char* langdeptype = mf->GetDefinition("CMAKE_NINJA_DEPTYPE_" + lang);
    if (langdeptype)
      {
      deptype = langdeptype;
      }
440
    depfile = "$DEP_FILE";
441
    const std::string flagsName = "CMAKE_DEPFILE_FLAGS_" + lang;
Stephen Kelly's avatar
Stephen Kelly committed
442
    std::string depfileFlags = mf->GetSafeDefinition(flagsName);
443
444
445
446
447
448
449
450
    if (!depfileFlags.empty())
      {
      cmSystemTools::ReplaceString(depfileFlags, "<DEPFILE>", "$DEP_FILE");
      cmSystemTools::ReplaceString(depfileFlags, "<OBJECT>",  "$out");
      cmSystemTools::ReplaceString(depfileFlags, "<CMAKE_C_COMPILER>",
                                   mf->GetDefinition("CMAKE_C_COMPILER"));
      flags += " " + depfileFlags;
      }
451
    }
452

453
454
  vars.Flags = flags.c_str();
  vars.DependencyFile = depfile.c_str();
Peter Kuemmel's avatar
Peter Kuemmel committed
455

456
  // Rule for compiling object file.
457
  const std::string cmdVar = std::string("CMAKE_") + lang + "_COMPILE_OBJECT";
Stephen Kelly's avatar
Stephen Kelly committed
458
  std::string compileCmd = mf->GetRequiredDefinition(cmdVar);
459
460
  std::vector<std::string> compileCmds;
  cmSystemTools::ExpandListArgument(compileCmd, compileCmds);
461

462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
  // Maybe insert an include-what-you-use runner.
  if (!compileCmds.empty() && (lang == "C" || lang == "CXX"))
    {
    std::string const iwyu_prop = lang + "_INCLUDE_WHAT_YOU_USE";
    const char *iwyu = this->Target->GetProperty(iwyu_prop);
    if (iwyu && *iwyu)
      {
      std::string run_iwyu =
        this->GetLocalGenerator()->ConvertToOutputFormat(
          cmSystemTools::GetCMakeCommand(), cmLocalGenerator::SHELL);
      run_iwyu += " -E __run_iwyu --iwyu=";
      run_iwyu += this->GetLocalGenerator()->EscapeForShell(iwyu);
      run_iwyu += " -- ";
      compileCmds.front().insert(0, run_iwyu);
      }
    }

479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
  // Maybe insert a compiler launcher like ccache or distcc
  if (!compileCmds.empty() && (lang == "C" || lang == "CXX"))
    {
    std::string const clauncher_prop = lang + "_COMPILER_LAUNCHER";
    const char *clauncher = this->Target->GetProperty(clauncher_prop);
    if (clauncher && *clauncher)
      {
      std::vector<std::string> launcher_cmd;
      cmSystemTools::ExpandListArgument(clauncher, launcher_cmd, true);
      for (std::vector<std::string>::iterator i = launcher_cmd.begin(),
             e = launcher_cmd.end(); i != e; ++i)
        {
        *i = this->LocalGenerator->EscapeForShell(*i);
        }
      std::string const& run_launcher = cmJoin(launcher_cmd, " ") + " ";
      compileCmds.front().insert(0, run_launcher);
      }
    }

498
499
500
501
  if (!compileCmds.empty())
    {
    compileCmds.front().insert(0, cldeps);
    }
502

503
504
505
506
  for (std::vector<std::string>::iterator i = compileCmds.begin();
       i != compileCmds.end(); ++i)
    this->GetLocalGenerator()->ExpandRuleVariables(*i, vars);

507
508
  std::string cmdLine =
    this->GetLocalGenerator()->BuildCommandLine(compileCmds);
509

510

511
  // Write the rule for compiling file of the given language.
512
  std::ostringstream comment;
513
  comment << "Rule for compiling " << lang << " files.";
514
  std::ostringstream description;
515
516
  description << "Building " << lang << " object $out";
  this->GetGlobalGenerator()->AddRule(this->LanguageCompilerRule(lang),
517
                                      cmdLine,
518
519
                                      description.str(),
                                      comment.str(),
520
521
522
523
                                      depfile,
                                      deptype,
                                      /*rspfile*/ "",
                                      /*rspcontent*/ "",
524
                                      /*restat*/ "",
525
                                      /*generator*/ false);
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
}

void
cmNinjaTargetGenerator
::WriteObjectBuildStatements()
{
  // Write comments.
  cmGlobalNinjaGenerator::WriteDivider(this->GetBuildFileStream());
  this->GetBuildFileStream()
    << "# Object build statements for "
    << cmTarget::GetTargetTypeName(this->GetTarget()->GetType())
    << " target "
    << this->GetTargetName()
    << "\n\n";

541
  std::string config = this->Makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
542
  std::vector<cmSourceFile const*> customCommands;
543
  this->GeneratorTarget->GetCustomCommands(customCommands, config);
544
  for(std::vector<cmSourceFile const*>::const_iterator
545
546
        si = customCommands.begin();
      si != customCommands.end(); ++si)
547
548
549
     {
     cmCustomCommand const* cc = (*si)->GetCustomCommand();
     this->GetLocalGenerator()->AddCustomCommandTarget(cc, this->GetTarget());
550
551
     // Record the custom commands for this target. The container is used
     // in WriteObjectBuildStatement when called in a loop below.
552
     this->CustomCommands.push_back(cc);
553
     }
554
  std::vector<cmSourceFile const*> headerSources;
555
  this->GeneratorTarget->GetHeaderSources(headerSources, config);
556
  this->OSXBundleGenerator->GenerateMacOSXContentStatements(
557
    headerSources,
Peter Kümmel's avatar
Peter Kümmel committed
558
    this->MacOSXContentGenerator);
559
  std::vector<cmSourceFile const*> extraSources;
560
  this->GeneratorTarget->GetExtraSources(extraSources, config);
561
  this->OSXBundleGenerator->GenerateMacOSXContentStatements(
562
    extraSources,
Peter Kümmel's avatar
Peter Kümmel committed
563
    this->MacOSXContentGenerator);
564
  std::vector<cmSourceFile const*> externalObjects;
565
  this->GeneratorTarget->GetExternalObjects(externalObjects, config);
566
  for(std::vector<cmSourceFile const*>::const_iterator
567
568
        si = externalObjects.begin();
      si != externalObjects.end(); ++si)
569
570
571
    {
    this->Objects.push_back(this->GetSourceFilePath(*si));
    }
572
573
574

  cmNinjaDeps orderOnlyDeps;
  this->GetLocalGenerator()->AppendTargetDepends(this->Target, orderOnlyDeps);
575
576
577
578
579
580
581
582
583
584

  // Add order-only dependencies on custom command outputs.
  for(std::vector<cmCustomCommand const*>::const_iterator
        cci = this->CustomCommands.begin();
      cci != this->CustomCommands.end(); ++cci)
    {
    cmCustomCommand const* cc = *cci;
    cmCustomCommandGenerator ccg(*cc, this->GetConfigName(),
                                 this->GetMakefile());
    const std::vector<std::string>& ccoutputs = ccg.GetOutputs();
585
    const std::vector<std::string>& ccbyproducts= ccg.GetByproducts();
586
587
    std::transform(ccoutputs.begin(), ccoutputs.end(),
                   std::back_inserter(orderOnlyDeps), MapToNinjaPath());
588
589
    std::transform(ccbyproducts.begin(), ccbyproducts.end(),
                   std::back_inserter(orderOnlyDeps), MapToNinjaPath());
590
591
    }

592
593
594
595
596
597
598
599
600
601
602
603
  if (!orderOnlyDeps.empty())
    {
    cmNinjaDeps orderOnlyTarget;
    orderOnlyTarget.push_back(this->OrderDependsTargetForTarget());
    this->GetGlobalGenerator()->WritePhonyBuild(this->GetBuildFileStream(),
                                                "Order-only phony target for "
                                                  + this->GetTargetName(),
                                                orderOnlyTarget,
                                                cmNinjaDeps(),
                                                cmNinjaDeps(),
                                                orderOnlyDeps);
    }
604
  std::vector<cmSourceFile const*> objectSources;
605
  this->GeneratorTarget->GetObjectSources(objectSources, config);
606
  for(std::vector<cmSourceFile const*>::const_iterator
607
        si = objectSources.begin(); si != objectSources.end(); ++si)
608
    {
609
    this->WriteObjectBuildStatement(*si, !orderOnlyDeps.empty());
610
    }
611
  std::string def = this->GeneratorTarget->GetModuleDefinitionFile(config);
612
  if(!def.empty())
613
    {
614
    this->ModuleDefinitionFile = this->ConvertToNinjaPath(def);
615
    }
616
617
618
619
620
621

  this->GetBuildFileStream() << "\n";
}

void
cmNinjaTargetGenerator
622
623
::WriteObjectBuildStatement(
  cmSourceFile const* source, bool writeOrderDependsTargetForTarget)
624
625
{
  std::string comment;
626
  const std::string language = source->GetLanguage();
627
628
629
630
631
632
633
634
635
  std::string rule = this->LanguageCompilerRule(language);

  cmNinjaDeps outputs;
  std::string objectFileName = this->GetObjectFilePath(source);
  outputs.push_back(objectFileName);
  // Add this object to the list of object files.
  this->Objects.push_back(objectFileName);

  cmNinjaDeps explicitDeps;
636
637
638
639
640
  std::string sourceFileName;
  if (language == "RC")
    sourceFileName = source->GetFullPath();
  else
    sourceFileName = this->GetSourceFilePath(source);
641
642
  explicitDeps.push_back(sourceFileName);

643
  cmNinjaDeps implicitDeps;
644
645
646
  if(const char* objectDeps = source->GetProperty("OBJECT_DEPENDS")) {
    std::vector<std::string> depList;
    cmSystemTools::ExpandListArgument(objectDeps, depList);
647
648
649
650
651
652
653
654
    for(std::vector<std::string>::iterator odi = depList.begin();
        odi != depList.end(); ++odi)
      {
      if (cmSystemTools::FileIsFullPath(*odi))
        {
        *odi = cmSystemTools::CollapseFullPath(*odi);
        }
      }
655
    std::transform(depList.begin(), depList.end(),
656
                   std::back_inserter(implicitDeps), MapToNinjaPath());
657
658
  }

659
  cmNinjaDeps orderOnlyDeps;
660
661
662
663
  if (writeOrderDependsTargetForTarget)
    {
    orderOnlyDeps.push_back(this->OrderDependsTargetForTarget());
    }
664

665
666
667
668
669
670
671
672
673
674
675
676
677
  // If the source file is GENERATED and does not have a custom command
  // (either attached to this source file or another one), assume that one of
  // the target dependencies, OBJECT_DEPENDS or header file custom commands
  // will rebuild the file.
  if (source->GetPropertyAsBool("GENERATED") && !source->GetCustomCommand() &&
      !this->GetGlobalGenerator()->HasCustomCommandOutput(sourceFileName)) {
    this->GetGlobalGenerator()->AddAssumedSourceDependencies(sourceFileName,
                                                             orderOnlyDeps);
  }

  cmNinjaVars vars;
  vars["FLAGS"] = this->ComputeFlagsForObject(source, language);
  vars["DEFINES"] = this->ComputeDefines(source, language);
678
  if (!this->NeedDepTypeMSVC(language)) {
679
680
681
    vars["DEP_FILE"] =
            cmGlobalNinjaGenerator::EncodeDepfileSpace(objectFileName + ".d");
  }
682
  EnsureParentDirectoryExists(objectFileName);
Peter Kuemmel's avatar
Peter Kuemmel committed
683

684
  std::string objectDir = this->Target->GetSupportDirectory();
685
  vars["OBJECT_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
686
                         ConvertToNinjaPath(objectDir),
687
                         cmLocalGenerator::SHELL);
688
689
  std::string objectFileDir = cmSystemTools::GetFilenamePath(objectFileName);
  vars["OBJECT_FILE_DIR"] = this->GetLocalGenerator()->ConvertToOutputFormat(
690
                              ConvertToNinjaPath(objectFileDir),
691
                              cmLocalGenerator::SHELL);
692

693
694
  this->addPoolNinjaVariable("JOB_POOL_COMPILE", this->GetTarget(), vars);

695
  this->SetMsvcTargetPdbVariable(vars);
696

697
698
699
700
701
  if(this->Makefile->IsOn("CMAKE_EXPORT_COMPILE_COMMANDS"))
    {
    cmLocalGenerator::RuleVariables compileObjectVars;
    std::string lang = language;
    compileObjectVars.Language = lang.c_str();
702

703
704
705
    std::string escapedSourceFileName = sourceFileName;

    if (!cmSystemTools::FileIsFullPath(sourceFileName.c_str()))
706
707
      {
      escapedSourceFileName = cmSystemTools::CollapseFullPath(
708
        escapedSourceFileName,
709
710
        this->GetGlobalGenerator()->GetCMakeInstance()->
          GetHomeOutputDirectory());
711
712
      }

713
    escapedSourceFileName =
714
      this->LocalGenerator->ConvertToOutputFormat(
Stephen Kelly's avatar
Stephen Kelly committed
715
        escapedSourceFileName, cmLocalGenerator::SHELL);
716

717
    compileObjectVars.Source = escapedSourceFileName.c_str();
718
    compileObjectVars.Object = objectFileName.c_str();
719
    compileObjectVars.ObjectDir = objectDir.c_str();
720
    compileObjectVars.ObjectFileDir = objectFileDir.c_str();
721
722
723
724
725
726
727
728
    compileObjectVars.Flags = vars["FLAGS"].c_str();
    compileObjectVars.Defines = vars["DEFINES"].c_str();

    // Rule for compiling object file.
    std::string compileCmdVar = "CMAKE_";
    compileCmdVar += language;
    compileCmdVar += "_COMPILE_OBJECT";
    std::string compileCmd =
Stephen Kelly's avatar
Stephen Kelly committed
729
      this->GetMakefile()->GetRequiredDefinition(compileCmdVar);
730
731
732
733
734
735
736
737
738
739
740
741
742
743
    std::vector<std::string> compileCmds;
    cmSystemTools::ExpandListArgument(compileCmd, compileCmds);

    for (std::vector<std::string>::iterator i = compileCmds.begin();
        i != compileCmds.end(); ++i)
      this->GetLocalGenerator()->ExpandRuleVariables(*i, compileObjectVars);

    std::string cmdLine =
      this->GetLocalGenerator()->BuildCommandLine(compileCmds);

    this->GetGlobalGenerator()->AddCXXCompileCommand(cmdLine,
                                                     sourceFileName);
    }

744
745
746
747
748
749
750
751
  this->GetGlobalGenerator()->WriteBuild(this->GetBuildFileStream(),
                                         comment,
                                         rule,
                                         outputs,
                                         explicitDeps,
                                         implicitDeps,
                                         orderOnlyDeps,
                                         vars);
752
753
754
755
756
757

  if(const char* objectOutputs = source->GetProperty("OBJECT_OUTPUTS")) {
    std::vector<std::string> outputList;
    cmSystemTools::ExpandListArgument(objectOutputs, outputList);
    std::transform(outputList.begin(), outputList.end(), outputList.begin(),
                   MapToNinjaPath());
758
759
760
761
    this->GetGlobalGenerator()->WritePhonyBuild(this->GetBuildFileStream(),
                                                "Additional output files.",
                                                outputList,
                                                outputs);
762
  }
763
}
Peter Kuemmel's avatar
Peter Kuemmel committed
764
765
766
767
768
769

//----------------------------------------------------------------------------
void
cmNinjaTargetGenerator
::AddModuleDefinitionFlag(std::string& flags)
{
770
  if(this->ModuleDefinitionFile.empty())
Peter Kuemmel's avatar
Peter Kuemmel committed
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
    {
    return;
    }

  // TODO: Create a per-language flag variable.
  const char* defFileFlag =
    this->Makefile->GetDefinition("CMAKE_LINK_DEF_FILE_FLAG");
  if(!defFileFlag)
    {
    return;
    }

  // Append the flag and value.  Use ConvertToLinkReference to help
  // vs6's "cl -link" pass it to the linker.
  std::string flag = defFileFlag;
  flag += (this->LocalGenerator->ConvertToLinkReference(
Stephen Kelly's avatar
Stephen Kelly committed
787
             this->ModuleDefinitionFile));
788
  this->LocalGenerator->AppendFlags(flags, flag);
Peter Kuemmel's avatar
Peter Kuemmel committed
789
}
790
791
792

void
cmNinjaTargetGenerator
793
::EnsureDirectoryExists(const std::string& path) const
794
{
795
796
797
798
799
800
801
802
803
804
805
  if (cmSystemTools::FileIsFullPath(path.c_str()))
    {
    cmSystemTools::MakeDirectory(path.c_str());
    }
  else
    {
    const std::string fullPath = std::string(this->GetGlobalGenerator()->
                                 GetCMakeInstance()->GetHomeOutputDirectory())
                                   + "/" + path;
    cmSystemTools::MakeDirectory(fullPath.c_str());
    }
806
807
808
809
}

void
cmNinjaTargetGenerator
810
::EnsureParentDirectoryExists(const std::string& path) const
811
{
812
  EnsureDirectoryExists(cmSystemTools::GetParentDirectory(path));
813
}
814
815
816


//----------------------------------------------------------------------------
817
818
void
cmNinjaTargetGenerator::MacOSXContentGeneratorType::operator()(
819
  cmSourceFile const& source, const char* pkgloc)
820
821
{
  // Skip OS X content when not building a Framework or Bundle.
822
  if(!this->Generator->GetTarget()->IsBundleOnApple())
823
824
825
826
    {
    return;
    }

827
  std::string macdir =
828
    this->Generator->OSXBundleGenerator->InitMacOSXContentDirectory(pkgloc);
829
830
831

  // Get the input file location.
  std::string input = source.GetFullPath();
832
  input =
833
    this->Generator->GetLocalGenerator()->ConvertToNinjaPath(input);
834
835
836
837
838

  // Get the output file location.
  std::string output = macdir;
  output += "/";
  output += cmSystemTools::GetFilenameName(input);
839
  output =
840
    this->Generator->GetLocalGenerator()->ConvertToNinjaPath(output);
841
842

  // Write a build statement to copy the content into the bundle.
843
844
  this->Generator->GetGlobalGenerator()->WriteMacOSXContentBuild(input,
                                                                 output);
845
846

  // Add as a dependency of all target so that it gets called.
847
  this->Generator->GetGlobalGenerator()->AddDependencyToAll(output);
848
}
849

Ben Boeckel's avatar
Ben Boeckel committed
850
851
852
853
void cmNinjaTargetGenerator::addPoolNinjaVariable(
                                              const std::string& pool_property,
                                              cmTarget* target,
                                              cmNinjaVars& vars)
854
855
856
857
858
859
860
{
    const char* pool = target->GetProperty(pool_property);
    if (pool)
      {
      vars["pool"] = pool;
      }
}