InitPreprocessor.cpp revision 200583
1//===--- InitPreprocessor.cpp - PP initialization code. ---------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the clang::InitializePreprocessor function.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Frontend/Utils.h"
15#include "clang/Basic/TargetInfo.h"
16#include "clang/Frontend/FrontendDiagnostic.h"
17#include "clang/Frontend/PreprocessorOptions.h"
18#include "clang/Lex/Preprocessor.h"
19#include "clang/Basic/FileManager.h"
20#include "clang/Basic/SourceManager.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/ADT/StringMap.h"
23#include "llvm/ADT/STLExtras.h"
24#include "llvm/Support/MemoryBuffer.h"
25#include "llvm/System/Path.h"
26using namespace clang;
27
28// Append a #define line to Buf for Macro.  Macro should be of the form XXX,
29// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
30// "#define XXX Y z W".  To get a #define with no value, use "XXX=".
31static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
32                               Diagnostic *Diags = 0) {
33  const char *Command = "#define ";
34  Buf.insert(Buf.end(), Command, Command+strlen(Command));
35  if (const char *Equal = strchr(Macro, '=')) {
36    // Turn the = into ' '.
37    Buf.insert(Buf.end(), Macro, Equal);
38    Buf.push_back(' ');
39
40    // Per GCC -D semantics, the macro ends at \n if it exists.
41    const char *End = strpbrk(Equal, "\n\r");
42    if (End) {
43      assert(Diags && "Unexpected macro with embedded newline!");
44      Diags->Report(diag::warn_fe_macro_contains_embedded_newline)
45        << std::string(Macro, Equal);
46    } else {
47      End = Equal+strlen(Equal);
48    }
49
50    Buf.insert(Buf.end(), Equal+1, End);
51  } else {
52    // Push "macroname 1".
53    Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
54    Buf.push_back(' ');
55    Buf.push_back('1');
56  }
57  Buf.push_back('\n');
58}
59
60// Append a #undef line to Buf for Macro.  Macro should be of the form XXX
61// and we emit "#undef XXX".
62static void UndefineBuiltinMacro(std::vector<char> &Buf, const char *Macro) {
63  // Push "macroname".
64  const char *Command = "#undef ";
65  Buf.insert(Buf.end(), Command, Command+strlen(Command));
66  Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
67  Buf.push_back('\n');
68}
69
70std::string clang::NormalizeDashIncludePath(llvm::StringRef File) {
71  // Implicit include paths should be resolved relative to the current
72  // working directory first, and then use the regular header search
73  // mechanism. The proper way to handle this is to have the
74  // predefines buffer located at the current working directory, but
75  // it has not file entry. For now, workaround this by using an
76  // absolute path if we find the file here, and otherwise letting
77  // header search handle it.
78  llvm::sys::Path Path(File);
79  Path.makeAbsolute();
80  if (!Path.exists())
81    Path = File;
82
83  return Lexer::Stringify(Path.str());
84}
85
86/// Add the quoted name of an implicit include file.
87static void AddQuotedIncludePath(std::vector<char> &Buf,
88                                 const std::string &File) {
89
90  // Escape double quotes etc.
91  Buf.push_back('"');
92  std::string EscapedFile = NormalizeDashIncludePath(File);
93  Buf.insert(Buf.end(), EscapedFile.begin(), EscapedFile.end());
94  Buf.push_back('"');
95}
96
97/// AddImplicitInclude - Add an implicit #include of the specified file to the
98/// predefines buffer.
99static void AddImplicitInclude(std::vector<char> &Buf,
100                               const std::string &File) {
101  const char *Inc = "#include ";
102  Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
103  AddQuotedIncludePath(Buf, File);
104  Buf.push_back('\n');
105}
106
107static void AddImplicitIncludeMacros(std::vector<char> &Buf,
108                                     const std::string &File) {
109  const char *Inc = "#__include_macros ";
110  Buf.insert(Buf.end(), Inc, Inc+strlen(Inc));
111  AddQuotedIncludePath(Buf, File);
112  Buf.push_back('\n');
113  // Marker token to stop the __include_macros fetch loop.
114  const char *Marker = "##\n"; // ##?
115  Buf.insert(Buf.end(), Marker, Marker+strlen(Marker));
116}
117
118/// AddImplicitIncludePTH - Add an implicit #include using the original file
119///  used to generate a PTH cache.
120static void AddImplicitIncludePTH(std::vector<char> &Buf, Preprocessor &PP,
121  const std::string& ImplicitIncludePTH) {
122  PTHManager *P = PP.getPTHManager();
123  assert(P && "No PTHManager.");
124  const char *OriginalFile = P->getOriginalSourceFile();
125
126  if (!OriginalFile) {
127    PP.getDiagnostics().Report(diag::err_fe_pth_file_has_no_source_header)
128      << ImplicitIncludePTH;
129    return;
130  }
131
132  AddImplicitInclude(Buf, OriginalFile);
133}
134
135/// PickFP - This is used to pick a value based on the FP semantics of the
136/// specified FP model.
137template <typename T>
138static T PickFP(const llvm::fltSemantics *Sem, T IEEESingleVal,
139                T IEEEDoubleVal, T X87DoubleExtendedVal, T PPCDoubleDoubleVal,
140                T IEEEQuadVal) {
141  if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEsingle)
142    return IEEESingleVal;
143  if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEdouble)
144    return IEEEDoubleVal;
145  if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::x87DoubleExtended)
146    return X87DoubleExtendedVal;
147  if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::PPCDoubleDouble)
148    return PPCDoubleDoubleVal;
149  assert(Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEquad);
150  return IEEEQuadVal;
151}
152
153static void DefineFloatMacros(std::vector<char> &Buf, const char *Prefix,
154                              const llvm::fltSemantics *Sem) {
155  const char *DenormMin, *Epsilon, *Max, *Min;
156  DenormMin = PickFP(Sem, "1.40129846e-45F", "4.9406564584124654e-324",
157                     "3.64519953188247460253e-4951L",
158                     "4.94065645841246544176568792868221e-324L",
159                     "6.47517511943802511092443895822764655e-4966L");
160  int Digits = PickFP(Sem, 6, 15, 18, 31, 33);
161  Epsilon = PickFP(Sem, "1.19209290e-7F", "2.2204460492503131e-16",
162                   "1.08420217248550443401e-19L",
163                   "4.94065645841246544176568792868221e-324L",
164                   "1.92592994438723585305597794258492732e-34L");
165  int HasInifinity = 1, HasQuietNaN = 1;
166  int MantissaDigits = PickFP(Sem, 24, 53, 64, 106, 113);
167  int Min10Exp = PickFP(Sem, -37, -307, -4931, -291, -4931);
168  int Max10Exp = PickFP(Sem, 38, 308, 4932, 308, 4932);
169  int MinExp = PickFP(Sem, -125, -1021, -16381, -968, -16381);
170  int MaxExp = PickFP(Sem, 128, 1024, 16384, 1024, 16384);
171  Min = PickFP(Sem, "1.17549435e-38F", "2.2250738585072014e-308",
172               "3.36210314311209350626e-4932L",
173               "2.00416836000897277799610805135016e-292L",
174               "3.36210314311209350626267781732175260e-4932L");
175  Max = PickFP(Sem, "3.40282347e+38F", "1.7976931348623157e+308",
176               "1.18973149535723176502e+4932L",
177               "1.79769313486231580793728971405301e+308L",
178               "1.18973149535723176508575932662800702e+4932L");
179
180  char MacroBuf[100];
181  sprintf(MacroBuf, "__%s_DENORM_MIN__=%s", Prefix, DenormMin);
182  DefineBuiltinMacro(Buf, MacroBuf);
183  sprintf(MacroBuf, "__%s_DIG__=%d", Prefix, Digits);
184  DefineBuiltinMacro(Buf, MacroBuf);
185  sprintf(MacroBuf, "__%s_EPSILON__=%s", Prefix, Epsilon);
186  DefineBuiltinMacro(Buf, MacroBuf);
187  sprintf(MacroBuf, "__%s_HAS_INFINITY__=%d", Prefix, HasInifinity);
188  DefineBuiltinMacro(Buf, MacroBuf);
189  sprintf(MacroBuf, "__%s_HAS_QUIET_NAN__=%d", Prefix, HasQuietNaN);
190  DefineBuiltinMacro(Buf, MacroBuf);
191  sprintf(MacroBuf, "__%s_MANT_DIG__=%d", Prefix, MantissaDigits);
192  DefineBuiltinMacro(Buf, MacroBuf);
193  sprintf(MacroBuf, "__%s_MAX_10_EXP__=%d", Prefix, Max10Exp);
194  DefineBuiltinMacro(Buf, MacroBuf);
195  sprintf(MacroBuf, "__%s_MAX_EXP__=%d", Prefix, MaxExp);
196  DefineBuiltinMacro(Buf, MacroBuf);
197  sprintf(MacroBuf, "__%s_MAX__=%s", Prefix, Max);
198  DefineBuiltinMacro(Buf, MacroBuf);
199  sprintf(MacroBuf, "__%s_MIN_10_EXP__=(%d)", Prefix, Min10Exp);
200  DefineBuiltinMacro(Buf, MacroBuf);
201  sprintf(MacroBuf, "__%s_MIN_EXP__=(%d)", Prefix, MinExp);
202  DefineBuiltinMacro(Buf, MacroBuf);
203  sprintf(MacroBuf, "__%s_MIN__=%s", Prefix, Min);
204  DefineBuiltinMacro(Buf, MacroBuf);
205  sprintf(MacroBuf, "__%s_HAS_DENORM__=1", Prefix);
206  DefineBuiltinMacro(Buf, MacroBuf);
207}
208
209
210/// DefineTypeSize - Emit a macro to the predefines buffer that declares a macro
211/// named MacroName with the max value for a type with width 'TypeWidth' a
212/// signedness of 'isSigned' and with a value suffix of 'ValSuffix' (e.g. LL).
213static void DefineTypeSize(const char *MacroName, unsigned TypeWidth,
214                           const char *ValSuffix, bool isSigned,
215                           std::vector<char> &Buf) {
216  char MacroBuf[60];
217  long long MaxVal;
218  if (isSigned)
219    MaxVal = (1LL << (TypeWidth - 1)) - 1;
220  else
221    MaxVal = ~0LL >> (64-TypeWidth);
222
223  // FIXME: Switch to using raw_ostream and avoid utostr().
224  sprintf(MacroBuf, "%s=%s%s", MacroName, llvm::utostr(MaxVal).c_str(),
225          ValSuffix);
226  DefineBuiltinMacro(Buf, MacroBuf);
227}
228
229/// DefineTypeSize - An overloaded helper that uses TargetInfo to determine
230/// the width, suffix, and signedness of the given type
231static void DefineTypeSize(const char *MacroName, TargetInfo::IntType Ty,
232                           const TargetInfo &TI, std::vector<char> &Buf) {
233  DefineTypeSize(MacroName, TI.getTypeWidth(Ty), TI.getTypeConstantSuffix(Ty),
234                 TI.isTypeSigned(Ty), Buf);
235}
236
237static void DefineType(const char *MacroName, TargetInfo::IntType Ty,
238                       std::vector<char> &Buf) {
239  char MacroBuf[60];
240  sprintf(MacroBuf, "%s=%s", MacroName, TargetInfo::getTypeName(Ty));
241  DefineBuiltinMacro(Buf, MacroBuf);
242}
243
244static void DefineTypeWidth(const char *MacroName, TargetInfo::IntType Ty,
245                            const TargetInfo &TI, std::vector<char> &Buf) {
246  char MacroBuf[60];
247  sprintf(MacroBuf, "%s=%d", MacroName, TI.getTypeWidth(Ty));
248  DefineBuiltinMacro(Buf, MacroBuf);
249}
250
251static void DefineExactWidthIntType(TargetInfo::IntType Ty,
252                               const TargetInfo &TI, std::vector<char> &Buf) {
253  char MacroBuf[60];
254  int TypeWidth = TI.getTypeWidth(Ty);
255  sprintf(MacroBuf, "__INT%d_TYPE__", TypeWidth);
256  DefineType(MacroBuf, Ty, Buf);
257
258
259  const char *ConstSuffix = TargetInfo::getTypeConstantSuffix(Ty);
260  if (strlen(ConstSuffix) > 0) {
261    sprintf(MacroBuf, "__INT%d_C_SUFFIX__=%s", TypeWidth, ConstSuffix);
262    DefineBuiltinMacro(Buf, MacroBuf);
263  }
264}
265
266static void InitializePredefinedMacros(const TargetInfo &TI,
267                                       const LangOptions &LangOpts,
268                                       std::vector<char> &Buf) {
269  char MacroBuf[60];
270  // Compiler version introspection macros.
271  DefineBuiltinMacro(Buf, "__llvm__=1");   // LLVM Backend
272  DefineBuiltinMacro(Buf, "__clang__=1");  // Clang Frontend
273
274  // Currently claim to be compatible with GCC 4.2.1-5621.
275  DefineBuiltinMacro(Buf, "__GNUC_MINOR__=2");
276  DefineBuiltinMacro(Buf, "__GNUC_PATCHLEVEL__=1");
277  DefineBuiltinMacro(Buf, "__GNUC__=4");
278  DefineBuiltinMacro(Buf, "__GXX_ABI_VERSION=1002");
279  DefineBuiltinMacro(Buf, "__VERSION__=\"4.2.1 Compatible Clang Compiler\"");
280
281
282  // Initialize language-specific preprocessor defines.
283
284  // These should all be defined in the preprocessor according to the
285  // current language configuration.
286  if (!LangOpts.Microsoft)
287    DefineBuiltinMacro(Buf, "__STDC__=1");
288  if (LangOpts.AsmPreprocessor)
289    DefineBuiltinMacro(Buf, "__ASSEMBLER__=1");
290
291  if (!LangOpts.CPlusPlus) {
292    if (LangOpts.C99)
293      DefineBuiltinMacro(Buf, "__STDC_VERSION__=199901L");
294    else if (!LangOpts.GNUMode && LangOpts.Digraphs)
295      DefineBuiltinMacro(Buf, "__STDC_VERSION__=199409L");
296  }
297
298  // Standard conforming mode?
299  if (!LangOpts.GNUMode)
300    DefineBuiltinMacro(Buf, "__STRICT_ANSI__=1");
301
302  if (LangOpts.CPlusPlus0x)
303    DefineBuiltinMacro(Buf, "__GXX_EXPERIMENTAL_CXX0X__");
304
305  if (LangOpts.Freestanding)
306    DefineBuiltinMacro(Buf, "__STDC_HOSTED__=0");
307  else
308    DefineBuiltinMacro(Buf, "__STDC_HOSTED__=1");
309
310  if (LangOpts.ObjC1) {
311    DefineBuiltinMacro(Buf, "__OBJC__=1");
312    if (LangOpts.ObjCNonFragileABI) {
313      DefineBuiltinMacro(Buf, "__OBJC2__=1");
314      DefineBuiltinMacro(Buf, "OBJC_ZEROCOST_EXCEPTIONS=1");
315    }
316
317    if (LangOpts.getGCMode() != LangOptions::NonGC)
318      DefineBuiltinMacro(Buf, "__OBJC_GC__=1");
319
320    if (LangOpts.NeXTRuntime)
321      DefineBuiltinMacro(Buf, "__NEXT_RUNTIME__=1");
322  }
323
324  // darwin_constant_cfstrings controls this. This is also dependent
325  // on other things like the runtime I believe.  This is set even for C code.
326  DefineBuiltinMacro(Buf, "__CONSTANT_CFSTRINGS__=1");
327
328  if (LangOpts.ObjC2)
329    DefineBuiltinMacro(Buf, "OBJC_NEW_PROPERTIES");
330
331  if (LangOpts.PascalStrings)
332    DefineBuiltinMacro(Buf, "__PASCAL_STRINGS__");
333
334  if (LangOpts.Blocks) {
335    DefineBuiltinMacro(Buf, "__block=__attribute__((__blocks__(byref)))");
336    DefineBuiltinMacro(Buf, "__BLOCKS__=1");
337  }
338
339  if (LangOpts.Exceptions)
340    DefineBuiltinMacro(Buf, "__EXCEPTIONS=1");
341
342  if (LangOpts.CPlusPlus) {
343    DefineBuiltinMacro(Buf, "__DEPRECATED=1");
344    DefineBuiltinMacro(Buf, "__GNUG__=4");
345    DefineBuiltinMacro(Buf, "__GXX_WEAK__=1");
346    if (LangOpts.GNUMode)
347      DefineBuiltinMacro(Buf, "__cplusplus=1");
348    else
349      // C++ [cpp.predefined]p1:
350      //   The name_ _cplusplusis defined to the value199711Lwhen compiling a
351      //   C++ translation unit.
352      DefineBuiltinMacro(Buf, "__cplusplus=199711L");
353    DefineBuiltinMacro(Buf, "__private_extern__=extern");
354    // Ugly hack to work with GNU libstdc++.
355    DefineBuiltinMacro(Buf, "_GNU_SOURCE=1");
356  }
357
358  if (LangOpts.Microsoft) {
359    // Filter out some microsoft extensions when trying to parse in ms-compat
360    // mode.
361    DefineBuiltinMacro(Buf, "__int8=__INT8_TYPE__");
362    DefineBuiltinMacro(Buf, "__int16=__INT16_TYPE__");
363    DefineBuiltinMacro(Buf, "__int32=__INT32_TYPE__");
364    DefineBuiltinMacro(Buf, "__int64=__INT64_TYPE__");
365    // Both __PRETTY_FUNCTION__ and __FUNCTION__ are GCC extensions, however
366    // VC++ appears to only like __FUNCTION__.
367    DefineBuiltinMacro(Buf, "__PRETTY_FUNCTION__=__FUNCTION__");
368    // Work around some issues with Visual C++ headerws.
369    if (LangOpts.CPlusPlus) {
370      // Since we define wchar_t in C++ mode.
371      DefineBuiltinMacro(Buf, "_WCHAR_T_DEFINED=1");
372      DefineBuiltinMacro(Buf, "_NATIVE_WCHAR_T_DEFINED=1");
373      // FIXME:  This should be temporary until we have a __pragma
374      // solution, to avoid some errors flagged in VC++ headers.
375      DefineBuiltinMacro(Buf, "_CRT_SECURE_CPP_OVERLOAD_SECURE_NAMES=0");
376    }
377  }
378
379  if (LangOpts.Optimize)
380    DefineBuiltinMacro(Buf, "__OPTIMIZE__=1");
381  if (LangOpts.OptimizeSize)
382    DefineBuiltinMacro(Buf, "__OPTIMIZE_SIZE__=1");
383
384  // Initialize target-specific preprocessor defines.
385
386  // Define type sizing macros based on the target properties.
387  assert(TI.getCharWidth() == 8 && "Only support 8-bit char so far");
388  DefineBuiltinMacro(Buf, "__CHAR_BIT__=8");
389
390  DefineTypeSize("__SCHAR_MAX__", TI.getCharWidth(), "", true, Buf);
391  DefineTypeSize("__SHRT_MAX__", TargetInfo::SignedShort, TI, Buf);
392  DefineTypeSize("__INT_MAX__", TargetInfo::SignedInt, TI, Buf);
393  DefineTypeSize("__LONG_MAX__", TargetInfo::SignedLong, TI, Buf);
394  DefineTypeSize("__LONG_LONG_MAX__", TargetInfo::SignedLongLong, TI, Buf);
395  DefineTypeSize("__WCHAR_MAX__", TI.getWCharType(), TI, Buf);
396  DefineTypeSize("__INTMAX_MAX__", TI.getIntMaxType(), TI, Buf);
397
398  DefineType("__INTMAX_TYPE__", TI.getIntMaxType(), Buf);
399  DefineType("__UINTMAX_TYPE__", TI.getUIntMaxType(), Buf);
400  DefineTypeWidth("__INTMAX_WIDTH__",  TI.getIntMaxType(), TI, Buf);
401  DefineType("__PTRDIFF_TYPE__", TI.getPtrDiffType(0), Buf);
402  DefineTypeWidth("__PTRDIFF_WIDTH__", TI.getPtrDiffType(0), TI, Buf);
403  DefineType("__INTPTR_TYPE__", TI.getIntPtrType(), Buf);
404  DefineTypeWidth("__INTPTR_WIDTH__", TI.getIntPtrType(), TI, Buf);
405  DefineType("__SIZE_TYPE__", TI.getSizeType(), Buf);
406  DefineTypeWidth("__SIZE_WIDTH__", TI.getSizeType(), TI, Buf);
407  DefineType("__WCHAR_TYPE__", TI.getWCharType(), Buf);
408  DefineTypeWidth("__WCHAR_WIDTH__", TI.getWCharType(), TI, Buf);
409  DefineType("__WINT_TYPE__", TI.getWIntType(), Buf);
410  DefineTypeWidth("__WINT_WIDTH__", TI.getWIntType(), TI, Buf);
411  DefineTypeWidth("__SIG_ATOMIC_WIDTH__", TI.getSigAtomicType(), TI, Buf);
412
413  DefineFloatMacros(Buf, "FLT", &TI.getFloatFormat());
414  DefineFloatMacros(Buf, "DBL", &TI.getDoubleFormat());
415  DefineFloatMacros(Buf, "LDBL", &TI.getLongDoubleFormat());
416
417  // Define a __POINTER_WIDTH__ macro for stdint.h.
418  sprintf(MacroBuf, "__POINTER_WIDTH__=%d", (int)TI.getPointerWidth(0));
419  DefineBuiltinMacro(Buf, MacroBuf);
420
421  if (!LangOpts.CharIsSigned)
422    DefineBuiltinMacro(Buf, "__CHAR_UNSIGNED__");
423
424  // Define exact-width integer types for stdint.h
425  sprintf(MacroBuf, "__INT%d_TYPE__=char", TI.getCharWidth());
426  DefineBuiltinMacro(Buf, MacroBuf);
427
428  if (TI.getShortWidth() > TI.getCharWidth())
429    DefineExactWidthIntType(TargetInfo::SignedShort, TI, Buf);
430
431  if (TI.getIntWidth() > TI.getShortWidth())
432    DefineExactWidthIntType(TargetInfo::SignedInt, TI, Buf);
433
434  if (TI.getLongWidth() > TI.getIntWidth())
435    DefineExactWidthIntType(TargetInfo::SignedLong, TI, Buf);
436
437  if (TI.getLongLongWidth() > TI.getLongWidth())
438    DefineExactWidthIntType(TargetInfo::SignedLongLong, TI, Buf);
439
440  // Add __builtin_va_list typedef.
441  {
442    const char *VAList = TI.getVAListDeclaration();
443    Buf.insert(Buf.end(), VAList, VAList+strlen(VAList));
444    Buf.push_back('\n');
445  }
446
447  if (const char *Prefix = TI.getUserLabelPrefix()) {
448    sprintf(MacroBuf, "__USER_LABEL_PREFIX__=%s", Prefix);
449    DefineBuiltinMacro(Buf, MacroBuf);
450  }
451
452  // Build configuration options.  FIXME: these should be controlled by
453  // command line options or something.
454  DefineBuiltinMacro(Buf, "__FINITE_MATH_ONLY__=0");
455
456  if (LangOpts.GNUInline)
457    DefineBuiltinMacro(Buf, "__GNUC_GNU_INLINE__=1");
458  else
459    DefineBuiltinMacro(Buf, "__GNUC_STDC_INLINE__=1");
460
461  if (LangOpts.NoInline)
462    DefineBuiltinMacro(Buf, "__NO_INLINE__=1");
463
464  if (unsigned PICLevel = LangOpts.PICLevel) {
465    sprintf(MacroBuf, "__PIC__=%d", PICLevel);
466    DefineBuiltinMacro(Buf, MacroBuf);
467
468    sprintf(MacroBuf, "__pic__=%d", PICLevel);
469    DefineBuiltinMacro(Buf, MacroBuf);
470  }
471
472  // Macros to control C99 numerics and <float.h>
473  DefineBuiltinMacro(Buf, "__FLT_EVAL_METHOD__=0");
474  DefineBuiltinMacro(Buf, "__FLT_RADIX__=2");
475  sprintf(MacroBuf, "__DECIMAL_DIG__=%d",
476          PickFP(&TI.getLongDoubleFormat(), -1/*FIXME*/, 17, 21, 33, 36));
477  DefineBuiltinMacro(Buf, MacroBuf);
478
479  if (LangOpts.getStackProtectorMode() == LangOptions::SSPOn)
480    DefineBuiltinMacro(Buf, "__SSP__=1");
481  else if (LangOpts.getStackProtectorMode() == LangOptions::SSPReq)
482    DefineBuiltinMacro(Buf, "__SSP_ALL__=2");
483
484  // Get other target #defines.
485  TI.getTargetDefines(LangOpts, Buf);
486}
487
488// Initialize the remapping of files to alternative contents, e.g.,
489// those specified through other files.
490static void InitializeFileRemapping(Diagnostic &Diags,
491                                    SourceManager &SourceMgr,
492                                    FileManager &FileMgr,
493                                    const PreprocessorOptions &InitOpts) {
494  // Remap files in the source manager.
495  for (PreprocessorOptions::remapped_file_iterator
496         Remap = InitOpts.remapped_file_begin(),
497         RemapEnd = InitOpts.remapped_file_end();
498       Remap != RemapEnd;
499       ++Remap) {
500    // Find the file that we're mapping to.
501    const FileEntry *ToFile = FileMgr.getFile(Remap->second);
502    if (!ToFile) {
503      Diags.Report(diag::err_fe_remap_missing_to_file)
504        << Remap->first << Remap->second;
505      continue;
506    }
507
508    // Create the file entry for the file that we're mapping from.
509    const FileEntry *FromFile = FileMgr.getVirtualFile(Remap->first,
510                                                       ToFile->getSize(),
511                                                       0);
512    if (!FromFile) {
513      Diags.Report(diag::err_fe_remap_missing_from_file)
514        << Remap->first;
515      continue;
516    }
517
518    // Load the contents of the file we're mapping to.
519    std::string ErrorStr;
520    const llvm::MemoryBuffer *Buffer
521      = llvm::MemoryBuffer::getFile(ToFile->getName(), &ErrorStr);
522    if (!Buffer) {
523      Diags.Report(diag::err_fe_error_opening)
524        << Remap->second << ErrorStr;
525      continue;
526    }
527
528    // Override the contents of the "from" file with the contents of
529    // the "to" file.
530    SourceMgr.overrideFileContents(FromFile, Buffer);
531  }
532}
533
534/// InitializePreprocessor - Initialize the preprocessor getting it and the
535/// environment ready to process a single file. This returns true on error.
536///
537void clang::InitializePreprocessor(Preprocessor &PP,
538                                   const PreprocessorOptions &InitOpts,
539                                   const HeaderSearchOptions &HSOpts) {
540  std::vector<char> PredefineBuffer;
541
542  InitializeFileRemapping(PP.getDiagnostics(), PP.getSourceManager(),
543                          PP.getFileManager(), InitOpts);
544
545  const char *LineDirective = "# 1 \"<built-in>\" 3\n";
546  PredefineBuffer.insert(PredefineBuffer.end(),
547                         LineDirective, LineDirective+strlen(LineDirective));
548
549  // Install things like __POWERPC__, __GNUC__, etc into the macro table.
550  if (InitOpts.UsePredefines)
551    InitializePredefinedMacros(PP.getTargetInfo(), PP.getLangOptions(),
552                               PredefineBuffer);
553
554  // Add on the predefines from the driver.  Wrap in a #line directive to report
555  // that they come from the command line.
556  LineDirective = "# 1 \"<command line>\" 1\n";
557  PredefineBuffer.insert(PredefineBuffer.end(),
558                         LineDirective, LineDirective+strlen(LineDirective));
559
560  // Process #define's and #undef's in the order they are given.
561  for (unsigned i = 0, e = InitOpts.Macros.size(); i != e; ++i) {
562    if (InitOpts.Macros[i].second)  // isUndef
563      UndefineBuiltinMacro(PredefineBuffer, InitOpts.Macros[i].first.c_str());
564    else
565      DefineBuiltinMacro(PredefineBuffer, InitOpts.Macros[i].first.c_str(),
566                         &PP.getDiagnostics());
567  }
568
569  // If -imacros are specified, include them now.  These are processed before
570  // any -include directives.
571  for (unsigned i = 0, e = InitOpts.MacroIncludes.size(); i != e; ++i)
572    AddImplicitIncludeMacros(PredefineBuffer, InitOpts.MacroIncludes[i]);
573
574  // Process -include directives.
575  for (unsigned i = 0, e = InitOpts.Includes.size(); i != e; ++i) {
576    const std::string &Path = InitOpts.Includes[i];
577    if (Path == InitOpts.ImplicitPTHInclude)
578      AddImplicitIncludePTH(PredefineBuffer, PP, Path);
579    else
580      AddImplicitInclude(PredefineBuffer, Path);
581  }
582
583  // Exit the command line and go back to <built-in> (2 is LC_LEAVE).
584  LineDirective = "# 1 \"<built-in>\" 2\n";
585  PredefineBuffer.insert(PredefineBuffer.end(),
586                         LineDirective, LineDirective+strlen(LineDirective));
587
588  // Null terminate PredefinedBuffer and add it.
589  PredefineBuffer.push_back(0);
590  PP.setPredefines(&PredefineBuffer[0]);
591
592  // Initialize the header search object.
593  ApplyHeaderSearchOptions(PP.getHeaderSearchInfo(), HSOpts,
594                           PP.getLangOptions(),
595                           PP.getTargetInfo().getTriple());
596}
597