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