blob: f08c768be35637cc25b78e292727d6b035e57e28 [file] [log] [blame]
Chris Lattner22eb9722006-06-18 05:43:12 +00001//===--- clang.cpp - C-Language Front-end ---------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner22eb9722006-06-18 05:43:12 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This utility may be invoked in the following manner:
Chris Lattner96327ea2006-11-21 05:52:55 +000011// clang --help - Output help info.
12// clang [options] - Read from stdin.
13// clang [options] file - Read from "file".
14// clang [options] file1 file2 - Read these files.
Chris Lattner22eb9722006-06-18 05:43:12 +000015//
16//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +000017
Daniel Dunbarf89a32a2009-11-10 19:51:53 +000018#include "Options.h"
Eli Friedman5b5bd902009-05-19 21:10:40 +000019#include "clang/Frontend/AnalysisConsumer.h"
Eli Friedman2b6d2812009-05-18 23:02:01 +000020#include "clang/Frontend/ASTConsumers.h"
Daniel Dunbare9fee8a2009-09-17 00:48:13 +000021#include "clang/Frontend/ASTUnit.h"
Daniel Dunbarb2eae892009-11-09 20:55:08 +000022#include "clang/Frontend/CompilerInvocation.h"
Daniel Dunbarc2e6a472009-11-04 06:24:30 +000023#include "clang/Frontend/DiagnosticOptions.h"
Douglas Gregor578dae52009-04-02 01:08:08 +000024#include "clang/Frontend/FixItRewriter.h"
Daniel Dunbar4f495982009-03-12 10:14:16 +000025#include "clang/Frontend/FrontendDiagnostic.h"
Daniel Dunbar8ec88042009-11-07 04:58:12 +000026#include "clang/Frontend/HeaderSearchOptions.h"
Douglas Gregoref84c4b2009-04-09 22:27:44 +000027#include "clang/Frontend/PCHReader.h"
Daniel Dunbar00f8a392009-11-07 04:20:15 +000028#include "clang/Frontend/PathDiagnosticClients.h"
29#include "clang/Frontend/PreprocessorOptions.h"
Daniel Dunbar51adf582009-03-02 06:16:29 +000030#include "clang/Frontend/TextDiagnosticBuffer.h"
31#include "clang/Frontend/TextDiagnosticPrinter.h"
Argyrios Kyrtzidis25ee5db2009-06-23 22:01:39 +000032#include "clang/Frontend/CommandLineSourceLoc.h"
Eli Friedman16b7b6f2009-05-19 04:14:29 +000033#include "clang/Frontend/Utils.h"
Ted Kremenek6efb0262008-03-27 06:17:42 +000034#include "clang/Analysis/PathDiagnostic.h"
Chris Lattneradf1f512008-02-06 02:01:47 +000035#include "clang/CodeGen/ModuleBuilder.h"
Douglas Gregor2436e712009-09-17 21:32:03 +000036#include "clang/Sema/CodeCompleteConsumer.h"
Chris Lattner8082d872008-02-06 00:23:21 +000037#include "clang/Sema/ParseAST.h"
Chris Lattner36790cf2009-01-29 06:55:46 +000038#include "clang/Sema/SemaDiagnostic.h"
Chris Lattner75e0c8c2007-09-15 22:56:56 +000039#include "clang/AST/ASTConsumer.h"
Chris Lattner1ad4eeb2009-03-28 04:31:31 +000040#include "clang/AST/ASTContext.h"
41#include "clang/AST/Decl.h"
Chris Lattner5bbb3c82009-03-29 16:50:03 +000042#include "clang/AST/DeclGroup.h"
Chris Lattner0bb5f832006-07-31 01:59:18 +000043#include "clang/Parse/Parser.h"
Chris Lattner07b019a2006-10-22 07:28:56 +000044#include "clang/Lex/HeaderSearch.h"
Chris Lattnerfa816692009-02-06 04:16:41 +000045#include "clang/Lex/LexDiagnostic.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000046#include "clang/Basic/FileManager.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000047#include "clang/Basic/SourceManager.h"
Chris Lattner2ba425e2006-10-14 19:54:37 +000048#include "clang/Basic/TargetInfo.h"
Daniel Dunbar67dba982009-05-06 04:07:06 +000049#include "clang/Basic/Version.h"
Owen Andersond9dd77f2009-07-01 17:00:06 +000050#include "llvm/LLVMContext.h"
Chris Lattnerb5c15e82008-09-30 20:16:56 +000051#include "llvm/ADT/OwningPtr.h"
Chris Lattner39911a22007-12-15 23:20:07 +000052#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerb5c15e82008-09-30 20:16:56 +000053#include "llvm/ADT/StringExtras.h"
Daniel Dunbar4dbaaa62009-05-06 03:16:41 +000054#include "llvm/ADT/StringMap.h"
Daniel Dunbar1de78552009-11-09 22:45:57 +000055#include "llvm/ADT/StringSwitch.h"
Chris Lattner14a7f392009-04-08 18:24:34 +000056#include "llvm/ADT/STLExtras.h"
Chris Lattnerb5c15e82008-09-30 20:16:56 +000057#include "llvm/Config/config.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000058#include "llvm/Support/CommandLine.h"
Daniel Dunbar71f22e72009-08-10 03:40:28 +000059#include "llvm/Support/ErrorHandling.h"
Daniel Dunbar460f8ee2008-10-28 00:38:08 +000060#include "llvm/Support/ManagedStatic.h"
Chris Lattner739e7392007-04-29 07:12:06 +000061#include "llvm/Support/MemoryBuffer.h"
Zhongxing Xu21148402008-11-26 05:23:17 +000062#include "llvm/Support/PluginLoader.h"
Chris Lattner07e85f32009-03-04 21:41:39 +000063#include "llvm/Support/PrettyStackTrace.h"
Chris Lattnerf53a9612009-02-18 01:51:21 +000064#include "llvm/Support/Timer.h"
Chris Lattner72bb4f62009-08-24 04:11:30 +000065#include "llvm/Support/raw_ostream.h"
Daniel Dunbard03c0282008-10-02 01:21:33 +000066#include "llvm/System/Host.h"
Chris Lattner184adbf2008-03-03 03:16:03 +000067#include "llvm/System/Path.h"
Eli Friedman94cf21e2009-05-18 22:20:00 +000068#include "llvm/System/Program.h"
Chris Lattnerb5c15e82008-09-30 20:16:56 +000069#include "llvm/System/Signals.h"
Chris Lattnera0e4ded2009-06-17 17:25:50 +000070#include "llvm/Target/TargetSelect.h"
Douglas Gregor9c0d38a2009-04-02 19:05:20 +000071#include <cstdlib>
Douglas Gregor6f5a38b2009-05-03 03:52:38 +000072#if HAVE_SYS_TYPES_H
Douglas Gregor637f5f72009-05-02 00:03:46 +000073# include <sys/types.h>
74#endif
Douglas Gregor9c0d38a2009-04-02 19:05:20 +000075
Chris Lattner22eb9722006-06-18 05:43:12 +000076using namespace clang;
77
78//===----------------------------------------------------------------------===//
Douglas Gregor9c0d38a2009-04-02 19:05:20 +000079// Source Location Parser
80//===----------------------------------------------------------------------===//
81
Argyrios Kyrtzidis25ee5db2009-06-23 22:01:39 +000082static bool ResolveParsedLocation(ParsedSourceLocation &ParsedLoc,
83 FileManager &FileMgr,
84 RequestedSourceLocation &Result) {
85 const FileEntry *File = FileMgr.getFile(ParsedLoc.FileName);
Douglas Gregor9c0d38a2009-04-02 19:05:20 +000086 if (!File)
87 return true;
88
89 Result.File = File;
Argyrios Kyrtzidis25ee5db2009-06-23 22:01:39 +000090 Result.Line = ParsedLoc.Line;
91 Result.Column = ParsedLoc.Column;
Douglas Gregor9c0d38a2009-04-02 19:05:20 +000092 return false;
93}
94
Douglas Gregor9c0d38a2009-04-02 19:05:20 +000095//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +000096// Global options.
97//===----------------------------------------------------------------------===//
98
Chris Lattnerf53a9612009-02-18 01:51:21 +000099/// ClangFrontendTimer - The front-end activities should charge time to it with
100/// TimeRegion. The -ftime-report option controls whether this will do
101/// anything.
102llvm::Timer *ClangFrontendTimer = 0;
103
Chris Lattner23b7eb62007-06-15 23:05:46 +0000104static llvm::cl::opt<bool>
105Verbose("v", llvm::cl::desc("Enable verbose output"));
106static llvm::cl::opt<bool>
Mike Stump11289f42009-09-09 15:08:12 +0000107Stats("print-stats",
Nate Begeman16a3a9d2007-12-30 01:38:50 +0000108 llvm::cl::desc("Print performance metrics and statistics"));
Daniel Dunbar33d29b32008-10-16 16:54:18 +0000109static llvm::cl::opt<bool>
110DisableFree("disable-free",
111 llvm::cl::desc("Disable freeing of memory on exit"),
112 llvm::cl::init(false));
Daniel Dunbarc6480e22009-04-27 21:19:07 +0000113static llvm::cl::opt<bool>
Mike Stump11289f42009-09-09 15:08:12 +0000114EmptyInputOnly("empty-input-only",
Daniel Dunbarc6480e22009-04-27 21:19:07 +0000115 llvm::cl::desc("Force running on an empty input file"));
Chris Lattner22eb9722006-06-18 05:43:12 +0000116
117enum ProgActions {
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000118 RewriteObjC, // ObjC->C Rewriter.
Steve Naroff9779e922008-09-18 14:10:13 +0000119 RewriteBlocks, // ObjC->C Rewriter for Blocks.
Chris Lattner3c04ff02008-05-08 06:52:13 +0000120 RewriteMacros, // Expand macros but not #includes.
Chris Lattner1782da22008-10-12 05:29:20 +0000121 RewriteTest, // Rewriter playground
Douglas Gregor578dae52009-04-02 01:08:08 +0000122 FixIt, // Fix-It Rewriter
Ted Kremenek216624c2008-03-19 07:53:42 +0000123 HTMLTest, // HTML displayer testing stuff.
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000124 EmitAssembly, // Emit a .s file.
Chris Lattnerf97fe382007-05-24 06:29:05 +0000125 EmitLLVM, // Emit a .ll file.
Seo Sanghyeon76270e62007-12-24 01:52:34 +0000126 EmitBC, // Emit a .bc file.
Mike Stump11289f42009-09-09 15:08:12 +0000127 EmitLLVMOnly, // Generate LLVM IR, but do not
Ted Kremenek7dcc8222008-03-18 21:19:49 +0000128 EmitHTML, // Translate input source into HTML.
Chris Lattner5e4c75f2007-10-11 00:18:28 +0000129 ASTPrint, // Parse ASTs and print them.
Douglas Gregor7f5601e52009-05-21 20:55:50 +0000130 ASTPrintXML, // Parse ASTs and print them in XML.
Chris Lattner5e4c75f2007-10-11 00:18:28 +0000131 ASTDump, // Parse ASTs and dump them.
132 ASTView, // Parse ASTs and view them in Graphviz.
Zhongxing Xu9aabf022009-01-13 01:29:24 +0000133 PrintDeclContext, // Print DeclContext and their Decls.
Anders Carlssond9340102009-09-24 18:54:49 +0000134 DumpRecordLayouts, // Dump record layout information.
Chris Lattner0bb5f832006-07-31 01:59:18 +0000135 ParsePrintCallbacks, // Parse and print each callback.
Chris Lattnerca96b892006-11-05 18:00:10 +0000136 ParseSyntaxOnly, // Parse and perform semantic analysis.
Chris Lattner0bb5f832006-07-31 01:59:18 +0000137 ParseNoop, // Parse with noop callbacks.
Chris Lattner22eb9722006-06-18 05:43:12 +0000138 RunPreprocessorOnly, // Just lex, no output.
139 PrintPreprocessedInput, // -E mode.
Chris Lattnerfc7d4a32008-10-12 05:03:36 +0000140 DumpTokens, // Dump out preprocessed tokens.
141 DumpRawTokens, // Dump out raw tokens.
Mike Stump11289f42009-09-09 15:08:12 +0000142 RunAnalysis, // Run one or more source code analyses.
Douglas Gregor97186b02009-04-02 23:43:50 +0000143 GeneratePTH, // Generate pre-tokenized header.
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000144 GeneratePCH, // Generate pre-compiled header.
Ted Kremenek45e2b902008-10-23 23:36:29 +0000145 InheritanceView // View C++ inheritance for a specified class.
Chris Lattner22eb9722006-06-18 05:43:12 +0000146};
147
Mike Stump11289f42009-09-09 15:08:12 +0000148static llvm::cl::opt<ProgActions>
Chris Lattner23b7eb62007-06-15 23:05:46 +0000149ProgAction(llvm::cl::desc("Choose output type:"), llvm::cl::ZeroOrMore,
150 llvm::cl::init(ParseSyntaxOnly),
151 llvm::cl::values(
Chris Lattner22eb9722006-06-18 05:43:12 +0000152 clEnumValN(RunPreprocessorOnly, "Eonly",
153 "Just run preprocessor, no output (for timings)"),
154 clEnumValN(PrintPreprocessedInput, "E",
155 "Run preprocessor, emit preprocessed file"),
Chris Lattnerfc7d4a32008-10-12 05:03:36 +0000156 clEnumValN(DumpRawTokens, "dump-raw-tokens",
157 "Lex file in raw mode and dump raw tokens"),
Daniel Dunbar34fc92f2009-01-20 23:17:32 +0000158 clEnumValN(RunAnalysis, "analyze",
159 "Run static analysis engine"),
Chris Lattnerfc7d4a32008-10-12 05:03:36 +0000160 clEnumValN(DumpTokens, "dump-tokens",
Chris Lattner22eb9722006-06-18 05:43:12 +0000161 "Run preprocessor, dump internal rep of tokens"),
Chris Lattner0bb5f832006-07-31 01:59:18 +0000162 clEnumValN(ParseNoop, "parse-noop",
163 "Run parser with noop callbacks (for timings)"),
Chris Lattner3e7bd4e2006-08-17 05:51:27 +0000164 clEnumValN(ParseSyntaxOnly, "fsyntax-only",
165 "Run parser and perform semantic analysis"),
Chris Lattnerca96b892006-11-05 18:00:10 +0000166 clEnumValN(ParsePrintCallbacks, "parse-print-callbacks",
167 "Run parser and print each callback invoked"),
Ted Kremenek7dcc8222008-03-18 21:19:49 +0000168 clEnumValN(EmitHTML, "emit-html",
169 "Output input source as HTML"),
Chris Lattner5e4c75f2007-10-11 00:18:28 +0000170 clEnumValN(ASTPrint, "ast-print",
171 "Build ASTs and then pretty-print them"),
Douglas Gregor7f5601e52009-05-21 20:55:50 +0000172 clEnumValN(ASTPrintXML, "ast-print-xml",
173 "Build ASTs and then print them in XML format"),
Chris Lattner5e4c75f2007-10-11 00:18:28 +0000174 clEnumValN(ASTDump, "ast-dump",
175 "Build ASTs and then debug dump them"),
Chris Lattner3472aee2007-10-11 00:37:43 +0000176 clEnumValN(ASTView, "ast-view",
Sanjiv Guptacd13ef02008-05-08 08:28:14 +0000177 "Build ASTs and view them with GraphViz"),
Zhongxing Xu9aabf022009-01-13 01:29:24 +0000178 clEnumValN(PrintDeclContext, "print-decl-contexts",
Ted Kremenek0df70512009-04-01 00:23:28 +0000179 "Print DeclContexts and their Decls"),
Anders Carlssond9340102009-09-24 18:54:49 +0000180 clEnumValN(DumpRecordLayouts, "dump-record-layouts",
181 "Dump record layout information"),
Douglas Gregor97186b02009-04-02 23:43:50 +0000182 clEnumValN(GeneratePTH, "emit-pth",
Ted Kremenek0df70512009-04-01 00:23:28 +0000183 "Generate pre-tokenized header file"),
Douglas Gregoref84c4b2009-04-09 22:27:44 +0000184 clEnumValN(GeneratePCH, "emit-pch",
185 "Generate pre-compiled header file"),
Daniel Dunbarc13935e2008-10-21 23:49:24 +0000186 clEnumValN(EmitAssembly, "S",
187 "Emit native assembly code"),
Chris Lattnerf97fe382007-05-24 06:29:05 +0000188 clEnumValN(EmitLLVM, "emit-llvm",
Ted Kremenek3f8ed262007-09-06 21:26:58 +0000189 "Build ASTs then convert to LLVM, emit .ll file"),
Seo Sanghyeon76270e62007-12-24 01:52:34 +0000190 clEnumValN(EmitBC, "emit-llvm-bc",
191 "Build ASTs then convert to LLVM, emit .bc file"),
Daniel Dunbar26d5f052009-02-26 22:39:37 +0000192 clEnumValN(EmitLLVMOnly, "emit-llvm-only",
193 "Build ASTs and convert to LLVM, discarding output"),
Chris Lattner1782da22008-10-12 05:29:20 +0000194 clEnumValN(RewriteTest, "rewrite-test",
195 "Rewriter playground"),
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000196 clEnumValN(RewriteObjC, "rewrite-objc",
Chris Lattner3c04ff02008-05-08 06:52:13 +0000197 "Rewrite ObjC into C (code rewriter example)"),
198 clEnumValN(RewriteMacros, "rewrite-macros",
199 "Expand macros without full preprocessing"),
Steve Naroff9779e922008-09-18 14:10:13 +0000200 clEnumValN(RewriteBlocks, "rewrite-blocks",
201 "Rewrite Blocks to C"),
Douglas Gregor578dae52009-04-02 01:08:08 +0000202 clEnumValN(FixIt, "fixit",
203 "Apply fix-it advice to the input source"),
Chris Lattner22eb9722006-06-18 05:43:12 +0000204 clEnumValEnd));
205
Ted Kremenek6c0b2242007-12-19 19:47:59 +0000206
207static llvm::cl::opt<std::string>
208OutputFile("o",
Ted Kremenekaff23432007-12-19 19:50:41 +0000209 llvm::cl::value_desc("path"),
Douglas Gregor48db39d2009-04-22 21:45:53 +0000210 llvm::cl::desc("Specify output file"));
Ted Kremenek751d4d22008-04-14 18:40:58 +0000211
Ted Kremenekda4d9df2008-12-02 19:57:31 +0000212
Douglas Gregor9eb77012009-11-07 00:00:49 +0000213enum CodeCompletionPrinter {
214 CCP_Debug,
215 CCP_CIndex
216};
217
Douglas Gregorea9b03e2009-09-22 21:11:38 +0000218static llvm::cl::opt<ParsedSourceLocation>
219CodeCompletionAt("code-completion-at",
220 llvm::cl::value_desc("file:line:column"),
221 llvm::cl::desc("Dump code-completion information at a location"));
Douglas Gregor2436e712009-09-17 21:32:03 +0000222
Douglas Gregor9eb77012009-11-07 00:00:49 +0000223static llvm::cl::opt<CodeCompletionPrinter>
224CodeCompletionPrinter("code-completion-printer",
225 llvm::cl::desc("Choose output type:"),
226 llvm::cl::init(CCP_Debug),
227 llvm::cl::values(
228 clEnumValN(CCP_Debug, "debug",
229 "Debug code-completion results"),
230 clEnumValN(CCP_CIndex, "cindex",
231 "Code-completion results for the CIndex library"),
232 clEnumValEnd));
233
234static llvm::cl::opt<bool>
235CodeCompletionWantsMacros("code-completion-macros",
236 llvm::cl::desc("Include macros in code-completion results"));
237
Douglas Gregor2436e712009-09-17 21:32:03 +0000238/// \brief Buld a new code-completion consumer that prints the results of
239/// code completion to standard output.
240static CodeCompleteConsumer *BuildPrintingCodeCompleter(Sema &S, void *) {
Douglas Gregor9eb77012009-11-07 00:00:49 +0000241 switch (CodeCompletionPrinter.getValue()) {
242 case CCP_Debug:
243 return new PrintingCodeCompleteConsumer(S, CodeCompletionWantsMacros,
244 llvm::outs());
245
246 case CCP_CIndex:
247 return new CIndexCodeCompleteConsumer(S, CodeCompletionWantsMacros,
248 llvm::outs());
249 };
250
251 return 0;
Douglas Gregor2436e712009-09-17 21:32:03 +0000252}
253
Ted Kremenekda4d9df2008-12-02 19:57:31 +0000254//===----------------------------------------------------------------------===//
255// PTH.
256//===----------------------------------------------------------------------===//
257
258static llvm::cl::opt<std::string>
259TokenCache("token-cache", llvm::cl::value_desc("path"),
260 llvm::cl::desc("Use specified token cache file"));
261
Sanjiv Gupta15cb6692008-05-08 08:54:20 +0000262//===----------------------------------------------------------------------===//
Ted Kremenek751d4d22008-04-14 18:40:58 +0000263// Diagnostic Options
264//===----------------------------------------------------------------------===//
265
Ted Kremeneka054c5b2007-09-26 19:42:19 +0000266static llvm::cl::opt<bool>
267VerifyDiagnostics("verify",
Sanjiv Guptacd13ef02008-05-08 08:28:14 +0000268 llvm::cl::desc("Verify emitted diagnostics and warnings"));
Ted Kremeneka054c5b2007-09-26 19:42:19 +0000269
Nico Weberb5fc3c32008-08-05 23:33:20 +0000270static llvm::cl::opt<bool>
271NoShowColumn("fno-show-column",
272 llvm::cl::desc("Do not include column number on diagnostics"));
273
274static llvm::cl::opt<bool>
Chris Lattner83ab0a82009-01-30 19:01:41 +0000275NoShowLocation("fno-show-source-location",
276 llvm::cl::desc("Do not include source location information with"
277 " diagnostics"));
278
279static llvm::cl::opt<bool>
Nico Weberb5fc3c32008-08-05 23:33:20 +0000280NoCaretDiagnostics("fno-caret-diagnostics",
281 llvm::cl::desc("Do not include source line and caret with"
282 " diagnostics"));
283
Chris Lattner44219f32009-03-13 01:08:23 +0000284static llvm::cl::opt<bool>
Chris Lattner29d34ca2009-04-19 07:44:08 +0000285NoDiagnosticsFixIt("fno-diagnostics-fixit-info",
286 llvm::cl::desc("Do not include fixit information in"
287 " diagnostics"));
288
289static llvm::cl::opt<bool>
Chris Lattner69686412009-04-21 05:34:31 +0000290PrintSourceRangeInfo("fdiagnostics-print-source-range-info",
291 llvm::cl::desc("Print source range spans in numeric form"));
292
Chris Lattner22cb8182009-04-16 05:44:38 +0000293static llvm::cl::opt<bool>
294PrintDiagnosticOption("fdiagnostics-show-option",
295 llvm::cl::desc("Print diagnostic name with mappable diagnostics"));
Nico Weberb5fc3c32008-08-05 23:33:20 +0000296
Douglas Gregor48185532009-05-01 21:53:04 +0000297static llvm::cl::opt<unsigned>
298MessageLength("fmessage-length",
Mike Stump11289f42009-09-09 15:08:12 +0000299 llvm::cl::desc("Format message diagnostics so that they fit "
300 "within N columns or fewer, when possible."),
301 llvm::cl::value_desc("N"));
Douglas Gregor48185532009-05-01 21:53:04 +0000302
Torok Edwinc91b6e02009-06-04 07:18:23 +0000303static llvm::cl::opt<bool>
Daniel Dunbar5ec95022009-11-04 06:24:57 +0000304PrintColorDiagnostic("fcolor-diagnostics",
305 llvm::cl::desc("Use colors in diagnostics"));
306
Chris Lattnerff438212006-10-17 05:16:26 +0000307//===----------------------------------------------------------------------===//
Ted Kremenek45e2b902008-10-23 23:36:29 +0000308// C++ Visualization.
309//===----------------------------------------------------------------------===//
310
311static llvm::cl::opt<std::string>
312InheritanceViewCls("cxx-inheritance-view",
313 llvm::cl::value_desc("class name"),
Daniel Dunbar1dad2d82009-01-14 18:56:36 +0000314 llvm::cl::desc("View C++ inheritance for a specified class"));
Ted Kremenek45e2b902008-10-23 23:36:29 +0000315
316//===----------------------------------------------------------------------===//
Douglas Gregor69c79512009-02-14 20:49:29 +0000317// Builtin Options
318//===----------------------------------------------------------------------===//
Chris Lattnera1580a62009-02-18 01:12:43 +0000319
320static llvm::cl::opt<bool>
321TimeReport("ftime-report",
322 llvm::cl::desc("Print the amount of time each "
323 "phase of compilation takes"));
324
Douglas Gregor69c79512009-02-14 20:49:29 +0000325static llvm::cl::opt<bool>
326Freestanding("ffreestanding",
Daniel Dunbar8eb018a2009-02-16 22:43:43 +0000327 llvm::cl::desc("Assert that the compilation takes place in a "
Douglas Gregor69c79512009-02-14 20:49:29 +0000328 "freestanding environment"));
329
Daniel Dunbar8eb018a2009-02-16 22:43:43 +0000330static llvm::cl::opt<bool>
Daniel Dunbard18049a2009-04-07 21:16:11 +0000331AllowBuiltins("fbuiltin", llvm::cl::init(true),
332 llvm::cl::desc("Disable implicit builtin knowledge of functions"));
Chris Lattnerc890aa22009-03-13 22:38:49 +0000333
334
335static llvm::cl::opt<bool>
Daniel Dunbard18049a2009-04-07 21:16:11 +0000336MathErrno("fmath-errno", llvm::cl::init(true),
337 llvm::cl::desc("Require math functions to respect errno"));
Daniel Dunbar8eb018a2009-02-16 22:43:43 +0000338
Douglas Gregor69c79512009-02-14 20:49:29 +0000339//===----------------------------------------------------------------------===//
Chris Lattnerff438212006-10-17 05:16:26 +0000340// Language Options
341//===----------------------------------------------------------------------===//
342
343enum LangKind {
344 langkind_unspecified,
345 langkind_c,
346 langkind_c_cpp,
Chris Lattner720d5152008-10-22 17:29:21 +0000347 langkind_asm_cpp,
Chris Lattnerff438212006-10-17 05:16:26 +0000348 langkind_cxx,
349 langkind_cxx_cpp,
350 langkind_objc,
351 langkind_objc_cpp,
352 langkind_objcxx,
Nate Begeman95f48a52009-06-25 22:43:10 +0000353 langkind_objcxx_cpp,
Daniel Dunbare9fee8a2009-09-17 00:48:13 +0000354 langkind_ocl,
355 langkind_ast
Chris Lattnerff438212006-10-17 05:16:26 +0000356};
357
Chris Lattner23b7eb62007-06-15 23:05:46 +0000358static llvm::cl::opt<LangKind>
359BaseLang("x", llvm::cl::desc("Base language to compile"),
360 llvm::cl::init(langkind_unspecified),
361 llvm::cl::values(clEnumValN(langkind_c, "c", "C"),
Nate Begeman95f48a52009-06-25 22:43:10 +0000362 clEnumValN(langkind_ocl, "cl", "OpenCL C"),
Chris Lattnerff438212006-10-17 05:16:26 +0000363 clEnumValN(langkind_cxx, "c++", "C++"),
364 clEnumValN(langkind_objc, "objective-c", "Objective C"),
365 clEnumValN(langkind_objcxx,"objective-c++","Objective C++"),
Daniel Dunbar38b9c052009-01-29 23:50:47 +0000366 clEnumValN(langkind_c_cpp, "cpp-output",
Chris Lattnerff438212006-10-17 05:16:26 +0000367 "Preprocessed C"),
Chris Lattner720d5152008-10-22 17:29:21 +0000368 clEnumValN(langkind_asm_cpp, "assembler-with-cpp",
369 "Preprocessed asm"),
Chris Lattnerff438212006-10-17 05:16:26 +0000370 clEnumValN(langkind_cxx_cpp, "c++-cpp-output",
Chris Lattnerf3020002009-02-06 06:19:20 +0000371 "Preprocessed C++"),
Chris Lattnerff438212006-10-17 05:16:26 +0000372 clEnumValN(langkind_objc_cpp, "objective-c-cpp-output",
373 "Preprocessed Objective C"),
Chris Lattnerf3020002009-02-06 06:19:20 +0000374 clEnumValN(langkind_objcxx_cpp, "objective-c++-cpp-output",
Chris Lattnerff438212006-10-17 05:16:26 +0000375 "Preprocessed Objective C++"),
Daniel Dunbar386ef882009-04-01 05:09:09 +0000376 clEnumValN(langkind_c, "c-header",
377 "C header"),
378 clEnumValN(langkind_objc, "objective-c-header",
379 "Objective-C header"),
380 clEnumValN(langkind_cxx, "c++-header",
381 "C++ header"),
382 clEnumValN(langkind_objcxx, "objective-c++-header",
383 "Objective-C++ header"),
Daniel Dunbare9fee8a2009-09-17 00:48:13 +0000384 clEnumValN(langkind_ast, "ast",
385 "Clang AST"),
Chris Lattnerff438212006-10-17 05:16:26 +0000386 clEnumValEnd));
387
Chris Lattner23b7eb62007-06-15 23:05:46 +0000388static llvm::cl::opt<bool>
Chris Lattner184e65d2009-04-14 23:22:57 +0000389ObjCExclusiveGC("fobjc-gc-only",
390 llvm::cl::desc("Use GC exclusively for Objective-C related "
391 "memory management"));
392
David Chisnall5778fce2009-08-31 16:41:57 +0000393static llvm::cl::opt<std::string>
394ObjCConstantStringClass("fconstant-string-class",
395 llvm::cl::value_desc("class name"),
396 llvm::cl::desc("Specify the class to use for constant "
397 "Objective-C string objects."));
398
Chris Lattner184e65d2009-04-14 23:22:57 +0000399static llvm::cl::opt<bool>
400ObjCEnableGC("fobjc-gc",
401 llvm::cl::desc("Enable Objective-C garbage collection"));
402
Fariborz Jahanian493d4e02009-04-17 03:04:15 +0000403static llvm::cl::opt<bool>
404ObjCEnableGCBitmapPrint("print-ivar-layout",
405 llvm::cl::desc("Enable Objective-C Ivar layout bitmap print trace"));
406
Chris Lattner184e65d2009-04-14 23:22:57 +0000407static llvm::cl::opt<LangOptions::VisibilityMode>
408SymbolVisibility("fvisibility",
409 llvm::cl::desc("Set the default symbol visibility:"),
410 llvm::cl::init(LangOptions::Default),
411 llvm::cl::values(clEnumValN(LangOptions::Default, "default",
412 "Use default symbol visibility"),
413 clEnumValN(LangOptions::Hidden, "hidden",
414 "Use hidden symbol visibility"),
415 clEnumValN(LangOptions::Protected,"protected",
416 "Use protected symbol visibility"),
417 clEnumValEnd));
418
419static llvm::cl::opt<bool>
420OverflowChecking("ftrapv",
421 llvm::cl::desc("Trap on integer overflow"),
422 llvm::cl::init(false));
423
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000424static llvm::cl::opt<bool>
Nate Begeman5ec4b312009-08-10 23:49:36 +0000425AltiVec("faltivec", llvm::cl::desc("Enable AltiVec vector initializer syntax"),
426 llvm::cl::init(false));
427
428static llvm::cl::opt<bool>
Daniel Dunbara77eaeb2009-09-03 04:54:28 +0000429PThread("pthread", llvm::cl::desc("Support POSIX threads in generated code"),
430 llvm::cl::init(false));
431
Ted Kremenek8ab23ad2008-10-21 00:54:44 +0000432static void InitializeCOptions(LangOptions &Options) {
433 // Do nothing.
434}
435
436static void InitializeObjCOptions(LangOptions &Options) {
437 Options.ObjC1 = Options.ObjC2 = 1;
438}
Mike Stump11289f42009-09-09 15:08:12 +0000439
Ted Kremenek8ab23ad2008-10-21 00:54:44 +0000440
Daniel Dunbar386ef882009-04-01 05:09:09 +0000441static void InitializeLangOptions(LangOptions &Options, LangKind LK){
Chris Lattnerff438212006-10-17 05:16:26 +0000442 bool NoPreprocess = false;
Mike Stump11289f42009-09-09 15:08:12 +0000443
Ted Kremenek260d01d2007-12-05 23:49:08 +0000444 switch (LK) {
Chris Lattnerff438212006-10-17 05:16:26 +0000445 default: assert(0 && "Unknown language kind!");
Chris Lattner720d5152008-10-22 17:29:21 +0000446 case langkind_asm_cpp:
Daniel Dunbar1f3d7842008-12-01 18:55:22 +0000447 Options.AsmPreprocessor = 1;
Chris Lattner720d5152008-10-22 17:29:21 +0000448 // FALLTHROUGH
Chris Lattnerff438212006-10-17 05:16:26 +0000449 case langkind_c_cpp:
450 NoPreprocess = true;
451 // FALLTHROUGH
452 case langkind_c:
Ted Kremenek8ab23ad2008-10-21 00:54:44 +0000453 InitializeCOptions(Options);
Chris Lattnerff438212006-10-17 05:16:26 +0000454 break;
455 case langkind_cxx_cpp:
456 NoPreprocess = true;
457 // FALLTHROUGH
458 case langkind_cxx:
459 Options.CPlusPlus = 1;
460 break;
461 case langkind_objc_cpp:
462 NoPreprocess = true;
463 // FALLTHROUGH
464 case langkind_objc:
Ted Kremenek8ab23ad2008-10-21 00:54:44 +0000465 InitializeObjCOptions(Options);
Chris Lattnerff438212006-10-17 05:16:26 +0000466 break;
467 case langkind_objcxx_cpp:
468 NoPreprocess = true;
469 // FALLTHROUGH
470 case langkind_objcxx:
471 Options.ObjC1 = Options.ObjC2 = 1;
472 Options.CPlusPlus = 1;
473 break;
Nate Begeman95f48a52009-06-25 22:43:10 +0000474 case langkind_ocl:
475 Options.OpenCL = 1;
476 Options.AltiVec = 1;
477 Options.CXXOperatorNames = 1;
478 Options.LaxVectorConversions = 1;
479 break;
Chris Lattnerff438212006-10-17 05:16:26 +0000480 }
Mike Stump11289f42009-09-09 15:08:12 +0000481
Chris Lattner184e65d2009-04-14 23:22:57 +0000482 if (ObjCExclusiveGC)
483 Options.setGCMode(LangOptions::GCOnly);
484 else if (ObjCEnableGC)
485 Options.setGCMode(LangOptions::HybridGC);
Mike Stump11289f42009-09-09 15:08:12 +0000486
Fariborz Jahanian493d4e02009-04-17 03:04:15 +0000487 if (ObjCEnableGCBitmapPrint)
488 Options.ObjCGCBitmapPrint = 1;
Mike Stump11289f42009-09-09 15:08:12 +0000489
Nate Begeman5ec4b312009-08-10 23:49:36 +0000490 if (AltiVec)
491 Options.AltiVec = 1;
Daniel Dunbara77eaeb2009-09-03 04:54:28 +0000492
493 if (PThread)
494 Options.POSIXThreads = 1;
Mike Stump11289f42009-09-09 15:08:12 +0000495
Chris Lattner184e65d2009-04-14 23:22:57 +0000496 Options.setVisibilityMode(SymbolVisibility);
497 Options.OverflowChecking = OverflowChecking;
Chris Lattnerff438212006-10-17 05:16:26 +0000498}
499
500/// LangStds - Language standards we support.
501enum LangStds {
Mike Stump11289f42009-09-09 15:08:12 +0000502 lang_unspecified,
Chris Lattnerff438212006-10-17 05:16:26 +0000503 lang_c89, lang_c94, lang_c99,
Douglas Gregor63b35562009-09-29 14:42:43 +0000504 lang_gnu89, lang_gnu99,
Chris Lattner539007a2007-07-16 04:18:29 +0000505 lang_cxx98, lang_gnucxx98,
506 lang_cxx0x, lang_gnucxx0x
Chris Lattnerff438212006-10-17 05:16:26 +0000507};
508
Chris Lattner23b7eb62007-06-15 23:05:46 +0000509static llvm::cl::opt<LangStds>
510LangStd("std", llvm::cl::desc("Language standard to compile for"),
511 llvm::cl::init(lang_unspecified),
512 llvm::cl::values(clEnumValN(lang_c89, "c89", "ISO C 1990"),
Chris Lattner229ce602006-11-21 01:21:07 +0000513 clEnumValN(lang_c89, "c90", "ISO C 1990"),
Chris Lattnerff438212006-10-17 05:16:26 +0000514 clEnumValN(lang_c89, "iso9899:1990", "ISO C 1990"),
515 clEnumValN(lang_c94, "iso9899:199409",
516 "ISO C 1990 with amendment 1"),
517 clEnumValN(lang_c99, "c99", "ISO C 1999"),
Chris Lattner88870722009-04-06 17:17:55 +0000518 clEnumValN(lang_c99, "c9x", "ISO C 1999"),
Chris Lattnerff438212006-10-17 05:16:26 +0000519 clEnumValN(lang_c99, "iso9899:1999", "ISO C 1999"),
Chris Lattner88870722009-04-06 17:17:55 +0000520 clEnumValN(lang_c99, "iso9899:199x", "ISO C 1999"),
Chris Lattnerff438212006-10-17 05:16:26 +0000521 clEnumValN(lang_gnu89, "gnu89",
Gabor Greiffda885d2009-02-28 09:22:15 +0000522 "ISO C 1990 with GNU extensions"),
Chris Lattnerff438212006-10-17 05:16:26 +0000523 clEnumValN(lang_gnu99, "gnu99",
Gabor Greiffda885d2009-02-28 09:22:15 +0000524 "ISO C 1999 with GNU extensions (default for C)"),
Chris Lattnerff438212006-10-17 05:16:26 +0000525 clEnumValN(lang_gnu99, "gnu9x",
526 "ISO C 1999 with GNU extensions"),
527 clEnumValN(lang_cxx98, "c++98",
528 "ISO C++ 1998 with amendments"),
529 clEnumValN(lang_gnucxx98, "gnu++98",
530 "ISO C++ 1998 with amendments and GNU "
531 "extensions (default for C++)"),
Chris Lattner539007a2007-07-16 04:18:29 +0000532 clEnumValN(lang_cxx0x, "c++0x",
533 "Upcoming ISO C++ 200x with amendments"),
534 clEnumValN(lang_gnucxx0x, "gnu++0x",
535 "Upcoming ISO C++ 200x with amendments and GNU "
Gabor Greif65fe8342009-03-11 23:07:18 +0000536 "extensions"),
Chris Lattnerff438212006-10-17 05:16:26 +0000537 clEnumValEnd));
538
Chris Lattner23b7eb62007-06-15 23:05:46 +0000539static llvm::cl::opt<bool>
Chris Lattner3e7592e2006-12-04 07:48:37 +0000540NoOperatorNames("fno-operator-names",
Chris Lattner23b7eb62007-06-15 23:05:46 +0000541 llvm::cl::desc("Do not treat C++ operator name keywords as "
542 "synonyms for operators"));
Chris Lattner3e7592e2006-12-04 07:48:37 +0000543
Anders Carlssoncbfc4b82007-10-15 02:50:23 +0000544static llvm::cl::opt<bool>
545PascalStrings("fpascal-strings",
546 llvm::cl::desc("Recognize and construct Pascal-style "
547 "string literals"));
Mike Stump11289f42009-09-09 15:08:12 +0000548
Steve Naroffb2c80c72008-02-07 03:50:06 +0000549static llvm::cl::opt<bool>
550MSExtensions("fms-extensions",
551 llvm::cl::desc("Accept some non-standard constructs used in "
Sanjiv Guptacd13ef02008-05-08 08:28:14 +0000552 "Microsoft header files "));
Chris Lattnerfb300092007-11-28 05:34:05 +0000553
554static llvm::cl::opt<bool>
555WritableStrings("fwritable-strings",
Sanjiv Guptacd13ef02008-05-08 08:28:14 +0000556 llvm::cl::desc("Store string literals as writable data"));
Anders Carlssone1af1d22007-11-30 04:21:22 +0000557
558static llvm::cl::opt<bool>
Anders Carlssonf6e60572009-01-30 23:26:40 +0000559NoLaxVectorConversions("fno-lax-vector-conversions",
Anders Carlssondb5a9b62009-01-30 23:17:46 +0000560 llvm::cl::desc("Disallow implicit conversions between "
561 "vectors with a different number of "
562 "elements or different element types"));
Chris Lattner2ca529c2008-12-04 23:20:07 +0000563
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000564static llvm::cl::opt<bool>
Daniel Dunbard18049a2009-04-07 21:16:11 +0000565EnableBlocks("fblocks", llvm::cl::desc("enable the 'blocks' language feature"));
Mike Stumpf126e592009-02-02 22:57:57 +0000566
567static llvm::cl::opt<bool>
Chris Lattnercda4d7e2009-03-13 17:38:01 +0000568EnableHeinousExtensions("fheinous-gnu-extensions",
569 llvm::cl::desc("enable GNU extensions that you really really shouldn't use"),
570 llvm::cl::ValueDisallowed, llvm::cl::Hidden);
571
572static llvm::cl::opt<bool>
Mike Stumpf126e592009-02-02 22:57:57 +0000573ObjCNonFragileABI("fobjc-nonfragile-abi",
574 llvm::cl::desc("enable objective-c's nonfragile abi"));
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000575
Daniel Dunbare993ba62009-05-04 05:16:21 +0000576
577static llvm::cl::opt<bool>
Daniel Dunbar1e8052b2009-02-04 21:19:06 +0000578EmitAllDecls("femit-all-decls",
579 llvm::cl::desc("Emit all declarations, even if unused"));
Ted Kremenekd796c182008-04-29 04:37:03 +0000580
Daniel Dunbarfb3043d2008-08-11 17:36:14 +0000581static llvm::cl::opt<bool>
582Exceptions("fexceptions",
Chris Lattner98b10052009-04-19 07:00:02 +0000583 llvm::cl::desc("Enable support for exception handling"));
Daniel Dunbarfb3043d2008-08-11 17:36:14 +0000584
Daniel Dunbar3ad53482008-08-11 21:35:06 +0000585static llvm::cl::opt<bool>
Mike Stump183c3d22009-07-31 23:15:31 +0000586Rtti("frtti", llvm::cl::init(true),
587 llvm::cl::desc("Enable generation of rtti information"));
588
589static llvm::cl::opt<bool>
Daniel Dunbar3ad53482008-08-11 21:35:06 +0000590GNURuntime("fgnu-runtime",
Ted Kremenek8ab23ad2008-10-21 00:54:44 +0000591 llvm::cl::desc("Generate output compatible with the standard GNU "
Chris Lattner98b10052009-04-19 07:00:02 +0000592 "Objective-C runtime"));
Daniel Dunbar3ad53482008-08-11 21:35:06 +0000593
594static llvm::cl::opt<bool>
595NeXTRuntime("fnext-runtime",
Ted Kremenek8ab23ad2008-10-21 00:54:44 +0000596 llvm::cl::desc("Generate output compatible with the NeXT "
Chris Lattner98b10052009-04-19 07:00:02 +0000597 "runtime"));
Daniel Dunbar3ad53482008-08-11 21:35:06 +0000598
Eli Friedman6be4b392009-06-05 07:12:17 +0000599static llvm::cl::opt<bool>
600CharIsSigned("fsigned-char",
601 llvm::cl::desc("Force char to be a signed/unsigned type"));
Ted Kremenekb4476342008-09-03 21:22:16 +0000602
John Thompsoned4e2952009-11-05 20:14:16 +0000603static llvm::cl::opt<bool>
604ShortWChar("fshort-wchar",
605 llvm::cl::desc("Force wchar_t to be a short unsigned int"));
606
Ted Kremenekb4476342008-09-03 21:22:16 +0000607
608static llvm::cl::opt<bool>
Chris Lattner98b10052009-04-19 07:00:02 +0000609Trigraphs("trigraphs", llvm::cl::desc("Process trigraph sequences"));
Ted Kremenekb4476342008-09-03 21:22:16 +0000610
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000611static llvm::cl::opt<unsigned>
612TemplateDepth("ftemplate-depth", llvm::cl::init(99),
613 llvm::cl::desc("Maximum depth of recursive template "
614 "instantiation"));
Chris Lattner98b10052009-04-19 07:00:02 +0000615static llvm::cl::opt<bool>
616DollarsInIdents("fdollars-in-identifiers",
617 llvm::cl::desc("Allow '$' in identifiers"));
Chris Lattnere6e4c032009-03-02 22:11:07 +0000618
Daniel Dunbar3b358a32009-04-08 05:11:16 +0000619static llvm::cl::opt<std::string>
620MainFileName("main-file-name",
621 llvm::cl::desc("Main file name to use for debug info"));
Anders Carlsson65cb90e2009-04-06 17:37:10 +0000622
Anders Carlsson5879fbd2009-05-13 19:49:53 +0000623static llvm::cl::opt<bool>
Mike Stump11289f42009-09-09 15:08:12 +0000624AccessControl("faccess-control",
Anders Carlsson5879fbd2009-05-13 19:49:53 +0000625 llvm::cl::desc("Enable C++ access control"));
626
Anders Carlsson9cedbef2009-08-22 22:30:33 +0000627static llvm::cl::opt<bool>
628NoElideConstructors("fno-elide-constructors",
629 llvm::cl::desc("Disable C++ copy constructor elision"));
630
Daniel Dunbar4e97bc32009-09-14 00:02:12 +0000631static llvm::cl::opt<std::string>
632TargetABI("target-abi",
633 llvm::cl::desc("Target a particular ABI type"));
634
Daniel Dunbarf3355a62009-10-30 18:12:31 +0000635static llvm::cl::opt<std::string>
636TargetTriple("triple",
637 llvm::cl::desc("Specify target triple (e.g. i686-apple-darwin9)"));
638
Anders Carlsson9cedbef2009-08-22 22:30:33 +0000639
Daniel Dunbarab7b2f52009-04-08 03:03:23 +0000640static llvm::cl::opt<unsigned>
Daniel Dunbar17ddaa62009-04-08 18:03:55 +0000641PICLevel("pic-level", llvm::cl::desc("Value for __PIC__"));
642
643static llvm::cl::opt<bool>
644StaticDefine("static-define", llvm::cl::desc("Should __STATIC__ be defined"));
Daniel Dunbarab7b2f52009-04-08 03:03:23 +0000645
Bill Wendlingd63bbad2009-06-28 07:36:13 +0000646static llvm::cl::opt<int>
647StackProtector("stack-protector",
648 llvm::cl::desc("Enable stack protectors"),
649 llvm::cl::init(-1));
650
Daniel Dunbarb8767ac2008-08-23 08:43:39 +0000651static void InitializeLanguageStandard(LangOptions &Options, LangKind LK,
Daniel Dunbard673bfa2009-11-09 22:46:09 +0000652 TargetInfo &Target,
Daniel Dunbara35a2cb2009-11-10 19:51:33 +0000653 const CompileOptions &CompileOpts,
Daniel Dunbar4dbaaa62009-05-06 03:16:41 +0000654 const llvm::StringMap<bool> &Features) {
Daniel Dunbar1de78552009-11-09 22:45:57 +0000655 // Allow the target to set the default the language options as it sees fit.
Daniel Dunbard673bfa2009-11-09 22:46:09 +0000656 Target.getDefaultLangOptions(Options);
Daniel Dunbar4dbaaa62009-05-06 03:16:41 +0000657
658 // Pass the map of target features to the target for validation and
659 // processing.
Daniel Dunbard673bfa2009-11-09 22:46:09 +0000660 Target.HandleTargetFeatures(Features);
Mike Stump11289f42009-09-09 15:08:12 +0000661
Chris Lattnerff438212006-10-17 05:16:26 +0000662 if (LangStd == lang_unspecified) {
663 // Based on the base language, pick one.
Ted Kremenek260d01d2007-12-05 23:49:08 +0000664 switch (LK) {
Daniel Dunbare9fee8a2009-09-17 00:48:13 +0000665 case langkind_ast: assert(0 && "Invalid call for AST inputs");
Ted Kremenek95cd5c62009-03-19 19:02:20 +0000666 case lang_unspecified: assert(0 && "Unknown base language");
Nate Begeman95f48a52009-06-25 22:43:10 +0000667 case langkind_ocl:
668 LangStd = lang_c99;
669 break;
Chris Lattnerff438212006-10-17 05:16:26 +0000670 case langkind_c:
Chris Lattner720d5152008-10-22 17:29:21 +0000671 case langkind_asm_cpp:
Chris Lattnerff438212006-10-17 05:16:26 +0000672 case langkind_c_cpp:
673 case langkind_objc:
674 case langkind_objc_cpp:
Steve Naroff17f76e02007-05-03 21:03:48 +0000675 LangStd = lang_gnu99;
Chris Lattnerff438212006-10-17 05:16:26 +0000676 break;
677 case langkind_cxx:
678 case langkind_cxx_cpp:
679 case langkind_objcxx:
680 case langkind_objcxx_cpp:
681 LangStd = lang_gnucxx98;
682 break;
683 }
684 }
Mike Stump11289f42009-09-09 15:08:12 +0000685
Chris Lattnerff438212006-10-17 05:16:26 +0000686 switch (LangStd) {
687 default: assert(0 && "Unknown language standard!");
688
689 // Fall through from newer standards to older ones. This isn't really right.
690 // FIXME: Enable specifically the right features based on the language stds.
Chris Lattner539007a2007-07-16 04:18:29 +0000691 case lang_gnucxx0x:
692 case lang_cxx0x:
693 Options.CPlusPlus0x = 1;
694 // FALL THROUGH
Chris Lattnerff438212006-10-17 05:16:26 +0000695 case lang_gnucxx98:
Chris Lattnerff438212006-10-17 05:16:26 +0000696 case lang_cxx98:
697 Options.CPlusPlus = 1;
Chris Lattner3e7592e2006-12-04 07:48:37 +0000698 Options.CXXOperatorNames = !NoOperatorNames;
Chris Lattnerff438212006-10-17 05:16:26 +0000699 // FALL THROUGH.
700 case lang_gnu99:
701 case lang_c99:
Chris Lattnerff438212006-10-17 05:16:26 +0000702 Options.C99 = 1;
703 Options.HexFloats = 1;
704 // FALL THROUGH.
705 case lang_gnu89:
706 Options.BCPLComment = 1; // Only for C99/C++.
707 // FALL THROUGH.
708 case lang_c94:
Chris Lattnercb0d62c2008-02-25 04:01:39 +0000709 Options.Digraphs = 1; // C94, C99, C++.
710 // FALL THROUGH.
Chris Lattnerff438212006-10-17 05:16:26 +0000711 case lang_c89:
712 break;
713 }
Argyrios Kyrtzidise7092ba2008-09-11 04:21:06 +0000714
Chris Lattner91d63d12009-03-20 15:44:26 +0000715 // GNUMode - Set if we're in gnu99, gnu89, gnucxx98, etc.
Douglas Gregor63b35562009-09-29 14:42:43 +0000716 switch (LangStd) {
717 default: assert(0 && "Unknown language standard!");
718 case lang_gnucxx0x:
719 case lang_gnucxx98:
720 case lang_gnu99:
721 case lang_gnu89:
722 Options.GNUMode = 1;
723 break;
724 case lang_cxx0x:
725 case lang_cxx98:
726 case lang_c99:
727 case lang_c94:
728 case lang_c89:
729 Options.GNUMode = 0;
730 break;
731 }
Mike Stump11289f42009-09-09 15:08:12 +0000732
Argyrios Kyrtzidise7092ba2008-09-11 04:21:06 +0000733 if (Options.CPlusPlus) {
734 Options.C99 = 0;
Eli Friedmanc00767d2009-08-26 20:15:14 +0000735 Options.HexFloats = 0;
Argyrios Kyrtzidise7092ba2008-09-11 04:21:06 +0000736 }
Mike Stump11289f42009-09-09 15:08:12 +0000737
Chris Lattner9d51f2b2008-04-05 06:32:51 +0000738 if (LangStd == lang_c89 || LangStd == lang_c94 || LangStd == lang_gnu89)
739 Options.ImplicitInt = 1;
740 else
741 Options.ImplicitInt = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000742
Daniel Dunbarc44b4cc2009-04-07 22:13:21 +0000743 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
744 // is specified, or -std is set to a conforming mode.
Chris Lattner91d63d12009-03-20 15:44:26 +0000745 Options.Trigraphs = !Options.GNUMode;
Chris Lattner5b492702008-12-05 00:10:44 +0000746 if (Trigraphs.getPosition())
Chris Lattner91d63d12009-03-20 15:44:26 +0000747 Options.Trigraphs = Trigraphs; // Command line option wins if specified.
Ted Kremenekb4476342008-09-03 21:22:16 +0000748
Chris Lattner5b492702008-12-05 00:10:44 +0000749 // If in a conformant language mode (e.g. -std=c99) Blocks defaults to off
750 // even if they are normally on for the target. In GNU modes (e.g.
751 // -std=gnu99) the default for blocks depends on the target settings.
Anders Carlssone26b9452009-01-21 18:47:36 +0000752 // However, blocks are not turned off when compiling Obj-C or Obj-C++ code.
Chris Lattner91d63d12009-03-20 15:44:26 +0000753 if (!Options.ObjC1 && !Options.GNUMode)
Chris Lattner5b492702008-12-05 00:10:44 +0000754 Options.Blocks = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000755
Chris Lattnerfc5070552009-04-19 07:06:52 +0000756 // Default to not accepting '$' in identifiers when preprocessing assembler,
757 // but do accept when preprocessing C. FIXME: these defaults are right for
758 // darwin, are they right everywhere?
759 Options.DollarIdents = LK != langkind_asm_cpp;
760 if (DollarsInIdents.getPosition()) // Explicit setting overrides default.
Chris Lattner98b10052009-04-19 07:00:02 +0000761 Options.DollarIdents = DollarsInIdents;
Mike Stump11289f42009-09-09 15:08:12 +0000762
Chris Lattner2ca529c2008-12-04 23:20:07 +0000763 if (PascalStrings.getPosition())
764 Options.PascalStrings = PascalStrings;
Eli Friedmanaa27a872009-06-08 06:11:14 +0000765 if (MSExtensions.getPosition())
766 Options.Microsoft = MSExtensions;
Chris Lattnerfb300092007-11-28 05:34:05 +0000767 Options.WritableStrings = WritableStrings;
Anders Carlssondb5a9b62009-01-30 23:17:46 +0000768 if (NoLaxVectorConversions.getPosition())
769 Options.LaxVectorConversions = 0;
Daniel Dunbarfb3043d2008-08-11 17:36:14 +0000770 Options.Exceptions = Exceptions;
Mike Stump183c3d22009-07-31 23:15:31 +0000771 Options.Rtti = Rtti;
Mike Stumpf126e592009-02-02 22:57:57 +0000772 if (EnableBlocks.getPosition())
Chris Lattner2ca529c2008-12-04 23:20:07 +0000773 Options.Blocks = EnableBlocks;
Eli Friedman6be4b392009-06-05 07:12:17 +0000774 if (CharIsSigned.getPosition())
775 Options.CharIsSigned = CharIsSigned;
John Thompson864bf752009-11-05 22:03:02 +0000776 if (ShortWChar.getPosition())
777 Options.ShortWChar = ShortWChar;
Daniel Dunbar3ad53482008-08-11 21:35:06 +0000778
Daniel Dunbara792bad2009-03-20 23:49:28 +0000779 if (!AllowBuiltins)
Chris Lattnerc890aa22009-03-13 22:38:49 +0000780 Options.NoBuiltin = 1;
Douglas Gregor69c79512009-02-14 20:49:29 +0000781 if (Freestanding)
Chris Lattnerc890aa22009-03-13 22:38:49 +0000782 Options.Freestanding = Options.NoBuiltin = 1;
Mike Stump11289f42009-09-09 15:08:12 +0000783
Chris Lattnercda4d7e2009-03-13 17:38:01 +0000784 if (EnableHeinousExtensions)
785 Options.HeinousExtensions = 1;
Douglas Gregor69c79512009-02-14 20:49:29 +0000786
Anders Carlsson5879fbd2009-05-13 19:49:53 +0000787 if (AccessControl)
788 Options.AccessControl = 1;
Mike Stump11289f42009-09-09 15:08:12 +0000789
Anders Carlsson9cedbef2009-08-22 22:30:33 +0000790 Options.ElideConstructors = !NoElideConstructors;
Mike Stump11289f42009-09-09 15:08:12 +0000791
Chris Lattnerc61089a2009-06-30 01:26:17 +0000792 // OpenCL and C++ both have bool, true, false keywords.
793 Options.Bool = Options.OpenCL | Options.CPlusPlus;
Mike Stump11289f42009-09-09 15:08:12 +0000794
Daniel Dunbar8eb018a2009-02-16 22:43:43 +0000795 Options.MathErrno = MathErrno;
796
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000797 Options.InstantiationDepth = TemplateDepth;
798
Chris Lattnerc7c6dd42008-12-04 22:54:33 +0000799 // Override the default runtime if the user requested it.
800 if (NeXTRuntime)
Daniel Dunbar3ad53482008-08-11 21:35:06 +0000801 Options.NeXTRuntime = 1;
Chris Lattnerc7c6dd42008-12-04 22:54:33 +0000802 else if (GNURuntime)
Daniel Dunbar3ad53482008-08-11 21:35:06 +0000803 Options.NeXTRuntime = 0;
Fariborz Jahanian279eda62009-01-21 22:04:16 +0000804
David Chisnall5778fce2009-08-31 16:41:57 +0000805 if (!ObjCConstantStringClass.empty())
806 Options.ObjCConstantStringClass = ObjCConstantStringClass.c_str();
807
Fariborz Jahanianb15a3d52009-01-22 23:02:58 +0000808 if (ObjCNonFragileABI)
809 Options.ObjCNonFragileABI = 1;
Fariborz Jahaniana4404f22009-05-22 20:17:16 +0000810
Daniel Dunbar1e8052b2009-02-04 21:19:06 +0000811 if (EmitAllDecls)
812 Options.EmitAllDecls = 1;
Anders Carlsson65cb90e2009-04-06 17:37:10 +0000813
Daniel Dunbarf89a32a2009-11-10 19:51:53 +0000814 // The __OPTIMIZE_SIZE__ define is tied to -Oz, which we don't support.
Daniel Dunbar17ddaa62009-04-08 18:03:55 +0000815 Options.OptimizeSize = 0;
Daniel Dunbara35a2cb2009-11-10 19:51:33 +0000816 Options.Optimize = !!CompileOpts.OptimizationLevel;
Daniel Dunbarab7b2f52009-04-08 03:03:23 +0000817
818 assert(PICLevel <= 2 && "Invalid value for -pic-level");
819 Options.PICLevel = PICLevel;
Daniel Dunbar3b358a32009-04-08 05:11:16 +0000820
Daniel Dunbar17ddaa62009-04-08 18:03:55 +0000821 Options.GNUInline = !Options.C99;
Mike Stump11289f42009-09-09 15:08:12 +0000822 // FIXME: This is affected by other options (-fno-inline).
Daniel Dunbara35a2cb2009-11-10 19:51:33 +0000823
824 // This is the __NO_INLINE__ define, which just depends on things like the
825 // optimization level and -fno-inline, not actually whether the backend has
826 // inlining enabled.
827 Options.NoInline = !CompileOpts.OptimizationLevel;
Daniel Dunbar17ddaa62009-04-08 18:03:55 +0000828
829 Options.Static = StaticDefine;
830
Bill Wendling18351072009-06-28 23:01:01 +0000831 switch (StackProtector) {
832 default:
833 assert(StackProtector <= 2 && "Invalid value for -stack-protector");
834 case -1: break;
835 case 0: Options.setStackProtectorMode(LangOptions::SSPOff); break;
836 case 1: Options.setStackProtectorMode(LangOptions::SSPOn); break;
837 case 2: Options.setStackProtectorMode(LangOptions::SSPReq); break;
838 }
Bill Wendlingd63bbad2009-06-28 07:36:13 +0000839
Daniel Dunbar3b358a32009-04-08 05:11:16 +0000840 if (MainFileName.getPosition())
841 Options.setMainFileName(MainFileName.c_str());
John Thompsoned4e2952009-11-05 20:14:16 +0000842
Daniel Dunbard673bfa2009-11-09 22:46:09 +0000843 Target.setForcedLangOptions(Options);
Chris Lattnerff438212006-10-17 05:16:26 +0000844}
Chris Lattner22eb9722006-06-18 05:43:12 +0000845
846//===----------------------------------------------------------------------===//
Chris Lattner2f5693f2009-04-21 05:40:52 +0000847// SourceManager initialization.
Chris Lattner22eb9722006-06-18 05:43:12 +0000848//===----------------------------------------------------------------------===//
849
Douglas Gregor92863e42009-04-10 23:10:45 +0000850static bool InitializeSourceManager(Preprocessor &PP,
851 const std::string &InFile) {
852 // Figure out where to get and map in the main file.
853 SourceManager &SourceMgr = PP.getSourceManager();
854 FileManager &FileMgr = PP.getFileManager();
Daniel Dunbarc6480e22009-04-27 21:19:07 +0000855
856 if (EmptyInputOnly) {
857 const char *EmptyStr = "";
Mike Stump11289f42009-09-09 15:08:12 +0000858 llvm::MemoryBuffer *SB =
Daniel Dunbarc6480e22009-04-27 21:19:07 +0000859 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<empty input>");
860 SourceMgr.createMainFileIDForMemBuffer(SB);
861 } else if (InFile != "-") {
Douglas Gregor92863e42009-04-10 23:10:45 +0000862 const FileEntry *File = FileMgr.getFile(InFile);
863 if (File) SourceMgr.createMainFileID(File, SourceLocation());
864 if (SourceMgr.getMainFileID().isInvalid()) {
Mike Stump11289f42009-09-09 15:08:12 +0000865 PP.getDiagnostics().Report(FullSourceLoc(), diag::err_fe_error_reading)
Douglas Gregor92863e42009-04-10 23:10:45 +0000866 << InFile.c_str();
867 return true;
868 }
869 } else {
870 llvm::MemoryBuffer *SB = llvm::MemoryBuffer::getSTDIN();
Douglas Gregor92863e42009-04-10 23:10:45 +0000871 SourceMgr.createMainFileIDForMemBuffer(SB);
872 if (SourceMgr.getMainFileID().isInvalid()) {
Mike Stump11289f42009-09-09 15:08:12 +0000873 PP.getDiagnostics().Report(FullSourceLoc(),
Douglas Gregor92863e42009-04-10 23:10:45 +0000874 diag::err_fe_error_reading_stdin);
875 return true;
876 }
877 }
878
879 return false;
880}
881
Chris Lattnerba1f37b2008-04-19 23:09:31 +0000882
Chris Lattner2f5693f2009-04-21 05:40:52 +0000883//===----------------------------------------------------------------------===//
884// Preprocessor Initialization
885//===----------------------------------------------------------------------===//
Sam Bishopcb1a37b2008-04-14 14:41:57 +0000886
Chris Lattnere9d7d782009-11-03 19:50:27 +0000887static llvm::cl::opt<bool>
Daniel Dunbarb27ec092009-11-04 21:13:02 +0000888UndefMacros("undef", llvm::cl::value_desc("macro"),
889 llvm::cl::desc("undef all system defines"));
Chris Lattnere9d7d782009-11-03 19:50:27 +0000890
Chris Lattner2f5693f2009-04-21 05:40:52 +0000891static llvm::cl::list<std::string>
892D_macros("D", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
893 llvm::cl::desc("Predefine the specified macro"));
894static llvm::cl::list<std::string>
895U_macros("U", llvm::cl::value_desc("macro"), llvm::cl::Prefix,
896 llvm::cl::desc("Undefine the specified macro"));
Chris Lattner14a7f392009-04-08 18:24:34 +0000897
Chris Lattner2f5693f2009-04-21 05:40:52 +0000898static llvm::cl::list<std::string>
899ImplicitIncludes("include", llvm::cl::value_desc("file"),
900 llvm::cl::desc("Include file before parsing"));
901static llvm::cl::list<std::string>
902ImplicitMacroIncludes("imacros", llvm::cl::value_desc("file"),
903 llvm::cl::desc("Include macros from file before parsing"));
Chris Lattner14a7f392009-04-08 18:24:34 +0000904
Chris Lattner2f5693f2009-04-21 05:40:52 +0000905static llvm::cl::opt<std::string>
906ImplicitIncludePCH("include-pch", llvm::cl::value_desc("file"),
907 llvm::cl::desc("Include precompiled header file"));
908
909static llvm::cl::opt<std::string>
910ImplicitIncludePTH("include-pth", llvm::cl::value_desc("file"),
911 llvm::cl::desc("Include file before parsing"));
912
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000913static llvm::cl::opt<bool>
Mike Stump11289f42009-09-09 15:08:12 +0000914RelocatablePCH("relocatable-pch",
Douglas Gregor0086a5a2009-07-07 00:12:59 +0000915 llvm::cl::desc("Whether to build a relocatable precompiled "
916 "header"));
Chris Lattner22eb9722006-06-18 05:43:12 +0000917
918//===----------------------------------------------------------------------===//
919// Preprocessor include path information.
920//===----------------------------------------------------------------------===//
921
922// This tool exports a large number of command line options to control how the
923// preprocessor searches for header files. At root, however, the Preprocessor
924// object takes a very simple interface: a list of directories to search for
Chris Lattner22eb9722006-06-18 05:43:12 +0000925
Chris Lattner23b7eb62007-06-15 23:05:46 +0000926static llvm::cl::opt<bool>
927nostdinc("nostdinc", llvm::cl::desc("Disable standard #include directories"));
Chris Lattner22eb9722006-06-18 05:43:12 +0000928
Rafael Espindolae7178952009-10-05 13:12:17 +0000929static llvm::cl::opt<bool>
Rafael Espindolab3549d72009-10-26 13:36:57 +0000930nobuiltininc("nobuiltininc",
931 llvm::cl::desc("Disable builtin #include directories"));
Rafael Espindolae7178952009-10-05 13:12:17 +0000932
Chris Lattner22eb9722006-06-18 05:43:12 +0000933// Various command line options. These four add directories to each chain.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000934static llvm::cl::list<std::string>
935F_dirs("F", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
936 llvm::cl::desc("Add directory to framework include search path"));
937static llvm::cl::list<std::string>
938I_dirs("I", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
939 llvm::cl::desc("Add directory to include search path"));
940static llvm::cl::list<std::string>
941idirafter_dirs("idirafter", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
942 llvm::cl::desc("Add directory to AFTER include search path"));
943static llvm::cl::list<std::string>
944iquote_dirs("iquote", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
945 llvm::cl::desc("Add directory to QUOTE include search path"));
946static llvm::cl::list<std::string>
947isystem_dirs("isystem", llvm::cl::value_desc("directory"), llvm::cl::Prefix,
948 llvm::cl::desc("Add directory to SYSTEM include search path"));
Chris Lattner22eb9722006-06-18 05:43:12 +0000949
950// These handle -iprefix/-iwithprefix/-iwithprefixbefore.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000951static llvm::cl::list<std::string>
952iprefix_vals("iprefix", llvm::cl::value_desc("prefix"), llvm::cl::Prefix,
953 llvm::cl::desc("Set the -iwithprefix/-iwithprefixbefore prefix"));
954static llvm::cl::list<std::string>
955iwithprefix_vals("iwithprefix", llvm::cl::value_desc("dir"), llvm::cl::Prefix,
956 llvm::cl::desc("Set directory to SYSTEM include search path with prefix"));
957static llvm::cl::list<std::string>
958iwithprefixbefore_vals("iwithprefixbefore", llvm::cl::value_desc("dir"),
959 llvm::cl::Prefix,
960 llvm::cl::desc("Set directory to include search path with prefix"));
Chris Lattner22eb9722006-06-18 05:43:12 +0000961
Chris Lattnerdd9a3192007-08-26 17:47:35 +0000962static llvm::cl::opt<std::string>
963isysroot("isysroot", llvm::cl::value_desc("dir"), llvm::cl::init("/"),
964 llvm::cl::desc("Set the system root directory (usually /)"));
965
Chris Lattner22eb9722006-06-18 05:43:12 +0000966// Finally, implement the code that groks the options above.
Chris Lattnerc1bc5412008-03-01 08:07:28 +0000967
Rafael Espindolae7178952009-10-05 13:12:17 +0000968// Add the clang headers, which are relative to the clang binary.
Daniel Dunbarb10ac0d2009-11-07 04:19:57 +0000969std::string GetBuiltinIncludePath(const char *Argv0) {
970 llvm::sys::Path P =
971 llvm::sys::Path::GetMainExecutable(Argv0,
972 (void*)(intptr_t) GetBuiltinIncludePath);
Rafael Espindolae7178952009-10-05 13:12:17 +0000973
Daniel Dunbarb10ac0d2009-11-07 04:19:57 +0000974 if (!P.isEmpty()) {
975 P.eraseComponent(); // Remove /clang from foo/bin/clang
976 P.eraseComponent(); // Remove /bin from foo/bin
Rafael Espindolae7178952009-10-05 13:12:17 +0000977
Daniel Dunbarb10ac0d2009-11-07 04:19:57 +0000978 // Get foo/lib/clang/<version>/include
979 P.appendComponent("lib");
980 P.appendComponent("clang");
981 P.appendComponent(CLANG_VERSION_STRING);
982 P.appendComponent("include");
983 }
Rafael Espindolae7178952009-10-05 13:12:17 +0000984
Daniel Dunbarb10ac0d2009-11-07 04:19:57 +0000985 return P.str();
Rafael Espindolae7178952009-10-05 13:12:17 +0000986}
987
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000988/// InitializeIncludePaths - Process the -I options and set them in the
989/// HeaderSearch object.
Daniel Dunbare213db82009-11-09 22:46:17 +0000990static void InitializeIncludePaths(HeaderSearchOptions &Opts,
991 const char *Argv0,
992 const LangOptions &Lang) {
993 Opts.Sysroot = isysroot;
Daniel Dunbar8ec88042009-11-07 04:58:12 +0000994 Opts.Verbose = Verbose;
Nico Webered9b4102008-08-22 09:25:22 +0000995
Ted Kremeneka3774662008-05-31 00:27:00 +0000996 // Handle -I... and -F... options, walking the lists in parallel.
997 unsigned Iidx = 0, Fidx = 0;
998 while (Iidx < I_dirs.size() && Fidx < F_dirs.size()) {
999 if (I_dirs.getPosition(Iidx) < F_dirs.getPosition(Fidx)) {
Daniel Dunbar4df9aa22009-11-09 23:02:47 +00001000 Opts.AddPath(I_dirs[Iidx], frontend::Angled, false, true, false);
Ted Kremeneka3774662008-05-31 00:27:00 +00001001 ++Iidx;
1002 } else {
Daniel Dunbar4df9aa22009-11-09 23:02:47 +00001003 Opts.AddPath(F_dirs[Fidx], frontend::Angled, false, true, true);
Ted Kremeneka3774662008-05-31 00:27:00 +00001004 ++Fidx;
1005 }
1006 }
Mike Stump11289f42009-09-09 15:08:12 +00001007
Ted Kremeneka3774662008-05-31 00:27:00 +00001008 // Consume what's left from whatever list was longer.
1009 for (; Iidx != I_dirs.size(); ++Iidx)
Daniel Dunbar4df9aa22009-11-09 23:02:47 +00001010 Opts.AddPath(I_dirs[Iidx], frontend::Angled, false, true, false);
Ted Kremeneka3774662008-05-31 00:27:00 +00001011 for (; Fidx != F_dirs.size(); ++Fidx)
Daniel Dunbar4df9aa22009-11-09 23:02:47 +00001012 Opts.AddPath(F_dirs[Fidx], frontend::Angled, false, true, true);
Mike Stump11289f42009-09-09 15:08:12 +00001013
Chris Lattner22eb9722006-06-18 05:43:12 +00001014 // Handle -idirafter... options.
1015 for (unsigned i = 0, e = idirafter_dirs.size(); i != e; ++i)
Daniel Dunbar4df9aa22009-11-09 23:02:47 +00001016 Opts.AddPath(idirafter_dirs[i], frontend::After,
Nico Webered9b4102008-08-22 09:25:22 +00001017 false, true, false);
Mike Stump11289f42009-09-09 15:08:12 +00001018
Chris Lattner22eb9722006-06-18 05:43:12 +00001019 // Handle -iquote... options.
1020 for (unsigned i = 0, e = iquote_dirs.size(); i != e; ++i)
Daniel Dunbar4df9aa22009-11-09 23:02:47 +00001021 Opts.AddPath(iquote_dirs[i], frontend::Quoted, false, true, false);
Mike Stump11289f42009-09-09 15:08:12 +00001022
Chris Lattner22eb9722006-06-18 05:43:12 +00001023 // Handle -isystem... options.
1024 for (unsigned i = 0, e = isystem_dirs.size(); i != e; ++i)
Daniel Dunbar4df9aa22009-11-09 23:02:47 +00001025 Opts.AddPath(isystem_dirs[i], frontend::System, false, true, false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001026
1027 // Walk the -iprefix/-iwithprefix/-iwithprefixbefore argument lists in
1028 // parallel, processing the values in order of occurance to get the right
1029 // prefixes.
1030 {
1031 std::string Prefix = ""; // FIXME: this isn't the correct default prefix.
1032 unsigned iprefix_idx = 0;
1033 unsigned iwithprefix_idx = 0;
1034 unsigned iwithprefixbefore_idx = 0;
1035 bool iprefix_done = iprefix_vals.empty();
1036 bool iwithprefix_done = iwithprefix_vals.empty();
1037 bool iwithprefixbefore_done = iwithprefixbefore_vals.empty();
1038 while (!iprefix_done || !iwithprefix_done || !iwithprefixbefore_done) {
1039 if (!iprefix_done &&
Mike Stump11289f42009-09-09 15:08:12 +00001040 (iwithprefix_done ||
1041 iprefix_vals.getPosition(iprefix_idx) <
Chris Lattner22eb9722006-06-18 05:43:12 +00001042 iwithprefix_vals.getPosition(iwithprefix_idx)) &&
Mike Stump11289f42009-09-09 15:08:12 +00001043 (iwithprefixbefore_done ||
1044 iprefix_vals.getPosition(iprefix_idx) <
Chris Lattner22eb9722006-06-18 05:43:12 +00001045 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
1046 Prefix = iprefix_vals[iprefix_idx];
1047 ++iprefix_idx;
1048 iprefix_done = iprefix_idx == iprefix_vals.size();
1049 } else if (!iwithprefix_done &&
Mike Stump11289f42009-09-09 15:08:12 +00001050 (iwithprefixbefore_done ||
1051 iwithprefix_vals.getPosition(iwithprefix_idx) <
Chris Lattner22eb9722006-06-18 05:43:12 +00001052 iwithprefixbefore_vals.getPosition(iwithprefixbefore_idx))) {
Daniel Dunbar8ec88042009-11-07 04:58:12 +00001053 Opts.AddPath(Prefix+iwithprefix_vals[iwithprefix_idx],
Daniel Dunbar4df9aa22009-11-09 23:02:47 +00001054 frontend::System, false, false, false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001055 ++iwithprefix_idx;
1056 iwithprefix_done = iwithprefix_idx == iwithprefix_vals.size();
1057 } else {
Daniel Dunbar8ec88042009-11-07 04:58:12 +00001058 Opts.AddPath(Prefix+iwithprefixbefore_vals[iwithprefixbefore_idx],
Daniel Dunbar4df9aa22009-11-09 23:02:47 +00001059 frontend::Angled, false, false, false);
Chris Lattner22eb9722006-06-18 05:43:12 +00001060 ++iwithprefixbefore_idx;
Mike Stump11289f42009-09-09 15:08:12 +00001061 iwithprefixbefore_done =
Chris Lattner22eb9722006-06-18 05:43:12 +00001062 iwithprefixbefore_idx == iwithprefixbefore_vals.size();
1063 }
1064 }
1065 }
Chris Lattnerc1bc5412008-03-01 08:07:28 +00001066
Daniel Dunbarec879912009-11-07 04:20:39 +00001067 // Add CPATH environment paths.
1068 if (const char *Env = getenv("CPATH"))
Daniel Dunbar8ec88042009-11-07 04:58:12 +00001069 Opts.EnvIncPath = Env;
Daniel Dunbarec879912009-11-07 04:20:39 +00001070
1071 // Add language specific environment paths.
1072 if (Lang.CPlusPlus && Lang.ObjC1) {
1073 if (const char *Env = getenv("OBJCPLUS_INCLUDE_PATH"))
Daniel Dunbar8ec88042009-11-07 04:58:12 +00001074 Opts.LangEnvIncPath = Env;
Daniel Dunbarec879912009-11-07 04:20:39 +00001075 } else if (Lang.CPlusPlus) {
1076 if (const char *Env = getenv("CPLUS_INCLUDE_PATH"))
Daniel Dunbar8ec88042009-11-07 04:58:12 +00001077 Opts.LangEnvIncPath = Env;
Daniel Dunbarec879912009-11-07 04:20:39 +00001078 } else if (Lang.ObjC1) {
1079 if (const char *Env = getenv("OBJC_INCLUDE_PATH"))
Daniel Dunbar8ec88042009-11-07 04:58:12 +00001080 Opts.LangEnvIncPath = Env;
Daniel Dunbarec879912009-11-07 04:20:39 +00001081 } else {
1082 if (const char *Env = getenv("C_INCLUDE_PATH"))
Daniel Dunbar8ec88042009-11-07 04:58:12 +00001083 Opts.LangEnvIncPath = Env;
Daniel Dunbarec879912009-11-07 04:20:39 +00001084 }
Chris Lattnerc1bc5412008-03-01 08:07:28 +00001085
Daniel Dunbar8ec88042009-11-07 04:58:12 +00001086 if (!nobuiltininc)
1087 Opts.BuiltinIncludePath = GetBuiltinIncludePath(Argv0);
Daniel Dunbarb10ac0d2009-11-07 04:19:57 +00001088
Daniel Dunbar8ec88042009-11-07 04:58:12 +00001089 Opts.UseStandardIncludes = !nostdinc;
Chris Lattner22eb9722006-06-18 05:43:12 +00001090}
1091
Daniel Dunbar60198df2009-11-09 23:12:31 +00001092static void InitializePreprocessorOptions(PreprocessorOptions &InitOpts) {
Daniel Dunbarb27ec092009-11-04 21:13:02 +00001093 // Use predefines?
1094 InitOpts.setUsePredefines(!UndefMacros);
1095
Chris Lattner2f5693f2009-04-21 05:40:52 +00001096 // Add macros from the command line.
1097 unsigned d = 0, D = D_macros.size();
1098 unsigned u = 0, U = U_macros.size();
1099 while (d < D || u < U) {
1100 if (u == U || (d < D && D_macros.getPosition(d) < U_macros.getPosition(u)))
1101 InitOpts.addMacroDef(D_macros[d++]);
1102 else
1103 InitOpts.addMacroUndef(U_macros[u++]);
1104 }
1105
1106 // If -imacros are specified, include them now. These are processed before
1107 // any -include directives.
1108 for (unsigned i = 0, e = ImplicitMacroIncludes.size(); i != e; ++i)
1109 InitOpts.addMacroInclude(ImplicitMacroIncludes[i]);
1110
Douglas Gregor45fe0362009-05-12 01:31:05 +00001111 if (!ImplicitIncludePTH.empty() || !ImplicitIncludes.empty() ||
1112 (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)) {
Chris Lattner2f5693f2009-04-21 05:40:52 +00001113 // We want to add these paths to the predefines buffer in order, make a
1114 // temporary vector to sort by their occurrence.
1115 llvm::SmallVector<std::pair<unsigned, std::string*>, 8> OrderedPaths;
1116
1117 if (!ImplicitIncludePTH.empty())
1118 OrderedPaths.push_back(std::make_pair(ImplicitIncludePTH.getPosition(),
1119 &ImplicitIncludePTH));
Douglas Gregor45fe0362009-05-12 01:31:05 +00001120 if (!ImplicitIncludePCH.empty() && ProgAction == PrintPreprocessedInput)
1121 OrderedPaths.push_back(std::make_pair(ImplicitIncludePCH.getPosition(),
1122 &ImplicitIncludePCH));
Chris Lattner2f5693f2009-04-21 05:40:52 +00001123 for (unsigned i = 0, e = ImplicitIncludes.size(); i != e; ++i)
1124 OrderedPaths.push_back(std::make_pair(ImplicitIncludes.getPosition(i),
1125 &ImplicitIncludes[i]));
1126 llvm::array_pod_sort(OrderedPaths.begin(), OrderedPaths.end());
1127
1128
1129 // Now that they are ordered by position, add to the predefines buffer.
1130 for (unsigned i = 0, e = OrderedPaths.size(); i != e; ++i) {
1131 std::string *Ptr = OrderedPaths[i].second;
1132 if (!ImplicitIncludes.empty() &&
1133 Ptr >= &ImplicitIncludes[0] &&
1134 Ptr <= &ImplicitIncludes[ImplicitIncludes.size()-1]) {
1135 InitOpts.addInclude(*Ptr, false);
Douglas Gregor45fe0362009-05-12 01:31:05 +00001136 } else if (Ptr == &ImplicitIncludePTH) {
Chris Lattner2f5693f2009-04-21 05:40:52 +00001137 InitOpts.addInclude(*Ptr, true);
Douglas Gregor45fe0362009-05-12 01:31:05 +00001138 } else {
1139 // We end up here when we're producing preprocessed output and
1140 // we loaded a PCH file. In this case, just include the header
1141 // file that was used to build the precompiled header.
1142 assert(Ptr == &ImplicitIncludePCH);
1143 std::string OriginalFile = PCHReader::getOriginalSourceFile(*Ptr);
1144 if (!OriginalFile.empty()) {
1145 InitOpts.addInclude(OriginalFile, false);
1146 ImplicitIncludePCH.clear();
1147 }
Chris Lattner2f5693f2009-04-21 05:40:52 +00001148 }
1149 }
1150 }
1151}
1152
Ted Kremenek306492d2008-04-17 21:38:34 +00001153//===----------------------------------------------------------------------===//
Daniel Dunbard0ba0e62009-11-04 23:56:25 +00001154// Preprocessor construction
Ted Kremenek306492d2008-04-17 21:38:34 +00001155//===----------------------------------------------------------------------===//
1156
Daniel Dunbard0ba0e62009-11-04 23:56:25 +00001157static Preprocessor *
Daniel Dunbar60198df2009-11-09 23:12:31 +00001158CreatePreprocessor(Diagnostic &Diags, const LangOptions &LangInfo,
1159 const PreprocessorOptions &PPOpts, TargetInfo &Target,
1160 SourceManager &SourceMgr, HeaderSearch &HeaderInfo) {
Daniel Dunbard0ba0e62009-11-04 23:56:25 +00001161 PTHManager *PTHMgr = 0;
1162 if (!TokenCache.empty() && !ImplicitIncludePTH.empty()) {
1163 fprintf(stderr, "error: cannot use both -token-cache and -include-pth "
1164 "options\n");
1165 exit(1);
Ted Kremenek306492d2008-04-17 21:38:34 +00001166 }
Daniel Dunbard0ba0e62009-11-04 23:56:25 +00001167
1168 // Use PTH?
1169 if (!TokenCache.empty() || !ImplicitIncludePTH.empty()) {
1170 const std::string& x = TokenCache.empty() ? ImplicitIncludePTH:TokenCache;
1171 PTHMgr = PTHManager::Create(x, &Diags,
1172 TokenCache.empty() ? Diagnostic::Error
1173 : Diagnostic::Warning);
1174 }
1175
1176 if (Diags.hasErrorOccurred())
1177 exit(1);
1178
1179 // Create the Preprocessor.
1180 Preprocessor *PP = new Preprocessor(Diags, LangInfo, Target,
1181 SourceMgr, HeaderInfo, PTHMgr);
1182
1183 // Note that this is different then passing PTHMgr to Preprocessor's ctor.
1184 // That argument is used as the IdentifierInfoLookup argument to
1185 // IdentifierTable's ctor.
1186 if (PTHMgr) {
1187 PTHMgr->setPreprocessor(PP);
1188 PP->setPTHManager(PTHMgr);
1189 }
1190
Daniel Dunbar60198df2009-11-09 23:12:31 +00001191 InitializePreprocessor(*PP, PPOpts);
Daniel Dunbard0ba0e62009-11-04 23:56:25 +00001192
1193 return PP;
Ted Kremenek306492d2008-04-17 21:38:34 +00001194}
Chris Lattner22eb9722006-06-18 05:43:12 +00001195
Chris Lattner0bb5f832006-07-31 01:59:18 +00001196//===----------------------------------------------------------------------===//
Chris Lattner73709ed2006-08-17 06:28:25 +00001197// Basic Parser driver
Chris Lattner0bb5f832006-07-31 01:59:18 +00001198//===----------------------------------------------------------------------===//
1199
Chris Lattner1a44f7f2008-04-19 23:25:44 +00001200static void ParseFile(Preprocessor &PP, MinimalAction *PA) {
Chris Lattner0bb5f832006-07-31 01:59:18 +00001201 Parser P(PP, *PA);
Ted Kremenek230bd912007-12-19 22:51:13 +00001202 PP.EnterMainSourceFile();
Mike Stump11289f42009-09-09 15:08:12 +00001203
Chris Lattner73709ed2006-08-17 06:28:25 +00001204 // Parsing the specified input file.
Chris Lattner0bb5f832006-07-31 01:59:18 +00001205 P.ParseTranslationUnit();
Chris Lattner0bb5f832006-07-31 01:59:18 +00001206 delete PA;
1207}
Chris Lattner22eb9722006-06-18 05:43:12 +00001208
1209//===----------------------------------------------------------------------===//
Douglas Gregor9c0d38a2009-04-02 19:05:20 +00001210// Fix-It Options
1211//===----------------------------------------------------------------------===//
1212static llvm::cl::list<ParsedSourceLocation>
1213FixItAtLocations("fixit-at", llvm::cl::value_desc("source-location"),
1214 llvm::cl::desc("Perform Fix-It modifications at the given source location"));
1215
1216//===----------------------------------------------------------------------===//
Eli Friedmanf22439a2009-05-18 22:39:16 +00001217// ObjC Rewriter Options
1218//===----------------------------------------------------------------------===//
1219static llvm::cl::opt<bool>
1220SilenceRewriteMacroWarning("Wno-rewrite-macros", llvm::cl::init(false),
1221 llvm::cl::desc("Silence ObjC rewriting warnings"));
1222
1223//===----------------------------------------------------------------------===//
Eli Friedman42279c02009-05-19 01:17:04 +00001224// Warning Options
1225//===----------------------------------------------------------------------===//
1226
1227// This gets all -W options, including -Werror, -W[no-]system-headers, etc. The
1228// driver has stripped off -Wa,foo etc. The driver has also translated -W to
1229// -Wextra, so we don't need to worry about it.
1230static llvm::cl::list<std::string>
1231OptWarnings("W", llvm::cl::Prefix, llvm::cl::ValueOptional);
1232
1233static llvm::cl::opt<bool> OptPedantic("pedantic");
1234static llvm::cl::opt<bool> OptPedanticErrors("pedantic-errors");
1235static llvm::cl::opt<bool> OptNoWarnings("w");
1236
1237//===----------------------------------------------------------------------===//
Eli Friedman6af494b2009-05-19 03:06:47 +00001238// Preprocessing (-E mode) Options
1239//===----------------------------------------------------------------------===//
1240static llvm::cl::opt<bool>
1241DisableLineMarkers("P", llvm::cl::desc("Disable linemarker output in -E mode"));
1242static llvm::cl::opt<bool>
1243EnableCommentOutput("C", llvm::cl::desc("Enable comment output in -E mode"));
1244static llvm::cl::opt<bool>
1245EnableMacroCommentOutput("CC",
1246 llvm::cl::desc("Enable comment output in -E mode, "
1247 "even from macro expansions"));
1248static llvm::cl::opt<bool>
1249DumpMacros("dM", llvm::cl::desc("Print macro definitions in -E mode instead of"
1250 " normal output"));
1251static llvm::cl::opt<bool>
1252DumpDefines("dD", llvm::cl::desc("Print macro definitions in -E mode in "
1253 "addition to normal output"));
Eli Friedman33cd03c2009-05-19 03:35:57 +00001254
1255//===----------------------------------------------------------------------===//
1256// Dependency file options
1257//===----------------------------------------------------------------------===//
1258static llvm::cl::opt<std::string>
1259DependencyFile("dependency-file",
1260 llvm::cl::desc("Filename (or -) to write dependency output to"));
1261
1262static llvm::cl::opt<bool>
1263DependenciesIncludeSystemHeaders("sys-header-deps",
1264 llvm::cl::desc("Include system headers in dependency output"));
1265
1266static llvm::cl::list<std::string>
1267DependencyTargets("MT",
1268 llvm::cl::desc("Specify target for dependency"));
1269
Eli Friedman33cd03c2009-05-19 03:35:57 +00001270static llvm::cl::opt<bool>
1271PhonyDependencyTarget("MP",
1272 llvm::cl::desc("Create phony target for each dependency "
1273 "(other than main file)"));
1274
Eli Friedman6af494b2009-05-19 03:06:47 +00001275//===----------------------------------------------------------------------===//
Eli Friedman996ef2f2009-05-19 10:18:02 +00001276// Analysis options
1277//===----------------------------------------------------------------------===//
1278
1279static llvm::cl::list<Analyses>
1280AnalysisList(llvm::cl::desc("Source Code Analysis - Checks and Analyses"),
1281llvm::cl::values(
1282#define ANALYSIS(NAME, CMDFLAG, DESC, SCOPE)\
1283clEnumValN(NAME, CMDFLAG, DESC),
Eli Friedman5b5bd902009-05-19 21:10:40 +00001284#include "clang/Frontend/Analyses.def"
Eli Friedman996ef2f2009-05-19 10:18:02 +00001285clEnumValEnd));
1286
Mike Stump11289f42009-09-09 15:08:12 +00001287static llvm::cl::opt<AnalysisStores>
Eli Friedman996ef2f2009-05-19 10:18:02 +00001288AnalysisStoreOpt("analyzer-store",
1289 llvm::cl::desc("Source Code Analysis - Abstract Memory Store Models"),
1290 llvm::cl::init(BasicStoreModel),
1291 llvm::cl::values(
1292#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN)\
1293clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman5b5bd902009-05-19 21:10:40 +00001294#include "clang/Frontend/Analyses.def"
Eli Friedman996ef2f2009-05-19 10:18:02 +00001295clEnumValEnd));
1296
Mike Stump11289f42009-09-09 15:08:12 +00001297static llvm::cl::opt<AnalysisConstraints>
Eli Friedman996ef2f2009-05-19 10:18:02 +00001298AnalysisConstraintsOpt("analyzer-constraints",
1299 llvm::cl::desc("Source Code Analysis - Symbolic Constraint Engines"),
1300 llvm::cl::init(RangeConstraintsModel),
1301 llvm::cl::values(
1302#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN)\
1303clEnumValN(NAME##Model, CMDFLAG, DESC),
Eli Friedman5b5bd902009-05-19 21:10:40 +00001304#include "clang/Frontend/Analyses.def"
Eli Friedman996ef2f2009-05-19 10:18:02 +00001305clEnumValEnd));
1306
1307static llvm::cl::opt<AnalysisDiagClients>
1308AnalysisDiagOpt("analyzer-output",
1309 llvm::cl::desc("Source Code Analysis - Output Options"),
1310 llvm::cl::init(PD_HTML),
1311 llvm::cl::values(
1312#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREATE)\
1313clEnumValN(PD_##NAME, CMDFLAG, DESC),
Eli Friedman5b5bd902009-05-19 21:10:40 +00001314#include "clang/Frontend/Analyses.def"
Eli Friedman996ef2f2009-05-19 10:18:02 +00001315clEnumValEnd));
1316
1317static llvm::cl::opt<bool>
1318VisualizeEGDot("analyzer-viz-egraph-graphviz",
1319 llvm::cl::desc("Display exploded graph using GraphViz"));
1320
1321static llvm::cl::opt<bool>
1322VisualizeEGUbi("analyzer-viz-egraph-ubigraph",
1323 llvm::cl::desc("Display exploded graph using Ubigraph"));
1324
1325static llvm::cl::opt<bool>
1326AnalyzeAll("analyzer-opt-analyze-headers",
1327 llvm::cl::desc("Force the static analyzer to analyze "
1328 "functions defined in header files"));
1329
1330static llvm::cl::opt<bool>
1331AnalyzerDisplayProgress("analyzer-display-progress",
1332 llvm::cl::desc("Emit verbose output about the analyzer's progress."));
1333
1334static llvm::cl::opt<bool>
1335PurgeDead("analyzer-purge-dead",
1336 llvm::cl::init(true),
1337 llvm::cl::desc("Remove dead symbols, bindings, and constraints before"
1338 " processing a statement."));
1339
1340static llvm::cl::opt<bool>
1341EagerlyAssume("analyzer-eagerly-assume",
1342 llvm::cl::init(false),
1343 llvm::cl::desc("Eagerly assume the truth/falseness of some "
1344 "symbolic constraints."));
1345
1346static llvm::cl::opt<std::string>
1347AnalyzeSpecificFunction("analyze-function",
1348 llvm::cl::desc("Run analysis on specific function"));
1349
1350static llvm::cl::opt<bool>
1351TrimGraph("trim-egraph",
1352 llvm::cl::desc("Only show error-related paths in the analysis graph"));
1353
1354static AnalyzerOptions ReadAnalyzerOptions() {
1355 AnalyzerOptions Opts;
1356 Opts.AnalysisList = AnalysisList;
1357 Opts.AnalysisStoreOpt = AnalysisStoreOpt;
1358 Opts.AnalysisConstraintsOpt = AnalysisConstraintsOpt;
1359 Opts.AnalysisDiagOpt = AnalysisDiagOpt;
1360 Opts.VisualizeEGDot = VisualizeEGDot;
1361 Opts.VisualizeEGUbi = VisualizeEGUbi;
1362 Opts.AnalyzeAll = AnalyzeAll;
1363 Opts.AnalyzerDisplayProgress = AnalyzerDisplayProgress;
1364 Opts.PurgeDead = PurgeDead;
1365 Opts.EagerlyAssume = EagerlyAssume;
1366 Opts.AnalyzeSpecificFunction = AnalyzeSpecificFunction;
1367 Opts.TrimGraph = TrimGraph;
1368 return Opts;
1369}
1370
1371//===----------------------------------------------------------------------===//
Chris Lattner63952852009-04-17 21:05:01 +00001372// -dump-build-information Stuff
1373//===----------------------------------------------------------------------===//
1374
1375static llvm::cl::opt<std::string>
1376DumpBuildInformation("dump-build-information",
1377 llvm::cl::value_desc("filename"),
1378 llvm::cl::desc("output a dump of some build information to a file"));
1379
1380static llvm::raw_ostream *BuildLogFile = 0;
1381
1382/// LoggingDiagnosticClient - This is a simple diagnostic client that forwards
1383/// all diagnostics to both BuildLogFile and a chained DiagnosticClient.
1384namespace {
1385class LoggingDiagnosticClient : public DiagnosticClient {
1386 llvm::OwningPtr<DiagnosticClient> Chain1;
1387 llvm::OwningPtr<DiagnosticClient> Chain2;
1388public:
Mike Stump11289f42009-09-09 15:08:12 +00001389
Daniel Dunbar1de78552009-11-09 22:45:57 +00001390 LoggingDiagnosticClient(const DiagnosticOptions &DiagOpts,
Daniel Dunbarb2eae892009-11-09 20:55:08 +00001391 DiagnosticClient *Normal) {
Chris Lattner63952852009-04-17 21:05:01 +00001392 // Output diags both where requested...
1393 Chain1.reset(Normal);
1394 // .. and to our log file.
Daniel Dunbar1de78552009-11-09 22:45:57 +00001395 Chain2.reset(new TextDiagnosticPrinter(*BuildLogFile, DiagOpts));
Chris Lattner63952852009-04-17 21:05:01 +00001396 }
Mike Stump11289f42009-09-09 15:08:12 +00001397
Daniel Dunbar02318952009-11-05 02:42:12 +00001398 virtual void BeginSourceFile(const LangOptions &LO) {
1399 Chain1->BeginSourceFile(LO);
1400 Chain2->BeginSourceFile(LO);
1401 }
1402
1403 virtual void EndSourceFile() {
1404 Chain1->EndSourceFile();
1405 Chain2->EndSourceFile();
Chris Lattner63952852009-04-17 21:05:01 +00001406 }
Mike Stump11289f42009-09-09 15:08:12 +00001407
Chris Lattner63952852009-04-17 21:05:01 +00001408 virtual bool IncludeInDiagnosticCounts() const {
1409 return Chain1->IncludeInDiagnosticCounts();
1410 }
1411
1412 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1413 const DiagnosticInfo &Info) {
1414 Chain1->HandleDiagnostic(DiagLevel, Info);
1415 Chain2->HandleDiagnostic(DiagLevel, Info);
1416 }
1417};
1418} // end anonymous namespace.
1419
Daniel Dunbar1de78552009-11-09 22:45:57 +00001420static void SetUpBuildDumpLog(const DiagnosticOptions &DiagOpts,
Daniel Dunbarb2eae892009-11-09 20:55:08 +00001421 unsigned argc, char **argv,
Chris Lattner63952852009-04-17 21:05:01 +00001422 llvm::OwningPtr<DiagnosticClient> &DiagClient) {
Mike Stump11289f42009-09-09 15:08:12 +00001423
Chris Lattner63952852009-04-17 21:05:01 +00001424 std::string ErrorInfo;
Chris Lattner84cffc22009-08-23 02:59:41 +00001425 BuildLogFile = new llvm::raw_fd_ostream(DumpBuildInformation.c_str(),
Dan Gohmana98e0e72009-08-25 15:36:09 +00001426 ErrorInfo);
Mike Stump11289f42009-09-09 15:08:12 +00001427
Chris Lattner63952852009-04-17 21:05:01 +00001428 if (!ErrorInfo.empty()) {
1429 llvm::errs() << "error opening -dump-build-information file '"
1430 << DumpBuildInformation << "', option ignored!\n";
1431 delete BuildLogFile;
1432 BuildLogFile = 0;
1433 DumpBuildInformation = "";
1434 return;
1435 }
1436
1437 (*BuildLogFile) << "clang-cc command line arguments: ";
1438 for (unsigned i = 0; i != argc; ++i)
1439 (*BuildLogFile) << argv[i] << ' ';
1440 (*BuildLogFile) << '\n';
Mike Stump11289f42009-09-09 15:08:12 +00001441
Chris Lattner63952852009-04-17 21:05:01 +00001442 // LoggingDiagnosticClient - Insert a new logging diagnostic client in between
1443 // the diagnostic producers and the normal receiver.
Daniel Dunbar1de78552009-11-09 22:45:57 +00001444 DiagClient.reset(new LoggingDiagnosticClient(DiagOpts, DiagClient.take()));
Chris Lattner63952852009-04-17 21:05:01 +00001445}
1446
1447
1448
1449//===----------------------------------------------------------------------===//
Chris Lattner22eb9722006-06-18 05:43:12 +00001450// Main driver
1451//===----------------------------------------------------------------------===//
1452
Daniel Dunbarb2eae892009-11-09 20:55:08 +00001453static llvm::raw_ostream *ComputeOutFile(const CompilerInvocation &CompOpts,
1454 const std::string &InFile,
Chris Lattner84cffc22009-08-23 02:59:41 +00001455 const char *Extension,
Eli Friedman94cf21e2009-05-18 22:20:00 +00001456 bool Binary,
1457 llvm::sys::Path& OutPath) {
Chris Lattner84cffc22009-08-23 02:59:41 +00001458 llvm::raw_ostream *Ret;
Eli Friedman94cf21e2009-05-18 22:20:00 +00001459 std::string OutFile;
Daniel Dunbarb2eae892009-11-09 20:55:08 +00001460 if (!CompOpts.getOutputFile().empty())
1461 OutFile = CompOpts.getOutputFile();
Chris Lattner84cffc22009-08-23 02:59:41 +00001462 else if (InFile == "-") {
1463 OutFile = "-";
Eli Friedman94cf21e2009-05-18 22:20:00 +00001464 } else if (Extension) {
1465 llvm::sys::Path Path(InFile);
1466 Path.eraseSuffix();
1467 Path.appendSuffix(Extension);
Chris Lattner3441b4f2009-08-23 22:45:33 +00001468 OutFile = Path.str();
Eli Friedman94cf21e2009-05-18 22:20:00 +00001469 } else {
Chris Lattner84cffc22009-08-23 02:59:41 +00001470 OutFile = "-";
Chris Lattnerbaba6fc2009-02-18 01:20:05 +00001471 }
Seo Sanghyeon76270e62007-12-24 01:52:34 +00001472
Chris Lattner84cffc22009-08-23 02:59:41 +00001473 std::string Error;
1474 Ret = new llvm::raw_fd_ostream(OutFile.c_str(), Error,
Dan Gohmana98e0e72009-08-25 15:36:09 +00001475 (Binary ? llvm::raw_fd_ostream::F_Binary : 0));
Chris Lattner84cffc22009-08-23 02:59:41 +00001476 if (!Error.empty()) {
1477 // FIXME: Don't fail this way.
1478 llvm::errs() << "ERROR: " << Error << "\n";
1479 ::exit(1);
Ted Kremeneka4c13bd2007-12-05 18:27:04 +00001480 }
Mike Stump11289f42009-09-09 15:08:12 +00001481
Chris Lattner84cffc22009-08-23 02:59:41 +00001482 if (OutFile != "-")
1483 OutPath = OutFile;
Eli Friedman94cf21e2009-05-18 22:20:00 +00001484
1485 return Ret;
Ted Kremeneka4c13bd2007-12-05 18:27:04 +00001486}
1487
Daniel Dunbarb2eae892009-11-09 20:55:08 +00001488static ASTConsumer *CreateConsumerAction(const CompilerInvocation &CompOpts,
1489 Preprocessor &PP,
Daniel Dunbar691b9332009-09-17 00:48:00 +00001490 const std::string &InFile,
1491 ProgActions PA,
1492 llvm::OwningPtr<llvm::raw_ostream> &OS,
1493 llvm::sys::Path &OutPath,
Daniel Dunbar691b9332009-09-17 00:48:00 +00001494 llvm::LLVMContext& Context) {
Ted Kremenek8ab23ad2008-10-21 00:54:44 +00001495 switch (PA) {
Bill Wendling469211a2007-06-27 03:19:45 +00001496 default:
Daniel Dunbar691b9332009-09-17 00:48:00 +00001497 return 0;
Eli Friedman94cf21e2009-05-18 22:20:00 +00001498
1499 case ASTPrint:
Daniel Dunbarb2eae892009-11-09 20:55:08 +00001500 OS.reset(ComputeOutFile(CompOpts, InFile, 0, false, OutPath));
Daniel Dunbar691b9332009-09-17 00:48:00 +00001501 return CreateASTPrinter(OS.get());
Mike Stump11289f42009-09-09 15:08:12 +00001502
Douglas Gregor7f5601e52009-05-21 20:55:50 +00001503 case ASTPrintXML:
Daniel Dunbarb2eae892009-11-09 20:55:08 +00001504 OS.reset(ComputeOutFile(CompOpts, InFile, "xml", false, OutPath));
Daniel Dunbar691b9332009-09-17 00:48:00 +00001505 return CreateASTPrinterXML(OS.get());
Douglas Gregor7f5601e52009-05-21 20:55:50 +00001506
Eli Friedman94cf21e2009-05-18 22:20:00 +00001507 case ASTDump:
Daniel Dunbar691b9332009-09-17 00:48:00 +00001508 return CreateASTDumper();
Eli Friedman94cf21e2009-05-18 22:20:00 +00001509
Eli Friedman94cf21e2009-05-18 22:20:00 +00001510 case ASTView:
Daniel Dunbar691b9332009-09-17 00:48:00 +00001511 return CreateASTViewer();
Eli Friedman94cf21e2009-05-18 22:20:00 +00001512
1513 case PrintDeclContext:
Daniel Dunbar691b9332009-09-17 00:48:00 +00001514 return CreateDeclContextPrinter();
Eli Friedman94cf21e2009-05-18 22:20:00 +00001515
Anders Carlssond9340102009-09-24 18:54:49 +00001516 case DumpRecordLayouts:
1517 return CreateRecordLayoutDumper();
1518
Eli Friedman94cf21e2009-05-18 22:20:00 +00001519 case InheritanceView:
Daniel Dunbar691b9332009-09-17 00:48:00 +00001520 return CreateInheritanceViewer(InheritanceViewCls);
Eli Friedman94cf21e2009-05-18 22:20:00 +00001521
1522 case EmitAssembly:
1523 case EmitLLVM:
Mike Stump11289f42009-09-09 15:08:12 +00001524 case EmitBC:
Eli Friedman94cf21e2009-05-18 22:20:00 +00001525 case EmitLLVMOnly: {
1526 BackendAction Act;
1527 if (ProgAction == EmitAssembly) {
1528 Act = Backend_EmitAssembly;
Daniel Dunbarb2eae892009-11-09 20:55:08 +00001529 OS.reset(ComputeOutFile(CompOpts, InFile, "s", true, OutPath));
Eli Friedman94cf21e2009-05-18 22:20:00 +00001530 } else if (ProgAction == EmitLLVM) {
1531 Act = Backend_EmitLL;
Daniel Dunbarb2eae892009-11-09 20:55:08 +00001532 OS.reset(ComputeOutFile(CompOpts, InFile, "ll", true, OutPath));
Eli Friedman94cf21e2009-05-18 22:20:00 +00001533 } else if (ProgAction == EmitLLVMOnly) {
1534 Act = Backend_EmitNothing;
1535 } else {
1536 Act = Backend_EmitBC;
Daniel Dunbarb2eae892009-11-09 20:55:08 +00001537 OS.reset(ComputeOutFile(CompOpts, InFile, "bc", true, OutPath));
Ted Kremeneka4c13bd2007-12-05 18:27:04 +00001538 }
Ted Kremenek6c780772007-12-19 22:24:34 +00001539
Daniel Dunbar691b9332009-09-17 00:48:00 +00001540 return CreateBackendConsumer(Act, PP.getDiagnostics(), PP.getLangOptions(),
Daniel Dunbar754c11e2009-11-10 16:19:45 +00001541 CompOpts.getCompileOpts(), InFile, OS.get(),
1542 Context);
Eli Friedman94cf21e2009-05-18 22:20:00 +00001543 }
1544
Daniel Dunbar691b9332009-09-17 00:48:00 +00001545 case RewriteObjC:
Daniel Dunbarb2eae892009-11-09 20:55:08 +00001546 OS.reset(ComputeOutFile(CompOpts, InFile, "cpp", true, OutPath));
Daniel Dunbar691b9332009-09-17 00:48:00 +00001547 return CreateObjCRewriter(InFile, OS.get(), PP.getDiagnostics(),
1548 PP.getLangOptions(), SilenceRewriteMacroWarning);
1549
1550 case RewriteBlocks:
1551 return CreateBlockRewriter(InFile, PP.getDiagnostics(),
1552 PP.getLangOptions());
1553 }
1554}
1555
1556/// ProcessInputFile - Process a single input file with the specified state.
1557///
Daniel Dunbarb2eae892009-11-09 20:55:08 +00001558static void ProcessInputFile(const CompilerInvocation &CompOpts,
1559 Preprocessor &PP, const std::string &InFile,
Daniel Dunbard0ba0e62009-11-04 23:56:25 +00001560 ProgActions PA,
Daniel Dunbar691b9332009-09-17 00:48:00 +00001561 llvm::LLVMContext& Context) {
1562 llvm::OwningPtr<llvm::raw_ostream> OS;
1563 llvm::OwningPtr<ASTConsumer> Consumer;
1564 bool ClearSourceMgr = false;
1565 FixItRewriter *FixItRewrite = 0;
1566 bool CompleteTranslationUnit = true;
1567 llvm::sys::Path OutPath;
1568
1569 switch (PA) {
1570 default:
Daniel Dunbarb2eae892009-11-09 20:55:08 +00001571 Consumer.reset(CreateConsumerAction(CompOpts, PP, InFile, PA, OS, OutPath,
Daniel Dunbare213db82009-11-09 22:46:17 +00001572 Context));
Daniel Dunbar691b9332009-09-17 00:48:00 +00001573
1574 if (!Consumer.get()) {
Daniel Dunbar7ad807f2009-10-29 21:05:18 +00001575 PP.getDiagnostics().Report(FullSourceLoc(),
1576 diag::err_fe_invalid_ast_action);
Daniel Dunbar691b9332009-09-17 00:48:00 +00001577 return;
1578 }
1579
1580 break;;
1581
1582 case EmitHTML:
Daniel Dunbarb2eae892009-11-09 20:55:08 +00001583 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Daniel Dunbard0ba0e62009-11-04 23:56:25 +00001584 Consumer.reset(CreateHTMLPrinter(OS.get(), PP));
Daniel Dunbar691b9332009-09-17 00:48:00 +00001585 break;
1586
1587 case RunAnalysis:
Daniel Dunbarb2eae892009-11-09 20:55:08 +00001588 Consumer.reset(CreateAnalysisConsumer(PP, CompOpts.getOutputFile(),
Daniel Dunbar691b9332009-09-17 00:48:00 +00001589 ReadAnalyzerOptions()));
1590 break;
1591
Eli Friedman94cf21e2009-05-18 22:20:00 +00001592 case GeneratePCH:
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001593 if (RelocatablePCH.getValue() && !isysroot.getNumOccurrences()) {
1594 PP.Diag(SourceLocation(), diag::err_relocatable_without_without_isysroot);
1595 RelocatablePCH.setValue(false);
1596 }
Mike Stump11289f42009-09-09 15:08:12 +00001597
Daniel Dunbarb2eae892009-11-09 20:55:08 +00001598 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001599 if (RelocatablePCH.getValue())
1600 Consumer.reset(CreatePCHGenerator(PP, OS.get(), isysroot.c_str()));
1601 else
1602 Consumer.reset(CreatePCHGenerator(PP, OS.get()));
Eli Friedman94cf21e2009-05-18 22:20:00 +00001603 CompleteTranslationUnit = false;
1604 break;
1605
Chris Lattnerfc7d4a32008-10-12 05:03:36 +00001606 case DumpRawTokens: {
Chris Lattnerf53a9612009-02-18 01:51:21 +00001607 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattnerfc7d4a32008-10-12 05:03:36 +00001608 SourceManager &SM = PP.getSourceManager();
Chris Lattnerfc7d4a32008-10-12 05:03:36 +00001609 // Start lexing the specified input file.
Chris Lattner08354fe2009-01-17 07:35:14 +00001610 Lexer RawLex(SM.getMainFileID(), SM, PP.getLangOptions());
Chris Lattnerfc7d4a32008-10-12 05:03:36 +00001611 RawLex.SetKeepWhitespaceMode(true);
1612
1613 Token RawTok;
Chris Lattnerfc7d4a32008-10-12 05:03:36 +00001614 RawLex.LexFromRawLexer(RawTok);
1615 while (RawTok.isNot(tok::eof)) {
1616 PP.DumpToken(RawTok, true);
1617 fprintf(stderr, "\n");
1618 RawLex.LexFromRawLexer(RawTok);
1619 }
1620 ClearSourceMgr = true;
1621 break;
1622 }
Chris Lattner0bb5f832006-07-31 01:59:18 +00001623 case DumpTokens: { // Token dump mode.
Chris Lattnerf53a9612009-02-18 01:51:21 +00001624 llvm::TimeRegion Timer(ClangFrontendTimer);
Chris Lattner146762e2007-07-20 16:59:19 +00001625 Token Tok;
Chris Lattnerfc7d4a32008-10-12 05:03:36 +00001626 // Start preprocessing the specified input file.
Ted Kremenek230bd912007-12-19 22:51:13 +00001627 PP.EnterMainSourceFile();
Chris Lattner0bb5f832006-07-31 01:59:18 +00001628 do {
1629 PP.Lex(Tok);
1630 PP.DumpToken(Tok, true);
Bill Wendling26e1f8c2007-06-22 22:43:15 +00001631 fprintf(stderr, "\n");
Chris Lattner3c69f122007-10-09 18:03:42 +00001632 } while (Tok.isNot(tok::eof));
Chris Lattner6b4db172007-07-22 06:05:44 +00001633 ClearSourceMgr = true;
Chris Lattner0bb5f832006-07-31 01:59:18 +00001634 break;
1635 }
Chris Lattner8575daa2009-04-27 21:45:14 +00001636 case RunPreprocessorOnly:
Chris Lattner22eb9722006-06-18 05:43:12 +00001637 break;
Mike Stump11289f42009-09-09 15:08:12 +00001638
Douglas Gregor97186b02009-04-02 23:43:50 +00001639 case GeneratePTH: {
Chris Lattnerf53a9612009-02-18 01:51:21 +00001640 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbarb2eae892009-11-09 20:55:08 +00001641 if (CompOpts.getOutputFile().empty() || CompOpts.getOutputFile() == "-") {
Eli Friedmanfcb57d52009-05-19 01:02:07 +00001642 // FIXME: Don't fail this way.
1643 // FIXME: Verify that we can actually seek in the given file.
Chris Lattner84cffc22009-08-23 02:59:41 +00001644 llvm::errs() << "ERROR: PTH requires an seekable file for output!\n";
Eli Friedmanfcb57d52009-05-19 01:02:07 +00001645 ::exit(1);
1646 }
Daniel Dunbarb2eae892009-11-09 20:55:08 +00001647 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Eli Friedmanfcb57d52009-05-19 01:02:07 +00001648 CacheTokens(PP, static_cast<llvm::raw_fd_ostream*>(OS.get()));
Ted Kremenek8ab23ad2008-10-21 00:54:44 +00001649 ClearSourceMgr = true;
1650 break;
Mike Stump11289f42009-09-09 15:08:12 +00001651 }
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001652
Chris Lattner8804f402009-04-27 22:02:30 +00001653 case PrintPreprocessedInput:
Daniel Dunbarb2eae892009-11-09 20:55:08 +00001654 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Chris Lattner22eb9722006-06-18 05:43:12 +00001655 break;
Mike Stump11289f42009-09-09 15:08:12 +00001656
Chris Lattner8575daa2009-04-27 21:45:14 +00001657 case ParseNoop:
Chris Lattner3e7bd4e2006-08-17 05:51:27 +00001658 break;
Mike Stump11289f42009-09-09 15:08:12 +00001659
Chris Lattnerf53a9612009-02-18 01:51:21 +00001660 case ParsePrintCallbacks: {
1661 llvm::TimeRegion Timer(ClangFrontendTimer);
Daniel Dunbarb2eae892009-11-09 20:55:08 +00001662 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Eli Friedmanfcb57d52009-05-19 01:02:07 +00001663 ParseFile(PP, CreatePrintParserActionsAction(PP, OS.get()));
Chris Lattner6b4db172007-07-22 06:05:44 +00001664 ClearSourceMgr = true;
Chris Lattner3e7bd4e2006-08-17 05:51:27 +00001665 break;
Chris Lattnerf53a9612009-02-18 01:51:21 +00001666 }
1667
1668 case ParseSyntaxOnly: { // -fsyntax-only
1669 llvm::TimeRegion Timer(ClangFrontendTimer);
Ted Kremenekdcb5e382008-08-08 02:46:37 +00001670 Consumer.reset(new ASTConsumer());
Ted Kremenek7e61e812007-09-17 20:49:30 +00001671 break;
Chris Lattnerf53a9612009-02-18 01:51:21 +00001672 }
Mike Stump11289f42009-09-09 15:08:12 +00001673
Chris Lattner3c04ff02008-05-08 06:52:13 +00001674 case RewriteMacros:
Daniel Dunbarb2eae892009-11-09 20:55:08 +00001675 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Eli Friedmanfcb57d52009-05-19 01:02:07 +00001676 RewriteMacrosInInput(PP, OS.get());
Chris Lattner3c04ff02008-05-08 06:52:13 +00001677 ClearSourceMgr = true;
1678 break;
Mike Stump11289f42009-09-09 15:08:12 +00001679
Eli Friedmanfcb57d52009-05-19 01:02:07 +00001680 case RewriteTest:
Daniel Dunbarb2eae892009-11-09 20:55:08 +00001681 OS.reset(ComputeOutFile(CompOpts, InFile, 0, true, OutPath));
Eli Friedmanfcb57d52009-05-19 01:02:07 +00001682 DoRewriteTest(PP, OS.get());
Chris Lattner1782da22008-10-12 05:29:20 +00001683 ClearSourceMgr = true;
1684 break;
Douglas Gregor578dae52009-04-02 01:08:08 +00001685
1686 case FixIt:
1687 llvm::TimeRegion Timer(ClangFrontendTimer);
1688 Consumer.reset(new ASTConsumer());
Douglas Gregora42bd842009-04-02 17:13:00 +00001689 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
Chris Lattner184e65d2009-04-14 23:22:57 +00001690 PP.getSourceManager(),
1691 PP.getLangOptions());
Douglas Gregor578dae52009-04-02 01:08:08 +00001692 break;
Chris Lattnerf53a9612009-02-18 01:51:21 +00001693 }
Ted Kremenek062115a2009-01-28 04:29:29 +00001694
Chris Lattner1f1e1c72009-04-27 21:25:27 +00001695 if (FixItAtLocations.size() > 0) {
1696 // Even without the "-fixit" flag, with may have some specific
1697 // locations where the user has requested fixes. Process those
1698 // locations now.
1699 if (!FixItRewrite)
1700 FixItRewrite = new FixItRewriter(PP.getDiagnostics(),
1701 PP.getSourceManager(),
1702 PP.getLangOptions());
Chris Lattner84bcc472009-03-28 01:37:17 +00001703
Chris Lattner1f1e1c72009-04-27 21:25:27 +00001704 bool AddedFixitLocation = false;
Mike Stump11289f42009-09-09 15:08:12 +00001705 for (unsigned Idx = 0, Last = FixItAtLocations.size();
Chris Lattner1f1e1c72009-04-27 21:25:27 +00001706 Idx != Last; ++Idx) {
1707 RequestedSourceLocation Requested;
Argyrios Kyrtzidis25ee5db2009-06-23 22:01:39 +00001708 if (ResolveParsedLocation(FixItAtLocations[Idx],
1709 PP.getFileManager(), Requested)) {
Chris Lattner1f1e1c72009-04-27 21:25:27 +00001710 fprintf(stderr, "FIX-IT could not find file \"%s\"\n",
1711 FixItAtLocations[Idx].FileName.c_str());
1712 } else {
1713 FixItRewrite->addFixItLocation(Requested);
1714 AddedFixitLocation = true;
Douglas Gregor9c0d38a2009-04-02 19:05:20 +00001715 }
1716 }
1717
Chris Lattner1f1e1c72009-04-27 21:25:27 +00001718 if (!AddedFixitLocation) {
1719 // All of the fix-it locations were bad. Don't fix anything.
1720 delete FixItRewrite;
1721 FixItRewrite = 0;
1722 }
1723 }
1724
1725 llvm::OwningPtr<ASTContext> ContextOwner;
Chris Lattner8575daa2009-04-27 21:45:14 +00001726 if (Consumer)
Chris Lattner84bcc472009-03-28 01:37:17 +00001727 ContextOwner.reset(new ASTContext(PP.getLangOptions(),
1728 PP.getSourceManager(),
1729 PP.getTargetInfo(),
1730 PP.getIdentifierTable(),
1731 PP.getSelectorTable(),
Chris Lattner15ba9492009-06-14 01:54:56 +00001732 PP.getBuiltinInfo(),
Douglas Gregor4621c6a2009-04-22 18:49:13 +00001733 /* FreeMemory = */ !DisableFree,
Chris Lattner15ba9492009-06-14 01:54:56 +00001734 /* size_reserve = */0));
Mike Stump11289f42009-09-09 15:08:12 +00001735
Chris Lattner8804f402009-04-27 22:02:30 +00001736 llvm::OwningPtr<PCHReader> Reader;
1737 llvm::OwningPtr<ExternalASTSource> Source;
Mike Stump11289f42009-09-09 15:08:12 +00001738
Chris Lattner8575daa2009-04-27 21:45:14 +00001739 if (!ImplicitIncludePCH.empty()) {
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001740 // If the user specified -isysroot, it will be used for relocatable PCH
1741 // files.
1742 const char *isysrootPCH = 0;
1743 if (isysroot.getNumOccurrences() != 0)
1744 isysrootPCH = isysroot.c_str();
Mike Stump11289f42009-09-09 15:08:12 +00001745
Douglas Gregor0086a5a2009-07-07 00:12:59 +00001746 Reader.reset(new PCHReader(PP, ContextOwner.get(), isysrootPCH));
Mike Stump11289f42009-09-09 15:08:12 +00001747
Chris Lattner8575daa2009-04-27 21:45:14 +00001748 // The user has asked us to include a precompiled header. Load
1749 // the precompiled header into the AST context.
Chris Lattner8575daa2009-04-27 21:45:14 +00001750 switch (Reader->ReadPCH(ImplicitIncludePCH)) {
1751 case PCHReader::Success: {
Douglas Gregorc379c072009-04-28 18:58:38 +00001752 // Set the predefines buffer as suggested by the PCH
1753 // reader. Typically, the predefines buffer will be empty.
1754 PP.setPredefines(Reader->getSuggestedPredefines());
1755
Chris Lattner8575daa2009-04-27 21:45:14 +00001756 // Attach the PCH reader to the AST context as an external AST
1757 // source, so that declarations will be deserialized from the
1758 // PCH file as needed.
Chris Lattner8804f402009-04-27 22:02:30 +00001759 if (ContextOwner) {
1760 Source.reset(Reader.take());
Douglas Gregor92863e42009-04-10 23:10:45 +00001761 ContextOwner->setExternalSource(Source);
Chris Lattner8804f402009-04-27 22:02:30 +00001762 }
Chris Lattner8575daa2009-04-27 21:45:14 +00001763 break;
Douglas Gregoref84c4b2009-04-09 22:27:44 +00001764 }
1765
Chris Lattner8575daa2009-04-27 21:45:14 +00001766 case PCHReader::Failure:
1767 // Unrecoverable failure: don't even try to process the input
1768 // file.
1769 return;
1770
1771 case PCHReader::IgnorePCH:
Douglas Gregorce1a9c52009-04-28 22:01:16 +00001772 // No suitable PCH file could be found. Return an error.
1773 return;
Chris Lattner8575daa2009-04-27 21:45:14 +00001774 }
1775
1776 // Finish preprocessor initialization. We do this now (rather
1777 // than earlier) because this initialization creates new source
1778 // location entries in the source manager, which must come after
1779 // the source location entries for the PCH file.
1780 if (InitializeSourceManager(PP, InFile))
1781 return;
Ted Kremenek062115a2009-01-28 04:29:29 +00001782 }
Daniel Dunbar938eb272009-10-29 01:53:18 +00001783
Chris Lattner8575daa2009-04-27 21:45:14 +00001784 // If we have an ASTConsumer, run the parser with it.
Douglas Gregor2436e712009-09-17 21:32:03 +00001785 if (Consumer) {
1786 CodeCompleteConsumer *(*CreateCodeCompleter)(Sema &, void *) = 0;
1787 void *CreateCodeCompleterData = 0;
Daniel Dunbar938eb272009-10-29 01:53:18 +00001788
Douglas Gregorea9b03e2009-09-22 21:11:38 +00001789 if (!CodeCompletionAt.FileName.empty()) {
1790 // Tell the source manager to chop off the given file at a specific
1791 // line and column.
Daniel Dunbar938eb272009-10-29 01:53:18 +00001792 if (const FileEntry *Entry
Douglas Gregorea9b03e2009-09-22 21:11:38 +00001793 = PP.getFileManager().getFile(CodeCompletionAt.FileName)) {
1794 // Truncate the named file at the given line/column.
1795 PP.getSourceManager().truncateFileAt(Entry, CodeCompletionAt.Line,
1796 CodeCompletionAt.Column);
Daniel Dunbar938eb272009-10-29 01:53:18 +00001797
Douglas Gregorea9b03e2009-09-22 21:11:38 +00001798 // Set up the creation routine for code-completion.
1799 CreateCodeCompleter = BuildPrintingCodeCompleter;
1800 } else {
Daniel Dunbar938eb272009-10-29 01:53:18 +00001801 PP.getDiagnostics().Report(FullSourceLoc(),
Douglas Gregorea9b03e2009-09-22 21:11:38 +00001802 diag::err_fe_invalid_code_complete_file)
1803 << CodeCompletionAt.FileName;
1804 }
Douglas Gregor2436e712009-09-17 21:32:03 +00001805 }
1806
Mike Stump11289f42009-09-09 15:08:12 +00001807 ParseAST(PP, Consumer.get(), *ContextOwner.get(), Stats,
Douglas Gregor2436e712009-09-17 21:32:03 +00001808 CompleteTranslationUnit,
1809 CreateCodeCompleter, CreateCodeCompleterData);
1810 }
Chris Lattner8575daa2009-04-27 21:45:14 +00001811
Daniel Dunbara5beced2009-11-04 23:41:40 +00001812 // Perform post processing actions and actions which don't use a consumer.
1813 switch (PA) {
1814 default: break;
1815
1816 case RunPreprocessorOnly: { // Just lex as fast as we can, no output.
Chris Lattner8575daa2009-04-27 21:45:14 +00001817 llvm::TimeRegion Timer(ClangFrontendTimer);
1818 Token Tok;
1819 // Start parsing the specified input file.
1820 PP.EnterMainSourceFile();
1821 do {
1822 PP.Lex(Tok);
1823 } while (Tok.isNot(tok::eof));
1824 ClearSourceMgr = true;
Daniel Dunbara5beced2009-11-04 23:41:40 +00001825 break;
1826 }
1827
1828 case ParseNoop: {
Chris Lattner8575daa2009-04-27 21:45:14 +00001829 llvm::TimeRegion Timer(ClangFrontendTimer);
1830 ParseFile(PP, new MinimalAction(PP));
1831 ClearSourceMgr = true;
Daniel Dunbara5beced2009-11-04 23:41:40 +00001832 break;
1833 }
1834
1835 case PrintPreprocessedInput: {
Chris Lattner8804f402009-04-27 22:02:30 +00001836 llvm::TimeRegion Timer(ClangFrontendTimer);
Eli Friedman6af494b2009-05-19 03:06:47 +00001837 if (DumpMacros)
1838 DoPrintMacros(PP, OS.get());
1839 else
1840 DoPrintPreprocessedInput(PP, OS.get(), EnableCommentOutput,
1841 EnableMacroCommentOutput,
1842 DisableLineMarkers, DumpDefines);
Chris Lattner8804f402009-04-27 22:02:30 +00001843 ClearSourceMgr = true;
Chris Lattner8575daa2009-04-27 21:45:14 +00001844 }
Mike Stump11289f42009-09-09 15:08:12 +00001845
Daniel Dunbara5beced2009-11-04 23:41:40 +00001846 }
1847
Chris Lattner1f1e1c72009-04-27 21:25:27 +00001848 if (FixItRewrite)
Daniel Dunbarb2eae892009-11-09 20:55:08 +00001849 FixItRewrite->WriteFixedFile(InFile, CompOpts.getOutputFile());
Daniel Dunbar13796e32009-07-29 02:40:09 +00001850
1851 // Disable the consumer prior to the context, the consumer may perform actions
1852 // in its destructor which require the context.
1853 if (DisableFree)
1854 Consumer.take();
1855 else
1856 Consumer.reset();
Mike Stump11289f42009-09-09 15:08:12 +00001857
Chris Lattner1f1e1c72009-04-27 21:25:27 +00001858 // If in -disable-free mode, don't deallocate ASTContext.
1859 if (DisableFree)
1860 ContextOwner.take();
1861 else
1862 ContextOwner.reset(); // Delete ASTContext
Eli Friedman94cf21e2009-05-18 22:20:00 +00001863
Daniel Dunbareb3e4142008-10-27 22:03:52 +00001864 if (VerifyDiagnostics)
Daniel Dunbar1a0625e2008-10-27 22:10:13 +00001865 if (CheckDiagnostics(PP))
1866 exit(1);
Chris Lattnerb5eda622008-02-06 01:42:25 +00001867
Chris Lattner96327ea2006-11-21 05:52:55 +00001868 if (Stats) {
Ted Kremenek6c780772007-12-19 22:24:34 +00001869 fprintf(stderr, "\nSTATISTICS FOR '%s':\n", InFile.c_str());
Chris Lattner96327ea2006-11-21 05:52:55 +00001870 PP.PrintStats();
Chris Lattnerad7cdd32006-11-21 06:08:20 +00001871 PP.getIdentifierTable().PrintStats();
Chris Lattner60a288a2007-12-15 20:48:40 +00001872 PP.getHeaderSearchInfo().PrintStats();
Ted Kremenekfeb26072009-01-09 18:20:21 +00001873 PP.getSourceManager().PrintStats();
Bill Wendling26e1f8c2007-06-22 22:43:15 +00001874 fprintf(stderr, "\n");
Chris Lattner96327ea2006-11-21 05:52:55 +00001875 }
Chris Lattner6b4db172007-07-22 06:05:44 +00001876
Mike Stump11289f42009-09-09 15:08:12 +00001877 // For a multi-file compilation, some things are ok with nuking the source
Chris Lattner6b4db172007-07-22 06:05:44 +00001878 // manager tables, other require stable fileid/macroid's across multiple
1879 // files.
Chris Lattner60a288a2007-12-15 20:48:40 +00001880 if (ClearSourceMgr)
1881 PP.getSourceManager().clearIDTables();
Daniel Dunbara94d8732008-11-11 06:35:39 +00001882
Eli Friedman94cf21e2009-05-18 22:20:00 +00001883 // Always delete the output stream because we don't want to leak file
1884 // handles. Also, we don't want to try to erase an open file.
1885 OS.reset();
1886
Daniel Dunbar7ad807f2009-10-29 21:05:18 +00001887 // If we had errors, try to erase the output file.
1888 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Eli Friedman94cf21e2009-05-18 22:20:00 +00001889 OutPath.eraseFromDisk();
Chris Lattner96327ea2006-11-21 05:52:55 +00001890}
1891
Daniel Dunbare9fee8a2009-09-17 00:48:13 +00001892/// ProcessInputFile - Process a single AST input file with the specified state.
1893///
Daniel Dunbarb2eae892009-11-09 20:55:08 +00001894static void ProcessASTInputFile(const CompilerInvocation &CompOpts,
1895 const std::string &InFile, ProgActions PA,
Daniel Dunbare9fee8a2009-09-17 00:48:13 +00001896 Diagnostic &Diags, FileManager &FileMgr,
1897 llvm::LLVMContext& Context) {
Daniel Dunbare9fee8a2009-09-17 00:48:13 +00001898 std::string Error;
Steve Naroff505fb842009-10-19 14:34:22 +00001899 llvm::OwningPtr<ASTUnit> AST(ASTUnit::LoadFromPCHFile(InFile, &Error));
Daniel Dunbare9fee8a2009-09-17 00:48:13 +00001900 if (!AST) {
1901 Diags.Report(FullSourceLoc(), diag::err_fe_invalid_ast_file) << Error;
1902 return;
1903 }
1904
1905 Preprocessor &PP = AST->getPreprocessor();
1906
1907 llvm::OwningPtr<llvm::raw_ostream> OS;
1908 llvm::sys::Path OutPath;
Daniel Dunbarb2eae892009-11-09 20:55:08 +00001909 llvm::OwningPtr<ASTConsumer> Consumer(CreateConsumerAction(CompOpts, PP,
1910 InFile, PA, OS,
Daniel Dunbare213db82009-11-09 22:46:17 +00001911 OutPath, Context));
Daniel Dunbare9fee8a2009-09-17 00:48:13 +00001912
1913 if (!Consumer.get()) {
1914 Diags.Report(FullSourceLoc(), diag::err_fe_invalid_ast_action);
1915 return;
1916 }
1917
Daniel Dunbar26e37a72009-09-21 03:03:56 +00001918 // Set the main file ID to an empty file.
1919 //
1920 // FIXME: We probably shouldn't need this, but for now this is the simplest
1921 // way to reuse the logic in ParseAST.
1922 const char *EmptyStr = "";
1923 llvm::MemoryBuffer *SB =
1924 llvm::MemoryBuffer::getMemBuffer(EmptyStr, EmptyStr, "<dummy input>");
1925 AST->getSourceManager().createMainFileIDForMemBuffer(SB);
Daniel Dunbare9fee8a2009-09-17 00:48:13 +00001926
Daniel Dunbar26e37a72009-09-21 03:03:56 +00001927 // Stream the input AST to the consumer.
Daniel Dunbar02318952009-11-05 02:42:12 +00001928 Diags.getClient()->BeginSourceFile(PP.getLangOptions());
Daniel Dunbar26e37a72009-09-21 03:03:56 +00001929 ParseAST(PP, Consumer.get(), AST->getASTContext(), Stats);
Daniel Dunbar02318952009-11-05 02:42:12 +00001930 Diags.getClient()->EndSourceFile();
Daniel Dunbare9fee8a2009-09-17 00:48:13 +00001931
1932 // Release the consumer and the AST, in that order since the consumer may
1933 // perform actions in its destructor which require the context.
1934 if (DisableFree) {
1935 Consumer.take();
1936 AST.take();
1937 } else {
1938 Consumer.reset();
1939 AST.reset();
1940 }
1941
1942 // Always delete the output stream because we don't want to leak file
1943 // handles. Also, we don't want to try to erase an open file.
1944 OS.reset();
1945
Daniel Dunbar7ad807f2009-10-29 21:05:18 +00001946 // If we had errors, try to erase the output file.
1947 if (PP.getDiagnostics().getNumErrors() && !OutPath.isEmpty())
Daniel Dunbare9fee8a2009-09-17 00:48:13 +00001948 OutPath.eraseFromDisk();
Daniel Dunbare9fee8a2009-09-17 00:48:13 +00001949}
1950
Chris Lattner23b7eb62007-06-15 23:05:46 +00001951static llvm::cl::list<std::string>
1952InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input files>"));
Chris Lattner96327ea2006-11-21 05:52:55 +00001953
Daniel Dunbar71f22e72009-08-10 03:40:28 +00001954static void LLVMErrorHandler(void *UserData, const std::string &Message) {
1955 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
1956
1957 Diags.Report(FullSourceLoc(), diag::err_fe_error_backend) << Message;
1958
1959 // We cannot recover from llvm errors.
1960 exit(1);
1961}
1962
Daniel Dunbar1de78552009-11-09 22:45:57 +00001963static LangKind GetLanguage() {
1964 // If -x was given, that's the language.
1965 if (BaseLang != langkind_unspecified)
1966 return BaseLang;
Daniel Dunbarb2eae892009-11-09 20:55:08 +00001967
Daniel Dunbar1de78552009-11-09 22:45:57 +00001968 // Otherwise guess it from the input filenames;
1969 LangKind LK = langkind_unspecified;
1970 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
1971 llvm::StringRef Name(InputFilenames[i]);
1972 LangKind ThisKind = llvm::StringSwitch<LangKind>(Name.rsplit('.').second)
1973 .Case("ast", langkind_ast)
1974 .Case("c", langkind_c)
1975 .Cases("S", "s", langkind_asm_cpp)
1976 .Case("i", langkind_c_cpp)
1977 .Case("ii", langkind_cxx_cpp)
1978 .Case("m", langkind_objc)
1979 .Case("mi", langkind_objc_cpp)
1980 .Cases("mm", "M", langkind_objcxx)
1981 .Case("mii", langkind_objcxx_cpp)
1982 .Case("C", langkind_cxx)
1983 .Cases("C", "cc", "cp", langkind_cxx)
1984 .Cases("cpp", "CPP", "c++", "cxx", langkind_cxx)
1985 .Case("cl", langkind_ocl)
1986 .Default(langkind_c);
1987
1988 if (LK != langkind_unspecified && ThisKind != LK) {
1989 llvm::errs() << "error: cannot have multiple input files of distinct "
1990 << "language kinds without -x\n";
1991 exit(1);
1992 }
1993
1994 LK = ThisKind;
1995 }
1996
1997 return LK;
1998}
1999
2000static void ConstructDiagnosticOptions(DiagnosticOptions &Opts) {
Daniel Dunbarb2eae892009-11-09 20:55:08 +00002001 // Initialize the diagnostic options.
Daniel Dunbar1de78552009-11-09 22:45:57 +00002002 Opts.ShowColumn = !NoShowColumn;
2003 Opts.ShowLocation = !NoShowLocation;
2004 Opts.ShowCarets = !NoCaretDiagnostics;
2005 Opts.ShowFixits = !NoDiagnosticsFixIt;
2006 Opts.ShowSourceRanges = PrintSourceRangeInfo;
2007 Opts.ShowOptionNames = PrintDiagnosticOption;
2008 Opts.ShowColors = PrintColorDiagnostic;
2009 Opts.MessageLength = MessageLength;
2010}
2011
Daniel Dunbarf89a32a2009-11-10 19:51:53 +00002012static void FinalizeCompileOptions(CompileOptions &Opts,
2013 const LangOptions &Lang) {
2014 if (Lang.NoBuiltin)
2015 Opts.SimplifyLibCalls = 0;
2016 if (Lang.CPlusPlus)
2017 Opts.NoCommon = 1;
2018
2019 // Handle -ftime-report.
2020 Opts.TimePasses = TimeReport;
2021}
2022
Daniel Dunbar1de78552009-11-09 22:45:57 +00002023static void ConstructCompilerInvocation(CompilerInvocation &Opts,
Daniel Dunbare213db82009-11-09 22:46:17 +00002024 const char *Argv0,
Daniel Dunbar1de78552009-11-09 22:45:57 +00002025 const DiagnosticOptions &DiagOpts,
Daniel Dunbare213db82009-11-09 22:46:17 +00002026 TargetInfo &Target,
2027 LangKind LK) {
Daniel Dunbar1de78552009-11-09 22:45:57 +00002028 Opts.getDiagnosticOpts() = DiagOpts;
2029
2030 Opts.getOutputFile() = OutputFile;
Daniel Dunbare213db82009-11-09 22:46:17 +00002031
2032 // Compute the feature set, which may effect the language.
2033 ComputeFeatureMap(Target, Opts.getTargetFeatures());
Daniel Dunbar754c11e2009-11-10 16:19:45 +00002034
Daniel Dunbaref2919f2009-11-10 18:47:35 +00002035 // Initialize backend options, which may also be used to key some language
2036 // options.
2037 InitializeCompileOptions(Opts.getCompileOpts(), Opts.getTargetFeatures());
2038
Daniel Dunbare213db82009-11-09 22:46:17 +00002039 // Initialize language options.
2040 LangOptions LangInfo;
Daniel Dunbar754c11e2009-11-10 16:19:45 +00002041
Daniel Dunbare213db82009-11-09 22:46:17 +00002042 // FIXME: These aren't used during operations on ASTs. Split onto a separate
2043 // code path to make this obvious.
2044 if (LK != langkind_ast) {
2045 InitializeLangOptions(Opts.getLangOpts(), LK);
2046 InitializeLanguageStandard(Opts.getLangOpts(), LK, Target,
Daniel Dunbara35a2cb2009-11-10 19:51:33 +00002047 Opts.getCompileOpts(), Opts.getTargetFeatures());
Daniel Dunbare213db82009-11-09 22:46:17 +00002048 }
2049
2050 // Initialize the header search options.
2051 InitializeIncludePaths(Opts.getHeaderSearchOpts(), Argv0, Opts.getLangOpts());
Daniel Dunbar60198df2009-11-09 23:12:31 +00002052
2053 // Initialize the other preprocessor options.
2054 InitializePreprocessorOptions(Opts.getPreprocessorOpts());
Daniel Dunbar754c11e2009-11-10 16:19:45 +00002055
Daniel Dunbarf89a32a2009-11-10 19:51:53 +00002056 // Finalize some code generation options.
Daniel Dunbaref2919f2009-11-10 18:47:35 +00002057 FinalizeCompileOptions(Opts.getCompileOpts(), Opts.getLangOpts());
Daniel Dunbarb2eae892009-11-09 20:55:08 +00002058}
2059
Chris Lattner96327ea2006-11-21 05:52:55 +00002060int main(int argc, char **argv) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00002061 llvm::sys::PrintStackTraceOnErrorSignal();
Chris Lattner07e85f32009-03-04 21:41:39 +00002062 llvm::PrettyStackTraceProgram X(argc, argv);
Owen Anderson9f98d372009-07-16 00:14:12 +00002063 llvm::LLVMContext &Context = llvm::getGlobalContext();
Daniel Dunbar12688512009-09-02 23:20:15 +00002064
Daniel Dunbar57f22242009-09-03 04:54:12 +00002065 // Initialize targets first, so that --version shows registered targets.
Chris Lattnera0e4ded2009-06-17 17:25:50 +00002066 llvm::InitializeAllTargets();
2067 llvm::InitializeAllAsmPrinters();
Daniel Dunbar12688512009-09-02 23:20:15 +00002068
2069 llvm::cl::ParseCommandLineOptions(argc, argv,
2070 "LLVM 'Clang' Compiler: http://clang.llvm.org\n");
Mike Stump11289f42009-09-09 15:08:12 +00002071
Chris Lattnerf53a9612009-02-18 01:51:21 +00002072 if (TimeReport)
2073 ClangFrontendTimer = new llvm::Timer("Clang front-end time");
Mike Stump11289f42009-09-09 15:08:12 +00002074
Daniel Dunbar044a7022009-05-28 16:37:33 +00002075 if (Verbose)
Mike Stumpa1874a92009-09-15 21:49:22 +00002076 llvm::errs() << "clang-cc version " CLANG_VERSION_STRING
2077 << " based upon " << PACKAGE_STRING
Daniel Dunbar0da4a5d2009-09-04 17:43:10 +00002078 << " hosted on " << llvm::sys::getHostTriple() << "\n";
Mike Stump11289f42009-09-09 15:08:12 +00002079
Chris Lattner96327ea2006-11-21 05:52:55 +00002080 // If no input was specified, read from stdin.
2081 if (InputFilenames.empty())
2082 InputFilenames.push_back("-");
Douglas Gregor637f5f72009-05-02 00:03:46 +00002083
Daniel Dunbar1de78552009-11-09 22:45:57 +00002084 // Construct the diagnostic options first, which cannot fail, so that we can
2085 // build a diagnostic client to use for any errors during option handling.
2086 DiagnosticOptions DiagOpts;
2087 ConstructDiagnosticOptions(DiagOpts);
Daniel Dunbarc2e6a472009-11-04 06:24:30 +00002088
Ted Kremenekfc095b12007-12-11 23:28:38 +00002089 // Create the diagnostic client for reporting errors or for
2090 // implementing -verify.
Chris Lattner25ef69a2009-04-17 20:40:01 +00002091 llvm::OwningPtr<DiagnosticClient> DiagClient;
2092 if (VerifyDiagnostics) {
2093 // When checking diagnostics, just buffer them up.
2094 DiagClient.reset(new TextDiagnosticBuffer());
2095 if (InputFilenames.size() != 1) {
Daniel Dunbar1de78552009-11-09 22:45:57 +00002096 fprintf(stderr, "-verify only works on single input files.\n");
Chris Lattner25ef69a2009-04-17 20:40:01 +00002097 return 1;
2098 }
Ted Kremenek31691ae2008-08-07 17:49:57 +00002099 } else {
Daniel Dunbar1de78552009-11-09 22:45:57 +00002100 DiagClient.reset(new TextDiagnosticPrinter(llvm::errs(), DiagOpts));
Chris Lattner23e63532007-06-28 04:54:17 +00002101 }
Mike Stump11289f42009-09-09 15:08:12 +00002102
Daniel Dunbaraef52f42009-11-05 02:11:37 +00002103 if (!DumpBuildInformation.empty())
Daniel Dunbar1de78552009-11-09 22:45:57 +00002104 SetUpBuildDumpLog(DiagOpts, argc, argv, DiagClient);
Ted Kremenek31691ae2008-08-07 17:49:57 +00002105
Chris Lattner23e63532007-06-28 04:54:17 +00002106 // Configure our handling of diagnostics.
Ted Kremenek31691ae2008-08-07 17:49:57 +00002107 Diagnostic Diags(DiagClient.get());
Eli Friedman42279c02009-05-19 01:17:04 +00002108 if (ProcessWarningOptions(Diags, OptWarnings, OptPedantic, OptPedanticErrors,
2109 OptNoWarnings))
Sebastian Redl48350102009-03-06 17:41:35 +00002110 return 1;
Ted Kremenekfc095b12007-12-11 23:28:38 +00002111
Daniel Dunbar71f22e72009-08-10 03:40:28 +00002112 // Set an error handler, so that any LLVM backend diagnostics go through our
2113 // error handler.
2114 llvm::llvm_install_error_handler(LLVMErrorHandler,
2115 static_cast<void*>(&Diags));
2116
Daniel Dunbarf3355a62009-10-30 18:12:31 +00002117 // Initialize base triple. If a -triple option has been specified, use
2118 // that triple. Otherwise, default to the host triple.
2119 llvm::Triple Triple(TargetTriple);
2120 if (Triple.getTriple().empty())
2121 Triple = llvm::Triple(llvm::sys::getHostTriple());
2122
Chris Lattnere8ec2802008-03-14 06:12:05 +00002123 // Get information about the target being compiled for.
Daniel Dunbar938eb272009-10-29 01:53:18 +00002124 llvm::OwningPtr<TargetInfo>
Chris Lattner46d90f72009-09-12 22:45:58 +00002125 Target(TargetInfo::CreateTargetInfo(Triple.getTriple()));
Mike Stump11289f42009-09-09 15:08:12 +00002126
Chris Lattnere8ec2802008-03-14 06:12:05 +00002127 if (Target == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00002128 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_triple)
Chris Lattner46d90f72009-09-12 22:45:58 +00002129 << Triple.getTriple().c_str();
Sebastian Redlecc54442009-03-07 12:09:25 +00002130 return 1;
Chris Lattnere8ec2802008-03-14 06:12:05 +00002131 }
Mike Stump11289f42009-09-09 15:08:12 +00002132
Daniel Dunbar4e97bc32009-09-14 00:02:12 +00002133 // Set the target ABI if specified.
2134 if (!TargetABI.empty()) {
2135 if (!Target->setABI(TargetABI)) {
2136 Diags.Report(FullSourceLoc(), diag::err_fe_unknown_target_abi)
2137 << TargetABI;
2138 return 1;
2139 }
2140 }
2141
Daniel Dunbar34fc92f2009-01-20 23:17:32 +00002142 if (!InheritanceViewCls.empty()) // C++ visualization?
Ted Kremenek45e2b902008-10-23 23:36:29 +00002143 ProgAction = InheritanceView;
Mike Stump11289f42009-09-09 15:08:12 +00002144
Daniel Dunbar1de78552009-11-09 22:45:57 +00002145 // Infer the input language.
2146 //
2147 // FIXME: We should move .ast inputs to taking a separate path, they are
2148 // really quite different.
2149 LangKind LK = GetLanguage();
2150
2151 // Now that we have initialized the diagnostics engine and the target, finish
2152 // setting up the compiler invocation.
2153 CompilerInvocation CompOpts;
Daniel Dunbare213db82009-11-09 22:46:17 +00002154 ConstructCompilerInvocation(CompOpts, argv[0], DiagOpts, *Target, LK);
Daniel Dunbar1de78552009-11-09 22:45:57 +00002155
Daniel Dunbarc00be152009-11-05 01:53:23 +00002156 // Create the source manager.
2157 SourceManager SourceMgr;
Mike Stump11289f42009-09-09 15:08:12 +00002158
Chris Lattner184e65d2009-04-14 23:22:57 +00002159 // Create a file manager object to provide access to and cache the filesystem.
2160 FileManager FileMgr;
Douglas Gregorc5046832009-04-27 18:38:38 +00002161
Chris Lattner23e63532007-06-28 04:54:17 +00002162 for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
Ted Kremenekfc095b12007-12-11 23:28:38 +00002163 const std::string &InFile = InputFilenames[i];
Mike Stump11289f42009-09-09 15:08:12 +00002164
Daniel Dunbare9fee8a2009-09-17 00:48:13 +00002165 // AST inputs are handled specially.
2166 if (LK == langkind_ast) {
Daniel Dunbare213db82009-11-09 22:46:17 +00002167 ProcessASTInputFile(CompOpts, InFile, ProgAction, Diags, FileMgr,
2168 Context);
Daniel Dunbare9fee8a2009-09-17 00:48:13 +00002169 continue;
2170 }
2171
Daniel Dunbarc00be152009-11-05 01:53:23 +00002172 // Reset the ID tables if we are reusing the SourceManager.
2173 if (i)
2174 SourceMgr.clearIDTables();
Mike Stump11289f42009-09-09 15:08:12 +00002175
Chris Lattner20fc2072009-03-04 21:40:56 +00002176 // Process the -I options and set them in the HeaderInfo.
2177 HeaderSearch HeaderInfo(FileMgr);
Mike Stump11289f42009-09-09 15:08:12 +00002178
Daniel Dunbare213db82009-11-09 22:46:17 +00002179 // Apply all the options to the header search object.
2180 ApplyHeaderSearchOptions(CompOpts.getHeaderSearchOpts(), HeaderInfo,
2181 CompOpts.getLangOpts(), Triple);
Mike Stump11289f42009-09-09 15:08:12 +00002182
Chris Lattner20fc2072009-03-04 21:40:56 +00002183 // Set up the preprocessor with these options.
Daniel Dunbar60198df2009-11-09 23:12:31 +00002184 llvm::OwningPtr<Preprocessor>
2185 PP(CreatePreprocessor(Diags, CompOpts.getLangOpts(),
2186 CompOpts.getPreprocessorOpts(), *Target, SourceMgr,
2187 HeaderInfo));
Ted Kremenek31691ae2008-08-07 17:49:57 +00002188
Daniel Dunbar7ad807f2009-10-29 21:05:18 +00002189 // Handle generating dependencies, if requested.
Eli Friedman33cd03c2009-05-19 03:35:57 +00002190 if (!DependencyFile.empty()) {
Eli Friedman33cd03c2009-05-19 03:35:57 +00002191 if (DependencyTargets.empty()) {
Daniel Dunbar7ad807f2009-10-29 21:05:18 +00002192 Diags.Report(FullSourceLoc(), diag::err_fe_dependency_file_requires_MT);
Eli Friedman33cd03c2009-05-19 03:35:57 +00002193 continue;
2194 }
2195 std::string ErrStr;
Daniel Dunbar7ad807f2009-10-29 21:05:18 +00002196 llvm::raw_ostream *DependencyOS =
Dan Gohmana98e0e72009-08-25 15:36:09 +00002197 new llvm::raw_fd_ostream(DependencyFile.c_str(), ErrStr);
Eli Friedman33cd03c2009-05-19 03:35:57 +00002198 if (!ErrStr.empty()) {
Daniel Dunbar7ad807f2009-10-29 21:05:18 +00002199 Diags.Report(FullSourceLoc(), diag::err_fe_error_opening)
2200 << DependencyFile << ErrStr;
Eli Friedman33cd03c2009-05-19 03:35:57 +00002201 continue;
2202 }
2203
2204 AttachDependencyFileGen(PP.get(), DependencyOS, DependencyTargets,
2205 DependenciesIncludeSystemHeaders,
2206 PhonyDependencyTarget);
2207 }
2208
Chris Lattner15ba9492009-06-14 01:54:56 +00002209 if (ImplicitIncludePCH.empty()) {
2210 if (InitializeSourceManager(*PP.get(), InFile))
2211 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002212
Chris Lattner15ba9492009-06-14 01:54:56 +00002213 // Initialize builtin info.
2214 PP->getBuiltinInfo().InitializeBuiltins(PP->getIdentifierTable(),
Chris Lattner15ba9492009-06-14 01:54:56 +00002215 PP->getLangOptions().NoBuiltin);
2216 }
Douglas Gregora7f71a92009-04-10 03:52:48 +00002217
Chris Lattner20fc2072009-03-04 21:40:56 +00002218 // Process the source file.
Daniel Dunbare213db82009-11-09 22:46:17 +00002219 Diags.getClient()->BeginSourceFile(CompOpts.getLangOpts());
2220 ProcessInputFile(CompOpts, *PP, InFile, ProgAction, Context);
Daniel Dunbar1de78552009-11-09 22:45:57 +00002221 Diags.getClient()->EndSourceFile();
Mike Stump11289f42009-09-09 15:08:12 +00002222
Chris Lattnerc6b56132009-04-17 20:16:08 +00002223 HeaderInfo.ClearFileInfo();
Chris Lattner23e63532007-06-28 04:54:17 +00002224 }
Chris Lattnere8ec2802008-03-14 06:12:05 +00002225
Daniel Dunbar19040152009-11-10 00:46:12 +00002226 if (CompOpts.getDiagnosticOpts().ShowCarets)
Mike Stump6ea352a2009-04-28 01:19:10 +00002227 if (unsigned NumDiagnostics = Diags.getNumDiagnostics())
2228 fprintf(stderr, "%d diagnostic%s generated.\n", NumDiagnostics,
2229 (NumDiagnostics == 1 ? "" : "s"));
Mike Stump11289f42009-09-09 15:08:12 +00002230
Chris Lattner22eb9722006-06-18 05:43:12 +00002231 if (Stats) {
Chris Lattnerad7cdd32006-11-21 06:08:20 +00002232 FileMgr.PrintStats();
Bill Wendling26e1f8c2007-06-22 22:43:15 +00002233 fprintf(stderr, "\n");
Chris Lattner22eb9722006-06-18 05:43:12 +00002234 }
Chris Lattner63952852009-04-17 21:05:01 +00002235
2236 delete ClangFrontendTimer;
2237 delete BuildLogFile;
Mike Stump11289f42009-09-09 15:08:12 +00002238
Daniel Dunbar1a0625e2008-10-27 22:10:13 +00002239 // If verifying diagnostics and we reached here, all is well.
2240 if (VerifyDiagnostics)
2241 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002242
Daniel Dunbar460f8ee2008-10-28 00:38:08 +00002243 // Managed static deconstruction. Useful for making things like
2244 // -time-passes usable.
2245 llvm::llvm_shutdown();
2246
Daniel Dunbar7ad807f2009-10-29 21:05:18 +00002247 return (Diags.getNumErrors() != 0);
Chris Lattner22eb9722006-06-18 05:43:12 +00002248}