1 //===--- InitPreprocessor.cpp - PP initialization code. ---------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the clang::InitializePreprocessor function. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/Basic/FileManager.h" 14 #include "clang/Basic/MacroBuilder.h" 15 #include "clang/Basic/SourceManager.h" 16 #include "clang/Basic/SyncScope.h" 17 #include "clang/Basic/TargetInfo.h" 18 #include "clang/Basic/Version.h" 19 #include "clang/Frontend/FrontendDiagnostic.h" 20 #include "clang/Frontend/FrontendOptions.h" 21 #include "clang/Frontend/Utils.h" 22 #include "clang/Lex/HeaderSearch.h" 23 #include "clang/Lex/Preprocessor.h" 24 #include "clang/Lex/PreprocessorOptions.h" 25 #include "clang/Serialization/ASTReader.h" 26 #include "llvm/ADT/APFloat.h" 27 #include "llvm/IR/DataLayout.h" 28 using namespace clang; 29 30 static bool MacroBodyEndsInBackslash(StringRef MacroBody) { 31 while (!MacroBody.empty() && isWhitespace(MacroBody.back())) 32 MacroBody = MacroBody.drop_back(); 33 return !MacroBody.empty() && MacroBody.back() == '\\'; 34 } 35 36 // Append a #define line to Buf for Macro. Macro should be of the form XXX, 37 // in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit 38 // "#define XXX Y z W". To get a #define with no value, use "XXX=". 39 static void DefineBuiltinMacro(MacroBuilder &Builder, StringRef Macro, 40 DiagnosticsEngine &Diags) { 41 std::pair<StringRef, StringRef> MacroPair = Macro.split('='); 42 StringRef MacroName = MacroPair.first; 43 StringRef MacroBody = MacroPair.second; 44 if (MacroName.size() != Macro.size()) { 45 // Per GCC -D semantics, the macro ends at \n if it exists. 46 StringRef::size_type End = MacroBody.find_first_of("\n\r"); 47 if (End != StringRef::npos) 48 Diags.Report(diag::warn_fe_macro_contains_embedded_newline) 49 << MacroName; 50 MacroBody = MacroBody.substr(0, End); 51 // We handle macro bodies which end in a backslash by appending an extra 52 // backslash+newline. This makes sure we don't accidentally treat the 53 // backslash as a line continuation marker. 54 if (MacroBodyEndsInBackslash(MacroBody)) 55 Builder.defineMacro(MacroName, Twine(MacroBody) + "\\\n"); 56 else 57 Builder.defineMacro(MacroName, MacroBody); 58 } else { 59 // Push "macroname 1". 60 Builder.defineMacro(Macro); 61 } 62 } 63 64 /// AddImplicitInclude - Add an implicit \#include of the specified file to the 65 /// predefines buffer. 66 /// As these includes are generated by -include arguments the header search 67 /// logic is going to search relatively to the current working directory. 68 static void AddImplicitInclude(MacroBuilder &Builder, StringRef File) { 69 Builder.append(Twine("#include \"") + File + "\""); 70 } 71 72 static void AddImplicitIncludeMacros(MacroBuilder &Builder, StringRef File) { 73 Builder.append(Twine("#__include_macros \"") + File + "\""); 74 // Marker token to stop the __include_macros fetch loop. 75 Builder.append("##"); // ##? 76 } 77 78 /// Add an implicit \#include using the original file used to generate 79 /// a PCH file. 80 static void AddImplicitIncludePCH(MacroBuilder &Builder, Preprocessor &PP, 81 const PCHContainerReader &PCHContainerRdr, 82 StringRef ImplicitIncludePCH) { 83 std::string OriginalFile = ASTReader::getOriginalSourceFile( 84 std::string(ImplicitIncludePCH), PP.getFileManager(), PCHContainerRdr, 85 PP.getDiagnostics()); 86 if (OriginalFile.empty()) 87 return; 88 89 AddImplicitInclude(Builder, OriginalFile); 90 } 91 92 /// PickFP - This is used to pick a value based on the FP semantics of the 93 /// specified FP model. 94 template <typename T> 95 static T PickFP(const llvm::fltSemantics *Sem, T IEEEHalfVal, T IEEESingleVal, 96 T IEEEDoubleVal, T X87DoubleExtendedVal, T PPCDoubleDoubleVal, 97 T IEEEQuadVal) { 98 if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEhalf()) 99 return IEEEHalfVal; 100 if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEsingle()) 101 return IEEESingleVal; 102 if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEdouble()) 103 return IEEEDoubleVal; 104 if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::x87DoubleExtended()) 105 return X87DoubleExtendedVal; 106 if (Sem == (const llvm::fltSemantics*)&llvm::APFloat::PPCDoubleDouble()) 107 return PPCDoubleDoubleVal; 108 assert(Sem == (const llvm::fltSemantics*)&llvm::APFloat::IEEEquad()); 109 return IEEEQuadVal; 110 } 111 112 static void DefineFloatMacros(MacroBuilder &Builder, StringRef Prefix, 113 const llvm::fltSemantics *Sem, StringRef Ext) { 114 const char *DenormMin, *Epsilon, *Max, *Min; 115 DenormMin = PickFP(Sem, "5.9604644775390625e-8", "1.40129846e-45", 116 "4.9406564584124654e-324", "3.64519953188247460253e-4951", 117 "4.94065645841246544176568792868221e-324", 118 "6.47517511943802511092443895822764655e-4966"); 119 int Digits = PickFP(Sem, 3, 6, 15, 18, 31, 33); 120 int DecimalDigits = PickFP(Sem, 5, 9, 17, 21, 33, 36); 121 Epsilon = PickFP(Sem, "9.765625e-4", "1.19209290e-7", 122 "2.2204460492503131e-16", "1.08420217248550443401e-19", 123 "4.94065645841246544176568792868221e-324", 124 "1.92592994438723585305597794258492732e-34"); 125 int MantissaDigits = PickFP(Sem, 11, 24, 53, 64, 106, 113); 126 int Min10Exp = PickFP(Sem, -4, -37, -307, -4931, -291, -4931); 127 int Max10Exp = PickFP(Sem, 4, 38, 308, 4932, 308, 4932); 128 int MinExp = PickFP(Sem, -13, -125, -1021, -16381, -968, -16381); 129 int MaxExp = PickFP(Sem, 16, 128, 1024, 16384, 1024, 16384); 130 Min = PickFP(Sem, "6.103515625e-5", "1.17549435e-38", "2.2250738585072014e-308", 131 "3.36210314311209350626e-4932", 132 "2.00416836000897277799610805135016e-292", 133 "3.36210314311209350626267781732175260e-4932"); 134 Max = PickFP(Sem, "6.5504e+4", "3.40282347e+38", "1.7976931348623157e+308", 135 "1.18973149535723176502e+4932", 136 "1.79769313486231580793728971405301e+308", 137 "1.18973149535723176508575932662800702e+4932"); 138 139 SmallString<32> DefPrefix; 140 DefPrefix = "__"; 141 DefPrefix += Prefix; 142 DefPrefix += "_"; 143 144 Builder.defineMacro(DefPrefix + "DENORM_MIN__", Twine(DenormMin)+Ext); 145 Builder.defineMacro(DefPrefix + "HAS_DENORM__"); 146 Builder.defineMacro(DefPrefix + "DIG__", Twine(Digits)); 147 Builder.defineMacro(DefPrefix + "DECIMAL_DIG__", Twine(DecimalDigits)); 148 Builder.defineMacro(DefPrefix + "EPSILON__", Twine(Epsilon)+Ext); 149 Builder.defineMacro(DefPrefix + "HAS_INFINITY__"); 150 Builder.defineMacro(DefPrefix + "HAS_QUIET_NAN__"); 151 Builder.defineMacro(DefPrefix + "MANT_DIG__", Twine(MantissaDigits)); 152 153 Builder.defineMacro(DefPrefix + "MAX_10_EXP__", Twine(Max10Exp)); 154 Builder.defineMacro(DefPrefix + "MAX_EXP__", Twine(MaxExp)); 155 Builder.defineMacro(DefPrefix + "MAX__", Twine(Max)+Ext); 156 157 Builder.defineMacro(DefPrefix + "MIN_10_EXP__","("+Twine(Min10Exp)+")"); 158 Builder.defineMacro(DefPrefix + "MIN_EXP__", "("+Twine(MinExp)+")"); 159 Builder.defineMacro(DefPrefix + "MIN__", Twine(Min)+Ext); 160 } 161 162 163 /// DefineTypeSize - Emit a macro to the predefines buffer that declares a macro 164 /// named MacroName with the max value for a type with width 'TypeWidth' a 165 /// signedness of 'isSigned' and with a value suffix of 'ValSuffix' (e.g. LL). 166 static void DefineTypeSize(const Twine &MacroName, unsigned TypeWidth, 167 StringRef ValSuffix, bool isSigned, 168 MacroBuilder &Builder) { 169 llvm::APInt MaxVal = isSigned ? llvm::APInt::getSignedMaxValue(TypeWidth) 170 : llvm::APInt::getMaxValue(TypeWidth); 171 Builder.defineMacro(MacroName, toString(MaxVal, 10, isSigned) + ValSuffix); 172 } 173 174 /// DefineTypeSize - An overloaded helper that uses TargetInfo to determine 175 /// the width, suffix, and signedness of the given type 176 static void DefineTypeSize(const Twine &MacroName, TargetInfo::IntType Ty, 177 const TargetInfo &TI, MacroBuilder &Builder) { 178 DefineTypeSize(MacroName, TI.getTypeWidth(Ty), TI.getTypeConstantSuffix(Ty), 179 TI.isTypeSigned(Ty), Builder); 180 } 181 182 static void DefineFmt(const Twine &Prefix, TargetInfo::IntType Ty, 183 const TargetInfo &TI, MacroBuilder &Builder) { 184 bool IsSigned = TI.isTypeSigned(Ty); 185 StringRef FmtModifier = TI.getTypeFormatModifier(Ty); 186 for (const char *Fmt = IsSigned ? "di" : "ouxX"; *Fmt; ++Fmt) { 187 Builder.defineMacro(Prefix + "_FMT" + Twine(*Fmt) + "__", 188 Twine("\"") + FmtModifier + Twine(*Fmt) + "\""); 189 } 190 } 191 192 static void DefineType(const Twine &MacroName, TargetInfo::IntType Ty, 193 MacroBuilder &Builder) { 194 Builder.defineMacro(MacroName, TargetInfo::getTypeName(Ty)); 195 } 196 197 static void DefineTypeWidth(StringRef MacroName, TargetInfo::IntType Ty, 198 const TargetInfo &TI, MacroBuilder &Builder) { 199 Builder.defineMacro(MacroName, Twine(TI.getTypeWidth(Ty))); 200 } 201 202 static void DefineTypeSizeof(StringRef MacroName, unsigned BitWidth, 203 const TargetInfo &TI, MacroBuilder &Builder) { 204 Builder.defineMacro(MacroName, 205 Twine(BitWidth / TI.getCharWidth())); 206 } 207 208 static void DefineExactWidthIntType(TargetInfo::IntType Ty, 209 const TargetInfo &TI, 210 MacroBuilder &Builder) { 211 int TypeWidth = TI.getTypeWidth(Ty); 212 bool IsSigned = TI.isTypeSigned(Ty); 213 214 // Use the target specified int64 type, when appropriate, so that [u]int64_t 215 // ends up being defined in terms of the correct type. 216 if (TypeWidth == 64) 217 Ty = IsSigned ? TI.getInt64Type() : TI.getUInt64Type(); 218 219 // Use the target specified int16 type when appropriate. Some MCU targets 220 // (such as AVR) have definition of [u]int16_t to [un]signed int. 221 if (TypeWidth == 16) 222 Ty = IsSigned ? TI.getInt16Type() : TI.getUInt16Type(); 223 224 const char *Prefix = IsSigned ? "__INT" : "__UINT"; 225 226 DefineType(Prefix + Twine(TypeWidth) + "_TYPE__", Ty, Builder); 227 DefineFmt(Prefix + Twine(TypeWidth), Ty, TI, Builder); 228 229 StringRef ConstSuffix(TI.getTypeConstantSuffix(Ty)); 230 Builder.defineMacro(Prefix + Twine(TypeWidth) + "_C_SUFFIX__", ConstSuffix); 231 } 232 233 static void DefineExactWidthIntTypeSize(TargetInfo::IntType Ty, 234 const TargetInfo &TI, 235 MacroBuilder &Builder) { 236 int TypeWidth = TI.getTypeWidth(Ty); 237 bool IsSigned = TI.isTypeSigned(Ty); 238 239 // Use the target specified int64 type, when appropriate, so that [u]int64_t 240 // ends up being defined in terms of the correct type. 241 if (TypeWidth == 64) 242 Ty = IsSigned ? TI.getInt64Type() : TI.getUInt64Type(); 243 244 const char *Prefix = IsSigned ? "__INT" : "__UINT"; 245 DefineTypeSize(Prefix + Twine(TypeWidth) + "_MAX__", Ty, TI, Builder); 246 } 247 248 static void DefineLeastWidthIntType(unsigned TypeWidth, bool IsSigned, 249 const TargetInfo &TI, 250 MacroBuilder &Builder) { 251 TargetInfo::IntType Ty = TI.getLeastIntTypeByWidth(TypeWidth, IsSigned); 252 if (Ty == TargetInfo::NoInt) 253 return; 254 255 const char *Prefix = IsSigned ? "__INT_LEAST" : "__UINT_LEAST"; 256 DefineType(Prefix + Twine(TypeWidth) + "_TYPE__", Ty, Builder); 257 DefineTypeSize(Prefix + Twine(TypeWidth) + "_MAX__", Ty, TI, Builder); 258 DefineFmt(Prefix + Twine(TypeWidth), Ty, TI, Builder); 259 } 260 261 static void DefineFastIntType(unsigned TypeWidth, bool IsSigned, 262 const TargetInfo &TI, MacroBuilder &Builder) { 263 // stdint.h currently defines the fast int types as equivalent to the least 264 // types. 265 TargetInfo::IntType Ty = TI.getLeastIntTypeByWidth(TypeWidth, IsSigned); 266 if (Ty == TargetInfo::NoInt) 267 return; 268 269 const char *Prefix = IsSigned ? "__INT_FAST" : "__UINT_FAST"; 270 DefineType(Prefix + Twine(TypeWidth) + "_TYPE__", Ty, Builder); 271 DefineTypeSize(Prefix + Twine(TypeWidth) + "_MAX__", Ty, TI, Builder); 272 273 DefineFmt(Prefix + Twine(TypeWidth), Ty, TI, Builder); 274 } 275 276 277 /// Get the value the ATOMIC_*_LOCK_FREE macro should have for a type with 278 /// the specified properties. 279 static const char *getLockFreeValue(unsigned TypeWidth, unsigned TypeAlign, 280 unsigned InlineWidth) { 281 // Fully-aligned, power-of-2 sizes no larger than the inline 282 // width will be inlined as lock-free operations. 283 if (TypeWidth == TypeAlign && (TypeWidth & (TypeWidth - 1)) == 0 && 284 TypeWidth <= InlineWidth) 285 return "2"; // "always lock free" 286 // We cannot be certain what operations the lib calls might be 287 // able to implement as lock-free on future processors. 288 return "1"; // "sometimes lock free" 289 } 290 291 /// Add definitions required for a smooth interaction between 292 /// Objective-C++ automated reference counting and libstdc++ (4.2). 293 static void AddObjCXXARCLibstdcxxDefines(const LangOptions &LangOpts, 294 MacroBuilder &Builder) { 295 Builder.defineMacro("_GLIBCXX_PREDEFINED_OBJC_ARC_IS_SCALAR"); 296 297 std::string Result; 298 { 299 // Provide specializations for the __is_scalar type trait so that 300 // lifetime-qualified objects are not considered "scalar" types, which 301 // libstdc++ uses as an indicator of the presence of trivial copy, assign, 302 // default-construct, and destruct semantics (none of which hold for 303 // lifetime-qualified objects in ARC). 304 llvm::raw_string_ostream Out(Result); 305 306 Out << "namespace std {\n" 307 << "\n" 308 << "struct __true_type;\n" 309 << "struct __false_type;\n" 310 << "\n"; 311 312 Out << "template<typename _Tp> struct __is_scalar;\n" 313 << "\n"; 314 315 if (LangOpts.ObjCAutoRefCount) { 316 Out << "template<typename _Tp>\n" 317 << "struct __is_scalar<__attribute__((objc_ownership(strong))) _Tp> {\n" 318 << " enum { __value = 0 };\n" 319 << " typedef __false_type __type;\n" 320 << "};\n" 321 << "\n"; 322 } 323 324 if (LangOpts.ObjCWeak) { 325 Out << "template<typename _Tp>\n" 326 << "struct __is_scalar<__attribute__((objc_ownership(weak))) _Tp> {\n" 327 << " enum { __value = 0 };\n" 328 << " typedef __false_type __type;\n" 329 << "};\n" 330 << "\n"; 331 } 332 333 if (LangOpts.ObjCAutoRefCount) { 334 Out << "template<typename _Tp>\n" 335 << "struct __is_scalar<__attribute__((objc_ownership(autoreleasing)))" 336 << " _Tp> {\n" 337 << " enum { __value = 0 };\n" 338 << " typedef __false_type __type;\n" 339 << "};\n" 340 << "\n"; 341 } 342 343 Out << "}\n"; 344 } 345 Builder.append(Result); 346 } 347 348 static void InitializeStandardPredefinedMacros(const TargetInfo &TI, 349 const LangOptions &LangOpts, 350 const FrontendOptions &FEOpts, 351 MacroBuilder &Builder) { 352 // C++ [cpp.predefined]p1: 353 // The following macro names shall be defined by the implementation: 354 355 // -- __STDC__ 356 // [C++] Whether __STDC__ is predefined and if so, what its value is, 357 // are implementation-defined. 358 // (Removed in C++20.) 359 if (!LangOpts.MSVCCompat && !LangOpts.TraditionalCPP) 360 Builder.defineMacro("__STDC__"); 361 // -- __STDC_HOSTED__ 362 // The integer literal 1 if the implementation is a hosted 363 // implementation or the integer literal 0 if it is not. 364 if (LangOpts.Freestanding) 365 Builder.defineMacro("__STDC_HOSTED__", "0"); 366 else 367 Builder.defineMacro("__STDC_HOSTED__"); 368 369 // -- __STDC_VERSION__ 370 // [C++] Whether __STDC_VERSION__ is predefined and if so, what its 371 // value is, are implementation-defined. 372 // (Removed in C++20.) 373 if (!LangOpts.CPlusPlus) { 374 // FIXME: Use correct value for C23. 375 if (LangOpts.C2x) 376 Builder.defineMacro("__STDC_VERSION__", "202000L"); 377 else if (LangOpts.C17) 378 Builder.defineMacro("__STDC_VERSION__", "201710L"); 379 else if (LangOpts.C11) 380 Builder.defineMacro("__STDC_VERSION__", "201112L"); 381 else if (LangOpts.C99) 382 Builder.defineMacro("__STDC_VERSION__", "199901L"); 383 else if (!LangOpts.GNUMode && LangOpts.Digraphs) 384 Builder.defineMacro("__STDC_VERSION__", "199409L"); 385 } else { 386 // -- __cplusplus 387 // FIXME: Use correct value for C++23. 388 if (LangOpts.CPlusPlus2b) 389 Builder.defineMacro("__cplusplus", "202101L"); 390 // [C++20] The integer literal 202002L. 391 else if (LangOpts.CPlusPlus20) 392 Builder.defineMacro("__cplusplus", "202002L"); 393 // [C++17] The integer literal 201703L. 394 else if (LangOpts.CPlusPlus17) 395 Builder.defineMacro("__cplusplus", "201703L"); 396 // [C++14] The name __cplusplus is defined to the value 201402L when 397 // compiling a C++ translation unit. 398 else if (LangOpts.CPlusPlus14) 399 Builder.defineMacro("__cplusplus", "201402L"); 400 // [C++11] The name __cplusplus is defined to the value 201103L when 401 // compiling a C++ translation unit. 402 else if (LangOpts.CPlusPlus11) 403 Builder.defineMacro("__cplusplus", "201103L"); 404 // [C++03] The name __cplusplus is defined to the value 199711L when 405 // compiling a C++ translation unit. 406 else 407 Builder.defineMacro("__cplusplus", "199711L"); 408 409 // -- __STDCPP_DEFAULT_NEW_ALIGNMENT__ 410 // [C++17] An integer literal of type std::size_t whose value is the 411 // alignment guaranteed by a call to operator new(std::size_t) 412 // 413 // We provide this in all language modes, since it seems generally useful. 414 Builder.defineMacro("__STDCPP_DEFAULT_NEW_ALIGNMENT__", 415 Twine(TI.getNewAlign() / TI.getCharWidth()) + 416 TI.getTypeConstantSuffix(TI.getSizeType())); 417 418 // -- __STDCPP_THREADS__ 419 // Defined, and has the value integer literal 1, if and only if a 420 // program can have more than one thread of execution. 421 if (LangOpts.getThreadModel() == LangOptions::ThreadModelKind::POSIX) 422 Builder.defineMacro("__STDCPP_THREADS__", "1"); 423 } 424 425 // In C11 these are environment macros. In C++11 they are only defined 426 // as part of <cuchar>. To prevent breakage when mixing C and C++ 427 // code, define these macros unconditionally. We can define them 428 // unconditionally, as Clang always uses UTF-16 and UTF-32 for 16-bit 429 // and 32-bit character literals. 430 Builder.defineMacro("__STDC_UTF_16__", "1"); 431 Builder.defineMacro("__STDC_UTF_32__", "1"); 432 433 if (LangOpts.ObjC) 434 Builder.defineMacro("__OBJC__"); 435 436 // OpenCL v1.0/1.1 s6.9, v1.2/2.0 s6.10: Preprocessor Directives and Macros. 437 if (LangOpts.OpenCL) { 438 if (LangOpts.CPlusPlus) { 439 switch (LangOpts.OpenCLCPlusPlusVersion) { 440 case 100: 441 Builder.defineMacro("__OPENCL_CPP_VERSION__", "100"); 442 break; 443 case 202100: 444 Builder.defineMacro("__OPENCL_CPP_VERSION__", "202100"); 445 break; 446 default: 447 llvm_unreachable("Unsupported C++ version for OpenCL"); 448 } 449 Builder.defineMacro("__CL_CPP_VERSION_1_0__", "100"); 450 Builder.defineMacro("__CL_CPP_VERSION_2021__", "202100"); 451 } else { 452 // OpenCL v1.0 and v1.1 do not have a predefined macro to indicate the 453 // language standard with which the program is compiled. __OPENCL_VERSION__ 454 // is for the OpenCL version supported by the OpenCL device, which is not 455 // necessarily the language standard with which the program is compiled. 456 // A shared OpenCL header file requires a macro to indicate the language 457 // standard. As a workaround, __OPENCL_C_VERSION__ is defined for 458 // OpenCL v1.0 and v1.1. 459 switch (LangOpts.OpenCLVersion) { 460 case 100: 461 Builder.defineMacro("__OPENCL_C_VERSION__", "100"); 462 break; 463 case 110: 464 Builder.defineMacro("__OPENCL_C_VERSION__", "110"); 465 break; 466 case 120: 467 Builder.defineMacro("__OPENCL_C_VERSION__", "120"); 468 break; 469 case 200: 470 Builder.defineMacro("__OPENCL_C_VERSION__", "200"); 471 break; 472 case 300: 473 Builder.defineMacro("__OPENCL_C_VERSION__", "300"); 474 break; 475 default: 476 llvm_unreachable("Unsupported OpenCL version"); 477 } 478 } 479 Builder.defineMacro("CL_VERSION_1_0", "100"); 480 Builder.defineMacro("CL_VERSION_1_1", "110"); 481 Builder.defineMacro("CL_VERSION_1_2", "120"); 482 Builder.defineMacro("CL_VERSION_2_0", "200"); 483 Builder.defineMacro("CL_VERSION_3_0", "300"); 484 485 if (TI.isLittleEndian()) 486 Builder.defineMacro("__ENDIAN_LITTLE__"); 487 488 if (LangOpts.FastRelaxedMath) 489 Builder.defineMacro("__FAST_RELAXED_MATH__"); 490 } 491 492 if (LangOpts.SYCLIsDevice || LangOpts.SYCLIsHost) { 493 // SYCL Version is set to a value when building SYCL applications 494 if (LangOpts.getSYCLVersion() == LangOptions::SYCL_2017) 495 Builder.defineMacro("CL_SYCL_LANGUAGE_VERSION", "121"); 496 else if (LangOpts.getSYCLVersion() == LangOptions::SYCL_2020) 497 Builder.defineMacro("SYCL_LANGUAGE_VERSION", "202001"); 498 } 499 500 // Not "standard" per se, but available even with the -undef flag. 501 if (LangOpts.AsmPreprocessor) 502 Builder.defineMacro("__ASSEMBLER__"); 503 if (LangOpts.CUDA && !LangOpts.HIP) 504 Builder.defineMacro("__CUDA__"); 505 if (LangOpts.HIP) { 506 Builder.defineMacro("__HIP__"); 507 Builder.defineMacro("__HIPCC__"); 508 Builder.defineMacro("__HIP_MEMORY_SCOPE_SINGLETHREAD", "1"); 509 Builder.defineMacro("__HIP_MEMORY_SCOPE_WAVEFRONT", "2"); 510 Builder.defineMacro("__HIP_MEMORY_SCOPE_WORKGROUP", "3"); 511 Builder.defineMacro("__HIP_MEMORY_SCOPE_AGENT", "4"); 512 Builder.defineMacro("__HIP_MEMORY_SCOPE_SYSTEM", "5"); 513 if (LangOpts.CUDAIsDevice) 514 Builder.defineMacro("__HIP_DEVICE_COMPILE__"); 515 } 516 } 517 518 /// Initialize the predefined C++ language feature test macros defined in 519 /// ISO/IEC JTC1/SC22/WG21 (C++) SD-6: "SG10 Feature Test Recommendations". 520 static void InitializeCPlusPlusFeatureTestMacros(const LangOptions &LangOpts, 521 MacroBuilder &Builder) { 522 // C++98 features. 523 if (LangOpts.RTTI) 524 Builder.defineMacro("__cpp_rtti", "199711L"); 525 if (LangOpts.CXXExceptions) 526 Builder.defineMacro("__cpp_exceptions", "199711L"); 527 528 // C++11 features. 529 if (LangOpts.CPlusPlus11) { 530 Builder.defineMacro("__cpp_unicode_characters", "200704L"); 531 Builder.defineMacro("__cpp_raw_strings", "200710L"); 532 Builder.defineMacro("__cpp_unicode_literals", "200710L"); 533 Builder.defineMacro("__cpp_user_defined_literals", "200809L"); 534 Builder.defineMacro("__cpp_lambdas", "200907L"); 535 Builder.defineMacro("__cpp_constexpr", 536 LangOpts.CPlusPlus20 ? "201907L" : 537 LangOpts.CPlusPlus17 ? "201603L" : 538 LangOpts.CPlusPlus14 ? "201304L" : "200704"); 539 Builder.defineMacro("__cpp_constexpr_in_decltype", "201711L"); 540 Builder.defineMacro("__cpp_range_based_for", 541 LangOpts.CPlusPlus17 ? "201603L" : "200907"); 542 Builder.defineMacro("__cpp_static_assert", 543 LangOpts.CPlusPlus17 ? "201411L" : "200410"); 544 Builder.defineMacro("__cpp_decltype", "200707L"); 545 Builder.defineMacro("__cpp_attributes", "200809L"); 546 Builder.defineMacro("__cpp_rvalue_references", "200610L"); 547 Builder.defineMacro("__cpp_variadic_templates", "200704L"); 548 Builder.defineMacro("__cpp_initializer_lists", "200806L"); 549 Builder.defineMacro("__cpp_delegating_constructors", "200604L"); 550 Builder.defineMacro("__cpp_nsdmi", "200809L"); 551 Builder.defineMacro("__cpp_inheriting_constructors", "201511L"); 552 Builder.defineMacro("__cpp_ref_qualifiers", "200710L"); 553 Builder.defineMacro("__cpp_alias_templates", "200704L"); 554 } 555 if (LangOpts.ThreadsafeStatics) 556 Builder.defineMacro("__cpp_threadsafe_static_init", "200806L"); 557 558 // C++14 features. 559 if (LangOpts.CPlusPlus14) { 560 Builder.defineMacro("__cpp_binary_literals", "201304L"); 561 Builder.defineMacro("__cpp_digit_separators", "201309L"); 562 Builder.defineMacro("__cpp_init_captures", 563 LangOpts.CPlusPlus20 ? "201803L" : "201304L"); 564 Builder.defineMacro("__cpp_generic_lambdas", 565 LangOpts.CPlusPlus20 ? "201707L" : "201304L"); 566 Builder.defineMacro("__cpp_decltype_auto", "201304L"); 567 Builder.defineMacro("__cpp_return_type_deduction", "201304L"); 568 Builder.defineMacro("__cpp_aggregate_nsdmi", "201304L"); 569 Builder.defineMacro("__cpp_variable_templates", "201304L"); 570 } 571 if (LangOpts.SizedDeallocation) 572 Builder.defineMacro("__cpp_sized_deallocation", "201309L"); 573 574 // C++17 features. 575 if (LangOpts.CPlusPlus17) { 576 Builder.defineMacro("__cpp_hex_float", "201603L"); 577 Builder.defineMacro("__cpp_inline_variables", "201606L"); 578 Builder.defineMacro("__cpp_noexcept_function_type", "201510L"); 579 Builder.defineMacro("__cpp_capture_star_this", "201603L"); 580 Builder.defineMacro("__cpp_if_constexpr", "201606L"); 581 Builder.defineMacro("__cpp_deduction_guides", "201703L"); // (not latest) 582 Builder.defineMacro("__cpp_template_auto", "201606L"); // (old name) 583 Builder.defineMacro("__cpp_namespace_attributes", "201411L"); 584 Builder.defineMacro("__cpp_enumerator_attributes", "201411L"); 585 Builder.defineMacro("__cpp_nested_namespace_definitions", "201411L"); 586 Builder.defineMacro("__cpp_variadic_using", "201611L"); 587 Builder.defineMacro("__cpp_aggregate_bases", "201603L"); 588 Builder.defineMacro("__cpp_structured_bindings", "201606L"); 589 Builder.defineMacro("__cpp_nontype_template_args", 590 "201411L"); // (not latest) 591 Builder.defineMacro("__cpp_fold_expressions", "201603L"); 592 Builder.defineMacro("__cpp_guaranteed_copy_elision", "201606L"); 593 Builder.defineMacro("__cpp_nontype_template_parameter_auto", "201606L"); 594 } 595 if (LangOpts.AlignedAllocation && !LangOpts.AlignedAllocationUnavailable) 596 Builder.defineMacro("__cpp_aligned_new", "201606L"); 597 if (LangOpts.RelaxedTemplateTemplateArgs) 598 Builder.defineMacro("__cpp_template_template_args", "201611L"); 599 600 // C++20 features. 601 if (LangOpts.CPlusPlus20) { 602 //Builder.defineMacro("__cpp_aggregate_paren_init", "201902L"); 603 Builder.defineMacro("__cpp_concepts", "201907L"); 604 Builder.defineMacro("__cpp_conditional_explicit", "201806L"); 605 //Builder.defineMacro("__cpp_consteval", "201811L"); 606 Builder.defineMacro("__cpp_constexpr_dynamic_alloc", "201907L"); 607 Builder.defineMacro("__cpp_constinit", "201907L"); 608 Builder.defineMacro("__cpp_impl_coroutine", "201902L"); 609 Builder.defineMacro("__cpp_designated_initializers", "201707L"); 610 Builder.defineMacro("__cpp_impl_three_way_comparison", "201907L"); 611 //Builder.defineMacro("__cpp_modules", "201907L"); 612 Builder.defineMacro("__cpp_using_enum", "201907L"); 613 } 614 // C++2b features. 615 if (LangOpts.CPlusPlus2b) { 616 Builder.defineMacro("__cpp_implicit_move", "202011L"); 617 Builder.defineMacro("__cpp_size_t_suffix", "202011L"); 618 Builder.defineMacro("__cpp_if_consteval", "202106L"); 619 } 620 if (LangOpts.Char8) 621 Builder.defineMacro("__cpp_char8_t", "201811L"); 622 Builder.defineMacro("__cpp_impl_destroying_delete", "201806L"); 623 624 // TS features. 625 if (LangOpts.Coroutines) 626 Builder.defineMacro("__cpp_coroutines", "201703L"); 627 } 628 629 /// InitializeOpenCLFeatureTestMacros - Define OpenCL macros based on target 630 /// settings and language version 631 void InitializeOpenCLFeatureTestMacros(const TargetInfo &TI, 632 const LangOptions &Opts, 633 MacroBuilder &Builder) { 634 const llvm::StringMap<bool> &OpenCLFeaturesMap = TI.getSupportedOpenCLOpts(); 635 // FIXME: OpenCL options which affect language semantics/syntax 636 // should be moved into LangOptions. 637 auto defineOpenCLExtMacro = [&](llvm::StringRef Name, auto... OptArgs) { 638 // Check if extension is supported by target and is available in this 639 // OpenCL version 640 if (TI.hasFeatureEnabled(OpenCLFeaturesMap, Name) && 641 OpenCLOptions::isOpenCLOptionAvailableIn(Opts, OptArgs...)) 642 Builder.defineMacro(Name); 643 }; 644 #define OPENCL_GENERIC_EXTENSION(Ext, ...) \ 645 defineOpenCLExtMacro(#Ext, __VA_ARGS__); 646 #include "clang/Basic/OpenCLExtensions.def" 647 648 // Assume compiling for FULL profile 649 Builder.defineMacro("__opencl_c_int64"); 650 } 651 652 static void InitializePredefinedMacros(const TargetInfo &TI, 653 const LangOptions &LangOpts, 654 const FrontendOptions &FEOpts, 655 const PreprocessorOptions &PPOpts, 656 MacroBuilder &Builder) { 657 // Compiler version introspection macros. 658 Builder.defineMacro("__llvm__"); // LLVM Backend 659 Builder.defineMacro("__clang__"); // Clang Frontend 660 #define TOSTR2(X) #X 661 #define TOSTR(X) TOSTR2(X) 662 Builder.defineMacro("__clang_major__", TOSTR(CLANG_VERSION_MAJOR)); 663 Builder.defineMacro("__clang_minor__", TOSTR(CLANG_VERSION_MINOR)); 664 Builder.defineMacro("__clang_patchlevel__", TOSTR(CLANG_VERSION_PATCHLEVEL)); 665 #undef TOSTR 666 #undef TOSTR2 667 Builder.defineMacro("__clang_version__", 668 "\"" CLANG_VERSION_STRING " " 669 + getClangFullRepositoryVersion() + "\""); 670 671 if (LangOpts.GNUCVersion != 0) { 672 // Major, minor, patch, are given two decimal places each, so 4.2.1 becomes 673 // 40201. 674 unsigned GNUCMajor = LangOpts.GNUCVersion / 100 / 100; 675 unsigned GNUCMinor = LangOpts.GNUCVersion / 100 % 100; 676 unsigned GNUCPatch = LangOpts.GNUCVersion % 100; 677 Builder.defineMacro("__GNUC__", Twine(GNUCMajor)); 678 Builder.defineMacro("__GNUC_MINOR__", Twine(GNUCMinor)); 679 Builder.defineMacro("__GNUC_PATCHLEVEL__", Twine(GNUCPatch)); 680 Builder.defineMacro("__GXX_ABI_VERSION", "1002"); 681 682 if (LangOpts.CPlusPlus) { 683 Builder.defineMacro("__GNUG__", Twine(GNUCMajor)); 684 Builder.defineMacro("__GXX_WEAK__"); 685 } 686 } 687 688 // Define macros for the C11 / C++11 memory orderings 689 Builder.defineMacro("__ATOMIC_RELAXED", "0"); 690 Builder.defineMacro("__ATOMIC_CONSUME", "1"); 691 Builder.defineMacro("__ATOMIC_ACQUIRE", "2"); 692 Builder.defineMacro("__ATOMIC_RELEASE", "3"); 693 Builder.defineMacro("__ATOMIC_ACQ_REL", "4"); 694 Builder.defineMacro("__ATOMIC_SEQ_CST", "5"); 695 696 // Define macros for the OpenCL memory scope. 697 // The values should match AtomicScopeOpenCLModel::ID enum. 698 static_assert( 699 static_cast<unsigned>(AtomicScopeOpenCLModel::WorkGroup) == 1 && 700 static_cast<unsigned>(AtomicScopeOpenCLModel::Device) == 2 && 701 static_cast<unsigned>(AtomicScopeOpenCLModel::AllSVMDevices) == 3 && 702 static_cast<unsigned>(AtomicScopeOpenCLModel::SubGroup) == 4, 703 "Invalid OpenCL memory scope enum definition"); 704 Builder.defineMacro("__OPENCL_MEMORY_SCOPE_WORK_ITEM", "0"); 705 Builder.defineMacro("__OPENCL_MEMORY_SCOPE_WORK_GROUP", "1"); 706 Builder.defineMacro("__OPENCL_MEMORY_SCOPE_DEVICE", "2"); 707 Builder.defineMacro("__OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES", "3"); 708 Builder.defineMacro("__OPENCL_MEMORY_SCOPE_SUB_GROUP", "4"); 709 710 // Support for #pragma redefine_extname (Sun compatibility) 711 Builder.defineMacro("__PRAGMA_REDEFINE_EXTNAME", "1"); 712 713 // Previously this macro was set to a string aiming to achieve compatibility 714 // with GCC 4.2.1. Now, just return the full Clang version 715 Builder.defineMacro("__VERSION__", "\"" + 716 Twine(getClangFullCPPVersion()) + "\""); 717 718 // Initialize language-specific preprocessor defines. 719 720 // Standard conforming mode? 721 if (!LangOpts.GNUMode && !LangOpts.MSVCCompat) 722 Builder.defineMacro("__STRICT_ANSI__"); 723 724 if (LangOpts.GNUCVersion && LangOpts.CPlusPlus11) 725 Builder.defineMacro("__GXX_EXPERIMENTAL_CXX0X__"); 726 727 if (LangOpts.ObjC) { 728 if (LangOpts.ObjCRuntime.isNonFragile()) { 729 Builder.defineMacro("__OBJC2__"); 730 731 if (LangOpts.ObjCExceptions) 732 Builder.defineMacro("OBJC_ZEROCOST_EXCEPTIONS"); 733 } 734 735 if (LangOpts.getGC() != LangOptions::NonGC) 736 Builder.defineMacro("__OBJC_GC__"); 737 738 if (LangOpts.ObjCRuntime.isNeXTFamily()) 739 Builder.defineMacro("__NEXT_RUNTIME__"); 740 741 if (LangOpts.ObjCRuntime.getKind() == ObjCRuntime::GNUstep) { 742 auto version = LangOpts.ObjCRuntime.getVersion(); 743 std::string versionString = "1"; 744 // Don't rely on the tuple argument, because we can be asked to target 745 // later ABIs than we actually support, so clamp these values to those 746 // currently supported 747 if (version >= VersionTuple(2, 0)) 748 Builder.defineMacro("__OBJC_GNUSTEP_RUNTIME_ABI__", "20"); 749 else 750 Builder.defineMacro("__OBJC_GNUSTEP_RUNTIME_ABI__", 751 "1" + Twine(std::min(8U, version.getMinor().getValueOr(0)))); 752 } 753 754 if (LangOpts.ObjCRuntime.getKind() == ObjCRuntime::ObjFW) { 755 VersionTuple tuple = LangOpts.ObjCRuntime.getVersion(); 756 757 unsigned minor = 0; 758 if (tuple.getMinor().hasValue()) 759 minor = tuple.getMinor().getValue(); 760 761 unsigned subminor = 0; 762 if (tuple.getSubminor().hasValue()) 763 subminor = tuple.getSubminor().getValue(); 764 765 Builder.defineMacro("__OBJFW_RUNTIME_ABI__", 766 Twine(tuple.getMajor() * 10000 + minor * 100 + 767 subminor)); 768 } 769 770 Builder.defineMacro("IBOutlet", "__attribute__((iboutlet))"); 771 Builder.defineMacro("IBOutletCollection(ClassName)", 772 "__attribute__((iboutletcollection(ClassName)))"); 773 Builder.defineMacro("IBAction", "void)__attribute__((ibaction)"); 774 Builder.defineMacro("IBInspectable", ""); 775 Builder.defineMacro("IB_DESIGNABLE", ""); 776 } 777 778 // Define a macro that describes the Objective-C boolean type even for C 779 // and C++ since BOOL can be used from non Objective-C code. 780 Builder.defineMacro("__OBJC_BOOL_IS_BOOL", 781 Twine(TI.useSignedCharForObjCBool() ? "0" : "1")); 782 783 if (LangOpts.CPlusPlus) 784 InitializeCPlusPlusFeatureTestMacros(LangOpts, Builder); 785 786 // darwin_constant_cfstrings controls this. This is also dependent 787 // on other things like the runtime I believe. This is set even for C code. 788 if (!LangOpts.NoConstantCFStrings) 789 Builder.defineMacro("__CONSTANT_CFSTRINGS__"); 790 791 if (LangOpts.ObjC) 792 Builder.defineMacro("OBJC_NEW_PROPERTIES"); 793 794 if (LangOpts.PascalStrings) 795 Builder.defineMacro("__PASCAL_STRINGS__"); 796 797 if (LangOpts.Blocks) { 798 Builder.defineMacro("__block", "__attribute__((__blocks__(byref)))"); 799 Builder.defineMacro("__BLOCKS__"); 800 } 801 802 if (!LangOpts.MSVCCompat && LangOpts.Exceptions) 803 Builder.defineMacro("__EXCEPTIONS"); 804 if (LangOpts.GNUCVersion && LangOpts.RTTI) 805 Builder.defineMacro("__GXX_RTTI"); 806 807 if (LangOpts.hasSjLjExceptions()) 808 Builder.defineMacro("__USING_SJLJ_EXCEPTIONS__"); 809 else if (LangOpts.hasSEHExceptions()) 810 Builder.defineMacro("__SEH__"); 811 else if (LangOpts.hasDWARFExceptions() && 812 (TI.getTriple().isThumb() || TI.getTriple().isARM())) 813 Builder.defineMacro("__ARM_DWARF_EH__"); 814 815 if (LangOpts.Deprecated) 816 Builder.defineMacro("__DEPRECATED"); 817 818 if (!LangOpts.MSVCCompat && LangOpts.CPlusPlus) 819 Builder.defineMacro("__private_extern__", "extern"); 820 821 if (LangOpts.MicrosoftExt) { 822 if (LangOpts.WChar) { 823 // wchar_t supported as a keyword. 824 Builder.defineMacro("_WCHAR_T_DEFINED"); 825 Builder.defineMacro("_NATIVE_WCHAR_T_DEFINED"); 826 } 827 } 828 829 // Macros to help identify the narrow and wide character sets 830 // FIXME: clang currently ignores -fexec-charset=. If this changes, 831 // then this may need to be updated. 832 Builder.defineMacro("__clang_literal_encoding__", "\"UTF-8\""); 833 if (TI.getTypeWidth(TI.getWCharType()) >= 32) { 834 // FIXME: 32-bit wchar_t signals UTF-32. This may change 835 // if -fwide-exec-charset= is ever supported. 836 Builder.defineMacro("__clang_wide_literal_encoding__", "\"UTF-32\""); 837 } else { 838 // FIXME: Less-than 32-bit wchar_t generally means UTF-16 839 // (e.g., Windows, 32-bit IBM). This may need to be 840 // updated if -fwide-exec-charset= is ever supported. 841 Builder.defineMacro("__clang_wide_literal_encoding__", "\"UTF-16\""); 842 } 843 844 if (LangOpts.Optimize) 845 Builder.defineMacro("__OPTIMIZE__"); 846 if (LangOpts.OptimizeSize) 847 Builder.defineMacro("__OPTIMIZE_SIZE__"); 848 849 if (LangOpts.FastMath) 850 Builder.defineMacro("__FAST_MATH__"); 851 852 // Initialize target-specific preprocessor defines. 853 854 // __BYTE_ORDER__ was added in GCC 4.6. It's analogous 855 // to the macro __BYTE_ORDER (no trailing underscores) 856 // from glibc's <endian.h> header. 857 // We don't support the PDP-11 as a target, but include 858 // the define so it can still be compared against. 859 Builder.defineMacro("__ORDER_LITTLE_ENDIAN__", "1234"); 860 Builder.defineMacro("__ORDER_BIG_ENDIAN__", "4321"); 861 Builder.defineMacro("__ORDER_PDP_ENDIAN__", "3412"); 862 if (TI.isBigEndian()) { 863 Builder.defineMacro("__BYTE_ORDER__", "__ORDER_BIG_ENDIAN__"); 864 Builder.defineMacro("__BIG_ENDIAN__"); 865 } else { 866 Builder.defineMacro("__BYTE_ORDER__", "__ORDER_LITTLE_ENDIAN__"); 867 Builder.defineMacro("__LITTLE_ENDIAN__"); 868 } 869 870 if (TI.getPointerWidth(0) == 64 && TI.getLongWidth() == 64 871 && TI.getIntWidth() == 32) { 872 Builder.defineMacro("_LP64"); 873 Builder.defineMacro("__LP64__"); 874 } 875 876 if (TI.getPointerWidth(0) == 32 && TI.getLongWidth() == 32 877 && TI.getIntWidth() == 32) { 878 Builder.defineMacro("_ILP32"); 879 Builder.defineMacro("__ILP32__"); 880 } 881 882 // Define type sizing macros based on the target properties. 883 assert(TI.getCharWidth() == 8 && "Only support 8-bit char so far"); 884 Builder.defineMacro("__CHAR_BIT__", Twine(TI.getCharWidth())); 885 886 DefineTypeSize("__SCHAR_MAX__", TargetInfo::SignedChar, TI, Builder); 887 DefineTypeSize("__SHRT_MAX__", TargetInfo::SignedShort, TI, Builder); 888 DefineTypeSize("__INT_MAX__", TargetInfo::SignedInt, TI, Builder); 889 DefineTypeSize("__LONG_MAX__", TargetInfo::SignedLong, TI, Builder); 890 DefineTypeSize("__LONG_LONG_MAX__", TargetInfo::SignedLongLong, TI, Builder); 891 DefineTypeSize("__WCHAR_MAX__", TI.getWCharType(), TI, Builder); 892 DefineTypeSize("__WINT_MAX__", TI.getWIntType(), TI, Builder); 893 DefineTypeSize("__INTMAX_MAX__", TI.getIntMaxType(), TI, Builder); 894 DefineTypeSize("__SIZE_MAX__", TI.getSizeType(), TI, Builder); 895 896 DefineTypeSize("__UINTMAX_MAX__", TI.getUIntMaxType(), TI, Builder); 897 DefineTypeSize("__PTRDIFF_MAX__", TI.getPtrDiffType(0), TI, Builder); 898 DefineTypeSize("__INTPTR_MAX__", TI.getIntPtrType(), TI, Builder); 899 DefineTypeSize("__UINTPTR_MAX__", TI.getUIntPtrType(), TI, Builder); 900 901 DefineTypeSizeof("__SIZEOF_DOUBLE__", TI.getDoubleWidth(), TI, Builder); 902 DefineTypeSizeof("__SIZEOF_FLOAT__", TI.getFloatWidth(), TI, Builder); 903 DefineTypeSizeof("__SIZEOF_INT__", TI.getIntWidth(), TI, Builder); 904 DefineTypeSizeof("__SIZEOF_LONG__", TI.getLongWidth(), TI, Builder); 905 DefineTypeSizeof("__SIZEOF_LONG_DOUBLE__",TI.getLongDoubleWidth(),TI,Builder); 906 DefineTypeSizeof("__SIZEOF_LONG_LONG__", TI.getLongLongWidth(), TI, Builder); 907 DefineTypeSizeof("__SIZEOF_POINTER__", TI.getPointerWidth(0), TI, Builder); 908 DefineTypeSizeof("__SIZEOF_SHORT__", TI.getShortWidth(), TI, Builder); 909 DefineTypeSizeof("__SIZEOF_PTRDIFF_T__", 910 TI.getTypeWidth(TI.getPtrDiffType(0)), TI, Builder); 911 DefineTypeSizeof("__SIZEOF_SIZE_T__", 912 TI.getTypeWidth(TI.getSizeType()), TI, Builder); 913 DefineTypeSizeof("__SIZEOF_WCHAR_T__", 914 TI.getTypeWidth(TI.getWCharType()), TI, Builder); 915 DefineTypeSizeof("__SIZEOF_WINT_T__", 916 TI.getTypeWidth(TI.getWIntType()), TI, Builder); 917 if (TI.hasInt128Type()) 918 DefineTypeSizeof("__SIZEOF_INT128__", 128, TI, Builder); 919 920 DefineType("__INTMAX_TYPE__", TI.getIntMaxType(), Builder); 921 DefineFmt("__INTMAX", TI.getIntMaxType(), TI, Builder); 922 Builder.defineMacro("__INTMAX_C_SUFFIX__", 923 TI.getTypeConstantSuffix(TI.getIntMaxType())); 924 DefineType("__UINTMAX_TYPE__", TI.getUIntMaxType(), Builder); 925 DefineFmt("__UINTMAX", TI.getUIntMaxType(), TI, Builder); 926 Builder.defineMacro("__UINTMAX_C_SUFFIX__", 927 TI.getTypeConstantSuffix(TI.getUIntMaxType())); 928 DefineTypeWidth("__INTMAX_WIDTH__", TI.getIntMaxType(), TI, Builder); 929 DefineType("__PTRDIFF_TYPE__", TI.getPtrDiffType(0), Builder); 930 DefineFmt("__PTRDIFF", TI.getPtrDiffType(0), TI, Builder); 931 DefineTypeWidth("__PTRDIFF_WIDTH__", TI.getPtrDiffType(0), TI, Builder); 932 DefineType("__INTPTR_TYPE__", TI.getIntPtrType(), Builder); 933 DefineFmt("__INTPTR", TI.getIntPtrType(), TI, Builder); 934 DefineTypeWidth("__INTPTR_WIDTH__", TI.getIntPtrType(), TI, Builder); 935 DefineType("__SIZE_TYPE__", TI.getSizeType(), Builder); 936 DefineFmt("__SIZE", TI.getSizeType(), TI, Builder); 937 DefineTypeWidth("__SIZE_WIDTH__", TI.getSizeType(), TI, Builder); 938 DefineType("__WCHAR_TYPE__", TI.getWCharType(), Builder); 939 DefineTypeWidth("__WCHAR_WIDTH__", TI.getWCharType(), TI, Builder); 940 DefineType("__WINT_TYPE__", TI.getWIntType(), Builder); 941 DefineTypeWidth("__WINT_WIDTH__", TI.getWIntType(), TI, Builder); 942 DefineTypeWidth("__SIG_ATOMIC_WIDTH__", TI.getSigAtomicType(), TI, Builder); 943 DefineTypeSize("__SIG_ATOMIC_MAX__", TI.getSigAtomicType(), TI, Builder); 944 DefineType("__CHAR16_TYPE__", TI.getChar16Type(), Builder); 945 DefineType("__CHAR32_TYPE__", TI.getChar32Type(), Builder); 946 947 DefineTypeWidth("__UINTMAX_WIDTH__", TI.getUIntMaxType(), TI, Builder); 948 DefineType("__UINTPTR_TYPE__", TI.getUIntPtrType(), Builder); 949 DefineFmt("__UINTPTR", TI.getUIntPtrType(), TI, Builder); 950 DefineTypeWidth("__UINTPTR_WIDTH__", TI.getUIntPtrType(), TI, Builder); 951 952 if (TI.hasFloat16Type()) 953 DefineFloatMacros(Builder, "FLT16", &TI.getHalfFormat(), "F16"); 954 DefineFloatMacros(Builder, "FLT", &TI.getFloatFormat(), "F"); 955 DefineFloatMacros(Builder, "DBL", &TI.getDoubleFormat(), ""); 956 DefineFloatMacros(Builder, "LDBL", &TI.getLongDoubleFormat(), "L"); 957 958 // Define a __POINTER_WIDTH__ macro for stdint.h. 959 Builder.defineMacro("__POINTER_WIDTH__", 960 Twine((int)TI.getPointerWidth(0))); 961 962 // Define __BIGGEST_ALIGNMENT__ to be compatible with gcc. 963 Builder.defineMacro("__BIGGEST_ALIGNMENT__", 964 Twine(TI.getSuitableAlign() / TI.getCharWidth()) ); 965 966 if (!LangOpts.CharIsSigned) 967 Builder.defineMacro("__CHAR_UNSIGNED__"); 968 969 if (!TargetInfo::isTypeSigned(TI.getWCharType())) 970 Builder.defineMacro("__WCHAR_UNSIGNED__"); 971 972 if (!TargetInfo::isTypeSigned(TI.getWIntType())) 973 Builder.defineMacro("__WINT_UNSIGNED__"); 974 975 // Define exact-width integer types for stdint.h 976 DefineExactWidthIntType(TargetInfo::SignedChar, TI, Builder); 977 978 if (TI.getShortWidth() > TI.getCharWidth()) 979 DefineExactWidthIntType(TargetInfo::SignedShort, TI, Builder); 980 981 if (TI.getIntWidth() > TI.getShortWidth()) 982 DefineExactWidthIntType(TargetInfo::SignedInt, TI, Builder); 983 984 if (TI.getLongWidth() > TI.getIntWidth()) 985 DefineExactWidthIntType(TargetInfo::SignedLong, TI, Builder); 986 987 if (TI.getLongLongWidth() > TI.getLongWidth()) 988 DefineExactWidthIntType(TargetInfo::SignedLongLong, TI, Builder); 989 990 DefineExactWidthIntType(TargetInfo::UnsignedChar, TI, Builder); 991 DefineExactWidthIntTypeSize(TargetInfo::UnsignedChar, TI, Builder); 992 DefineExactWidthIntTypeSize(TargetInfo::SignedChar, TI, Builder); 993 994 if (TI.getShortWidth() > TI.getCharWidth()) { 995 DefineExactWidthIntType(TargetInfo::UnsignedShort, TI, Builder); 996 DefineExactWidthIntTypeSize(TargetInfo::UnsignedShort, TI, Builder); 997 DefineExactWidthIntTypeSize(TargetInfo::SignedShort, TI, Builder); 998 } 999 1000 if (TI.getIntWidth() > TI.getShortWidth()) { 1001 DefineExactWidthIntType(TargetInfo::UnsignedInt, TI, Builder); 1002 DefineExactWidthIntTypeSize(TargetInfo::UnsignedInt, TI, Builder); 1003 DefineExactWidthIntTypeSize(TargetInfo::SignedInt, TI, Builder); 1004 } 1005 1006 if (TI.getLongWidth() > TI.getIntWidth()) { 1007 DefineExactWidthIntType(TargetInfo::UnsignedLong, TI, Builder); 1008 DefineExactWidthIntTypeSize(TargetInfo::UnsignedLong, TI, Builder); 1009 DefineExactWidthIntTypeSize(TargetInfo::SignedLong, TI, Builder); 1010 } 1011 1012 if (TI.getLongLongWidth() > TI.getLongWidth()) { 1013 DefineExactWidthIntType(TargetInfo::UnsignedLongLong, TI, Builder); 1014 DefineExactWidthIntTypeSize(TargetInfo::UnsignedLongLong, TI, Builder); 1015 DefineExactWidthIntTypeSize(TargetInfo::SignedLongLong, TI, Builder); 1016 } 1017 1018 DefineLeastWidthIntType(8, true, TI, Builder); 1019 DefineLeastWidthIntType(8, false, TI, Builder); 1020 DefineLeastWidthIntType(16, true, TI, Builder); 1021 DefineLeastWidthIntType(16, false, TI, Builder); 1022 DefineLeastWidthIntType(32, true, TI, Builder); 1023 DefineLeastWidthIntType(32, false, TI, Builder); 1024 DefineLeastWidthIntType(64, true, TI, Builder); 1025 DefineLeastWidthIntType(64, false, TI, Builder); 1026 1027 DefineFastIntType(8, true, TI, Builder); 1028 DefineFastIntType(8, false, TI, Builder); 1029 DefineFastIntType(16, true, TI, Builder); 1030 DefineFastIntType(16, false, TI, Builder); 1031 DefineFastIntType(32, true, TI, Builder); 1032 DefineFastIntType(32, false, TI, Builder); 1033 DefineFastIntType(64, true, TI, Builder); 1034 DefineFastIntType(64, false, TI, Builder); 1035 1036 Builder.defineMacro("__USER_LABEL_PREFIX__", TI.getUserLabelPrefix()); 1037 1038 if (LangOpts.FastMath || LangOpts.FiniteMathOnly) 1039 Builder.defineMacro("__FINITE_MATH_ONLY__", "1"); 1040 else 1041 Builder.defineMacro("__FINITE_MATH_ONLY__", "0"); 1042 1043 if (LangOpts.GNUCVersion) { 1044 if (LangOpts.GNUInline || LangOpts.CPlusPlus) 1045 Builder.defineMacro("__GNUC_GNU_INLINE__"); 1046 else 1047 Builder.defineMacro("__GNUC_STDC_INLINE__"); 1048 1049 // The value written by __atomic_test_and_set. 1050 // FIXME: This is target-dependent. 1051 Builder.defineMacro("__GCC_ATOMIC_TEST_AND_SET_TRUEVAL", "1"); 1052 } 1053 1054 auto addLockFreeMacros = [&](const llvm::Twine &Prefix) { 1055 // Used by libc++ and libstdc++ to implement ATOMIC_<foo>_LOCK_FREE. 1056 unsigned InlineWidthBits = TI.getMaxAtomicInlineWidth(); 1057 #define DEFINE_LOCK_FREE_MACRO(TYPE, Type) \ 1058 Builder.defineMacro(Prefix + #TYPE "_LOCK_FREE", \ 1059 getLockFreeValue(TI.get##Type##Width(), \ 1060 TI.get##Type##Align(), \ 1061 InlineWidthBits)); 1062 DEFINE_LOCK_FREE_MACRO(BOOL, Bool); 1063 DEFINE_LOCK_FREE_MACRO(CHAR, Char); 1064 if (LangOpts.Char8) 1065 DEFINE_LOCK_FREE_MACRO(CHAR8_T, Char); // Treat char8_t like char. 1066 DEFINE_LOCK_FREE_MACRO(CHAR16_T, Char16); 1067 DEFINE_LOCK_FREE_MACRO(CHAR32_T, Char32); 1068 DEFINE_LOCK_FREE_MACRO(WCHAR_T, WChar); 1069 DEFINE_LOCK_FREE_MACRO(SHORT, Short); 1070 DEFINE_LOCK_FREE_MACRO(INT, Int); 1071 DEFINE_LOCK_FREE_MACRO(LONG, Long); 1072 DEFINE_LOCK_FREE_MACRO(LLONG, LongLong); 1073 Builder.defineMacro(Prefix + "POINTER_LOCK_FREE", 1074 getLockFreeValue(TI.getPointerWidth(0), 1075 TI.getPointerAlign(0), 1076 InlineWidthBits)); 1077 #undef DEFINE_LOCK_FREE_MACRO 1078 }; 1079 addLockFreeMacros("__CLANG_ATOMIC_"); 1080 if (LangOpts.GNUCVersion) 1081 addLockFreeMacros("__GCC_ATOMIC_"); 1082 1083 if (LangOpts.NoInlineDefine) 1084 Builder.defineMacro("__NO_INLINE__"); 1085 1086 if (unsigned PICLevel = LangOpts.PICLevel) { 1087 Builder.defineMacro("__PIC__", Twine(PICLevel)); 1088 Builder.defineMacro("__pic__", Twine(PICLevel)); 1089 if (LangOpts.PIE) { 1090 Builder.defineMacro("__PIE__", Twine(PICLevel)); 1091 Builder.defineMacro("__pie__", Twine(PICLevel)); 1092 } 1093 } 1094 1095 // Macros to control C99 numerics and <float.h> 1096 Builder.defineMacro("__FLT_EVAL_METHOD__", Twine(TI.getFloatEvalMethod())); 1097 Builder.defineMacro("__FLT_RADIX__", "2"); 1098 Builder.defineMacro("__DECIMAL_DIG__", "__LDBL_DECIMAL_DIG__"); 1099 1100 if (LangOpts.getStackProtector() == LangOptions::SSPOn) 1101 Builder.defineMacro("__SSP__"); 1102 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong) 1103 Builder.defineMacro("__SSP_STRONG__", "2"); 1104 else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 1105 Builder.defineMacro("__SSP_ALL__", "3"); 1106 1107 if (PPOpts.SetUpStaticAnalyzer) 1108 Builder.defineMacro("__clang_analyzer__"); 1109 1110 if (LangOpts.FastRelaxedMath) 1111 Builder.defineMacro("__FAST_RELAXED_MATH__"); 1112 1113 if (FEOpts.ProgramAction == frontend::RewriteObjC || 1114 LangOpts.getGC() != LangOptions::NonGC) { 1115 Builder.defineMacro("__weak", "__attribute__((objc_gc(weak)))"); 1116 Builder.defineMacro("__strong", "__attribute__((objc_gc(strong)))"); 1117 Builder.defineMacro("__autoreleasing", ""); 1118 Builder.defineMacro("__unsafe_unretained", ""); 1119 } else if (LangOpts.ObjC) { 1120 Builder.defineMacro("__weak", "__attribute__((objc_ownership(weak)))"); 1121 Builder.defineMacro("__strong", "__attribute__((objc_ownership(strong)))"); 1122 Builder.defineMacro("__autoreleasing", 1123 "__attribute__((objc_ownership(autoreleasing)))"); 1124 Builder.defineMacro("__unsafe_unretained", 1125 "__attribute__((objc_ownership(none)))"); 1126 } 1127 1128 // On Darwin, there are __double_underscored variants of the type 1129 // nullability qualifiers. 1130 if (TI.getTriple().isOSDarwin()) { 1131 Builder.defineMacro("__nonnull", "_Nonnull"); 1132 Builder.defineMacro("__null_unspecified", "_Null_unspecified"); 1133 Builder.defineMacro("__nullable", "_Nullable"); 1134 } 1135 1136 // Add a macro to differentiate between regular iOS/tvOS/watchOS targets and 1137 // the corresponding simulator targets. 1138 if (TI.getTriple().isOSDarwin() && TI.getTriple().isSimulatorEnvironment()) 1139 Builder.defineMacro("__APPLE_EMBEDDED_SIMULATOR__", "1"); 1140 1141 // OpenMP definition 1142 // OpenMP 2.2: 1143 // In implementations that support a preprocessor, the _OPENMP 1144 // macro name is defined to have the decimal value yyyymm where 1145 // yyyy and mm are the year and the month designations of the 1146 // version of the OpenMP API that the implementation support. 1147 if (!LangOpts.OpenMPSimd) { 1148 switch (LangOpts.OpenMP) { 1149 case 0: 1150 break; 1151 case 31: 1152 Builder.defineMacro("_OPENMP", "201107"); 1153 break; 1154 case 40: 1155 Builder.defineMacro("_OPENMP", "201307"); 1156 break; 1157 case 45: 1158 Builder.defineMacro("_OPENMP", "201511"); 1159 break; 1160 case 51: 1161 Builder.defineMacro("_OPENMP", "202011"); 1162 break; 1163 case 52: 1164 Builder.defineMacro("_OPENMP", "202111"); 1165 break; 1166 default: 1167 // Default version is OpenMP 5.0 1168 Builder.defineMacro("_OPENMP", "201811"); 1169 break; 1170 } 1171 } 1172 1173 // CUDA device path compilaton 1174 if (LangOpts.CUDAIsDevice && !LangOpts.HIP) { 1175 // The CUDA_ARCH value is set for the GPU target specified in the NVPTX 1176 // backend's target defines. 1177 Builder.defineMacro("__CUDA_ARCH__"); 1178 } 1179 1180 // We need to communicate this to our CUDA header wrapper, which in turn 1181 // informs the proper CUDA headers of this choice. 1182 if (LangOpts.CUDADeviceApproxTranscendentals || LangOpts.FastMath) { 1183 Builder.defineMacro("__CLANG_CUDA_APPROX_TRANSCENDENTALS__"); 1184 } 1185 1186 // Define a macro indicating that the source file is being compiled with a 1187 // SYCL device compiler which doesn't produce host binary. 1188 if (LangOpts.SYCLIsDevice) { 1189 Builder.defineMacro("__SYCL_DEVICE_ONLY__", "1"); 1190 } 1191 1192 // OpenCL definitions. 1193 if (LangOpts.OpenCL) { 1194 InitializeOpenCLFeatureTestMacros(TI, LangOpts, Builder); 1195 1196 if (TI.getTriple().isSPIR() || TI.getTriple().isSPIRV()) 1197 Builder.defineMacro("__IMAGE_SUPPORT__"); 1198 } 1199 1200 if (TI.hasInt128Type() && LangOpts.CPlusPlus && LangOpts.GNUMode) { 1201 // For each extended integer type, g++ defines a macro mapping the 1202 // index of the type (0 in this case) in some list of extended types 1203 // to the type. 1204 Builder.defineMacro("__GLIBCXX_TYPE_INT_N_0", "__int128"); 1205 Builder.defineMacro("__GLIBCXX_BITSIZE_INT_N_0", "128"); 1206 } 1207 1208 // Get other target #defines. 1209 TI.getTargetDefines(LangOpts, Builder); 1210 } 1211 1212 /// InitializePreprocessor - Initialize the preprocessor getting it and the 1213 /// environment ready to process a single file. This returns true on error. 1214 /// 1215 void clang::InitializePreprocessor( 1216 Preprocessor &PP, const PreprocessorOptions &InitOpts, 1217 const PCHContainerReader &PCHContainerRdr, 1218 const FrontendOptions &FEOpts) { 1219 const LangOptions &LangOpts = PP.getLangOpts(); 1220 std::string PredefineBuffer; 1221 PredefineBuffer.reserve(4080); 1222 llvm::raw_string_ostream Predefines(PredefineBuffer); 1223 MacroBuilder Builder(Predefines); 1224 1225 // Emit line markers for various builtin sections of the file. We don't do 1226 // this in asm preprocessor mode, because "# 4" is not a line marker directive 1227 // in this mode. 1228 if (!PP.getLangOpts().AsmPreprocessor) 1229 Builder.append("# 1 \"<built-in>\" 3"); 1230 1231 // Install things like __POWERPC__, __GNUC__, etc into the macro table. 1232 if (InitOpts.UsePredefines) { 1233 // FIXME: This will create multiple definitions for most of the predefined 1234 // macros. This is not the right way to handle this. 1235 if ((LangOpts.CUDA || LangOpts.OpenMPIsDevice || LangOpts.SYCLIsDevice) && 1236 PP.getAuxTargetInfo()) 1237 InitializePredefinedMacros(*PP.getAuxTargetInfo(), LangOpts, FEOpts, 1238 PP.getPreprocessorOpts(), Builder); 1239 1240 InitializePredefinedMacros(PP.getTargetInfo(), LangOpts, FEOpts, 1241 PP.getPreprocessorOpts(), Builder); 1242 1243 // Install definitions to make Objective-C++ ARC work well with various 1244 // C++ Standard Library implementations. 1245 if (LangOpts.ObjC && LangOpts.CPlusPlus && 1246 (LangOpts.ObjCAutoRefCount || LangOpts.ObjCWeak)) { 1247 switch (InitOpts.ObjCXXARCStandardLibrary) { 1248 case ARCXX_nolib: 1249 case ARCXX_libcxx: 1250 break; 1251 1252 case ARCXX_libstdcxx: 1253 AddObjCXXARCLibstdcxxDefines(LangOpts, Builder); 1254 break; 1255 } 1256 } 1257 } 1258 1259 // Even with predefines off, some macros are still predefined. 1260 // These should all be defined in the preprocessor according to the 1261 // current language configuration. 1262 InitializeStandardPredefinedMacros(PP.getTargetInfo(), PP.getLangOpts(), 1263 FEOpts, Builder); 1264 1265 // Add on the predefines from the driver. Wrap in a #line directive to report 1266 // that they come from the command line. 1267 if (!PP.getLangOpts().AsmPreprocessor) 1268 Builder.append("# 1 \"<command line>\" 1"); 1269 1270 // Process #define's and #undef's in the order they are given. 1271 for (unsigned i = 0, e = InitOpts.Macros.size(); i != e; ++i) { 1272 if (InitOpts.Macros[i].second) // isUndef 1273 Builder.undefineMacro(InitOpts.Macros[i].first); 1274 else 1275 DefineBuiltinMacro(Builder, InitOpts.Macros[i].first, 1276 PP.getDiagnostics()); 1277 } 1278 1279 // Exit the command line and go back to <built-in> (2 is LC_LEAVE). 1280 if (!PP.getLangOpts().AsmPreprocessor) 1281 Builder.append("# 1 \"<built-in>\" 2"); 1282 1283 // If -imacros are specified, include them now. These are processed before 1284 // any -include directives. 1285 for (unsigned i = 0, e = InitOpts.MacroIncludes.size(); i != e; ++i) 1286 AddImplicitIncludeMacros(Builder, InitOpts.MacroIncludes[i]); 1287 1288 // Process -include-pch/-include-pth directives. 1289 if (!InitOpts.ImplicitPCHInclude.empty()) 1290 AddImplicitIncludePCH(Builder, PP, PCHContainerRdr, 1291 InitOpts.ImplicitPCHInclude); 1292 1293 // Process -include directives. 1294 for (unsigned i = 0, e = InitOpts.Includes.size(); i != e; ++i) { 1295 const std::string &Path = InitOpts.Includes[i]; 1296 AddImplicitInclude(Builder, Path); 1297 } 1298 1299 // Instruct the preprocessor to skip the preamble. 1300 PP.setSkipMainFilePreamble(InitOpts.PrecompiledPreambleBytes.first, 1301 InitOpts.PrecompiledPreambleBytes.second); 1302 1303 // Copy PredefinedBuffer into the Preprocessor. 1304 PP.setPredefines(Predefines.str()); 1305 } 1306