InitPreprocessor.cpp revision 752c74d99b647710a495c2ff5f815c30a30c3264
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/Basic/Version.h"
15#include "clang/Frontend/Utils.h"
16#include "clang/Basic/MacroBuilder.h"
17#include "clang/Basic/TargetInfo.h"
18#include "clang/Frontend/FrontendDiagnostic.h"
19#include "clang/Frontend/FrontendOptions.h"
20#include "clang/Frontend/PreprocessorOptions.h"
21#include "clang/Lex/HeaderSearch.h"
22#include "clang/Lex/Preprocessor.h"
23#include "clang/Basic/FileManager.h"
24#include "clang/Basic/SourceManager.h"
25#include "llvm/ADT/APFloat.h"
26#include "llvm/Support/FileSystem.h"
27#include "llvm/Support/MemoryBuffer.h"
28#include "llvm/Support/Path.h"
29using namespace clang;
30
31// Append a #define line to Buf for Macro.  Macro should be of the form XXX,
32// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
33// "#define XXX Y z W".  To get a #define with no value, use "XXX=".
34static void DefineBuiltinMacro(MacroBuilder &Builder, StringRef Macro,
35                               DiagnosticsEngine &Diags) {
36  std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
37  StringRef MacroName = MacroPair.first;
38  StringRef MacroBody = MacroPair.second;
39  if (MacroName.size() != Macro.size()) {
40    // Per GCC -D semantics, the macro ends at \n if it exists.
41    StringRef::size_type End = MacroBody.find_first_of("\n\r");
42    if (End != StringRef::npos)
43      Diags.Report(diag::warn_fe_macro_contains_embedded_newline)
44        << MacroName;
45    Builder.defineMacro(MacroName, MacroBody.substr(0, End));
46  } else {
47    // Push "macroname 1".
48    Builder.defineMacro(Macro);
49  }
50}
51
52/// AddImplicitInclude - Add an implicit #include of the specified file to the
53/// predefines buffer.
54static void AddImplicitInclude(MacroBuilder &Builder, StringRef File,
55                               FileManager &FileMgr) {
56  Builder.append(Twine("#include \"") +
57                 HeaderSearch::NormalizeDashIncludePath(File, FileMgr) + "\"");
58}
59
60static void AddImplicitIncludeMacros(MacroBuilder &Builder,
61                                     StringRef File,
62                                     FileManager &FileMgr) {
63  Builder.append(Twine("#__include_macros \"") +
64                 HeaderSearch::NormalizeDashIncludePath(File, FileMgr) + "\"");
65  // Marker token to stop the __include_macros fetch loop.
66  Builder.append("##"); // ##?
67}
68
69/// AddImplicitIncludePTH - Add an implicit #include using the original file
70///  used to generate a PTH cache.
71static void AddImplicitIncludePTH(MacroBuilder &Builder, Preprocessor &PP,
72                                  StringRef ImplicitIncludePTH) {
73  PTHManager *P = PP.getPTHManager();
74  // Null check 'P' in the corner case where it couldn't be created.
75  const char *OriginalFile = P ? P->getOriginalSourceFile() : 0;
76
77  if (!OriginalFile) {
78    PP.getDiagnostics().Report(diag::err_fe_pth_file_has_no_source_header)
79      << ImplicitIncludePTH;
80    return;
81  }
82
83  AddImplicitInclude(Builder, OriginalFile, PP.getFileManager());
84}
85
86/// PickFP - This is used to pick a value based on the FP semantics of the
87/// specified FP model.
88template <typename T>
89static T PickFP(const llvm::fltSemantics *Sem, T IEEESingleVal,
90                T IEEEDoubleVal, T X87DoubleExtendedVal, T PPCDoubleDoubleVal,
91                T IEEEQuadVal) {
92  if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEsingle)
93    return IEEESingleVal;
94  if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEdouble)
95    return IEEEDoubleVal;
96  if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::x87DoubleExtended)
97    return X87DoubleExtendedVal;
98  if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::PPCDoubleDouble)
99    return PPCDoubleDoubleVal;
100  assert(Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEquad);
101  return IEEEQuadVal;
102}
103
104static void DefineFloatMacros(MacroBuilder &Builder, StringRef Prefix,
105                              const llvm::fltSemantics *Sem) {
106  const char *DenormMin, *Epsilon, *Max, *Min;
107  DenormMin = PickFP(Sem, "1.40129846e-45F", "4.9406564584124654e-324",
108                     "3.64519953188247460253e-4951L",
109                     "4.94065645841246544176568792868221e-324L",
110                     "6.47517511943802511092443895822764655e-4966L");
111  int Digits = PickFP(Sem, 6, 15, 18, 31, 33);
112  Epsilon = PickFP(Sem, "1.19209290e-7F", "2.2204460492503131e-16",
113                   "1.08420217248550443401e-19L",
114                   "4.94065645841246544176568792868221e-324L",
115                   "1.92592994438723585305597794258492732e-34L");
116  int MantissaDigits = PickFP(Sem, 24, 53, 64, 106, 113);
117  int Min10Exp = PickFP(Sem, -37, -307, -4931, -291, -4931);
118  int Max10Exp = PickFP(Sem, 38, 308, 4932, 308, 4932);
119  int MinExp = PickFP(Sem, -125, -1021, -16381, -968, -16381);
120  int MaxExp = PickFP(Sem, 128, 1024, 16384, 1024, 16384);
121  Min = PickFP(Sem, "1.17549435e-38F", "2.2250738585072014e-308",
122               "3.36210314311209350626e-4932L",
123               "2.00416836000897277799610805135016e-292L",
124               "3.36210314311209350626267781732175260e-4932L");
125  Max = PickFP(Sem, "3.40282347e+38F", "1.7976931348623157e+308",
126               "1.18973149535723176502e+4932L",
127               "1.79769313486231580793728971405301e+308L",
128               "1.18973149535723176508575932662800702e+4932L");
129
130  llvm::SmallString<32> DefPrefix;
131  DefPrefix = "__";
132  DefPrefix += Prefix;
133  DefPrefix += "_";
134
135  Builder.defineMacro(DefPrefix + "DENORM_MIN__", DenormMin);
136  Builder.defineMacro(DefPrefix + "HAS_DENORM__");
137  Builder.defineMacro(DefPrefix + "DIG__", Twine(Digits));
138  Builder.defineMacro(DefPrefix + "EPSILON__", Twine(Epsilon));
139  Builder.defineMacro(DefPrefix + "HAS_INFINITY__");
140  Builder.defineMacro(DefPrefix + "HAS_QUIET_NAN__");
141  Builder.defineMacro(DefPrefix + "MANT_DIG__", Twine(MantissaDigits));
142
143  Builder.defineMacro(DefPrefix + "MAX_10_EXP__", Twine(Max10Exp));
144  Builder.defineMacro(DefPrefix + "MAX_EXP__", Twine(MaxExp));
145  Builder.defineMacro(DefPrefix + "MAX__", Twine(Max));
146
147  Builder.defineMacro(DefPrefix + "MIN_10_EXP__","("+Twine(Min10Exp)+")");
148  Builder.defineMacro(DefPrefix + "MIN_EXP__", "("+Twine(MinExp)+")");
149  Builder.defineMacro(DefPrefix + "MIN__", Twine(Min));
150}
151
152
153/// DefineTypeSize - Emit a macro to the predefines buffer that declares a macro
154/// named MacroName with the max value for a type with width 'TypeWidth' a
155/// signedness of 'isSigned' and with a value suffix of 'ValSuffix' (e.g. LL).
156static void DefineTypeSize(StringRef MacroName, unsigned TypeWidth,
157                           StringRef ValSuffix, bool isSigned,
158                           MacroBuilder &Builder) {
159  llvm::APInt MaxVal = isSigned ? llvm::APInt::getSignedMaxValue(TypeWidth)
160                                : llvm::APInt::getMaxValue(TypeWidth);
161  Builder.defineMacro(MacroName, MaxVal.toString(10, isSigned) + ValSuffix);
162}
163
164/// DefineTypeSize - An overloaded helper that uses TargetInfo to determine
165/// the width, suffix, and signedness of the given type
166static void DefineTypeSize(StringRef MacroName, TargetInfo::IntType Ty,
167                           const TargetInfo &TI, MacroBuilder &Builder) {
168  DefineTypeSize(MacroName, TI.getTypeWidth(Ty), TI.getTypeConstantSuffix(Ty),
169                 TI.isTypeSigned(Ty), Builder);
170}
171
172static void DefineType(const Twine &MacroName, TargetInfo::IntType Ty,
173                       MacroBuilder &Builder) {
174  Builder.defineMacro(MacroName, TargetInfo::getTypeName(Ty));
175}
176
177static void DefineTypeWidth(StringRef MacroName, TargetInfo::IntType Ty,
178                            const TargetInfo &TI, MacroBuilder &Builder) {
179  Builder.defineMacro(MacroName, Twine(TI.getTypeWidth(Ty)));
180}
181
182static void DefineTypeSizeof(StringRef MacroName, unsigned BitWidth,
183                             const TargetInfo &TI, MacroBuilder &Builder) {
184  Builder.defineMacro(MacroName,
185                      Twine(BitWidth / TI.getCharWidth()));
186}
187
188static void DefineExactWidthIntType(TargetInfo::IntType Ty,
189                               const TargetInfo &TI, MacroBuilder &Builder) {
190  int TypeWidth = TI.getTypeWidth(Ty);
191
192  // Use the target specified int64 type, when appropriate, so that [u]int64_t
193  // ends up being defined in terms of the correct type.
194  if (TypeWidth == 64)
195    Ty = TI.getInt64Type();
196
197  DefineType("__INT" + Twine(TypeWidth) + "_TYPE__", Ty, Builder);
198
199  StringRef ConstSuffix(TargetInfo::getTypeConstantSuffix(Ty));
200  if (!ConstSuffix.empty())
201    Builder.defineMacro("__INT" + Twine(TypeWidth) + "_C_SUFFIX__",
202                        ConstSuffix);
203}
204
205/// \brief Add definitions required for a smooth interaction between
206/// Objective-C++ automated reference counting and libstdc++ (4.2).
207static void AddObjCXXARCLibstdcxxDefines(const LangOptions &LangOpts,
208                                         MacroBuilder &Builder) {
209  Builder.defineMacro("_GLIBCXX_PREDEFINED_OBJC_ARC_IS_SCALAR");
210
211  std::string Result;
212  {
213    // Provide specializations for the __is_scalar type trait so that
214    // lifetime-qualified objects are not considered "scalar" types, which
215    // libstdc++ uses as an indicator of the presence of trivial copy, assign,
216    // default-construct, and destruct semantics (none of which hold for
217    // lifetime-qualified objects in ARC).
218    llvm::raw_string_ostream Out(Result);
219
220    Out << "namespace std {\n"
221        << "\n"
222        << "struct __true_type;\n"
223        << "struct __false_type;\n"
224        << "\n";
225
226    Out << "template<typename _Tp> struct __is_scalar;\n"
227        << "\n";
228
229    Out << "template<typename _Tp>\n"
230        << "struct __is_scalar<__attribute__((objc_ownership(strong))) _Tp> {\n"
231        << "  enum { __value = 0 };\n"
232        << "  typedef __false_type __type;\n"
233        << "};\n"
234        << "\n";
235
236    if (LangOpts.ObjCRuntimeHasWeak) {
237      Out << "template<typename _Tp>\n"
238          << "struct __is_scalar<__attribute__((objc_ownership(weak))) _Tp> {\n"
239          << "  enum { __value = 0 };\n"
240          << "  typedef __false_type __type;\n"
241          << "};\n"
242          << "\n";
243    }
244
245    Out << "template<typename _Tp>\n"
246        << "struct __is_scalar<__attribute__((objc_ownership(autoreleasing)))"
247        << " _Tp> {\n"
248        << "  enum { __value = 0 };\n"
249        << "  typedef __false_type __type;\n"
250        << "};\n"
251        << "\n";
252
253    Out << "}\n";
254  }
255  Builder.append(Result);
256}
257
258static void InitializeStandardPredefinedMacros(const TargetInfo &TI,
259                                               const LangOptions &LangOpts,
260                                               const FrontendOptions &FEOpts,
261                                               MacroBuilder &Builder) {
262  if (!LangOpts.MicrosoftMode && !LangOpts.TraditionalCPP)
263    Builder.defineMacro("__STDC__");
264  if (LangOpts.Freestanding)
265    Builder.defineMacro("__STDC_HOSTED__", "0");
266  else
267    Builder.defineMacro("__STDC_HOSTED__");
268
269  if (!LangOpts.CPlusPlus) {
270    if (LangOpts.C11)
271      Builder.defineMacro("__STDC_VERSION__", "201112L");
272    else if (LangOpts.C99)
273      Builder.defineMacro("__STDC_VERSION__", "199901L");
274    else if (!LangOpts.GNUMode && LangOpts.Digraphs)
275      Builder.defineMacro("__STDC_VERSION__", "199409L");
276  } else {
277    if (LangOpts.GNUMode)
278      Builder.defineMacro("__cplusplus");
279    else {
280      // C++0x [cpp.predefined]p1:
281      //   The name_ _cplusplus is defined to the value 201103L when compiling a
282      //   C++ translation unit.
283      if (LangOpts.CPlusPlus0x)
284        Builder.defineMacro("__cplusplus", "201103L");
285      // C++03 [cpp.predefined]p1:
286      //   The name_ _cplusplus is defined to the value 199711L when compiling a
287      //   C++ translation unit.
288      else
289        Builder.defineMacro("__cplusplus", "199711L");
290    }
291  }
292
293  if (LangOpts.ObjC1)
294    Builder.defineMacro("__OBJC__");
295
296  // Not "standard" per se, but available even with the -undef flag.
297  if (LangOpts.AsmPreprocessor)
298    Builder.defineMacro("__ASSEMBLER__");
299}
300
301static void InitializePredefinedMacros(const TargetInfo &TI,
302                                       const LangOptions &LangOpts,
303                                       const FrontendOptions &FEOpts,
304                                       MacroBuilder &Builder) {
305  // Compiler version introspection macros.
306  Builder.defineMacro("__llvm__");  // LLVM Backend
307  Builder.defineMacro("__clang__"); // Clang Frontend
308#define TOSTR2(X) #X
309#define TOSTR(X) TOSTR2(X)
310  Builder.defineMacro("__clang_major__", TOSTR(CLANG_VERSION_MAJOR));
311  Builder.defineMacro("__clang_minor__", TOSTR(CLANG_VERSION_MINOR));
312#ifdef CLANG_VERSION_PATCHLEVEL
313  Builder.defineMacro("__clang_patchlevel__", TOSTR(CLANG_VERSION_PATCHLEVEL));
314#else
315  Builder.defineMacro("__clang_patchlevel__", "0");
316#endif
317  Builder.defineMacro("__clang_version__",
318                      "\"" CLANG_VERSION_STRING " ("
319                      + getClangFullRepositoryVersion() + ")\"");
320#undef TOSTR
321#undef TOSTR2
322  // Currently claim to be compatible with GCC 4.2.1-5621.
323  Builder.defineMacro("__GNUC_MINOR__", "2");
324  Builder.defineMacro("__GNUC_PATCHLEVEL__", "1");
325  Builder.defineMacro("__GNUC__", "4");
326  Builder.defineMacro("__GXX_ABI_VERSION", "1002");
327
328  // As sad as it is, enough software depends on the __VERSION__ for version
329  // checks that it is necessary to report 4.2.1 (the base GCC version we claim
330  // compatibility with) first.
331  Builder.defineMacro("__VERSION__", "\"4.2.1 Compatible " +
332                      Twine(getClangFullCPPVersion()) + "\"");
333
334  // Initialize language-specific preprocessor defines.
335
336  // Standard conforming mode?
337  if (!LangOpts.GNUMode)
338    Builder.defineMacro("__STRICT_ANSI__");
339
340  if (LangOpts.CPlusPlus0x)
341    Builder.defineMacro("__GXX_EXPERIMENTAL_CXX0X__");
342
343  if (LangOpts.ObjC1) {
344    if (LangOpts.ObjCNonFragileABI) {
345      Builder.defineMacro("__OBJC2__");
346
347      if (LangOpts.ObjCExceptions)
348        Builder.defineMacro("OBJC_ZEROCOST_EXCEPTIONS");
349    }
350
351    if (LangOpts.getGC() != LangOptions::NonGC)
352      Builder.defineMacro("__OBJC_GC__");
353
354    if (LangOpts.NeXTRuntime)
355      Builder.defineMacro("__NEXT_RUNTIME__");
356  }
357
358  // darwin_constant_cfstrings controls this. This is also dependent
359  // on other things like the runtime I believe.  This is set even for C code.
360  if (!LangOpts.NoConstantCFStrings)
361      Builder.defineMacro("__CONSTANT_CFSTRINGS__");
362
363  if (LangOpts.ObjC2)
364    Builder.defineMacro("OBJC_NEW_PROPERTIES");
365
366  if (LangOpts.PascalStrings)
367    Builder.defineMacro("__PASCAL_STRINGS__");
368
369  if (LangOpts.Blocks) {
370    Builder.defineMacro("__block", "__attribute__((__blocks__(byref)))");
371    Builder.defineMacro("__BLOCKS__");
372  }
373
374  if (LangOpts.CXXExceptions)
375    Builder.defineMacro("__EXCEPTIONS");
376  if (LangOpts.RTTI)
377    Builder.defineMacro("__GXX_RTTI");
378  if (LangOpts.SjLjExceptions)
379    Builder.defineMacro("__USING_SJLJ_EXCEPTIONS__");
380
381  if (LangOpts.Deprecated)
382    Builder.defineMacro("__DEPRECATED");
383
384  if (LangOpts.CPlusPlus) {
385    Builder.defineMacro("__GNUG__", "4");
386    Builder.defineMacro("__GXX_WEAK__");
387    Builder.defineMacro("__private_extern__", "extern");
388  }
389
390  if (LangOpts.MicrosoftExt) {
391    // Both __PRETTY_FUNCTION__ and __FUNCTION__ are GCC extensions, however
392    // VC++ appears to only like __FUNCTION__.
393    Builder.defineMacro("__PRETTY_FUNCTION__", "__FUNCTION__");
394    // Work around some issues with Visual C++ headerws.
395    if (LangOpts.CPlusPlus) {
396      // Since we define wchar_t in C++ mode.
397      Builder.defineMacro("_WCHAR_T_DEFINED");
398      Builder.defineMacro("_NATIVE_WCHAR_T_DEFINED");
399      // FIXME: Support Microsoft's __identifier extension in the lexer.
400      Builder.append("#define __identifier(x) x");
401      Builder.append("class type_info;");
402    }
403
404    if (LangOpts.CPlusPlus0x) {
405      Builder.defineMacro("_HAS_CHAR16_T_LANGUAGE_SUPPORT", "1");
406    }
407  }
408
409  if (LangOpts.Optimize)
410    Builder.defineMacro("__OPTIMIZE__");
411  if (LangOpts.OptimizeSize)
412    Builder.defineMacro("__OPTIMIZE_SIZE__");
413
414  if (LangOpts.FastMath)
415    Builder.defineMacro("__FAST_MATH__");
416
417  // Initialize target-specific preprocessor defines.
418
419  // Define type sizing macros based on the target properties.
420  assert(TI.getCharWidth() == 8 && "Only support 8-bit char so far");
421  Builder.defineMacro("__CHAR_BIT__", "8");
422
423  DefineTypeSize("__SCHAR_MAX__", TI.getCharWidth(), "", true, Builder);
424  DefineTypeSize("__SHRT_MAX__", TargetInfo::SignedShort, TI, Builder);
425  DefineTypeSize("__INT_MAX__", TargetInfo::SignedInt, TI, Builder);
426  DefineTypeSize("__LONG_MAX__", TargetInfo::SignedLong, TI, Builder);
427  DefineTypeSize("__LONG_LONG_MAX__", TargetInfo::SignedLongLong, TI, Builder);
428  DefineTypeSize("__WCHAR_MAX__", TI.getWCharType(), TI, Builder);
429  DefineTypeSize("__INTMAX_MAX__", TI.getIntMaxType(), TI, Builder);
430
431  DefineTypeSizeof("__SIZEOF_DOUBLE__", TI.getDoubleWidth(), TI, Builder);
432  DefineTypeSizeof("__SIZEOF_FLOAT__", TI.getFloatWidth(), TI, Builder);
433  DefineTypeSizeof("__SIZEOF_INT__", TI.getIntWidth(), TI, Builder);
434  DefineTypeSizeof("__SIZEOF_LONG__", TI.getLongWidth(), TI, Builder);
435  DefineTypeSizeof("__SIZEOF_LONG_DOUBLE__",TI.getLongDoubleWidth(),TI,Builder);
436  DefineTypeSizeof("__SIZEOF_LONG_LONG__", TI.getLongLongWidth(), TI, Builder);
437  DefineTypeSizeof("__SIZEOF_POINTER__", TI.getPointerWidth(0), TI, Builder);
438  DefineTypeSizeof("__SIZEOF_SHORT__", TI.getShortWidth(), TI, Builder);
439  DefineTypeSizeof("__SIZEOF_PTRDIFF_T__",
440                   TI.getTypeWidth(TI.getPtrDiffType(0)), TI, Builder);
441  DefineTypeSizeof("__SIZEOF_SIZE_T__",
442                   TI.getTypeWidth(TI.getSizeType()), TI, Builder);
443  DefineTypeSizeof("__SIZEOF_WCHAR_T__",
444                   TI.getTypeWidth(TI.getWCharType()), TI, Builder);
445  DefineTypeSizeof("__SIZEOF_WINT_T__",
446                   TI.getTypeWidth(TI.getWIntType()), TI, Builder);
447
448  DefineType("__INTMAX_TYPE__", TI.getIntMaxType(), Builder);
449  DefineType("__UINTMAX_TYPE__", TI.getUIntMaxType(), Builder);
450  DefineTypeWidth("__INTMAX_WIDTH__",  TI.getIntMaxType(), TI, Builder);
451  DefineType("__PTRDIFF_TYPE__", TI.getPtrDiffType(0), Builder);
452  DefineTypeWidth("__PTRDIFF_WIDTH__", TI.getPtrDiffType(0), TI, Builder);
453  DefineType("__INTPTR_TYPE__", TI.getIntPtrType(), Builder);
454  DefineTypeWidth("__INTPTR_WIDTH__", TI.getIntPtrType(), TI, Builder);
455  DefineType("__SIZE_TYPE__", TI.getSizeType(), Builder);
456  DefineTypeWidth("__SIZE_WIDTH__", TI.getSizeType(), TI, Builder);
457  DefineType("__WCHAR_TYPE__", TI.getWCharType(), Builder);
458  DefineTypeWidth("__WCHAR_WIDTH__", TI.getWCharType(), TI, Builder);
459  DefineType("__WINT_TYPE__", TI.getWIntType(), Builder);
460  DefineTypeWidth("__WINT_WIDTH__", TI.getWIntType(), TI, Builder);
461  DefineTypeWidth("__SIG_ATOMIC_WIDTH__", TI.getSigAtomicType(), TI, Builder);
462  DefineType("__CHAR16_TYPE__", TI.getChar16Type(), Builder);
463  DefineType("__CHAR32_TYPE__", TI.getChar32Type(), Builder);
464
465  DefineFloatMacros(Builder, "FLT", &TI.getFloatFormat());
466  DefineFloatMacros(Builder, "DBL", &TI.getDoubleFormat());
467  DefineFloatMacros(Builder, "LDBL", &TI.getLongDoubleFormat());
468
469  // Define a __POINTER_WIDTH__ macro for stdint.h.
470  Builder.defineMacro("__POINTER_WIDTH__",
471                      Twine((int)TI.getPointerWidth(0)));
472
473  if (!LangOpts.CharIsSigned)
474    Builder.defineMacro("__CHAR_UNSIGNED__");
475
476  if (!TargetInfo::isTypeSigned(TI.getWIntType()))
477    Builder.defineMacro("__WINT_UNSIGNED__");
478
479  // Define exact-width integer types for stdint.h
480  Builder.defineMacro("__INT" + Twine(TI.getCharWidth()) + "_TYPE__",
481                      "char");
482
483  if (TI.getShortWidth() > TI.getCharWidth())
484    DefineExactWidthIntType(TargetInfo::SignedShort, TI, Builder);
485
486  if (TI.getIntWidth() > TI.getShortWidth())
487    DefineExactWidthIntType(TargetInfo::SignedInt, TI, Builder);
488
489  if (TI.getLongWidth() > TI.getIntWidth())
490    DefineExactWidthIntType(TargetInfo::SignedLong, TI, Builder);
491
492  if (TI.getLongLongWidth() > TI.getLongWidth())
493    DefineExactWidthIntType(TargetInfo::SignedLongLong, TI, Builder);
494
495  // Add __builtin_va_list typedef.
496  Builder.append(TI.getVAListDeclaration());
497
498  if (const char *Prefix = TI.getUserLabelPrefix())
499    Builder.defineMacro("__USER_LABEL_PREFIX__", Prefix);
500
501  // Build configuration options.  FIXME: these should be controlled by
502  // command line options or something.
503  Builder.defineMacro("__FINITE_MATH_ONLY__", "0");
504
505  if (LangOpts.GNUInline)
506    Builder.defineMacro("__GNUC_GNU_INLINE__");
507  else
508    Builder.defineMacro("__GNUC_STDC_INLINE__");
509
510  if (LangOpts.NoInline)
511    Builder.defineMacro("__NO_INLINE__");
512
513  if (unsigned PICLevel = LangOpts.PICLevel) {
514    Builder.defineMacro("__PIC__", Twine(PICLevel));
515    Builder.defineMacro("__pic__", Twine(PICLevel));
516  }
517
518  // Macros to control C99 numerics and <float.h>
519  Builder.defineMacro("__FLT_EVAL_METHOD__", Twine(TI.getFloatEvalMethod()));
520  Builder.defineMacro("__FLT_RADIX__", "2");
521  int Dig = PickFP(&TI.getLongDoubleFormat(), -1/*FIXME*/, 17, 21, 33, 36);
522  Builder.defineMacro("__DECIMAL_DIG__", Twine(Dig));
523
524  if (LangOpts.getStackProtector() == LangOptions::SSPOn)
525    Builder.defineMacro("__SSP__");
526  else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
527    Builder.defineMacro("__SSP_ALL__", "2");
528
529  if (FEOpts.ProgramAction == frontend::RewriteObjC)
530    Builder.defineMacro("__weak", "__attribute__((objc_gc(weak)))");
531
532  // Define a macro that exists only when using the static analyzer.
533  if (FEOpts.ProgramAction == frontend::RunAnalysis)
534    Builder.defineMacro("__clang_analyzer__");
535
536  if (LangOpts.FastRelaxedMath)
537    Builder.defineMacro("__FAST_RELAXED_MATH__");
538
539  if (LangOpts.ObjCAutoRefCount) {
540    Builder.defineMacro("__weak", "__attribute__((objc_ownership(weak)))");
541    Builder.defineMacro("__strong", "__attribute__((objc_ownership(strong)))");
542    Builder.defineMacro("__autoreleasing",
543                        "__attribute__((objc_ownership(autoreleasing)))");
544    Builder.defineMacro("__unsafe_unretained",
545                        "__attribute__((objc_ownership(none)))");
546  }
547
548  // Get other target #defines.
549  TI.getTargetDefines(LangOpts, Builder);
550}
551
552// Initialize the remapping of files to alternative contents, e.g.,
553// those specified through other files.
554static void InitializeFileRemapping(DiagnosticsEngine &Diags,
555                                    SourceManager &SourceMgr,
556                                    FileManager &FileMgr,
557                                    const PreprocessorOptions &InitOpts) {
558  // Remap files in the source manager (with buffers).
559  for (PreprocessorOptions::const_remapped_file_buffer_iterator
560         Remap = InitOpts.remapped_file_buffer_begin(),
561         RemapEnd = InitOpts.remapped_file_buffer_end();
562       Remap != RemapEnd;
563       ++Remap) {
564    // Create the file entry for the file that we're mapping from.
565    const FileEntry *FromFile = FileMgr.getVirtualFile(Remap->first,
566                                                Remap->second->getBufferSize(),
567                                                       0);
568    if (!FromFile) {
569      Diags.Report(diag::err_fe_remap_missing_from_file)
570        << Remap->first;
571      if (!InitOpts.RetainRemappedFileBuffers)
572        delete Remap->second;
573      continue;
574    }
575
576    // Override the contents of the "from" file with the contents of
577    // the "to" file.
578    SourceMgr.overrideFileContents(FromFile, Remap->second,
579                                   InitOpts.RetainRemappedFileBuffers);
580  }
581
582  // Remap files in the source manager (with other files).
583  for (PreprocessorOptions::const_remapped_file_iterator
584         Remap = InitOpts.remapped_file_begin(),
585         RemapEnd = InitOpts.remapped_file_end();
586       Remap != RemapEnd;
587       ++Remap) {
588    // Find the file that we're mapping to.
589    const FileEntry *ToFile = FileMgr.getFile(Remap->second);
590    if (!ToFile) {
591      Diags.Report(diag::err_fe_remap_missing_to_file)
592      << Remap->first << Remap->second;
593      continue;
594    }
595
596    // Create the file entry for the file that we're mapping from.
597    const FileEntry *FromFile = FileMgr.getVirtualFile(Remap->first,
598                                                       ToFile->getSize(), 0);
599    if (!FromFile) {
600      Diags.Report(diag::err_fe_remap_missing_from_file)
601      << Remap->first;
602      continue;
603    }
604
605    // Override the contents of the "from" file with the contents of
606    // the "to" file.
607    SourceMgr.overrideFileContents(FromFile, ToFile);
608  }
609
610  SourceMgr.setOverridenFilesKeepOriginalName(
611                                        InitOpts.RemappedFilesKeepOriginalName);
612}
613
614/// InitializePreprocessor - Initialize the preprocessor getting it and the
615/// environment ready to process a single file. This returns true on error.
616///
617void clang::InitializePreprocessor(Preprocessor &PP,
618                                   const PreprocessorOptions &InitOpts,
619                                   const HeaderSearchOptions &HSOpts,
620                                   const FrontendOptions &FEOpts) {
621  const LangOptions &LangOpts = PP.getLangOptions();
622  std::string PredefineBuffer;
623  PredefineBuffer.reserve(4080);
624  llvm::raw_string_ostream Predefines(PredefineBuffer);
625  MacroBuilder Builder(Predefines);
626
627  InitializeFileRemapping(PP.getDiagnostics(), PP.getSourceManager(),
628                          PP.getFileManager(), InitOpts);
629
630  // Emit line markers for various builtin sections of the file.  We don't do
631  // this in asm preprocessor mode, because "# 4" is not a line marker directive
632  // in this mode.
633  if (!PP.getLangOptions().AsmPreprocessor)
634    Builder.append("# 1 \"<built-in>\" 3");
635
636  // Install things like __POWERPC__, __GNUC__, etc into the macro table.
637  if (InitOpts.UsePredefines) {
638    InitializePredefinedMacros(PP.getTargetInfo(), LangOpts, FEOpts, Builder);
639
640    // Install definitions to make Objective-C++ ARC work well with various
641    // C++ Standard Library implementations.
642    if (LangOpts.ObjC1 && LangOpts.CPlusPlus && LangOpts.ObjCAutoRefCount) {
643      switch (InitOpts.ObjCXXARCStandardLibrary) {
644      case ARCXX_nolib:
645        case ARCXX_libcxx:
646        break;
647
648      case ARCXX_libstdcxx:
649        AddObjCXXARCLibstdcxxDefines(LangOpts, Builder);
650        break;
651      }
652    }
653  }
654
655  // Even with predefines off, some macros are still predefined.
656  // These should all be defined in the preprocessor according to the
657  // current language configuration.
658  InitializeStandardPredefinedMacros(PP.getTargetInfo(), PP.getLangOptions(),
659                                     FEOpts, Builder);
660
661  // Add on the predefines from the driver.  Wrap in a #line directive to report
662  // that they come from the command line.
663  if (!PP.getLangOptions().AsmPreprocessor)
664    Builder.append("# 1 \"<command line>\" 1");
665
666  // Process #define's and #undef's in the order they are given.
667  for (unsigned i = 0, e = InitOpts.Macros.size(); i != e; ++i) {
668    if (InitOpts.Macros[i].second)  // isUndef
669      Builder.undefineMacro(InitOpts.Macros[i].first);
670    else
671      DefineBuiltinMacro(Builder, InitOpts.Macros[i].first,
672                         PP.getDiagnostics());
673  }
674
675  // If -imacros are specified, include them now.  These are processed before
676  // any -include directives.
677  for (unsigned i = 0, e = InitOpts.MacroIncludes.size(); i != e; ++i)
678    AddImplicitIncludeMacros(Builder, InitOpts.MacroIncludes[i],
679                             PP.getFileManager());
680
681  // Process -include directives.
682  for (unsigned i = 0, e = InitOpts.Includes.size(); i != e; ++i) {
683    const std::string &Path = InitOpts.Includes[i];
684    if (Path == InitOpts.ImplicitPTHInclude)
685      AddImplicitIncludePTH(Builder, PP, Path);
686    else
687      AddImplicitInclude(Builder, Path, PP.getFileManager());
688  }
689
690  // Exit the command line and go back to <built-in> (2 is LC_LEAVE).
691  if (!PP.getLangOptions().AsmPreprocessor)
692    Builder.append("# 1 \"<built-in>\" 2");
693
694  // Instruct the preprocessor to skip the preamble.
695  PP.setSkipMainFilePreamble(InitOpts.PrecompiledPreambleBytes.first,
696                             InitOpts.PrecompiledPreambleBytes.second);
697
698  // Copy PredefinedBuffer into the Preprocessor.
699  PP.setPredefines(Predefines.str());
700
701  // Initialize the header search object.
702  ApplyHeaderSearchOptions(PP.getHeaderSearchInfo(), HSOpts,
703                           PP.getLangOptions(),
704                           PP.getTargetInfo().getTriple());
705}
706